From 565fe68239280b093515bf06b88af392bcd817de Mon Sep 17 00:00:00 2001 From: BinaryHuman Date: Thu, 27 Aug 2026 14:41:49 +0300 Subject: [PATCH] Adds independent metadata and artwork enrichment Splits the single combined enrichment phase of the media library scan into independent, modular jobs, so that the metadata and the artwork of a book are enriched separately and only when their respective triggers fire. - Adds the MediaContributorRoleCategory enum (Other first, then Author, Translator, Illustrator, Publisher and Narrator) and makes the role category canonical, so that roles describing the same kind of contribution are never treated as distinct. - Realizes the media contributor bounded context: a MediaContributor is a person, unique by display name, without a role. The role moves to the per-work participation (BookContributors), so that a single contributor can play multiple roles. Contributors are created and linked by the metadata enrichment job, and exposed to subsequent jobs. - Makes the Book aggregate pure: the enrichment tracking state (metadata status, providers, timestamps and covers) no longer lives on the domain aggregate, but stays in the Books table, managed directly by the jobs. - Models artwork generically as a BookArtwork child table (type, ordinal, content hash, status and provider), so that each piece of artwork is tracked independently and a change of one does not require the others to be re-fetched. - Splits the scan DAG into ResultsSave, ProviderConfigurationInvalidation, MetadataEnrichment and ArtworkEnrichment jobs. The invalidation job fingerprints the provider configuration of a library and resets the enrichment state of the affected channel when it changed. The artwork job resolves the missing artwork, hashing it to detect identical covers and skip re-copying. Content-changed books are reset by the results save job. - Deletes the book and its stored artwork when the file disappears from the library. - Adds the migration creating the new tables, backfilling the existing covers into the artwork table, and adding the configuration fingerprints. - Localizes the new scan job stages, and fixes the invalidation job wiping the library content locations by persisting the fingerprints through the change tracker instead of the repository update action. --- .../Core/Mapping/CalibreMapper.cs | 21 +- .../Core/Mapping/OpenLibraryMapper.cs | 25 +- .../BookContributorEntity.cs | 62 + .../MediaContributorEntity.cs | 65 +- .../MediaContributorNameEntity.cs | 16 - .../MediaContributorRoleEntity.cs | 16 - .../MediaLibrary/Management/LibraryEntity.cs | 14 +- .../BookLibrary/BookArtworkEntity.cs | 84 + .../BookLibrary/BookEntity.cs | 15 +- .../Repositories/Books/IBookRepository.cs | 64 + .../IMediaContributorRepository.cs | 37 + .../ILibraryScanStagingResultsRepository.cs | 9 + .../Common/DataAccess/UoW/IUnitOfWork.cs | 6 + .../Security/IFileHashService.cs | 7 + .../BookLibrary/Books/BookEntityMapping.cs | 11 +- .../BookLibrary/Books/BookMapping.cs | 45 +- .../Books/BookMetadataDtoMapping.cs | 13 +- ...braryMediaItemDeletedDomainEventHandler.cs | 81 + .../AddBook/AddBookCommandValidator.cs | 4 +- .../MediaContributorRoleDto.cs | 9 +- .../Configuration/BookArtworkConfiguration.cs | 73 + .../Common/Configuration/BookConfiguration.cs | 38 +- .../BookContributorConfiguration.cs | 61 + .../Configuration/LibraryConfiguration.cs | 18 +- .../MediaContributorConfiguration.cs | 61 + ...ntMetadataAndArtworkEnrichment.Designer.cs | 1566 +++++++++++++++++ ...IndependentMetadataAndArtworkEnrichment.cs | 256 +++ .../LuminaDbContextModelSnapshot.cs | 222 ++- .../Core/Repositories/Books/BookRepository.cs | 151 ++ .../LibraryScanStagingResultsRepository.cs | 24 + .../MediaContributorRepository.cs | 89 + .../Core/UoW/LuminaDbContext.cs | 3 + src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 12 + .../Common/Enums/BookLibrary/ArtworkStatus.cs | 22 + .../MediaContributorRoleCategory.cs | 44 + .../Common/Enums/MediaLibrary/ArtworkType.cs | 20 + .../Common/Errors/Errors.MediaContributor.cs | 1 - .../Common/Errors/Errors.MediaContributors.cs | 17 + .../IMediaLibraryScanArtworkEnrichmentJob.cs | 8 + ...canProviderConfigurationInvalidationJob.cs | 9 + .../MediaContributor.cs | 35 +- .../ValueObjects/ContributorName.cs | 5 +- .../ValueObjects/MediaContributorRole.cs | 40 +- .../BookLibraryAggregate/Book.cs | 63 +- .../Scanners/BookLibraryTypeScanner.cs | 21 +- .../InfrastructureLayerServices.cs | 2 + .../MediaLibraryScanArtworkEnrichmentJob.cs | 412 +++++ .../MediaLibraryScanMetadataEnrichmentJob.cs | 224 ++- ...canProviderConfigurationInvalidationJob.cs | 183 ++ .../Common/MediaLibraryScanResultsSaveJob.cs | 13 + .../ProviderConfigurationFingerprint.cs | 64 + .../Core/Security/FileHashService.cs | 15 + .../Books/AddBook/AddBookEndpointSummary.cs | 10 +- .../Books/GetBooks/GetBooksEndpointSummary.cs | 9 +- .../Views/Library/Management/Index.ar-SA.resx | 6 + .../Views/Library/Management/Index.de-DE.resx | 6 + .../Views/Library/Management/Index.en-US.resx | 6 + .../Views/Library/Management/Index.es-ES.resx | 6 + .../Views/Library/Management/Index.fr-FR.resx | 6 + .../Views/Library/Management/Index.it-IT.resx | 6 + .../Views/Library/Management/Index.ja-JP.resx | 6 + .../Views/Library/Management/Index.resx | 6 + .../Views/Library/Management/Index.ro-RO.resx | 6 + .../Views/Library/Management/Index.uk-UA.resx | 6 + .../Views/Library/Management/Index.zh-CN.resx | 6 + .../Views/Library/Management/Index.cshtml | 4 +- .../BookContributorEntityFixture.cs | 60 + .../MediaContributorEntityFixture.cs | 63 + .../Management/LibraryEntityFixture.cs | 8 +- .../BookLibrary/BookArtworkEntityFixture.cs | 73 + .../Commands/AddBook/AddBookCommandFixture.cs | 3 +- .../MediaContributorDtoFixture.cs | 9 +- .../MediaContributorRoleDtoFixture.cs | 7 +- .../Books/AddBookRequestFixture.cs | 3 +- .../BookLibrary/Books/BookResponseFixture.cs | 3 +- .../MediaContributorFixture.cs | 60 + .../MediaContributorRoleFixture.cs | 5 +- .../Books/AddBook/AddBookEndpointTests.cs | 18 - .../Books/AddBookRequestMappingTests.cs | 3 +- .../Books/BookMetadataDtoMappingTests.cs | 12 +- ...MediaItemDeletedDomainEventHandlerTests.cs | 218 +++ .../AddBook/AddBookCommandValidatorTests.cs | 14 - .../MediaContributorDtoTests.cs | 3 +- .../MediaContributorRoleDtoTests.cs | 3 +- .../BookLibrary/BookMetadataDtoTests.cs | 3 +- .../Repositories/Books/BookRepositoryTests.cs | 236 +++ .../MediaContributorRepositoryTests.cs | 115 ++ .../Core/UoW/LuminaDbContextTests.cs | 5 +- .../MediaContributorTests.cs | 43 +- .../ValueObjects/MediaContributorRoleTests.cs | 37 +- .../BookLibraryAggregate/BookTests.cs | 58 +- .../Scanners/BookLibraryTypeScannerTests.cs | 21 +- ...diaLibraryScanArtworkEnrichmentJobTests.cs | 299 ++++ ...iaLibraryScanMetadataEnrichmentJobTests.cs | 287 ++- ...oviderConfigurationInvalidationJobTests.cs | 291 +++ .../MediaLibraryScanResultsSaveJobTests.cs | 34 + .../Core/Mapping/CalibreMapperTests.cs | 13 +- .../Core/Mapping/OpenLibraryMapperTests.cs | 3 +- 98 files changed, 5845 insertions(+), 630 deletions(-) create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs delete mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs delete mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/MediaContributors/IMediaContributorRepository.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/BookArtworkConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/MediaContributorConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.MediaContributors.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanArtworkEnrichmentJob.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanProviderConfigurationInvalidationJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/BookContributorEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/MediaContributorEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntityFixture.cs create mode 100644 tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorFixture.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs diff --git a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs index 60c2dc54..a6361e3b 100644 --- a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs +++ b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs @@ -4,6 +4,7 @@ using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; using System; using System.Collections.Generic; @@ -123,7 +124,7 @@ internal static class CalibreMapper List result = []; HashSet seen = new(StringComparer.OrdinalIgnoreCase); - void Add(string? displayName, string role, string category) + void Add(string? displayName, string role, MediaContributorRoleCategory category) { if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) return; @@ -134,7 +135,7 @@ internal static class CalibreMapper } foreach (OpfCreatorDto creator in creators) - Add(creator.Name, "Author", "Writing"); + Add(creator.Name, "Author", MediaContributorRoleCategory.Author); foreach (OpfContributorDto contributor in contributors) Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role)); @@ -223,20 +224,20 @@ internal static class CalibreMapper } /// - /// Maps a creator or contributor role code into a contributor category. + /// Maps a creator or contributor role code into the canonical category of the role. /// /// The role code to map. - /// The mapped contributor category. - private static string MapContributorCategory(string? role) + /// The canonical category of the role. + private static MediaContributorRoleCategory MapContributorCategory(string? role) { if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true) - return "Writing"; + return MediaContributorRoleCategory.Author; if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase)) - return "Art"; + return MediaContributorRoleCategory.Illustrator; if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase)) - return "Translation"; + return MediaContributorRoleCategory.Translator; if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase)) - return "Production"; - return "Other"; + return MediaContributorRoleCategory.Publisher; + return MediaContributorRoleCategory.Other; } } diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs index 04058a62..94f19e72 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs @@ -5,6 +5,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using System; using System.Collections.Generic; @@ -272,7 +273,7 @@ internal static partial class OpenLibraryMapper List result = []; HashSet seen = new(StringComparer.OrdinalIgnoreCase); - void Add(string? displayName, string? legalName, string role, string category) + void Add(string? displayName, string? legalName, string role, MediaContributorRoleCategory category) { if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) return; @@ -280,9 +281,9 @@ internal static partial class OpenLibraryMapper } foreach (OpenLibraryAuthorResponse author in authors) - Add(author.Name, author.PersonalName, "Author", "Writing"); + Add(author.Name, author.PersonalName, "Author", MediaContributorRoleCategory.Author); foreach (string authorName in fallbackAuthors ?? []) - Add(authorName, null, "Author", "Writing"); + Add(authorName, null, "Author", MediaContributorRoleCategory.Author); foreach (string contribution in contributions ?? []) { @@ -490,24 +491,24 @@ internal static partial class OpenLibraryMapper } /// - /// Maps a contributor role into a contributor category. + /// Maps a contribution role into the canonical category of the role. /// /// The role to categorize. - /// The mapped contributor category. - private static string ContributorCategory(string role) + /// The canonical category of the role. + private static MediaContributorRoleCategory ContributorCategory(string role) { if (role.Contains("illustr", StringComparison.OrdinalIgnoreCase) || role.Contains("artist", StringComparison.OrdinalIgnoreCase)) - return "Art"; + return MediaContributorRoleCategory.Illustrator; if (role.Contains("translat", StringComparison.OrdinalIgnoreCase)) - return "Translation"; + return MediaContributorRoleCategory.Translator; + if (role.Contains("narrat", StringComparison.OrdinalIgnoreCase)) + return MediaContributorRoleCategory.Narrator; if (role.Contains("edit", StringComparison.OrdinalIgnoreCase) || role.Contains("author", StringComparison.OrdinalIgnoreCase) || role.Contains("writer", StringComparison.OrdinalIgnoreCase)) - return "Writing"; - if (role.Contains("narrat", StringComparison.OrdinalIgnoreCase)) - return "Performance"; - return "Other"; + return MediaContributorRoleCategory.Author; + return MediaContributorRoleCategory.Other; } /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs new file mode 100644 index 00000000..2aea5dde --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors; + +/// +/// 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. +/// +[DebuggerDisplay("BookId: {BookId} MediaContributorId: {MediaContributorId}")] +public class BookContributorEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the participation. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the book the contributor participated in. + /// + public required Guid BookId { get; set; } + + /// + /// Gets or sets the Id of the media contributor. + /// + public required Guid MediaContributorId { get; set; } + + /// + /// Gets or sets the display name of the role the contributor played in the book. + /// + public required string RoleName { get; set; } + + /// + /// Gets or sets the canonical category of the role the contributor played in the book. + /// + public required MediaContributorRoleCategory RoleCategory { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs index 19929100..dfc0b1ad 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorEntity.cs @@ -1,16 +1,65 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using System; using System.Diagnostics; #endregion namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors; /// -/// Repository entity for a media contributor. +/// Repository entity for a media contributor, the person that contributed to one or more media items. +/// The contributor is a person, unique by name, and agnostic of the kind of media it contributed to. /// -/// The name details of the media contributor, including display and legal names. -/// The role details of the media contributor, including the role name and category. -[DebuggerDisplay("Name: {Name}, Role: {Role}")] -public record MediaContributorEntity( - MediaContributorNameEntity? Name, - MediaContributorRoleEntity? Role -); +[DebuggerDisplay("DisplayName: {DisplayName}")] +public class MediaContributorEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the media contributor. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the name by which the contributor is popularly known. + /// + public required string DisplayName { get; set; } + + /// + /// Gets or sets the legal name of the contributor. + /// + public string? LegalName { get; set; } + + /// + /// Gets or sets the biography of the contributor. + /// + public string? Biography { get; set; } + + /// + /// Gets or sets the date of birth of the contributor. + /// + public DateOnly? DateOfBirth { get; set; } + + /// + /// Gets or sets the date of death of the contributor. + /// + public DateOnly? DateOfDeath { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs deleted file mode 100644 index b454b894..00000000 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorNameEntity.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors; - -/// -/// Repository entity for a media contributor name. -/// -/// The display name of the media contributor. -/// The legal name of the media contributor. -[DebuggerDisplay("DisplayName: {DisplayName}")] -public record MediaContributorNameEntity( - string? DisplayName, - string? LegalName -); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs deleted file mode 100644 index f718f6cd..00000000 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/MediaContributorRoleEntity.cs +++ /dev/null @@ -1,16 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors; - -/// -/// Repository entity for a media contributor role. -/// -/// The name of the role assigned to the media contributor. -/// The category of the role. -[DebuggerDisplay("Name: {Name}, Category: {Category}")] -public record MediaContributorRoleEntity( - string? Name, - string? Category -); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs index a7c07954..3dfdaa16 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -71,10 +71,22 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity public bool ShouldSaveMetadataInMediaDirectories { get; init; } /// - /// Gets whether this media library should skip the directories whose contents have not changed since the last scan, during the scan. + /// Gets or sets whether the unchanged directories are skipped during the scan of the media library. /// public bool ShouldSkipUnchangedDirectoriesDuringScan { get; init; } + /// + /// Gets or sets the fingerprint of the metadata provider configuration of the media library, used to detect + /// whether the configuration changed since the last scan, and thus whether the books need re-enrichment. + /// + public string? MetadataProvidersConfigurationFingerprint { get; set; } + + /// + /// Gets or sets the fingerprint of the artwork provider configuration of the media library, used to detect + /// whether the configuration changed since the last scan, and thus whether the books need their artwork re-resolved. + /// + public string? ArtworkProvidersConfigurationFingerprint { get; set; } + /// /// Gets the user that owns the media library. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntity.cs new file mode 100644 index 00000000..7256e30a --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntity.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Repository entity for a piece of artwork of a book, like its cover. +/// A book can have multiple pieces of artwork of different types, and multiple instances of the same type +/// (like the booklet pages of an audio album), each tracked independently so that a change of one artwork +/// does not require the others to be re-fetched. +/// +[DebuggerDisplay("BookId: {BookId} Type: {ArtworkType} Ordinal: {Ordinal}")] +public class BookArtworkEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the artwork. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the book the artwork belongs to. + /// + public required Guid BookId { get; set; } + + /// + /// Gets or sets the type of the artwork. + /// + public required ArtworkType ArtworkType { get; set; } + + /// + /// Gets or sets the ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered. + /// + public required int Ordinal { get; set; } + + /// + /// Gets or sets the relative file name of the stored artwork, if the artwork has been resolved. + /// + public string? FileName { get; set; } + + /// + /// Gets or sets the content hash of the stored artwork, used to detect whether a re-resolved artwork differs from the stored one. + /// + public ulong ContentHash { get; set; } + + /// + /// Gets or sets the status of the artwork enrichment. + /// + public required ArtworkStatus Status { get; set; } + + /// + /// Gets or sets the name of the plugin that resolved the artwork, if applicable. + /// + public string? Provider { get; set; } + + /// + /// Gets or sets the date and time when the artwork was last resolved, if applicable. + /// + public DateTime? LastUpdateUtc { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs index dd02ed01..f43a92d8 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; @@ -190,20 +191,20 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// public string? AppleBooksId { get; set; } - /// - /// Gets or sets the file system path of the cover image of the book, if applicable. - /// - public string? CoverImagePath { get; set; } - /// /// Gets or sets the list of ISBN (International Standard Book Number) of the book. /// public List ISBNs { get; set; } = []; /// - /// Gets or sets the list of media contributors (actors, directors, etc) starring in this book. + /// Gets or sets the participations of the media contributors in the book, each carrying the role the contributor played. /// - //public List ContributorIds { get; set; } = []; + public List BookContributors { get; set; } = []; + + /// + /// Gets or sets the pieces of artwork of the book, each tracked independently with its own enrichment state. + /// + public List BookArtwork { get; set; } = []; /// /// Gets or sets the list of ratings for this book. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs index 9265254b..3c59813c 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs @@ -56,4 +56,68 @@ public interface IBookRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either the number of books needing their metadata enriched, or an error. Task> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets a page of the books of the media library identified by that need their artwork resolved, + /// meaning they lack at least one required piece of artwork with an enriched status, ordered by path, using keyset pagination. + /// + /// The Id of the media library whose books are retrieved. + /// The path of the last retrieved book, used for keyset pagination. Pass to get the first page. + /// The maximum number of books to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of books needing their artwork resolved, or an error. + Task>> GetBooksNeedingArtworkAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken); + + /// + /// Gets the number of books of the media library identified by that need their artwork resolved. + /// + /// The Id of the media library whose books are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of books needing their artwork resolved, or an error. + Task> GetBooksNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Resets the enrichment state of the books stored at the provided in the media library identified by + /// , so that they are re-enriched, because their content changed since the last scan. + /// + /// The Id of the media library whose books are reset. + /// The file system paths of the books whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken); + + /// + /// Resets the metadata enrichment status of all the books of the media library identified by , + /// so that they are re-enriched, because the metadata provider configuration of the library changed. + /// + /// The Id of the media library whose books are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Resets the artwork status of all the artwork of the books of the media library identified by , + /// so that they are re-resolved, because the artwork provider configuration of the library changed. + /// + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetArtworkStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the display names of the author of the books identified by the provided , + /// keyed by the Id of the book, or when a book has no author. + /// + /// The unique identifiers of the books whose authors are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the display names of the authors of the books, keyed by book Id, or an error. + Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken); + + /// + /// Deletes the book identified by . + /// + /// The Id of the book to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteAsync(Guid bookId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaContributors/IMediaContributorRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaContributors/IMediaContributorRepository.cs new file mode 100644 index 00000000..e4b8b5a4 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaContributors/IMediaContributorRepository.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MediaContributors; + +/// +/// Interface for the repository for media contributors. +/// +public interface IMediaContributorRepository : IRepository, + IInsertRepositoryAction +{ + /// + /// Gets the media contributor whose display name matches the provided , or creates and inserts a new one + /// when no contributor with that name exists yet, guaranteeing a single contributor per person. + /// + /// The name by which the contributor is popularly known. + /// The optional legal name of the contributor. + /// Cancellation token that can be used to stop the execution. + /// An containing either the existing or newly created , or an error. + Task> FindOrCreateByDisplayNameAsync(string displayName, string? legalName, CancellationToken cancellationToken); + + /// + /// Gets the media contributors identified by the provided . + /// + /// The unique identifiers of the media contributors to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the retrieved s, or an error. + Task>> GetByIdsAsync(IReadOnlyCollection ids, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs index 5e280fb4..8c042ba8 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs @@ -46,6 +46,15 @@ public interface ILibraryScanStagingResultsRepository : IRepositoryAn containing either a page of staging results that need hashing, or an error. Task>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken); + /// + /// Gets the paths of the media library scan staging results of the current scan that changed, meaning their content needs to be re-hashed + /// and the books stored at those paths need to be re-enriched, excluding the staging results that are new. + /// + /// The unique identifier of the media library scan whose staging results are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the paths of the changed staging results, or an error. + Task>> GetChangedPathsAsync(Guid scanId, CancellationToken cancellationToken); + /// /// Updates the content hashes of the provided media library scan staging results. /// diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 17a48b83..b314bfab 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Authorization; 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.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Themes; @@ -41,6 +42,11 @@ public interface IUnitOfWork /// IBookRepository BookRepository { get; } + /// + /// Gets the media contributor repository. + /// + IMediaContributorRepository MediaContributorRepository { get; } + /// /// Gets the directory scan fingerprint repository. /// diff --git a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs index 74284d33..d6326591 100644 --- a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs @@ -21,4 +21,11 @@ public interface IFileHashService /// Cancellation token that can be used to stop the execution. /// A collection of the hashed files, along with their hashes. Task> HashFilesAsync(IReadOnlyCollection files, Func callback, CancellationToken cancellationToken); + + /// + /// Computes the content hash of the file stored at , by sampling chunks from it. + /// + /// The path of the file to hash. + /// The content hash of the file. + ulong ComputeFileHash(string filePath); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index ed2abbc8..0ef8978f 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -10,11 +10,13 @@ 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.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -131,14 +133,11 @@ public static class BookEntityMapping repositoryEntity.CreatedOnUtc, Optional.FromNullable(repositoryEntity.UpdatedOnUtc), [.. isbnsResult.Select(isbn => isbn.Value)], - [], + [.. repositoryEntity.BookContributors.Select(bookContributor => MediaContributorId.Create(bookContributor.MediaContributorId))], [.. bookRatingsResult.Select(bookRating => bookRating.Value)]); if (bookResult.IsFailure) return bookResult.Errors; - if (repositoryEntity.CoverImagePath is not null) - bookResult.Value.SetBookCoverImagePath(repositoryEntity.CoverImagePath); - return bookResult; } @@ -225,7 +224,7 @@ public static class BookEntityMapping repositoryEntity.MetadataProvider, repositoryEntity.CreatedOnUtc, repositoryEntity.UpdatedOnUtc, - repositoryEntity.CoverImagePath + repositoryEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName ); } @@ -267,7 +266,7 @@ public static class BookEntityMapping repositoryEntity.Id, repositoryEntity.Title, repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear, - repositoryEntity.CoverImagePath + repositoryEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs index 3ad75ac6..8e1edf71 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -56,16 +56,53 @@ public static class BookMapping GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null, BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, - CoverImagePath = domainEntity.CoverImagePath.HasValue ? domainEntity.CoverImagePath.Value : null, ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], - 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, UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null, }; } + + /// + /// Applies the metadata fields of onto the existing , + /// without touching the enrichment tracking columns, which are managed directly by the enrichment jobs. + /// + /// The repository entity onto which the metadata is applied. + /// The domain entity whose metadata is applied. + public static void ApplyMetadataToEntity(this BookEntity entity, Book domainEntity) + { + entity.Title = domainEntity.Metadata.Title; + entity.OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null; + entity.Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.Value : null; + entity.OriginalReleaseDate = domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null; + entity.OriginalReleaseYear = domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null; + entity.ReReleaseDate = domainEntity.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseDate.Value : null; + entity.ReReleaseYear = domainEntity.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseYear.Value : null; + entity.ReleaseCountry = domainEntity.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseCountry.Value : null; + entity.ReleaseVersion = domainEntity.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseVersion.Value : null; + entity.LanguageCode = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageCode : null; + entity.LanguageName = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageName : null; + entity.LanguageNativeName = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.NativeName.Value : null; + entity.OriginalLanguageCode = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageCode : null; + entity.OriginalLanguageName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.LanguageName : null; + entity.OriginalLanguageNativeName = domainEntity.Metadata.OriginalLanguage.HasValue ? domainEntity.Metadata.OriginalLanguage.Value.NativeName.Value : null; + entity.Publisher = domainEntity.Metadata.Publisher.HasValue ? domainEntity.Metadata.Publisher.Value : null; + entity.PageCount = domainEntity.Metadata.PageCount.HasValue ? domainEntity.Metadata.PageCount.Value : null; + entity.Format = domainEntity.Format.HasValue ? domainEntity.Format.Value : null; + entity.Edition = domainEntity.Edition.HasValue ? domainEntity.Edition.Value : null; + entity.VolumeNumber = domainEntity.VolumeNumber.HasValue ? domainEntity.VolumeNumber.Value : null; + entity.ASIN = domainEntity.ASIN.HasValue ? domainEntity.ASIN.Value : null; + entity.GoodreadsId = domainEntity.GoodreadsId.HasValue ? domainEntity.GoodreadsId.Value : null; + entity.LCCN = domainEntity.LCCN.HasValue ? domainEntity.LCCN.Value : null; + entity.OCLCNumber = domainEntity.OCLCNumber.HasValue ? domainEntity.OCLCNumber.Value : null; + entity.OpenLibraryId = domainEntity.OpenLibraryId.HasValue ? domainEntity.OpenLibraryId.Value : null; + entity.LibraryThingId = domainEntity.LibraryThingId.HasValue ? domainEntity.LibraryThingId.Value : null; + entity.GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null; + entity.BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null; + entity.AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null; + entity.UpdatedOnUtc = DateTime.UtcNow; + entity.UpdatedBy = Guid.NewGuid(); + } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs index 59747d48..2b7d8206 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs @@ -19,14 +19,12 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B public static class BookMetadataDtoMapping { /// - /// Applies the metadata of to , marking its metadata as enriched by the provided . + /// Applies the metadata of to . /// /// The domain book to which the metadata is applied. /// The metadata to be applied. - /// The name of the metadata provider that enriched the book. - /// The date and time when the metadata was enriched. /// An representing either a successful operation, or an error. - public static Result ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc) + public static Result ApplyMetadata(this Book book, BookMetadataDto metadata) { if (string.IsNullOrWhiteSpace(metadata.Title)) return Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; @@ -126,14 +124,9 @@ public static class BookMetadataDtoMapping Optional.FromNullable(metadata.BarnesAndNobleId), Optional.FromNullable(metadata.AppleBooksId), [.. domainIsbnsResult.Select(isbnResult => isbnResult.Value)], - [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)], - providerName, - lastUpdateUtc + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)] ); - if (!string.IsNullOrWhiteSpace(metadata.CoverImagePath)) - book.SetBookCoverImagePath(metadata.CoverImagePath); - return Result.Success; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs new file mode 100644 index 00000000..84050f4e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +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.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Events; + +/// +/// Handler for the domain event raised when a media library item is no longer present in the media library scan snapshot. +/// The book stored at the deleted path is removed, together with its stored artwork. +/// +public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IBookArtworkService _bookArtworkService; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for storing the artwork of the books. + /// Injected logger used to report the issues encountered while deleting the media library item. + public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger logger) + { + _unitOfWork = unitOfWork; + _bookArtworkService = bookArtworkService; + _logger = logger; + } + + /// + /// Handles the event raised when a media library item is no longer present in the media library scan snapshot. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + public async ValueTask HandleAsync(LibraryMediaItemDeletedDomainEvent domainEvent, CancellationToken cancellationToken) + { + Guid libraryId = domainEvent.LibraryId.Value; + + // load the book stored at the deleted path, which might have been already removed + Result getBookResult = await _unitOfWork.BookRepository.GetByPathAsync(libraryId, domainEvent.Path, cancellationToken).ConfigureAwait(false); + if (getBookResult.IsFailure) + throw new EventualConsistencyException(getBookResult.FirstError, getBookResult.Errors); + BookEntity? book = getBookResult.Value; + if (book is null) + return; + + // delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors); + LibraryEntity library = getLibraryResult.Value; + + Result> getAuthorsResult = await _unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([book.Id], cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + throw new EventualConsistencyException(getAuthorsResult.FirstError, getAuthorsResult.Errors); + string authorName = getAuthorsResult.Value.TryGetValue(book.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; + + Result deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, book.Id, library.Title, authorName, book.Title); + if (deleteArtworkResult.IsFailure) + _logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", book.Id, book.Path); + + // delete the book, whose stored artwork and participations are removed by the database cascade + Result deleteBookResult = await _unitOfWork.BookRepository.DeleteAsync(book.Id, cancellationToken).ConfigureAwait(false); + if (deleteBookResult.IsFailure) + throw new EventualConsistencyException(deleteBookResult.FirstError, deleteBookResult.Errors); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 1e804b10..0f7a760f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -326,9 +326,7 @@ public class AddBookCommandValidator : AbstractValidator .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); role.RuleFor(r => r!.Category) .NotEmpty() - .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty) - .MaximumLength(50) - .WithError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong); + .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); }); }); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs index f659de93..d9265dda 100644 --- a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs @@ -1,16 +1,17 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System.Diagnostics; #endregion namespace Lumina.Contracts.DTO.MediaContributors; /// -/// Data transfer object for a media contributor role. +/// Data transfer object for the role of a media contributor in a media item. /// -/// The name of the role assigned to the media contributor. -/// The category of the role. +/// The display name of the role assigned to the media contributor. +/// The canonical category of the role. [DebuggerDisplay("Name: {Name}, Category: {Category}")] public record MediaContributorRoleDto( string? Name, - string? Category + MediaContributorRoleCategory? Category ); diff --git a/src/Lumina.DataAccess/Common/Configuration/BookArtworkConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookArtworkConfiguration.cs new file mode 100644 index 00000000..4152a5a2 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/BookArtworkConfiguration.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class BookArtworkConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("BookArtwork"); + builder.HasKey(bookArtwork => bookArtwork.Id); + builder.Property(bookArtwork => bookArtwork.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(bookArtwork => bookArtwork.BookId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(bookArtwork => bookArtwork.ArtworkType) + .IsRequired() + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(2); + builder.Property(bookArtwork => bookArtwork.Ordinal) + .IsRequired() + .HasColumnOrder(3); + builder.Property(bookArtwork => bookArtwork.FileName) + .HasMaxLength(2048) + .HasColumnOrder(4); + builder.Property(bookArtwork => bookArtwork.ContentHash) + .HasColumnOrder(5); + builder.Property(bookArtwork => bookArtwork.Status) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(6); + builder.Property(bookArtwork => bookArtwork.Provider) + .HasMaxLength(100) + .HasColumnOrder(7); + builder.Property(bookArtwork => bookArtwork.LastUpdateUtc) + .HasColumnOrder(8); + + // audit + builder.Property(bookArtwork => bookArtwork.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(9); + + builder.Property(bookArtwork => bookArtwork.CreatedBy) + .IsRequired() + .HasColumnOrder(10); + + builder.Property(bookArtwork => bookArtwork.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(11); + + builder.Property(bookArtwork => bookArtwork.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(12); + + builder.HasIndex(bookArtwork => new { bookArtwork.BookId, bookArtwork.ArtworkType, bookArtwork.Ordinal }) + .IsUnique(); + builder.HasIndex(bookArtwork => bookArtwork.Status); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index 0ad36b8a..0512ef27 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -152,27 +152,15 @@ public class BookConfiguration : IEntityTypeConfiguration builder.Property(book => book.UpdatedOnUtc) .HasColumnOrder(31); - //builder.HasMany() - //.WithMany() - //.UsingEntity>( - // "BookContributors", - // j => j.HasOne().WithMany().HasForeignKey("ContributorId"), - // j => j.HasOne().WithMany().HasForeignKey("BookId"), - // j => - // { - // j.HasKey("BookId", "ContributorId"); - // j.ToTable("BookContributors"); - // }); + builder.HasMany(book => book.BookContributors) + .WithOne() + .HasForeignKey(bookContributor => bookContributor.BookId) + .OnDelete(DeleteBehavior.Cascade); - //builder.OwnsMany(book => book.ContributorIds, ownedBuilder => - //{ - // ownedBuilder.ToTable("BookContributors"); - // ownedBuilder.WithOwner().HasForeignKey("BookId"); - // ownedBuilder.Property(c => c.Id) - // .HasColumnName("ContributorId") - // .HasColumnType("uniqueidentifier"); - // ownedBuilder.HasKey("BookId", "Id"); // Use the actual property name 'Id' here - //}); + builder.HasMany(book => book.BookArtwork) + .WithOne() + .HasForeignKey(bookArtwork => bookArtwork.BookId) + .OnDelete(DeleteBehavior.Cascade); builder.OwnsMany(book => book.Ratings, ratingBuilder => { @@ -241,13 +229,3 @@ public class BookConfiguration : IEntityTypeConfiguration builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus }); } } - -//public class ContributorConfiguration : IEntityTypeConfiguration -//{ -// public void Configure(EntityTypeBuilder builder) -// { -// builder.ToTable("Contributors"); -// builder.HasKey(c => c.Id); -// builder.Property(c => c.Id).ValueGeneratedNever(); -// } -//} diff --git a/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs new file mode 100644 index 00000000..dbc3ff30 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class BookContributorConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("BookContributors"); + builder.HasKey(bookContributor => bookContributor.Id); + 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() + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(4); + + // audit + builder.Property(bookContributor => bookContributor.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(bookContributor => bookContributor.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(bookContributor => bookContributor.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(bookContributor => bookContributor.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + builder.HasIndex(bookContributor => new { bookContributor.BookId, bookContributor.MediaContributorId }); + builder.HasIndex(bookContributor => bookContributor.MediaContributorId); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index 8c27891a..5f20f98a 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -56,6 +56,16 @@ public class LibraryConfiguration : IEntityTypeConfiguration builder.Property(library => library.ShouldSkipUnchangedDirectoriesDuringScan) .HasColumnOrder(8); + builder.Property(library => library.MetadataProvidersConfigurationFingerprint) + .HasMaxLength(64) + .HasDefaultValue(null) + .HasColumnOrder(9); + + builder.Property(library => library.ArtworkProvidersConfigurationFingerprint) + .HasMaxLength(64) + .HasDefaultValue(null) + .HasColumnOrder(10); + // one user with many libraries builder.HasOne(library => library.User) .WithMany(user => user.Libraries) @@ -88,18 +98,18 @@ public class LibraryConfiguration : IEntityTypeConfiguration // audit builder.Property(library => library.CreatedOnUtc) .IsRequired() - .HasColumnOrder(9); + .HasColumnOrder(11); builder.Property(library => library.CreatedBy) .IsRequired() - .HasColumnOrder(10); + .HasColumnOrder(12); builder.Property(library => library.UpdatedOnUtc) .HasDefaultValue(null) - .HasColumnOrder(11); + .HasColumnOrder(13); builder.Property(library => library.UpdatedBy) .HasDefaultValue(null) - .HasColumnOrder(12); + .HasColumnOrder(14); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/MediaContributorConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MediaContributorConfiguration.cs new file mode 100644 index 00000000..6f5552f1 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/MediaContributorConfiguration.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class MediaContributorConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MediaContributors"); + builder.HasKey(contributor => contributor.Id); + builder.Property(contributor => contributor.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(contributor => contributor.DisplayName) + .IsRequired() + .HasMaxLength(255) + .UseCollation("NOCASE") + .HasColumnOrder(1); + builder.Property(contributor => contributor.LegalName) + .HasMaxLength(255) + .HasColumnOrder(2); + builder.Property(contributor => contributor.Biography) + .HasMaxLength(2000) + .HasColumnOrder(3); + builder.Property(contributor => contributor.DateOfBirth) + .HasColumnOrder(4); + builder.Property(contributor => contributor.DateOfDeath) + .HasColumnOrder(5); + + // audit + builder.Property(contributor => contributor.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(contributor => contributor.CreatedBy) + .IsRequired() + .HasColumnOrder(7); + + builder.Property(contributor => contributor.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(8); + + builder.Property(contributor => contributor.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(9); + + builder.HasIndex(contributor => contributor.DisplayName) + .IsUnique(); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.Designer.cs new file mode 100644 index 00000000..2cb92898 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.Designer.cs @@ -0,0 +1,1566 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260826204815_AddsIndependentMetadataAndArtworkEnrichment")] + partial class AddsIndependentMetadataAndArtworkEnrichment + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.cs b/src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.cs new file mode 100644 index 00000000..a5733aab --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260826204815_AddsIndependentMetadataAndArtworkEnrichment.cs @@ -0,0 +1,256 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsIndependentMetadataAndArtworkEnrichment : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 13) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 14) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 10); + + migrationBuilder.AddColumn( + name: "ArtworkProvidersConfigurationFingerprint", + table: "Libraries", + type: "TEXT", + maxLength: 64, + nullable: true) + .Annotation("Relational:ColumnOrder", 10); + + migrationBuilder.AddColumn( + name: "MetadataProvidersConfigurationFingerprint", + table: "Libraries", + type: "TEXT", + maxLength: 64, + nullable: true) + .Annotation("Relational:ColumnOrder", 9); + + migrationBuilder.CreateTable( + name: "BookArtwork", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + BookId = table.Column(type: "TEXT", nullable: false), + ArtworkType = table.Column(type: "TEXT", maxLength: 50, nullable: false), + Ordinal = table.Column(type: "INTEGER", nullable: false), + FileName = table.Column(type: "TEXT", maxLength: 2048, nullable: true), + ContentHash = table.Column(type: "INTEGER", nullable: false), + Status = table.Column(type: "TEXT", maxLength: 20, nullable: false), + Provider = table.Column(type: "TEXT", maxLength: 100, nullable: true), + LastUpdateUtc = table.Column(type: "TEXT", nullable: true), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_BookArtwork", x => x.Id); + table.ForeignKey( + name: "FK_BookArtwork_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + // backfill the artwork of the books that already had a cover, so that the stored covers are preserved as enriched cover artwork + // before the CoverImagePath column is dropped + migrationBuilder.Sql(""" + INSERT INTO BookArtwork (Id, BookId, ArtworkType, Ordinal, FileName, ContentHash, Status, Provider, LastUpdateUtc, CreatedOnUtc, CreatedBy, UpdatedOnUtc, UpdatedBy) + SELECT lower(hex(randomblob(16))), Id, 'Cover', 0, CoverImagePath, 0, 'Enriched', NULL, NULL, datetime('now'), '00000000-0000-0000-0000-000000000000', NULL, NULL + FROM Books + WHERE CoverImagePath IS NOT NULL; + """); + + migrationBuilder.DropColumn( + name: "CoverImagePath", + table: "Books"); + + migrationBuilder.CreateTable( + name: "BookContributors", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + BookId = table.Column(type: "TEXT", nullable: false), + MediaContributorId = table.Column(type: "TEXT", nullable: false), + RoleName = table.Column(type: "TEXT", maxLength: 100, nullable: false), + RoleCategory = table.Column(type: "TEXT", maxLength: 50, nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_BookContributors", x => x.Id); + table.ForeignKey( + name: "FK_BookContributors_Books_BookId", + column: x => x.BookId, + principalTable: "Books", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "MediaContributors", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + DisplayName = table.Column(type: "TEXT", maxLength: 255, nullable: false, collation: "NOCASE"), + LegalName = table.Column(type: "TEXT", maxLength: 255, nullable: true), + Biography = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + DateOfBirth = table.Column(type: "TEXT", nullable: true), + DateOfDeath = table.Column(type: "TEXT", nullable: true), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_MediaContributors", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_BookArtwork_BookId_ArtworkType_Ordinal", + table: "BookArtwork", + columns: new[] { "BookId", "ArtworkType", "Ordinal" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_BookArtwork_Status", + table: "BookArtwork", + column: "Status"); + + migrationBuilder.CreateIndex( + name: "IX_BookContributors_BookId_MediaContributorId", + table: "BookContributors", + columns: new[] { "BookId", "MediaContributorId" }); + + migrationBuilder.CreateIndex( + name: "IX_BookContributors_MediaContributorId", + table: "BookContributors", + column: "MediaContributorId"); + + migrationBuilder.CreateIndex( + name: "IX_MediaContributors_DisplayName", + table: "MediaContributors", + column: "DisplayName", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "BookArtwork"); + + migrationBuilder.DropTable( + name: "BookContributors"); + + migrationBuilder.DropTable( + name: "MediaContributors"); + + migrationBuilder.DropColumn( + name: "ArtworkProvidersConfigurationFingerprint", + table: "Libraries"); + + migrationBuilder.DropColumn( + name: "MetadataProvidersConfigurationFingerprint", + table: "Libraries"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 11) + .OldAnnotation("Relational:ColumnOrder", 13); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "Libraries", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 12) + .OldAnnotation("Relational:ColumnOrder", 14); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 11); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 12); + + migrationBuilder.AddColumn( + name: "CoverImagePath", + table: "Books", + type: "TEXT", + nullable: true); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index fbd03351..6d6090c1 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -239,6 +239,112 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Tags", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("RoleCategory") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId"); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => { b.Property("LibraryId") @@ -270,6 +376,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(0); + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + b.Property("CanDownloadMetadataFromWeb") .ValueGeneratedOnAdd() .HasColumnType("INTEGER") @@ -283,11 +394,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(10); + .HasColumnOrder(12); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(9); + .HasColumnOrder(11); b.Property("IsEnabled") .ValueGeneratedOnAdd() @@ -304,6 +415,11 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(2); + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + b.Property("ShouldSaveMetadataInMediaDirectories") .HasColumnType("INTEGER") .HasColumnOrder(7); @@ -320,11 +436,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(12); + .HasColumnOrder(14); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(11); + .HasColumnOrder(13); b.Property("UserId") .HasColumnType("TEXT"); @@ -515,6 +631,76 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("LibraryScanStagingResults", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => { b.Property("Id") @@ -535,9 +721,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(28); - b.Property("CoverImagePath") - .HasColumnType("TEXT"); - b.Property("CreatedBy") .HasColumnType("TEXT") .HasColumnOrder(33); @@ -1139,6 +1322,15 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("User"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookContributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) @@ -1236,6 +1428,15 @@ namespace Lumina.DataAccess.Common.Migrations .IsRequired(); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("BookArtwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => { b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => @@ -1339,6 +1540,13 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("LibraryScanResults"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("BookArtwork"); + + b.Navigation("BookContributors"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => { b.Navigation("Libraries"); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index 1d369cef..054a10f7 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; +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; @@ -11,6 +12,8 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -84,6 +87,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.BookArtwork) .FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); } @@ -98,6 +102,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.BookArtwork) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -118,6 +123,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) + .Include(book => book.BookArtwork) .AsNoTracking(); // books should always be retrieved only per owning libraries @@ -180,6 +186,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.BookArtwork) .Where(book => book.LibraryId == libraryId) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -197,6 +204,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.BookArtwork) .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); } @@ -215,6 +223,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) + .Include(book => book.BookContributors) .Where(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) @@ -235,6 +244,148 @@ internal sealed class BookRepository : IBookRepository .CountAsync(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched, cancellationToken).ConfigureAwait(false); } + /// + /// Gets a page of the books of the media library identified by that need their artwork resolved, + /// meaning they lack at least one required piece of artwork with an enriched status, ordered by path, using keyset pagination. + /// + /// The Id of the media library whose books are retrieved. + /// The path of the last retrieved book, used for keyset pagination. Pass to get the first page. + /// The maximum number of books to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of books needing their artwork resolved, or an error. + public async Task>> GetBooksNeedingArtworkAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken) + { + return await _luminaDbContext.Books + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.BookArtwork) + .Where(book => book.LibraryId == libraryId + && !book.BookArtwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched) + && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) + .OrderBy(book => book.Path) + .Take(pageSize) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the number of books of the media library identified by that need their artwork resolved. + /// + /// The Id of the media library whose books are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of books needing their artwork resolved, or an error. + public async Task> GetBooksNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Books + .CountAsync(book => book.LibraryId == libraryId + && !book.BookArtwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken) + .ConfigureAwait(false); + } + + /// + /// Resets the enrichment state of the books stored at the provided in the media library identified by + /// , so that they are re-enriched, because their content changed since the last scan. + /// + /// The Id of the media library whose books are reset. + /// The file system paths of the books whose enrichment state is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken) + { + await _luminaDbContext.Books + .Where(book => book.LibraryId == libraryId && paths.Contains(book.Path)) + .ExecuteUpdateAsync(setters => setters.SetProperty(book => book.MetadataStatus, MetadataStatus.Pending), cancellationToken) + .ConfigureAwait(false); + + await _luminaDbContext.Set() + .Where(artwork => _luminaDbContext.Books.Any(book => book.Id == artwork.BookId && book.LibraryId == libraryId && paths.Contains(book.Path))) + .ExecuteUpdateAsync(setters => setters.SetProperty(artwork => artwork.Status, ArtworkStatus.Pending), cancellationToken) + .ConfigureAwait(false); + + return Result.Updated; + } + + /// + /// Resets the metadata enrichment status of all the books of the media library identified by , + /// so that they are re-enriched, because the metadata provider configuration of the library changed. + /// + /// The Id of the media library whose books are reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + await _luminaDbContext.Books + .Where(book => book.LibraryId == libraryId) + .ExecuteUpdateAsync(setters => setters.SetProperty(book => book.MetadataStatus, MetadataStatus.Pending), cancellationToken) + .ConfigureAwait(false); + + return Result.Updated; + } + + /// + /// Resets the artwork status of all the artwork of the books of the media library identified by , + /// so that they are re-resolved, because the artwork provider configuration of the library changed. + /// + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetArtworkStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + await _luminaDbContext.Set() + .Where(artwork => _luminaDbContext.Books.Any(book => book.Id == artwork.BookId && book.LibraryId == libraryId)) + .ExecuteUpdateAsync(setters => setters.SetProperty(artwork => artwork.Status, ArtworkStatus.Pending), cancellationToken) + .ConfigureAwait(false); + + return Result.Updated; + } + + /// + /// Gets the display names of the author of the books identified by the provided , + /// keyed by the Id of the book, or when a book has no author. + /// + /// The unique identifiers of the books whose authors are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the display names of the authors of the books, keyed by book Id, or an error. + public async Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken) + { + List authorRows = await _luminaDbContext.BookContributors + .Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.RoleCategory == MediaContributorRoleCategory.Author) + .Join(_luminaDbContext.MediaContributors, + bookContributor => bookContributor.MediaContributorId, + contributor => contributor.Id, + (bookContributor, contributor) => new AuthorRow(bookContributor.BookId, contributor.DisplayName)) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + return authorRows + .GroupBy(row => row.BookId) + .ToDictionary(group => group.Key, group => (string?)group.Min(row => row.DisplayName)); + } + + /// + /// The author row of a book, joining the participation of an author contributor in a book with the display name of the contributor. + /// + /// The Id of the book. + /// The display name of the author contributor. + private sealed record AuthorRow(Guid BookId, string DisplayName); + + /// + /// Deletes the book identified by . + /// + /// The Id of the book to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteAsync(Guid bookId, CancellationToken cancellationToken) + { + BookEntity? book = await _luminaDbContext.Books + .FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == bookId, cancellationToken).ConfigureAwait(false); + if (book is null) + return Errors.WrittenContent.BookNotFound; + + _luminaDbContext.Books.Remove(book); + return Result.Deleted; + } + /// /// Updates a book. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs index 661f9452..2c5c87fb 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs @@ -145,6 +145,30 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR return page.ToList(); } + /// + /// Gets the paths of the media library scan staging results of the current scan that changed, meaning their content needs to be re-hashed + /// and the books stored at those paths need to be re-enriched, excluding the staging results that are new. + /// + /// The unique identifier of the media library scan whose staging results are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the paths of the changed staging results, or an error. + public async Task>> GetChangedPathsAsync(Guid scanId, CancellationToken cancellationToken) + { + await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false); + const string GET_CHANGED_PATHS_SQL = """ + SELECT Path + FROM LibraryScanStagingResults + WHERE LibraryScanId = @scanId + AND NeedsRehash = 1 + AND IsNew = 0; + """; + + CommandDefinition command = new(GET_CHANGED_PATHS_SQL, new { scanId }, cancellationToken: cancellationToken); + + IEnumerable paths = await connection.QueryAsync(command).ConfigureAwait(false); + return paths.ToList(); + } + /// /// Updates the content hashes of the provided media library scan staging results. /// diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs new file mode 100644 index 00000000..ca219011 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MediaContributors/MediaContributorRepository.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.MediaContributors; + +/// +/// Repository for media contributors. +/// +internal sealed class MediaContributorRepository : IMediaContributorRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public MediaContributorRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new media contributor. + /// + /// The media contributor to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(MediaContributorEntity contributor, CancellationToken cancellationToken) + { + _luminaDbContext.MediaContributors.Add(contributor); + return Result.Created; + } + + /// + /// Gets the media contributor whose display name matches the provided , or creates and inserts a new one + /// when no contributor with that name exists yet, guaranteeing a single contributor per person. + /// + /// The name by which the contributor is popularly known. + /// The optional legal name of the contributor. + /// Cancellation token that can be used to stop the execution. + /// An containing either the existing or newly created , or an error. + public async Task> FindOrCreateByDisplayNameAsync(string displayName, string? legalName, CancellationToken cancellationToken) + { + // the comparison is case-insensitive, so that "Stephen King" and "stephen king" are never treated as distinct contributors + string normalizedDisplayName = displayName.ToLowerInvariant(); + + MediaContributorEntity? existingContributor = await _luminaDbContext.MediaContributors + .FirstOrDefaultAsync(contributor => contributor.DisplayName.ToLower() == normalizedDisplayName, cancellationToken) + .ConfigureAwait(false); + if (existingContributor is not null) + return existingContributor; + + MediaContributorEntity contributor = new() + { + Id = Guid.NewGuid(), + DisplayName = displayName, + LegalName = legalName, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + _luminaDbContext.MediaContributors.Add(contributor); + return contributor; + } + + /// + /// Gets the media contributors identified by the provided . + /// + /// The unique identifiers of the media contributors to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either the retrieved s, or an error. + public async Task>> GetByIdsAsync(IReadOnlyCollection ids, CancellationToken cancellationToken) + { + return await _luminaDbContext.MediaContributors + .Where(contributor => ids.Contains(contributor.Id)) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 09a1d62a..066b02a5 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +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.Entities.Plugins; @@ -35,6 +36,8 @@ public class LuminaDbContext : DbContext public virtual DbSet LibraryMetadataProviderConfigurations { get; set; } = null!; public virtual DbSet LibraryArtworkProviderConfigurations { get; set; } = null!; public virtual DbSet Themes { get; set; } = null!; + public virtual DbSet MediaContributors { get; set; } = null!; + public virtual DbSet BookContributors { get; set; } = null!; /// /// Initializes a new instance of the class. diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 96cc1296..48274881 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Authorization; 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.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Themes; @@ -9,6 +10,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.DataAccess.Core.Repositories.Authorization; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.Repositories.Themes; using Lumina.DataAccess.Core.Repositories.Users; @@ -33,6 +35,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable private IRoleRepository? _roleRepository; private IUserRoleRepository? _userRoleRepository; private IBookRepository? _bookRepository; + private IMediaContributorRepository? _mediaContributorRepository; private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository; private ILibraryRepository? _libraryRepository; private ILibraryScanRepository? _libraryScanRepository; @@ -105,6 +108,15 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + public IMediaContributorRepository MediaContributorRepository + { + get + { + _mediaContributorRepository ??= new MediaContributorRepository(_luminaDbContext); + return _mediaContributorRepository; + } + } + /// /// Gets the directory scan fingerprint repository. /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs new file mode 100644 index 00000000..4337752e --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/ArtworkStatus.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; + +/// +/// Enumeration for the status of the artwork enrichment of a book artwork. +/// +public enum ArtworkStatus +{ + /// + /// The artwork of the book has not been resolved yet. + /// + Pending, + + /// + /// The artwork of the book has been successfully resolved. + /// + Enriched, + + /// + /// The artwork resolution of the book failed. + /// + Failed +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs new file mode 100644 index 00000000..1005ee9b --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; + +/// +/// 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. +/// +[DebuggerDisplay("{ToString()}")] +public enum MediaContributorRoleCategory +{ + /// + /// The role does not fall into any of the known categories. + /// + Other, + + /// + /// The contributor created the media item, like a book, a movie, or a piece of music. + /// + Author, + + /// + /// The contributor translated the media item into another language. + /// + Translator, + + /// + /// The contributor created the illustrations of the media item. + /// + Illustrator, + + /// + /// The contributor published the media item. + /// + Publisher, + + /// + /// The contributor narrated the media item. + /// + Narrator +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs new file mode 100644 index 00000000..eef84f22 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaLibrary/ArtworkType.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the type of artwork of a media library item. +/// Each media library item can have multiple artwork of different types, and multiple instances of the same +/// type (like the booklet pages of an audio album), tracked independently so that a change of one artwork +/// does not require the others to be re-fetched. +/// +[DebuggerDisplay("{ToString()}")] +public enum ArtworkType +{ + /// + /// The main artwork of the media library item, like the cover of a book. + /// + Cover +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index 4d443366..ee185d0c 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -19,7 +19,6 @@ public static partial class Errors public static Error RoleNameCannotBeEmpty => Error.Validation(description: nameof(RoleNameCannotBeEmpty)); public static Error RoleNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(RoleNameMustBeMaximum50CharactersLong)); public static Error RoleCategoryCannotBeEmpty => Error.Validation(description: nameof(RoleCategoryCannotBeEmpty)); - public static Error RoleCategoryMustBeMaximum50CharactersLong => Error.Validation(description: nameof(RoleCategoryMustBeMaximum50CharactersLong)); public static Error ContributorRoleCannotBeNull => Error.Validation(description: nameof(ContributorRoleCannotBeNull)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaContributors.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributors.cs new file mode 100644 index 00000000..c6bccb77 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributors.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Media contributor error types. +/// +public static partial class Errors +{ + public static class MediaContributors + { + public static Error MediaContributorNameCannotBeEmpty => Error.Validation(description: nameof(MediaContributorNameCannotBeEmpty)); + public static Error MediaContributorRoleNameCannotBeEmpty => Error.Validation(description: nameof(MediaContributorRoleNameCannotBeEmpty)); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanArtworkEnrichmentJob.cs new file mode 100644 index 00000000..6e0b7478 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanArtworkEnrichmentJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for resolving the artwork of the media library items, using the artwork providers configured for the media library. +/// +public interface IMediaLibraryScanArtworkEnrichmentJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanProviderConfigurationInvalidationJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanProviderConfigurationInvalidationJob.cs new file mode 100644 index 00000000..f28e1567 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanProviderConfigurationInvalidationJob.cs @@ -0,0 +1,9 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for invalidating the enrichment state of the media library items +/// whose metadata or artwork providers changed since the last scan. +/// +public interface IMediaLibraryScanProviderConfigurationInvalidationJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs index 4794bb2a..a2f59b1e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributor.cs @@ -6,11 +6,13 @@ using System; using System.Diagnostics; #endregion - namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; /// -/// Aggregate Root for a media contributor. +/// Aggregate root for a media contributor, the person that contributed to a media item. +/// A media contributor is a person, unique by name, agnostic of the kind of media it contributed to, and of +/// the roles it played in the media items. The roles a contributor plays are tracked per media item, so that a +/// single contributor that is both an actor and a writer is never duplicated. /// [DebuggerDisplay("{Id}: {Name}")] public class MediaContributor : AggregateRoot @@ -20,11 +22,6 @@ public class MediaContributor : AggregateRoot /// public MediaContributorName Name { get; private set; } - /// - /// Gets the role of the contributor. - /// - public MediaContributorRole Role { get; private set; } - /// /// Gets the biography of the contributor. /// @@ -45,19 +42,19 @@ public class MediaContributor : AggregateRoot /// /// The unique identifier of the contributor. /// The name of the contributor. - /// The role of the contributor. + /// The optional biography of the contributor. /// The optional date of birth of the contributor. - /// The optional date of death of the contributor. + /// The optional date of death of the contributor. private MediaContributor( MediaContributorId id, MediaContributorName name, - MediaContributorRole role, + Optional biography, Optional dateOfBirth, Optional dateOfDeath) : base(id) { Id = id; Name = name; - Role = role; + Biography = biography; DateOfBirth = dateOfBirth; DateOfDeath = dateOfDeath; } @@ -69,9 +66,12 @@ public class MediaContributor : AggregateRoot /// The created instance. public static Result Create(MediaContributorName name) { - // TODO: enforce invariants - throw new NotImplementedException(); - //return new MediaContributor(id, name); + return new MediaContributor( + MediaContributorId.CreateUnique(), + name, + Optional.None(), + Optional.None(), + Optional.None()); } /// @@ -79,14 +79,17 @@ public class MediaContributor : AggregateRoot /// /// The unique identifier of the contributor. /// The name of the contributor. + /// The optional biography of the contributor. + /// The optional date of birth of the contributor. + /// The optional date of death of the contributor. /// The created instance. public static Result Create( MediaContributorId id, MediaContributorName name, - MediaContributorRole role, + Optional biography, Optional dateOfBirth, Optional dateOfDeath) { - return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath); + return new MediaContributor(id, name, biography, dateOfBirth, dateOfDeath); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs index 8527c602..1dbd3a5e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/ContributorName.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using System.Collections.Generic; @@ -42,7 +43,9 @@ public sealed class MediaContributorName : ValueObject /// The created instance. public static Result Create(string displayName, Optional legalName) { - // TODO: enforce invariants + if (string.IsNullOrWhiteSpace(displayName)) + return Errors.MediaContributors.MediaContributorNameCannotBeEmpty; + return new MediaContributorName(displayName, legalName); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs index 2acbe69a..80ba5336 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs @@ -1,5 +1,8 @@ #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 @@ -7,42 +10,47 @@ using System.Diagnostics; namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; /// -/// Value Object for the role of a media contributor. +/// 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. /// [DebuggerDisplay("{DisplayName}")] public sealed class MediaContributorRole : ValueObject { /// - /// Gets the value representing this object. + /// Gets the display name of the role. /// - public string Name { get; } + public string DisplayName { get; } /// - /// Gets the category of this object. + /// Gets the canonical category of the role. /// - public string Category { get; } + public MediaContributorRoleCategory Category { get; } /// /// Initializes a new instance of the class. /// - /// The value representing this object. - /// The category of this object. - private MediaContributorRole(string name, string category) + /// The display name of the role. + /// The canonical category of the role. + private MediaContributorRole(string displayName, MediaContributorRoleCategory category) { - Name = name; + DisplayName = displayName; Category = category; } /// - /// Creates a new instance of the class, from a pre-existing . + /// Creates a new instance of the class, from a display and its canonical . /// - /// The value representing this object. - /// The category of this object. + /// The display name of the role. + /// The canonical category of the role. /// The created instance. - public static MediaContributorRole Create(string name, string category) + public static Result Create(string displayName, MediaContributorRoleCategory category) { - // TODO: enforce invariants - return new MediaContributorRole(name, category); + if (string.IsNullOrWhiteSpace(displayName)) + return Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty; + + return new MediaContributorRole(displayName, category); } /// @@ -51,7 +59,7 @@ public sealed class MediaContributorRole : ValueObject /// A list of items defining the equality. public override IEnumerable GetEqualityComponents() { - yield return Name; + yield return DisplayName; yield return Category; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index 5fc666a9..914b0c97 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -38,21 +38,6 @@ public sealed class Book : AggregateRoot /// public string Path { get; private set; } - /// - /// Gets the status of the metadata enrichment of the book. - /// - public MetadataStatus MetadataStatus { get; private set; } - - /// - /// Gets the date and time when the metadata of the book was last enriched, if applicable. - /// - public Optional LastMetadataUpdateUtc { get; private set; } - - /// - /// Gets the name of the plugin that enriched the metadata of the book, if applicable. - /// - public Optional MetadataProvider { get; private set; } - /// /// Gets the format of the book (e.g., Hardcover, Paperback), if applicable. /// @@ -118,11 +103,6 @@ public sealed class Book : AggregateRoot /// public Optional AppleBooksId { get; private set; } - /// - /// Gets the file system path of the cover image of the book, if applicable. - /// - public Optional CoverImagePath { get; private set; } - /// /// Gets the list of ISBN (International Standard Book Number) of the book. /// @@ -191,9 +171,6 @@ public sealed class Book : AggregateRoot LibraryId = libraryId; Path = path; Metadata = metadata; - MetadataStatus = MetadataStatus.Pending; - LastMetadataUpdateUtc = Optional.None(); - MetadataProvider = Optional.None(); Format = format; Edition = edition; VolumeNumber = volumeNumber; @@ -207,7 +184,6 @@ public sealed class Book : AggregateRoot GoogleBooksId = googleBooksId; BarnesAndNobleId = barnesAndNobleId; AppleBooksId = appleBooksId; - CoverImagePath = Optional.None(); CreatedOnUtc = createdOnUtc; UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null; _isbns = isbns; @@ -368,36 +344,18 @@ public sealed class Book : AggregateRoot } /// - /// Marks the metadata of the book as enriched by the provided . + /// Replaces the media contributors of the book with the provided , identified by their unique identifiers. /// - /// The name of the metadata provider that enriched the book. - /// The date and time when the metadata of the book was enriched. - public void MarkMetadataAsEnriched(string providerName, DateTime lastUpdateUtc) + /// The unique identifiers of the media contributors of the book. + public void UpdateContributors(IReadOnlyCollection contributors) { - MetadataProvider = providerName; - LastMetadataUpdateUtc = lastUpdateUtc; - MetadataStatus = MetadataStatus.Enriched; + // replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate + _contributors.Clear(); + _contributors.AddRange(contributors); } /// - /// Marks the metadata enrichment of the book as failed. - /// - public void MarkMetadataAsFailed() - { - MetadataStatus = MetadataStatus.Failed; - } - - /// - /// Sets the file system path of the cover image of the book. - /// - /// The file system path of the cover image of the book. - public void SetBookCoverImagePath(string coverImagePath) - { - CoverImagePath = coverImagePath; - } - - /// - /// Applies the enriched and the related fields to the book, marking its metadata as enriched by the provided . + /// Applies the enriched and the related fields to the book. /// /// The enriched metadata of the book. /// The optional format of the book. @@ -415,8 +373,6 @@ public sealed class Book : AggregateRoot /// The optional Apple Books ID of the book. /// The list of ISBNs of the book. /// The list of ratings for the book. - /// The name of the metadata provider that enriched the book. - /// The date and time when the metadata was enriched. public void ApplyEnrichedMetadata( WrittenContentMetadata metadata, Optional format, @@ -433,9 +389,7 @@ public sealed class Book : AggregateRoot Optional barnesAndNobleId, Optional appleBooksId, List isbns, - List ratings, - string providerName, - DateTime lastUpdateUtc) + List ratings) { Metadata = metadata; Format = format; @@ -456,6 +410,5 @@ public sealed class Book : AggregateRoot _isbns.AddRange(isbns); _ratings.Clear(); _ratings.AddRange(ratings); - MarkMetadataAsEnriched(providerName, lastUpdateUtc); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index 1b0e72f1..82d379a6 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -52,12 +52,23 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob); mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob); - // the metadata enrichment job is always the last job in the directed acyclic job graph, running after the scan results save job, - // so that the books are materialized before their metadata is enriched. The job itself is the host-side gate that skips the providers - // requiring access to the web when the media library does not permit downloading data from the web, so that the local providers still run offline + // the enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration + // invalidation job invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, the + // metadata enrichment job enriches the metadata and links the media contributors, and the artwork enrichment job resolves the artwork. + // The artwork enrichment job is always the last job in the directed acyclic job graph, running after the metadata enrichment job, so that + // the artwork is resolved after the metadata, and thus after the contributors that provide the author names used to build the artwork directories. + IMediaLibraryScanProviderConfigurationInvalidationJob mediaLibraryScanProviderConfigurationInvalidationJob = _mediaScanJobFactory.CreateJob(libraryId); IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); - mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); - mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob); + IMediaLibraryScanArtworkEnrichmentJob mediaLibraryScanArtworkEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); + + mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanProviderConfigurationInvalidationJob); + mediaLibraryScanProviderConfigurationInvalidationJob.AddParent(mediaLibraryScanResultsSaveJob); + + mediaLibraryScanProviderConfigurationInvalidationJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); + mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanProviderConfigurationInvalidationJob); + + mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob); + mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob); // return the top level jobs that will be triggered when the scan will be started yield return fileSystemDiscoveryJob; diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 7f8bd90f..809b7ce3 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -99,7 +99,9 @@ public static class InfrastructureLayerServices services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs new file mode 100644 index 00000000..c82c66a9 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs @@ -0,0 +1,412 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Media library scan job for resolving the artwork of the media library items, using the artwork providers configured for the media library. +/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched. +/// +internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob +{ + private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + /// + /// Injected logger used to report the issues encountered while resolving the artwork. + public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsCompleted == Parents.Count) + { + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // load the media library, whose name is used to build the directory of the book artwork, and whose setting determines + // whether the providers that require access to the web are used during the enrichment + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // get the artwork providers configured for the media library, in their configured order, that support the media library type. + // the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + artworkProviders.AddRange(configuredProviders); + } + } + } + + // when no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely + if (artworkProviders.Count > 0) + { + IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); + int totalBooksToEnrich = getBooksToEnrichCountResult.Value; + + // set the initial progress of the scan job + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size + string? lastPath = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) + throw new InvalidOperationException(getBooksPageResult.FirstError.Description); + IReadOnlyList booksPage = getBooksPageResult.Value; + if (booksPage.Count == 0) + break; + + // load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory + Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + throw new InvalidOperationException(getAuthorsResult.FirstError.Description); + + foreach (BookEntity bookEntity in booksPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); + + // check if enough time has passed since last update + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + unitOfWork.ClearTrackedEntities(); + + lastPath = booksPage[^1].Path; + } + } + else + { + _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value); + } + + Status = LibraryScanJobStatus.Completed; + // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Resolves the cover artwork of the provided from the , in their configured order, + /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book. + /// + /// The book whose artwork is resolved. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the book belongs to. + /// The display names of the authors of the books of the current page, keyed by the Id of the book. + /// Cancellation token that can be used to stop the execution. + private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken) + { + // when no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped + if (bookArtworkService is null || artworkProviders.Count == 0) + return; + + ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false); + if (resolvedArtwork is null) + { + // no artwork provider returned usable artwork, mark the cover artwork of the book as failed to resolve + BookArtworkEntity? coverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + if (coverArtwork is null) + { + bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); + } + else + { + coverArtwork.Status = ArtworkStatus.Failed; + coverArtwork.UpdatedOnUtc = DateTime.UtcNow; + coverArtwork.UpdatedBy = Guid.NewGuid(); + } + return; + } + + BookArtworkEntity? existingCoverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + + // when the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one + // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it. + ulong contentHash = 0; + bool shouldStoreArtwork = true; + if (!string.IsNullOrWhiteSpace(resolvedArtwork.Artwork.LocalPath)) + { + contentHash = fileHashService.ComputeFileHash(resolvedArtwork.Artwork.LocalPath); + shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash; + } + + if (shouldStoreArtwork) + { + string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; + Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false); + if (saveArtworkResult.IsFailure) + { + // a failing artwork storage must not prevent the book from being tracked as failed to resolve + if (existingCoverArtwork is null) + { + bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); + } + else + { + existingCoverArtwork.Status = ArtworkStatus.Failed; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + return; + } + + // for remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one + if (contentHash == 0) + { + string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\')); + contentHash = fileHashService.ComputeFileHash(storedArtworkPath); + } + + if (existingCoverArtwork is null) + { + bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); + } + else + { + existingCoverArtwork.FileName = saveArtworkResult.Value; + existingCoverArtwork.ContentHash = contentHash; + existingCoverArtwork.Status = ArtworkStatus.Enriched; + existingCoverArtwork.Provider = resolvedArtwork.ProviderName; + existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + } + else + { + // the resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched + existingCoverArtwork!.Status = ArtworkStatus.Enriched; + existingCoverArtwork.Provider = resolvedArtwork.ProviderName; + existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + } + + /// + /// Resolves the artwork of the from the , in their configured order, + /// returning the artwork of the first provider that returns it. + /// + /// The book whose artwork is resolved. + /// The artwork providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork. + private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken) + { + BookMetadataLookupDto artworkLookup = new( + LibraryId: bookEntity.LibraryId, + Path: bookEntity.Path, + Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, + OpenLibraryId: bookEntity.OpenLibraryId, + Title: bookEntity.Title, + Author: null, + LanguageCode: bookEntity.LanguageCode + ); + + foreach (IArtworkProvider provider in artworkProviders) + { + ArtworkDto? artwork = null; + try + { + artwork = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + // a failing artwork provider must not prevent the other providers from being tried + } + + if (artwork is null) + continue; + + // a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract + if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) + continue; + + return new ResolvedArtwork(artwork, provider.Name); + } + return null; + } + + /// + /// Creates a cover artwork entity for the book identified by . + /// + /// The Id of the book the artwork belongs to. + /// The status of the artwork enrichment. + /// The relative file name of the stored artwork, if the artwork has been resolved. + /// The content hash of the stored artwork. + /// The name of the plugin that resolved the artwork, if applicable. + /// The date and time when the artwork was resolved, if applicable. + /// The created cover artwork entity. + private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc) + { + return new BookArtworkEntity + { + Id = Guid.NewGuid(), + BookId = bookId, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = fileName, + ContentHash = contentHash, + Status = status, + Provider = provider, + LastUpdateUtc = lastUpdateUtc, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The artwork resolved for a book, along with the provider that supplied it. + /// + /// The resolved artwork of the book. + /// The name of the provider that supplied the artwork. + private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index 7548e7a7..a861002a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -1,13 +1,15 @@ #region ========================================================================= USING ===================================================================================== +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.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; @@ -15,6 +17,8 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; @@ -30,7 +34,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// /// Media library scan job for enriching the metadata of the media library items, using the metadata providers configured for the media library. -/// This should always be the last job in the directed acyclic job graph. +/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them. /// internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob { @@ -77,23 +81,18 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // load the media library, whose name is used to build the directory of the book artwork, and whose setting determines - // whether the providers that require access to the web are used during the enrichment - string libraryName = string.Empty; + // load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment bool canDownloadMetadataFromWeb = false; if (unitOfWork.LibraryRepository is not null) { Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); + _logger.LogWarning("Failed to read the media library, the providers requiring the web will not be used."); else - { - libraryName = getLibraryResult.Value.Title; canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; - } } // get the metadata providers configured for the media library, in their configured order, that support the media library type, @@ -124,34 +123,6 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; } - // get the artwork providers configured for the media library, in their configured order, that support the media library type. - // the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the metadata enrichment from proceeding - List artworkProviders = []; - if (unitOfWork.ArtworkProviderConfigurationRepository is not null) - { - Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getArtworkConfigurationsResult.IsFailure) - _logger.LogWarning("Failed to read the artwork provider configurations."); - else - { - foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) - { - List configuredProviders = [.. asyncServiceScope.ServiceProvider - .GetKeyedServices(configuration.PluginId) - .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) - && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; - if (configuredProviders.Count == 0) - _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); - artworkProviders.AddRange(configuredProviders); - } - } - } - - IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); - - // count the books that need their metadata enriched, for progress reporting purposes - string? lastPath = null; - // when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely if (providers.Count > 0) { @@ -169,7 +140,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo int minUpdateIntervalMs = 100; int processedBooksCount = 0; + // the contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only + // created once even when the same person is discovered for many books of the same page + Dictionary contributorsByNormalizedName = []; + // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size + string? lastPath = null; while (true) { cancellationToken.ThrowIfCancellationRequested(); @@ -185,7 +161,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { cancellationToken.ThrowIfCancellationRequested(); - await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, artworkProviders, bookArtworkService, libraryName, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false); + await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); // check if enough time has passed since last update DateTime now = DateTime.UtcNow; @@ -202,6 +178,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); unitOfWork.ClearTrackedEntities(); + contributorsByNormalizedName.Clear(); lastPath = booksPage[^1].Path; } @@ -211,13 +188,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value); } - // persist the changes when no page was processed, so that the scan still saves even when there are no books to enrich - if (lastPath is null) - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - - // this job finished, and it's the last in the chain, the scan is completed Status = LibraryScanJobStatus.Completed; - await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); // call each linked child with the obtained payload foreach (IMediaLibraryScanJob child in Children) @@ -238,22 +212,18 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } /// - /// Enriches the metadata and the artwork of the provided , using the provided metadata and artwork providers in their configured order. + /// Enriches the metadata of the provided , using the provided metadata providers in their configured order, + /// linking the media contributors discovered while enriching to the book. /// - /// The book whose metadata and artwork are enriched. + /// The book whose metadata is enriched. /// The metadata providers, in their configured order. /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not. - /// The artwork providers, in their configured order. - /// The service used to store the artwork of the book. - /// The name of the media library the book belongs to. /// The repository used to persist the enriched book. + /// The repository used to persist the media contributors discovered while enriching. + /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. /// Cancellation token that can be used to stop the execution. - private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken) + private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken) { - // when no metadata provider is available, the book must not be marked as failed to enrich, so the enrichment is skipped - if (metadataProviders.Count == 0) - return; - // convert the book to a domain object Result getBookResult = bookEntity.ToDomainEntity(); if (getBookResult.IsFailure) @@ -270,26 +240,79 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo LanguageCode: bookEntity.LanguageCode ); - BookMetadataDto? appliedMetadata = shouldAggregateMetadataWhenMissing + ResolvedMetadata? resolvedMetadata = shouldAggregateMetadataWhenMissing ? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false) : await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false); - if (appliedMetadata is null) + if (resolvedMetadata is null) { - // no metadata provider returned usable metadata, mark the book as failed to enrich - book.MarkMetadataAsFailed(); - Result markFailedResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (markFailedResult.IsFailure) - _logger.LogWarning("Failed to persist the failed enrichment state of the book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path); + // no metadata provider returned usable metadata, mark the book as failed to enrich, keeping its previous metadata + bookEntity.MetadataStatus = MetadataStatus.Failed; + bookEntity.UpdatedOnUtc = DateTime.UtcNow; + bookEntity.UpdatedBy = Guid.NewGuid(); return; } - // resolve the artwork of the book from the artwork providers, in their configured order - await EnrichBookArtworkAsync(book, appliedMetadata, artworkProviders, bookArtworkService, libraryName, cancellationToken).ConfigureAwait(false); + // apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns + book.ApplyMetadata(resolvedMetadata.Metadata); + bookEntity.ApplyMetadataToEntity(book); - Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateBookResult.IsFailure) - _logger.LogWarning("Failed to persist the enriched book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path); + // link the media contributors discovered while enriching to the book, finding or creating a single contributor per person + List linkedContributors = []; + foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? []) + { + if (contributor.Name?.DisplayName is null) + continue; + + MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false); + + string roleName = contributor.Role?.Name ?? "Contributor"; + MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other; + linkedContributors.Add(new BookContributorEntity + { + Id = Guid.NewGuid(), + BookId = bookEntity.Id, + MediaContributorId = contributorEntity.Id, + RoleName = roleName, + RoleCategory = roleCategory, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }); + } + bookEntity.BookContributors.Clear(); + bookEntity.BookContributors.AddRange(linkedContributors); + book.UpdateContributors([.. linkedContributors.Select(linkedContributor => Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects.MediaContributorId.Create(linkedContributor.MediaContributorId))]); + + // mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern + bookEntity.MetadataStatus = MetadataStatus.Enriched; + bookEntity.MetadataProvider = resolvedMetadata.ProviderName; + bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow; + } + + /// + /// Finds the media contributor with the name of the provided , or creates it, caching it by its normalized display name + /// so that a contributor is only created once even when the same person is discovered for many books of the same page. + /// + /// The repository used to persist the media contributors discovered while enriching. + /// The cache of the media contributors discovered in the current page, keyed by their normalized display name. + /// The contributor to find or create. + /// Cancellation token that can be used to stop the execution. + /// The found or created media contributor. + private async Task FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken) + { + string displayName = contributor.Name!.DisplayName!; + string normalizedDisplayName = displayName.ToLowerInvariant(); + + if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor)) + return cachedContributor; + + Result getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, null, cancellationToken).ConfigureAwait(false); + if (getContributorResult.IsFailure) + throw new InvalidOperationException(getContributorResult.FirstError.Description); + + contributorsByNormalizedName[normalizedDisplayName] = getContributorResult.Value; + return getContributorResult.Value; } /// @@ -299,8 +322,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// The lookup describing the book. /// The metadata providers, in their configured order. /// Cancellation token that can be used to stop the execution. - /// The applied metadata, or when no provider returned usable metadata. - private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + /// The applied metadata and the provider that supplied it, or when no provider returned usable metadata. + private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) { foreach (IMetadataProvider metadataProvider in metadataProviders) { @@ -310,10 +333,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) continue; - Result applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow); + Result applyMetadataResult = book.ApplyMetadata(bookMetadata); if (applyMetadataResult.IsFailure) continue; - return bookMetadata; + return new ResolvedMetadata(bookMetadata, metadataProvider.Name); } catch (Exception) { @@ -330,8 +353,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// The lookup describing the book. /// The metadata providers, in their configured order. /// Cancellation token that can be used to stop the execution. - /// The applied aggregated metadata, or when no provider returned usable metadata. - private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + /// The applied aggregated metadata and the providers that contributed to it, or when no provider returned usable metadata. + private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) { BookMetadataDto? mergedMetadata = null; List contributingProviders = []; @@ -358,52 +381,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo if (mergedMetadata is null) return null; - Result applyMetadataResult = book.ApplyMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)), DateTime.UtcNow); - return applyMetadataResult.IsFailure ? null : mergedMetadata; - } - - /// - /// Resolves the artwork of the from the , in their configured order, storing the artwork of the first provider that returns it. - /// - /// The book whose artwork is enriched. - /// The metadata applied to the book, used to build the directory of the book artwork. - /// The artwork providers, in their configured order. - /// The service used to store the artwork of the book. - /// The name of the media library the book belongs to. - /// Cancellation token that can be used to stop the execution. - private static async Task EnrichBookArtworkAsync(Book book, BookMetadataDto appliedMetadata, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, CancellationToken cancellationToken) - { - if (bookArtworkService is null || artworkProviders.Count == 0) - return; - - foreach (IArtworkProvider provider in artworkProviders) - { - ArtworkDto? artwork = null; - try - { - artwork = await provider.GetArtworkAsync(new BookMetadataLookupDto(LibraryId: book.LibraryId.Value, Path: book.Path), cancellationToken).ConfigureAwait(false); - } - catch (Exception) - { - // a failing artwork provider must not prevent the other providers from being tried - } - - if (artwork is null) - continue; - - // a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract - if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) - continue; - - string authorName = appliedMetadata.Contributors?.FirstOrDefault(contributor => contributor.Name?.DisplayName is not null)?.Name?.DisplayName ?? string.Empty; - string bookTitle = appliedMetadata.Title ?? book.Metadata.Title; - Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(book.LibraryId.Value, book.Id.Value, libraryName, authorName, bookTitle, artwork, cancellationToken).ConfigureAwait(false); - if (saveArtworkResult.IsFailure) - continue; - - book.SetBookCoverImagePath(saveArtworkResult.Value); - return; - } + Result applyMetadataResult = book.ApplyMetadata(mergedMetadata); + return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal))); } /// @@ -455,4 +434,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo return Result.Success; } + + /// + /// The metadata resolved for a book, along with the providers that supplied it. + /// + /// The resolved metadata of the book. + /// The name of the provider, or the providers, that supplied the metadata. + private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs new file mode 100644 index 00000000..487e3e38 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Media library scan job for invalidating the enrichment state of the books whose metadata or artwork provider configuration +/// changed since the last scan, so that they are re-enriched by the enrichment jobs that follow. +/// +internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : MediaLibraryScanJob, IMediaLibraryScanProviderConfigurationInvalidationJob +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Injected factory for creating scopes in which services are requested. + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. + /// + /// Injected logger used to report the issues encountered while invalidating the enrichment state. + public MediaLibraryScanProviderConfigurationInvalidationJob(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + try + { + // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted); + // only execute this job's payload when it has no parents, or when all the parents finished their execution + if (Parents.Count == 0 || parentsCompleted == Parents.Count) + { + // this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous + // processing that takes time, and would block the processing of scan jobs in the in-memory queue + await Task.Run(async () => + { + Status = LibraryScanJobStatus.Running; + // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details: + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // set the initial progress of the scan job, it's a 1 step job - invalidating the stale enrichment state + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + // load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints + // are compared against the current provider configuration to detect whether it changed since the last scan + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryEntity library = getLibraryResult.Value; + + // load the provider configurations of the media library, whose fingerprint is compared against the stored one + Result> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getMetadataConfigurationsResult.IsFailure) + throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description); + + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description); + + // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing + bool shouldAggregateMetadataWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the metadata provider configuration fingerprint will not include the metadata aggregation setting."); + else + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + } + + // compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration + // changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration + // was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored. + string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb); + string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, library.CanDownloadMetadataFromWeb); + + if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint) + { + Result resetMetadataResult = await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (resetMetadataResult.IsFailure) + throw new InvalidOperationException(resetMetadataResult.FirstError.Description); + } + + if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint) + { + Result resetArtworkResult = await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (resetArtworkResult.IsFailure) + throw new InvalidOperationException(resetArtworkResult.FirstError.Description); + } + + // store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. + // the library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository + // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed + library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; + library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; + library.UpdatedOnUtc = DateTime.UtcNow; + library.UpdatedBy = Guid.NewGuid(); + + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + Status = LibraryScanJobStatus.Completed; + // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is completed + if (Children.Count == 0) + await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + // call each linked child with the obtained payload + foreach (IMediaLibraryScanJob child in Children) + await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Canceled; + throw; + } + catch (Exception exception) + { + Status = LibraryScanJobStatus.Failed; + await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "InvalidatingStaleEnrichment"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index bdf3646e..a00ae9ba 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -80,11 +80,24 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (getDeletedPathsResult.IsFailure) throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description); + // get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched + Result> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false); + if (getChangedPathsResult.IsFailure) + throw new InvalidOperationException(getChangedPathsResult.FirstError.Description); + // apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan Result applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); if (applySnapshotSwapResult.IsFailure) throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description); + // reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow + if (getChangedPathsResult.Value.Count > 0) + { + Result resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false); + if (resetEnrichmentStateResult.IsFailure) + throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description); + } + // raise a deletion event for every media library scan snapshot item that is no longer present on disk foreach (string deletedPath in getDeletedPathsResult.Value) { diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs new file mode 100644 index 00000000..3c3c9208 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO.Hashing; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Computes the fingerprint of the provider configuration of a media library, used to detect whether the configuration +/// changed since the last scan, and thus whether the books of the library need their metadata or artwork re-enriched. +/// Any change to the configuration, like adding, removing, reordering, enabling, or disabling a provider, changes the fingerprint. +/// +internal static class ProviderConfigurationFingerprint +{ + /// + /// Computes the fingerprint of the metadata provider configuration of a media library. + /// + /// The metadata provider configurations of the media library. + /// Whether the metadata of the books is aggregated from multiple providers, when fields are missing. + /// Whether the media library permits downloading data from the web. + /// The fingerprint of the metadata provider configuration. + public static string ComputeMetadataFingerprint(IReadOnlyList configurations, bool shouldAggregateMetadataWhenMissing, bool canDownloadMetadataFromWeb) + { + StringBuilder canonicalRepresentation = new(); + foreach (LibraryMetadataProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank)) + canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};"); + canonicalRepresentation.Append($"aggregate:{shouldAggregateMetadataWhenMissing};web:{canDownloadMetadataFromWeb};"); + + return ComputeFingerprint(canonicalRepresentation.ToString()); + } + + /// + /// Computes the fingerprint of the artwork provider configuration of a media library. + /// + /// The artwork provider configurations of the media library. + /// Whether the media library permits downloading data from the web. + /// The fingerprint of the artwork provider configuration. + public static string ComputeArtworkFingerprint(IReadOnlyList configurations, bool canDownloadMetadataFromWeb) + { + StringBuilder canonicalRepresentation = new(); + foreach (LibraryArtworkProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank)) + canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};"); + canonicalRepresentation.Append($"web:{canDownloadMetadataFromWeb};"); + + return ComputeFingerprint(canonicalRepresentation.ToString()); + } + + /// + /// Computes the fingerprint of the provided canonical representation, by hashing it. + /// + /// The canonical representation of the configuration. + /// The fingerprint of the canonical representation. + private static string ComputeFingerprint(string canonicalRepresentation) + { + byte[] bytes = Encoding.UTF8.GetBytes(canonicalRepresentation); + ulong hash = XxHash64.HashToUInt64(bytes); + return hash.ToString("X16", CultureInfo.InvariantCulture); + } +} diff --git a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs index d95eee68..6a4aba9f 100644 --- a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs +++ b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs @@ -69,6 +69,21 @@ internal class FileHashService : IFileHashService return outputFiles; } + /// + /// Computes the content hash of the file stored at , by sampling chunks from it. + /// + /// The path of the file to hash. + /// The content hash of the file. + public ulong ComputeFileHash(string filePath) + { + long fileSize = new FileInfo(filePath).Length; + if (fileSize == 0) + return s_emptyFileHash; // precomputed constant: XxHash64 hash of zero-length input + + ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, fileSize); + return ComputeFileHash(filePath, fileSize, bufferSize); + } + /// /// Computes content hash using memory-mapped sampling. /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs index 197d0cc7..a4269711 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -99,7 +100,7 @@ public class AddLibraryEndpointSummary : Summary حفظ بيانات الفحص... + + إبطال التخصيب القديم... + + + جاري حل العمل الفني... + الفحص diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx index fd3f500c..ea60c1a2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.de-DE.resx @@ -255,6 +255,12 @@ Scandaten werden gespeichert... + + Ungültigmachen veralteter Anreicherungen... + + + Artwork wird aufgelöst... + Scannen diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx index b5b3f263..b772f4af 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.en-US.resx @@ -255,6 +255,12 @@ Saving scan data... + + Invalidating stale enrichment... + + + Resolving artwork... + Scan diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx index 18ea70c2..b91da2a4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.es-ES.resx @@ -255,6 +255,12 @@ Guardando datos del escaneo... + + Invalidando el enriquecimiento obsoleto... + + + Resolviendo la carátula... + Escanear diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx index 3ca27a25..d8b63ab0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.fr-FR.resx @@ -255,6 +255,12 @@ Sauvegarde des données de scan en cours... + + Invalidation de l'enrichissement obsolète... + + + Résolution de l'illustration... + Scanner diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx index 9387d8eb..b8cdd83a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.it-IT.resx @@ -255,6 +255,12 @@ Salvataggio dei dati di scansione... + + Invalidazione dell'arricchimento obsoleto... + + + Risoluzione della copertina... + Scansiona diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx index a88d1ea1..d9b01cb4 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ja-JP.resx @@ -255,6 +255,12 @@ スキャンデータを保存中... + + 古い補完を無効化しています... + + + アートワークを取得しています... + スキャン diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx index b5b3f263..b772f4af 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.resx @@ -255,6 +255,12 @@ Saving scan data... + + Invalidating stale enrichment... + + + Resolving artwork... + Scan diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx index b1735455..dd574f10 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.ro-RO.resx @@ -255,6 +255,12 @@ Se salvează datele de scanare... + + Se invalidează îmbogățirea învechită... + + + Se rezolvă coperta... + Scanează diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx index cb4c6356..49cec819 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.uk-UA.resx @@ -255,6 +255,12 @@ Збереження даних сканування... + + Інвалідація застарілого збагачення... + + + Вирішення зображення... + Сканувати diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx index fa8f6f81..7fe4fc70 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Index.zh-CN.resx @@ -255,6 +255,12 @@ 正在保存扫描数据... + + 正在使过期的补全失效... + + + 正在获取封面图... + 扫描 diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index 57e6b5f7..d7fdaafa 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -174,8 +174,10 @@ DiscoveringFiles: '@_localizer["DiscoveringFiles"]', ComparingFileHashes: '@_localizer["ComparingFileHashes"]', HashingFileContents: '@_localizer["HashingFileContents"]', + SavingScanData: '@_localizer["SavingScanData"]', + InvalidatingStaleEnrichment: '@_localizer["InvalidatingStaleEnrichment"]', EnrichingMetadata: '@_localizer["EnrichingMetadata"]', - SavingScanData: '@_localizer["SavingScanData"]' + ResolvingArtwork: '@_localizer["ResolvingArtwork"]' }; const jsLocalizedLibraryTypes = { Book: '@_localizer["Book"]', diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/BookContributorEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/BookContributorEntityFixture.cs new file mode 100644 index 00000000..6645f6ed --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/BookContributorEntityFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookContributorEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the participation. + /// Optional. The Id of the book the contributor participated in. + /// Optional. The Id of the media contributor. + /// Optional. The display name of the role the contributor played in the book. + /// Optional. The canonical category of the role the contributor played in the book. + /// The created . + public BookContributorEntity Create( + Guid? id = null, + Guid? bookId = null, + Guid? mediaContributorId = null, + string? roleName = null, + MediaContributorRoleCategory? roleCategory = 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(), + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/MediaContributorEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/MediaContributorEntityFixture.cs new file mode 100644 index 00000000..d38b1a2d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/MediaContributorEntityFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.Setup; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media contributor. + /// Optional. The name by which the contributor is popularly known. + /// Optional. The legal name of the contributor. + /// Optional. The biography of the contributor. + /// Optional. The date of birth of the contributor. + /// Optional. The date of death of the contributor. + /// The created . + public MediaContributorEntity Create( + Guid? id = null, + string? displayName = null, + string? legalName = null, + string? biography = null, + DateOnly? dateOfBirth = null, + DateOnly? dateOfDeath = null) + { + return new MediaContributorEntity + { + Id = id ?? Guid.NewGuid(), + DisplayName = displayName ?? _faker.Person.FullName, + LegalName = legalName ?? _faker.Person.FullName, + Biography = biography ?? _faker.Lorem.Sentence(), + DateOfBirth = dateOfBirth ?? _faker.DateOnlyBetween(new DateOnly(1900, 1, 1), new DateOnly(2000, 12, 31)), + DateOfDeath = dateOfDeath, + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index deda345c..ecc55b88 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -30,6 +30,8 @@ public class LibraryEntityFixture /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. + /// Optional. The fingerprint of the metadata provider configuration of the media library. + /// Optional. The fingerprint of the artwork provider configuration of the media library. /// The created media library entity. public LibraryEntity Create( Guid? id = null, @@ -42,7 +44,9 @@ public class LibraryEntityFixture bool isLocked = false, bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, - bool shouldSkipUnchangedDirectoriesDuringScan = false) + bool shouldSkipUnchangedDirectoriesDuringScan = false, + string? metadataProvidersConfigurationFingerprint = null, + string? artworkProvidersConfigurationFingerprint = null) { return new Faker() .CustomInstantiator(f => new LibraryEntity @@ -59,6 +63,8 @@ public class LibraryEntityFixture CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, + MetadataProvidersConfigurationFingerprint = metadataProvidersConfigurationFingerprint, + ArtworkProvidersConfigurationFingerprint = artworkProvidersConfigurationFingerprint, CreatedOnUtc = default, CreatedBy = default, UpdatedOnUtc = null, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntityFixture.cs new file mode 100644 index 00000000..3887d0ff --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookArtworkEntityFixture.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookArtworkEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the artwork. + /// Optional. The Id of the book the artwork belongs to. + /// Optional. The type of the artwork. + /// Optional. The ordinal of the artwork within its type. + /// Optional. The relative file name of the stored artwork. + /// Optional. The content hash of the stored artwork. + /// Optional. The status of the artwork enrichment. + /// Optional. The name of the plugin that resolved the artwork. + /// Optional. The date and time when the artwork was last resolved. + /// The created . + public BookArtworkEntity Create( + Guid? id = null, + Guid? bookId = null, + ArtworkType? artworkType = null, + int? ordinal = null, + string? fileName = null, + ulong? contentHash = null, + ArtworkStatus? status = null, + string? provider = null, + DateTime? lastUpdateUtc = null) + { + return new BookArtworkEntity + { + Id = id ?? Guid.NewGuid(), + BookId = bookId ?? Guid.NewGuid(), + ArtworkType = artworkType ?? ArtworkType.Cover, + Ordinal = ordinal ?? 0, + FileName = fileName ?? _faker.System.FilePath(), + ContentHash = contentHash ?? (ulong)_faker.Random.ULong(), + Status = status ?? _faker.PickRandom(), + Provider = provider ?? _faker.Company.CompanyName(), + LastUpdateUtc = lastUpdateUtc ?? _faker.Date.Recent(), + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs index 217d5283..1fddb040 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs @@ -8,6 +8,7 @@ using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -78,7 +79,7 @@ public class AddBookCommandFixture default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); + .RuleFor(e => e.Category, f => f.PickRandom()); Faker mediaContributorName = new Faker() .CustomInstantiator(f => new MediaContributorNameDto( diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs index 6082894e..10440fca 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -1,6 +1,7 @@ #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; @@ -24,13 +25,13 @@ public class MediaContributorDtoFixture /// Optional. The category of the role. /// The created . public MediaContributorDto Create( - string? displayName = null, - string? roleName = null, - string? roleCategory = null) + string? displayName = null, + string? roleName = null, + MediaContributorRoleCategory? roleCategory = null) { return new MediaContributorDto( Name: new MediaContributorNameDto(DisplayName: displayName ?? _faker.Name.FullName(), LegalName: null), - Role: new MediaContributorRoleDto(Name: roleName ?? _faker.Commerce.Department(), Category: roleCategory ?? "Writing")); + Role: new MediaContributorRoleDto(Name: roleName ?? _faker.Commerce.Department(), Category: roleCategory ?? _faker.PickRandom())); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs index 93e8d187..58c5243f 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs @@ -1,6 +1,7 @@ #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; @@ -23,12 +24,12 @@ public class MediaContributorRoleDtoFixture /// Optional. The category of the role. /// The created . public MediaContributorRoleDto Create( - string? name = null, - string? category = null) + string? name = null, + MediaContributorRoleCategory? category = null) { return new MediaContributorRoleDto( name ?? _faker.Commerce.Department(), - category ?? _faker.Commerce.Department()); + category ?? _faker.PickRandom()); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs index 0217fa67..cdc04793 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs @@ -8,6 +8,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Common.Setup; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -119,7 +120,7 @@ public class AddBookRequestFixture default! )) .RuleFor(e => e.Name, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(e => e.Category, f => f.Random.String2(f.Random.Number(1, 50))); + .RuleFor(e => e.Category, f => f.PickRandom()); Faker mediaContributorName = new Faker() .CustomInstantiator(f => new MediaContributorNameDto( diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs index e7dd6e27..d23afb4a 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -65,7 +66,7 @@ public class BookResponseFixture [new IsbnDto(_faker.Random.Replace("###-#-##-#####-#"), IsbnFormat.Isbn13)], [new MediaContributorDto( new MediaContributorNameDto(_faker.Name.FullName(), _faker.Name.FullName()), - new MediaContributorRoleDto(_faker.Commerce.ProductAdjective(), _faker.Commerce.Department()))], + new MediaContributorRoleDto(_faker.Commerce.ProductAdjective(), _faker.PickRandom()))], [new BookRatingDto(_faker.Random.Decimal(1m, 5m), 5m, BookRatingSource.Goodreads, _faker.Random.Int(1, 1000))], metadataStatus ?? _faker.PickRandom(), _faker.Date.Recent().ToUniversalTime(), diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorFixture.cs new file mode 100644 index 00000000..cba83b58 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorFixture +{ + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + private readonly MediaContributorNameFixture _mediaContributorNameFixture = new(); + + /// + /// Creates a random valid domain aggregate. + /// + /// Optional. The Id of the contributor. + /// Optional. The name of the contributor. + /// Optional. The biography of the contributor. + /// Optional. The date of birth of the contributor. + /// Optional. The date of death of the contributor. + /// The created domain aggregate. + public MediaContributor Create( + MediaContributorId? id = null, + MediaContributorName? name = null, + Optional? biography = null, + Optional? dateOfBirth = null, + Optional? dateOfDeath = null) + { + Result result = MediaContributor.Create( + id ?? _mediaContributorIdFixture.Create(), + name ?? _mediaContributorNameFixture.Create(), + biography ?? Optional.None(), + dateOfBirth ?? Optional.None(), + dateOfDeath ?? Optional.None()); + + if (result.IsFailure) + throw new InvalidOperationException("Failed to create MediaContributor: " + string.Join(", ", result.Errors)); + return result.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs index 74ba2906..cd3744d6 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs @@ -1,6 +1,7 @@ #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; @@ -22,11 +23,11 @@ public class MediaContributorRoleFixture /// Optional. The name of the role. If not provided, a random name is generated. /// Optional. The category of the role. If not provided, a random category is generated. /// The created . - public MediaContributorRole Create(string? name = null, string? category = null) + public MediaContributorRole Create(string? name = null, MediaContributorRoleCategory? category = null) { return MediaContributorRole.Create( name ?? _faker.Lorem.Word(), - category ?? _faker.Commerce.Department()); + category ?? _faker.PickRandom()).Value; } /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 05e297c6..6e2216f1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1473,24 +1473,6 @@ public class AddBookEndpointTests : IClassFixture await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description); } - [Fact] - public async Task AddBook_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldReturnUnprocessableEntity() - { - // Arrange - AddBookRequest bookRequest = _requestBookFixture.Create(); - bookRequest = bookRequest with - { - Contributors = [.. bookRequest.Contributors!.Select((contributor, index) => index == 0 ? contributor with - { Role = contributor.Role! with { Category = new Faker().Random.String2(100) } } : contributor)] - }; - - // Act - HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/books", bookRequest); - - // Assert - await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description); - } - [Fact] public async Task AddBook_WhenCalledWithNullRatings_ShouldReturnUnprocessableEntity() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs index 87d15376..308f0d31 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs @@ -6,6 +6,7 @@ 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.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -101,7 +102,7 @@ public class AddBookRequestMappingTests [ new( _mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"), - _mediaContributorRoleDtoFixture.Create(name: "Author", category: "Writing") + _mediaContributorRoleDtoFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author) ) ], ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)], diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 634bebee..ad0cd120 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -7,7 +7,6 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -24,7 +23,7 @@ public class BookMetadataDtoMappingTests private readonly GenreDtoFixture _genreDtoFixture = new(); [Fact] - public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched() + public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItToTheBook() { // Arrange Book book = _bookFixture.Create(); @@ -37,7 +36,7 @@ public class BookMetadataDtoMappingTests pageCount: 398); // Act - Result result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); + Result result = book.ApplyMetadata(metadata); // Assert Assert.False(result.IsFailure); @@ -46,9 +45,6 @@ public class BookMetadataDtoMappingTests Assert.Equal("The first part of J.R.R. Tolkien's epic adventure.", book.Metadata.Description.Value); Assert.Equal(BookFormat.Paperback, book.Format.Value); Assert.Equal("Houghton Mifflin", book.Metadata.Publisher.Value); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("Goodreads", book.MetadataProvider.Value); - Assert.True(book.LastMetadataUpdateUtc.HasValue); } [Fact] @@ -64,10 +60,10 @@ public class BookMetadataDtoMappingTests }; // Act - Result result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); + Result result = book.ApplyMetadata(metadata); // Assert Assert.True(result.IsFailure); - Assert.Equal(MetadataStatus.Pending, book.MetadataStatus); + Assert.NotEqual("The Fellowship of the Ring", book.Metadata.Title); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs new file mode 100644 index 00000000..6bc3687e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +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.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryMediaItemDeletedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IBookArtworkService _mockBookArtworkService; + private readonly ILogger _mockLogger; + private readonly LibraryMediaItemDeletedDomainEventHandler _sut; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryMediaItemDeletedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + + _mockBookArtworkService = Substitute.For(); + _mockLogger = Substitute.For>(); + + _sut = new LibraryMediaItemDeletedDomainEventHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger); + } + + [Fact] + public async Task HandleAsync_WhenBookExistsAtPath_ShouldDeleteTheBookAndItsArtwork() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); + _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + LibraryMediaItemDeletedDomainEvent domainEvent = new( + Guid.NewGuid(), + libraryId, + MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), + book.Path, + DateTime.UtcNow); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title); + await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .Returns(Result.From(null)); + + LibraryMediaItemDeletedDomainEvent domainEvent = new( + Guid.NewGuid(), + libraryId, + MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), + "/books/deleted.epub", + DateTime.UtcNow); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteArtworkFails_ShouldStillDeleteTheBook() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); + _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork")); + _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + LibraryMediaItemDeletedDomainEvent domainEvent = new( + Guid.NewGuid(), + libraryId, + MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), + book.Path, + DateTime.UtcNow); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + // a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged + await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetBookFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get the book"); + _mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any()) + .Returns(error); + + LibraryMediaItemDeletedDomainEvent domainEvent = new( + Guid.NewGuid(), + libraryId, + MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), + "/books/deleted.epub", + DateTime.UtcNow); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteBookFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + BookEntity book = _bookEntityFixture.Create(path: "/books/deleted.epub"); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId.Value, title: "My Library"); + _mockBookRepository.GetByPathAsync(libraryId.Value, book.Path, Arg.Any()) + .Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any()) + .Returns(Result.From(library)); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + Error error = Error.Failure("Database.Error", "Failed to delete the book"); + _mockBookRepository.DeleteAsync(book.Id, Arg.Any()) + .Returns(error); + + LibraryMediaItemDeletedDomainEvent domainEvent = new( + Guid.NewGuid(), + libraryId, + MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()), + book.Path, + DateTime.UtcNow); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index 37421e16..d53729d2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1765,20 +1765,6 @@ public class AddBookCommandValidatorTests result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); } - [Fact] - public void Validate_WhenCalledWithInvalidLengthContributorRoleCategory_ShouldHaveValidationError() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Contributors = [.. bookCommand.Contributors!.Select((contributor, index) => index == 0 ? contributor with { Role = contributor.Role! with { Category = new Faker().Random.String2(51) } } : contributor)] }; - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong); - } - [Fact] public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs index 03e7652c..39220186 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System.Diagnostics.CodeAnalysis; using System.Text.Json; #endregion @@ -23,7 +24,7 @@ public class MediaContributorDtoTests // Arrange MediaContributorDto expected = new( new MediaContributorNameDto("John Smith", "Johnathan Smith"), - new MediaContributorRoleDto("Author", "Writer") + new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author) ); // Act diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs index a8a60fd4..35423d71 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System.Diagnostics.CodeAnalysis; using System.Text.Json; #endregion @@ -21,7 +22,7 @@ public class MediaContributorRoleDtoTests public void RoundTrip_WhenSerializingRole_ShouldPreserveValues() { // Arrange - MediaContributorRoleDto expected = new("Author", "Writer"); + MediaContributorRoleDto expected = new("Author", MediaContributorRoleCategory.Author); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs index 3a159c46..3eb6eed7 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs @@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -53,7 +54,7 @@ public class BookMetadataDtoTests "1234567890", "id12345", [new IsbnDto("978-0-306-40615-7", IsbnFormat.Isbn13)], - [new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", "Writer"))], + [new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author))], [new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)], "https://example.com/dune.jpg" ); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index 1847e96d..b6fd72d0 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DTO.Filtering; using Lumina.Application.Fixtures.Common.DTO.Pagination; @@ -14,6 +16,9 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using System; @@ -39,6 +44,9 @@ public class BookRepositoryTests private readonly TagEntityFixture _tagEntityFixture = new(); private readonly GenreEntityFixture _genreEntityFixture = new(); private readonly IsbnEntityFixture _isbnEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new(); private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new(); @@ -528,4 +536,232 @@ public class BookRepositoryTests Assert.Single(retrievedBook.Ratings); Assert.Equal(4.5M, retrievedBook.Ratings.First().Value); } + + [Fact] + public async Task GetBooksNeedingArtworkAsync_WhenCalled_ShouldReturnOnlyBooksWithoutAnEnrichedCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity bookWithoutCover = _bookEntityFixture.Create(); + bookWithoutCover.LibraryId = libraryId; + bookWithoutCover.Path = "/books/a.epub"; + bookWithoutCover.BookArtwork = []; + BookEntity bookWithEnrichedCover = _bookEntityFixture.Create(); + bookWithEnrichedCover.LibraryId = libraryId; + bookWithEnrichedCover.Path = "/books/b.epub"; + bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity bookWithFailedCover = _bookEntityFixture.Create(); + bookWithFailedCover.LibraryId = libraryId; + bookWithFailedCover.Path = "/books/c.epub"; + bookWithFailedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)]; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.BookArtwork = []; + _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetBooksNeedingArtworkAsync(libraryId, null, 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Contains(result.Value, book => book.Id == bookWithoutCover.Id); + Assert.Contains(result.Value, book => book.Id == bookWithFailedCover.Id); + } + + [Fact] + public async Task GetBooksNeedingArtworkCountAsync_WhenCalled_ShouldCountOnlyBooksWithoutAnEnrichedCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity bookWithoutCover = _bookEntityFixture.Create(); + bookWithoutCover.LibraryId = libraryId; + bookWithoutCover.BookArtwork = []; + BookEntity bookWithEnrichedCover = _bookEntityFixture.Create(); + bookWithEnrichedCover.LibraryId = libraryId; + bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.BookArtwork = []; + _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetBooksNeedingArtworkCountAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1, result.Value); + } + + [Fact] + public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths() + { + // Arrange + // the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity changedBook = _bookEntityFixture.Create(); + changedBook.LibraryId = libraryId; + changedBook.Path = "/books/changed.epub"; + changedBook.MetadataStatus = MetadataStatus.Enriched; + changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity unchangedBook = _bookEntityFixture.Create(); + unchangedBook.LibraryId = libraryId; + unchangedBook.Path = "/books/unchanged.epub"; + unchangedBook.MetadataStatus = MetadataStatus.Enriched; + unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + context.Books.AddRange(changedBook, unchangedBook); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id); + Assert.NotNull(resetBook); + Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); + Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status); + BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id); + Assert.NotNull(keptBook); + Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); + } + + [Fact] + public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary() + { + // Arrange + // the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity enrichedBook = _bookEntityFixture.Create(); + enrichedBook.LibraryId = libraryId; + enrichedBook.MetadataStatus = MetadataStatus.Enriched; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched; + context.Books.AddRange(enrichedBook, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id); + Assert.NotNull(resetBook); + Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); + BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id); + Assert.NotNull(keptBook); + Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); + } + + [Fact] + public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks() + { + // Arrange + // the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + context.Books.AddRange(book, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookArtworkEntity? resetArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id); + Assert.NotNull(resetArtwork); + Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status); + BookArtworkEntity? keptArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id); + Assert.NotNull(keptArtwork); + Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status); + } + + [Fact] + public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenCalled_ShouldReturnTheAuthorDisplayNames() + { + // Arrange + BookEntity firstBook = _bookEntityFixture.Create(); + BookEntity secondBook = _bookEntityFixture.Create(); + BookEntity bookWithoutAuthor = _bookEntityFixture.Create(); + _mockContext.Books.AddRange(firstBook, secondBook, bookWithoutAuthor); + await _mockContext.SaveChangesAsync(); + + MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); + MediaContributorEntity translator = _mediaContributorEntityFixture.Create(displayName: "Jane Translator"); + _mockContext.MediaContributors.AddRange(author, translator); + 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)); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAuthorsDisplayNamesByBookIdsAsync([firstBook.Id, secondBook.Id, bookWithoutAuthor.Id], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + // only the author contributor of the first book is returned; the book with no author is not included + Assert.Single(result.Value); + Assert.Equal("Frank Herbert", result.Value[firstBook.Id]); + } + + [Fact] + public async Task DeleteAsync_WhenBookExists_ShouldRemoveItAndReturnDeleted() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteAsync(book.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + EntityEntry? deletedBook = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == book.Id); + Assert.NotNull(deletedBook); + } + + [Fact] + public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError() + { + // Act + Result result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs new file mode 100644 index 00000000..3f0c4b72 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MediaContributors/MediaContributorRepositoryTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.DataAccess.Core.Repositories.MediaContributors; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.MediaContributors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly MediaContributorRepository _sut; + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MediaContributorRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new MediaContributorRepository(_mockContext); + } + + [Fact] + public async Task FindOrCreateByDisplayNameAsync_WhenContributorExists_ShouldReturnTheExistingContributor() + { + // Arrange + MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King"); + _mockContext.MediaContributors.Add(existingContributor); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.FindOrCreateByDisplayNameAsync("stephen king", null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + // the comparison is case-insensitive, so the existing contributor is returned and no new one is created + Assert.Equal(existingContributor.Id, result.Value.Id); + Assert.Equal("Stephen King", result.Value.DisplayName); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task FindOrCreateByDisplayNameAsync_WhenContributorDoesNotExist_ShouldCreateAndAddANewContributor() + { + // Arrange + string displayName = "Frank Herbert"; + + // Act + Result result = await _sut.FindOrCreateByDisplayNameAsync(displayName, "Franklin Patrick Herbert", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(displayName, result.Value.DisplayName); + Assert.Equal("Franklin Patrick Herbert", result.Value.LegalName); + + EntityEntry? addedContributor = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == result.Value.Id); + Assert.NotNull(addedContributor); + } + + [Fact] + public async Task FindOrCreateByDisplayNameAsync_WhenContributorWithSameNameExistsInDifferentCase_ShouldNotCreateADuplicate() + { + // Arrange + MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); + _mockContext.MediaContributors.Add(existingContributor); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.FindOrCreateByDisplayNameAsync("FRANK HERBERT", "Franklin Patrick Herbert", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(existingContributor.Id, result.Value.Id); + Assert.Equal(existingContributor.DisplayName, result.Value.DisplayName); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds() + { + // Arrange + MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(); + MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(); + MediaContributorEntity thirdContributor = _mediaContributorEntityFixture.Create(); + _mockContext.MediaContributors.AddRange(firstContributor, secondContributor, thirdContributor); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByIdsAsync([firstContributor.Id, thirdContributor.Id], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id); + Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs index fc94cdc6..b42b9064 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs @@ -47,7 +47,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(25, tableNames.Length); + Assert.Equal(28, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -73,6 +73,9 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("BookRatings", tableNames); Assert.Contains("BookISBNs", tableNames); Assert.Contains("Themes", tableNames); + Assert.Contains("MediaContributors", tableNames); + Assert.Contains("BookContributors", tableNames); + Assert.Contains("BookArtwork", tableNames); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs index a27e416b..4152109f 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs @@ -2,6 +2,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; @@ -17,7 +18,7 @@ public class MediaContributorTests { private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); private readonly MediaContributorNameFixture _mediaContributorNameFixture = new(); - private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new(); + private readonly MediaContributorFixture _mediaContributorFixture = new(); [Fact] public void Create_WhenCalledWithPreExistingIdAndValues_ShouldCreateContributor() @@ -25,22 +26,22 @@ public class MediaContributorTests // Arrange MediaContributorId id = _mediaContributorIdFixture.Create(); MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.Some("Jane Doe Smith")); - MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + Optional biography = Optional.Some("A well-known author."); Optional dateOfBirth = Optional.Some(new DateOnly(1980, 1, 1)); Optional dateOfDeath = Optional.None(); // Act - Result result = MediaContributor.Create(id, name, role, dateOfBirth, dateOfDeath); + Result result = MediaContributor.Create(id, name, biography, dateOfBirth, dateOfDeath); // Assert Assert.False(result.IsFailure); Assert.Equal(id, result.Value.Id); Assert.Equal(name, result.Value.Name); - Assert.Equal(role, result.Value.Role); + Assert.True(result.Value.Biography.HasValue); + Assert.Equal("A well-known author.", result.Value.Biography.Value); Assert.True(result.Value.DateOfBirth.HasValue); Assert.Equal(new DateOnly(1980, 1, 1), result.Value.DateOfBirth.Value); Assert.False(result.Value.DateOfDeath.HasValue); - Assert.False(result.Value.Biography.HasValue); } [Fact] @@ -48,24 +49,46 @@ public class MediaContributorTests { // Arrange MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); - MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); // Act - Result result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, role, Optional.None(), Optional.None()); + Result result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, Optional.None(), Optional.None(), Optional.None()); // Assert Assert.False(result.IsFailure); + Assert.False(result.Value.Biography.HasValue); Assert.False(result.Value.DateOfBirth.HasValue); Assert.False(result.Value.DateOfDeath.HasValue); } [Fact] - public void Create_WhenCalledWithoutId_ShouldThrowNotImplementedException() + public void Create_WhenCalledWithoutId_ShouldCreateContributorWithGeneratedId() { // Arrange MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); - // Act & Assert - Assert.Throws(() => MediaContributor.Create(name)); + // Act + Result result = MediaContributor.Create(name); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value.Id); + Assert.Equal(name, result.Value.Name); + Assert.False(result.Value.Biography.HasValue); + Assert.False(result.Value.DateOfBirth.HasValue); + Assert.False(result.Value.DateOfDeath.HasValue); + } + + [Fact] + public void Create_WhenCalledWithPreExistingId_ShouldNotContainARole() + { + // Arrange + MediaContributor contributor = _mediaContributorFixture.Create(); + + // Act + Type contributorType = contributor.GetType(); + + // Assert + // the contributor is a person, agnostic of the roles it played in the media items, so it must not expose a role + Assert.Null(contributorType.GetProperty("Role")); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs index f97b010f..d7e7bac7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs @@ -1,6 +1,9 @@ #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 @@ -15,22 +18,34 @@ public class MediaContributorRoleTests private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new(); [Fact] - public void Create_WhenCalledWithNameAndCategory_ShouldCreateRole() + public void Create_WhenCalledWithDisplayNameAndCategory_ShouldCreateRole() { // Act - MediaContributorRole role = MediaContributorRole.Create("Actor", "Crew"); + Result result = MediaContributorRole.Create("Author", MediaContributorRoleCategory.Author); // Assert - Assert.Equal("Actor", role.Name); - Assert.Equal("Crew", role.Category); + 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 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: "Actor", category: "Crew"); - MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); + MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); // Act bool result = firstRole.Equals(secondRole); @@ -40,11 +55,11 @@ public class MediaContributorRoleTests } [Fact] - public void Equals_WithDifferentName_ShouldReturnFalse() + public void Equals_WithDifferentDisplayName_ShouldReturnFalse() { // Arrange - MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); - MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Director", category: "Crew"); + MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); + MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Writer", category: MediaContributorRoleCategory.Author); // Act bool result = firstRole.Equals(secondRole); @@ -57,8 +72,8 @@ public class MediaContributorRoleTests public void Equals_WithDifferentCategory_ShouldReturnFalse() { // Arrange - MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); - MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Voice"); + MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); + MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Translator); // Act bool result = firstRole.Equals(secondRole); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs index 11427070..e90f14cf 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookTests.cs @@ -1,8 +1,11 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,46 +18,73 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoun public class BookTests { private readonly BookFixture _bookFixture = new(); + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); [Fact] - public void Create_WhenCalledWithValidData_ShouldCreateBookWithPendingMetadataStatus() + public void Create_WhenCalledWithValidData_ShouldCreateBook() { // Act Book book = _bookFixture.Create(); // Assert Assert.NotNull(book); - Assert.Equal(MetadataStatus.Pending, book.MetadataStatus); - Assert.False(book.LastMetadataUpdateUtc.HasValue); - Assert.False(book.MetadataProvider.HasValue); + Assert.NotNull(book.Metadata); + Assert.NotNull(book.Path); + Assert.NotNull(book.LibraryId); } [Fact] - public void MarkMetadataAsEnriched_WhenCalled_ShouldUpdateStatusAndProvider() + public void UpdateContributors_WhenCalled_ShouldReplaceTheContributors() { // Arrange Book book = _bookFixture.Create(); - DateTime lastUpdateUtc = DateTime.UtcNow; + MediaContributorId firstContributorId = _mediaContributorIdFixture.Create(); + MediaContributorId secondContributorId = _mediaContributorIdFixture.Create(); // Act - book.MarkMetadataAsEnriched("Goodreads", lastUpdateUtc); + book.UpdateContributors([firstContributorId, secondContributorId]); // Assert - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("Goodreads", book.MetadataProvider.Value); - Assert.Equal(lastUpdateUtc, book.LastMetadataUpdateUtc.Value); + Assert.Equal(2, book.Contributors.Count); + Assert.Contains(book.Contributors, contributorId => contributorId == firstContributorId); + Assert.Contains(book.Contributors, contributorId => contributorId == secondContributorId); } [Fact] - public void MarkMetadataAsFailed_WhenCalled_ShouldUpdateStatus() + public void UpdateContributors_WhenCalledAgain_ShouldReplaceTheContributors() { // Arrange Book book = _bookFixture.Create(); + book.UpdateContributors([_mediaContributorIdFixture.Create()]); + MediaContributorId replacementContributorId = _mediaContributorIdFixture.Create(); // Act - book.MarkMetadataAsFailed(); + book.UpdateContributors([replacementContributorId]); // Assert - Assert.Equal(MetadataStatus.Failed, book.MetadataStatus); + // the previous contributors are replaced, not appended + MediaContributorId contributorId = Assert.Single(book.Contributors); + Assert.Equal(replacementContributorId, contributorId); + } + + [Fact] + public void Create_WhenCalled_ShouldNotExposeEnrichmentTracking() + { + // Arrange + Book book = _bookFixture.Create(); + Type bookType = book.GetType(); + + // Act + bool hasMetadataStatus = bookType.GetProperty("MetadataStatus") is not null; + bool hasLastMetadataUpdateUtc = bookType.GetProperty("LastMetadataUpdateUtc") is not null; + bool hasMetadataProvider = bookType.GetProperty("MetadataProvider") is not null; + bool hasCoverImagePath = bookType.GetProperty("CoverImagePath") is not null; + + // Assert + // the enrichment state is a persistence concern, tracked on the repository entity by the enrichment jobs + Assert.False(hasMetadataStatus); + Assert.False(hasLastMetadataUpdateUtc); + Assert.False(hasMetadataProvider); + Assert.False(hasCoverImagePath); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs index b100f5d6..16c76795 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs @@ -40,7 +40,7 @@ public class BookLibraryTypeScannerTests } [Fact] - public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithMetadataEnrichment() + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithEnrichmentJobs() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); @@ -48,7 +48,9 @@ public class BookLibraryTypeScannerTests TestScanJob diffJob = CreateJob(); TestScanJob hashJob = CreateJob(); TestScanJob saveJob = CreateJob(); + TestScanJob invalidationJob = CreateJob(); TestScanJob enrichmentJob = CreateJob(); + TestScanJob artworkEnrichmentJob = CreateJob(); BookLibraryTypeScanner sut = new(_mockJobFactory); // Act @@ -63,9 +65,14 @@ public class BookLibraryTypeScannerTests Assert.Contains(diffJob, hashJob.Parents); Assert.Contains(saveJob, hashJob.Children); Assert.Contains(hashJob, saveJob.Parents); - Assert.Contains(enrichmentJob, saveJob.Children); - Assert.Contains(saveJob, enrichmentJob.Parents); + Assert.Contains(invalidationJob, saveJob.Children); + Assert.Contains(saveJob, invalidationJob.Parents); + Assert.Contains(enrichmentJob, invalidationJob.Children); + Assert.Contains(invalidationJob, enrichmentJob.Parents); + Assert.Contains(artworkEnrichmentJob, enrichmentJob.Children); + Assert.Contains(enrichmentJob, artworkEnrichmentJob.Parents); _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); } [Fact] @@ -77,7 +84,9 @@ public class BookLibraryTypeScannerTests CreateJob(); CreateJob(); CreateJob(); + CreateJob(); CreateJob(); + CreateJob(); BookLibraryTypeScanner sut = new(_mockJobFactory); // Act @@ -88,7 +97,9 @@ public class BookLibraryTypeScannerTests _mockJobFactory.Received(1).CreateJob(libraryId); _mockJobFactory.Received(1).CreateJob(libraryId); _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); } private TestScanJob CreateJob() where TJob : class, IMediaLibraryScanJob @@ -111,7 +122,9 @@ public class BookLibraryTypeScannerTests IMediaLibraryScanDiffJob, IMediaLibraryScanHashJob, IMediaLibraryScanResultsSaveJob, - IMediaLibraryScanMetadataEnrichmentJob + IMediaLibraryScanProviderConfigurationInvalidationJob, + IMediaLibraryScanMetadataEnrichmentJob, + IMediaLibraryScanArtworkEnrichmentJob { /// /// Executes the payload of the media library scan job. diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs new file mode 100644 index 00000000..0a3358b6 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs @@ -0,0 +1,299 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanArtworkEnrichmentJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; + private readonly MediaLibraryScanArtworkEnrichmentJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanArtworkEnrichmentJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockArtworkConfigurationRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _mockLogger = Substitute.For>(); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndTrackTheCoverArtworkAsEnriched() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title"); + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await mockBookArtworkService.Received(1).SaveBookArtworkAsync( + _libraryId.Value, + book.Id, + "My Library", + "Frank Herbert", + "Test Title", + Arg.Any(), + Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); + Assert.Equal(0, coverArtwork.Ordinal); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); + Assert.Equal(123ul, coverArtwork.ContentHash); + Assert.Equal("Artwork Provider", coverArtwork.Provider); + Assert.NotNull(coverArtwork.LastUpdateUtc); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenResolvedArtworkIsIdenticalToTheStoredOne_ShouldKeepTheStoredArtworkAndMarkItAsEnriched() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + // the book already has a stored cover with the same content hash as the resolved artwork + book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept + await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); + Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); + Assert.Equal("Artwork Provider", coverArtwork.Provider); + Assert.NotNull(coverArtwork.LastUpdateUtc); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenNoProviderReturnsArtwork_ShouldMarkTheCoverArtworkAsFailed() + { + // Arrange + Guid artworkPluginId = Guid.NewGuid(); + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns((ArtworkDto?)null); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + IFileHashService mockFileHashService = Substitute.For(); + + SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, artworkPluginId); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); + Assert.Equal(0, coverArtwork.Ordinal); + Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); + Assert.Null(coverArtwork.FileName); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichmentWithoutMarkingBooksAsFailed() + { + // Arrange + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a library without artwork providers must not mark its books as failed to resolve, so the books are not even queried + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + /// + /// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container. + /// + /// The Id of the plugin providing the artwork. + /// The artwork provider to resolve. + /// The service used to store the artwork of the books. + /// The service used to hash the artwork. + private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService) + { + ServiceCollection services = new(); + services.AddKeyedSingleton(artworkPluginId, artworkProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(bookArtworkService); + services.AddSingleton(fileHashService); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + } + + /// + /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider. + /// + /// The book whose artwork the job must resolve. + /// The Id of the plugin configured as artwork provider for the library. + private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId) + { + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1) + ])); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index fab2baae..343f32c5 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -1,21 +1,25 @@ #region ========================================================================= USING ===================================================================================== +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.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; 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.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; @@ -27,6 +31,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContex using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Plugins.Contracts.Core.Metadata; @@ -55,6 +60,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; private readonly IBookRepository _mockBookRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; private readonly IDomainEventPublisher _mockDomainEventPublisher; private readonly ILogger _mockLogger; private readonly MediaLibraryScanMetadataEnrichmentJob _sut; @@ -62,11 +68,11 @@ public class MediaLibraryScanMetadataEnrichmentJobTests private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); - private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; @@ -86,8 +92,10 @@ public class MediaLibraryScanMetadataEnrichmentJobTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockBookRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); _mockDomainEventPublisher = Substitute.For(); @@ -125,7 +133,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Assert Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); } @@ -145,8 +153,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -285,116 +292,125 @@ public class MediaLibraryScanMetadataEnrichmentJobTests SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the enrichment state is tracked directly on the entity, so the failed status is visible on the same instance + Assert.Equal(MetadataStatus.Failed, book.MetadataStatus); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenMetadataIsEnriched_ShouldSetTheEnrichmentTrackingColumnsOnTheEntity() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the enrichment tracking columns are managed directly on the entity by the enrichment job + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal("First Provider", book.MetadataProvider); + Assert.NotNull(book.LastMetadataUpdateUtc); + Assert.Equal("First Title", book.Title); + Assert.Equal("First Publisher", book.Publisher); + } + + [Fact] + public async Task ExecuteAsync_WhenMetadataHasContributors_ShouldFindOrCreateThemAndLinkThemToTheBook() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); + MediaContributorEntity translatorEntity = _mediaContributorEntityFixture.Create(displayName: "Jane Translator"); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) + .Returns(Result.From(authorEntity)); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()) + .Returns(Result.From(translatorEntity)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()); + + // the participation rows are replaced on the entity, carrying the role and the category of each contributor + Assert.Equal(2, book.BookContributors.Count); + BookContributorEntity linkedAuthor = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == authorEntity.Id); + Assert.Equal("Author", linkedAuthor.RoleName); + Assert.Equal(MediaContributorRoleCategory.Author, linkedAuthor.RoleCategory); + Assert.Equal(book.Id, linkedAuthor.BookId); + BookContributorEntity linkedTranslator = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == translatorEntity.Id); + Assert.Equal("Translator", linkedTranslator.RoleName); + Assert.Equal(MediaContributorRoleCategory.Translator, linkedTranslator.RoleCategory); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + } + + [Fact] + public async Task ExecuteAsync_WhenTheSameContributorAppearsInMultipleBooksOfAPage_ShouldFindOrCreateItOnlyOnce() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + + BookEntity firstBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/a.epub"); + BookEntity secondBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/b.epub"); _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1) - ])); + .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); + .Returns(Result.From(2)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); + .Returns(Result.From>([firstBook, secondBook]), Result.From>([])); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await _mockBookRepository.Received(1).UpdateAsync( - Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Failed), - Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); - mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure(description: "Failed to get the artwork provider configurations")); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) + .Returns(Result.From(authorEntity)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid artworkPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); - - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - services.AddKeyedSingleton(artworkPluginId, artworkProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - using ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); - mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); - _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); - - IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); - mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await mockBookArtworkService.Received(1).SaveBookArtworkAsync( - _libraryId.Value, - book.Id, - Arg.Any(), - Arg.Any(), - "First Title", - Arg.Any(), - Arg.Any()); - await _mockBookRepository.Received(1).UpdateAsync( - Arg.Is(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"), - Arg.Any()); + // the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); + Assert.Single(firstBook.BookContributors); + Assert.Single(secondBook.BookContributors); + Assert.Equal(authorEntity.Id, firstBook.BookContributors[0].MediaContributorId); + Assert.Equal(authorEntity.Id, secondBook.BookContributors[0].MediaContributorId); } [Fact] @@ -472,63 +488,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } - [Fact] - public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess() - { - // Arrange - Guid localPluginId = Guid.NewGuid(); - Guid artworkPluginId = Guid.NewGuid(); - IMetadataProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.RequiresWebAccess.Returns(false); - localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Local Title")); - - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Web Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.RequiresWebAccess.Returns(true); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - ServiceCollection services = new(); - services.AddKeyedSingleton(localPluginId, localProvider); - services.AddKeyedSingleton(artworkPluginId, artworkProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - using ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); - mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); - _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); - - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); - mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, localPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web - await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - /// /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. /// @@ -570,8 +529,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From(1)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([book]), Result.From>([])); - _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs new file mode 100644 index 00000000..2ec4efc1 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs @@ -0,0 +1,291 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanProviderConfigurationInvalidationJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository; + private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; + private readonly MediaLibraryScanProviderConfigurationInvalidationJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanProviderConfigurationInvalidationJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMetadataConfigurationRepository = Substitute.For(); + _mockArtworkConfigurationRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _mockLogger = Substitute.For>(); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new MediaLibraryScanProviderConfigurationInvalidationJob(_mockServiceScopeFactory, _mockLogger) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenNoFingerprintIsStored_ShouldSeedTheFingerprintsWithoutResettingAnything() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: null); + SetupLibraryAndConfigurations(library); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted + await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE", artworkProvidersConfigurationFingerprint: null); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job + await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()); + await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenArtworkFingerprintDiffers_ShouldResetTheArtworkStatus() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE"); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job + await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()); + await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenFingerprintsMatch_ShouldNotResetAnythingButStillPersistTheFingerprints() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + List metadataConfigurations = _metadataConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); + List artworkConfigurations = _artworkConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); + SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations); + + // the stored fingerprints match the ones computed from the current provider configuration + string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb); + string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, library.CanDownloadMetadataFromWeb); + library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; + library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted + await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly() + { + // Arrange + // both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK"); + SetupLibraryAndConfigurations(library); + _mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and + // flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run + await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()); + await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the media library")); + SetupConfigurations(); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + /// + /// Stubs the repositories so that the job reads the provided library and its provider configurations. + /// + /// The media library the job must read. + /// The metadata provider configurations of the media library. + /// The artwork provider configurations of the media library. + private void SetupLibraryAndConfigurations(LibraryEntity library, List? metadataConfigurations = null, List? artworkConfigurations = null) + { + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(library)); + SetupConfigurations(metadataConfigurations, artworkConfigurations); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + } + + /// + /// Stubs the provider configuration repositories and the user settings repository used by the job. + /// + /// The metadata provider configurations of the media library, if already created by the caller. + /// The artwork provider configurations of the media library, if already created by the caller. + private void SetupConfigurations(List? metadataConfigurations = null, List? artworkConfigurations = null) + { + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>( + metadataConfigurations ?? [ + _metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1), + _metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2) + ])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>( + artworkConfigurations ?? [ + _artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1), + _artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2) + ])); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs index 1189a17c..e1f9c3a9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs @@ -21,6 +21,7 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -38,6 +39,7 @@ public class MediaLibraryScanResultsSaveJobTests private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; private readonly IBookRepository _mockBookRepository; private readonly IDomainEventPublisher _mockDomainEventPublisher; private readonly MediaLibraryScanResultsSaveJob _sut; @@ -62,8 +64,10 @@ public class MediaLibraryScanResultsSaveJobTests _mockUnitOfWork = Substitute.For(); _mockSnapshotRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); _mockBookRepository = Substitute.For(); _mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); @@ -89,6 +93,10 @@ public class MediaLibraryScanResultsSaveJobTests // Arrange _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) .Returns(Result.From>(["deleted.pdf"])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>(["changed.pdf"])); + _mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) @@ -105,18 +113,44 @@ public class MediaLibraryScanResultsSaveJobTests // Assert Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any()); + await _mockBookRepository.Received(1).ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Is>(paths => paths.Any(path => path == "changed.pdf")), Arg.Any()); await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any()); await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // no book content changed since the last scan, so the enrichment state of the books must not be reset + await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt() { // Arrange _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs index 297ebbad..6fddda13 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs @@ -2,6 +2,7 @@ using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; using Lumina.Plugins.Calibre.Core.Mapping; using Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; @@ -210,32 +211,32 @@ public class CalibreMapperTests MediaContributorDto author = result.Contributors[0]; Assert.Equal("Test Author", author.Name!.DisplayName); Assert.Equal("Author", author.Role!.Name); - Assert.Equal("Writing", author.Role.Category); + Assert.Equal(MediaContributorRoleCategory.Author, author.Role.Category); MediaContributorDto coAuthor = result.Contributors[1]; Assert.Equal("Co Author", coAuthor.Name!.DisplayName); Assert.Equal("Author", coAuthor.Role!.Name); - Assert.Equal("Writing", coAuthor.Role.Category); + Assert.Equal(MediaContributorRoleCategory.Author, coAuthor.Role.Category); MediaContributorDto translator = result.Contributors[2]; Assert.Equal("Test Translator", translator.Name!.DisplayName); Assert.Equal("trl", translator.Role!.Name); - Assert.Equal("Translation", translator.Role.Category); + Assert.Equal(MediaContributorRoleCategory.Translator, translator.Role.Category); MediaContributorDto illustrator = result.Contributors[3]; Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName); Assert.Equal("ill", illustrator.Role!.Name); - Assert.Equal("Art", illustrator.Role.Category); + Assert.Equal(MediaContributorRoleCategory.Illustrator, illustrator.Role.Category); MediaContributorDto production = result.Contributors[4]; Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName); Assert.Equal("bkp", production.Role!.Name); - Assert.Equal("Production", production.Role.Category); + Assert.Equal(MediaContributorRoleCategory.Publisher, production.Role.Category); MediaContributorDto misc = result.Contributors[5]; Assert.Equal("Misc Contributor", misc.Name!.DisplayName); Assert.Equal("Contributor", misc.Role!.Name); - Assert.Equal("Other", misc.Role.Category); + Assert.Equal(MediaContributorRoleCategory.Other, misc.Role.Category); } [Fact] diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs index 1a98265b..5228b0f2 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using Lumina.Plugins.OpenLibrary.Core.Mapping; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; @@ -276,7 +277,7 @@ public class OpenLibraryMapperTests Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); Assert.Contains(result.ISBNs!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10); Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role!.Name == "Author"); - Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == "Art"); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == MediaContributorRoleCategory.Illustrator); BookRatingDto mappedRating = Assert.Single(result.Ratings!); Assert.Equal(4.2m, mappedRating.Value); Assert.Equal(5m, mappedRating.MaxValue);