mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
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.
This commit is contained in:
1 parent
4ee2976806
commit
565fe68239
98 files changed
+5845
-630
No files matched your search
@@ -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<MediaContributorDto> result = [];
|
||||
HashSet<string> 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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="role">The role code to map.</param>
|
||||
/// <returns>The mapped contributor category.</returns>
|
||||
private static string MapContributorCategory(string? role)
|
||||
/// <returns>The canonical category of the role.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<MediaContributorDto> result = [];
|
||||
HashSet<string> 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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a contributor role into a contributor category.
|
||||
/// Maps a contribution role into the canonical category of the role.
|
||||
/// </summary>
|
||||
/// <param name="role">The role to categorize.</param>
|
||||
/// <returns>The mapped contributor category.</returns>
|
||||
private static string ContributorCategory(string role)
|
||||
/// <returns>The canonical category of the role.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+62
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor
|
||||
/// played in that book. The role is tracked per participation, so that a single contributor can play multiple
|
||||
/// roles in the same book, or different roles in different books.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("BookId: {BookId} MediaContributorId: {MediaContributorId}")]
|
||||
public class BookContributorEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the participation.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the book the contributor participated in.
|
||||
/// </summary>
|
||||
public required Guid BookId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media contributor.
|
||||
/// </summary>
|
||||
public required Guid MediaContributorId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the display name of the role the contributor played in the book.
|
||||
/// </summary>
|
||||
public required string RoleName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the canonical category of the role the contributor played in the book.
|
||||
/// </summary>
|
||||
public required MediaContributorRoleCategory RoleCategory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+57
-8
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name details of the media contributor, including display and legal names.</param>
|
||||
/// <param name="Role">The role details of the media contributor, including the role name and category.</param>
|
||||
[DebuggerDisplay("Name: {Name}, Role: {Role}")]
|
||||
public record MediaContributorEntity(
|
||||
MediaContributorNameEntity? Name,
|
||||
MediaContributorRoleEntity? Role
|
||||
);
|
||||
[DebuggerDisplay("DisplayName: {DisplayName}")]
|
||||
public class MediaContributorEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the media contributor.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name by which the contributor is popularly known.
|
||||
/// </summary>
|
||||
public required string DisplayName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the legal name of the contributor.
|
||||
/// </summary>
|
||||
public string? LegalName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the biography of the contributor.
|
||||
/// </summary>
|
||||
public string? Biography { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date of birth of the contributor.
|
||||
/// </summary>
|
||||
public DateOnly? DateOfBirth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date of death of the contributor.
|
||||
/// </summary>
|
||||
public DateOnly? DateOfDeath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a media contributor name.
|
||||
/// </summary>
|
||||
/// <param name="DisplayName">The display name of the media contributor.</param>
|
||||
/// <param name="LegalName">The legal name of the media contributor.</param>
|
||||
[DebuggerDisplay("DisplayName: {DisplayName}")]
|
||||
public record MediaContributorNameEntity(
|
||||
string? DisplayName,
|
||||
string? LegalName
|
||||
);
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a media contributor role.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the role assigned to the media contributor.</param>
|
||||
/// <param name="Category">The category of the role.</param>
|
||||
[DebuggerDisplay("Name: {Name}, Category: {Category}")]
|
||||
public record MediaContributorRoleEntity(
|
||||
string? Name,
|
||||
string? Category
|
||||
);
|
||||
+13
-1
@@ -71,10 +71,22 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
|
||||
public bool ShouldSaveMetadataInMediaDirectories { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public bool ShouldSkipUnchangedDirectoriesDuringScan { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string? MetadataProvidersConfigurationFingerprint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string? ArtworkProvidersConfigurationFingerprint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user that owns the media library.
|
||||
/// </summary>
|
||||
|
||||
+84
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("BookId: {BookId} Type: {ArtworkType} Ordinal: {Ordinal}")]
|
||||
public class BookArtworkEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the artwork.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the book the artwork belongs to.
|
||||
/// </summary>
|
||||
public required Guid BookId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the artwork.
|
||||
/// </summary>
|
||||
public required ArtworkType ArtworkType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered.
|
||||
/// </summary>
|
||||
public required int Ordinal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the relative file name of the stored artwork, if the artwork has been resolved.
|
||||
/// </summary>
|
||||
public string? FileName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the content hash of the stored artwork, used to detect whether a re-resolved artwork differs from the stored one.
|
||||
/// </summary>
|
||||
public ulong ContentHash { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the status of the artwork enrichment.
|
||||
/// </summary>
|
||||
public required ArtworkStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the plugin that resolved the artwork, if applicable.
|
||||
/// </summary>
|
||||
public string? Provider { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time when the artwork was last resolved, if applicable.
|
||||
/// </summary>
|
||||
public DateTime? LastUpdateUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+8
-7
@@ -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
|
||||
/// </summary>
|
||||
public string? AppleBooksId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the file system path of the cover image of the book, if applicable.
|
||||
/// </summary>
|
||||
public string? CoverImagePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of ISBN (International Standard Book Number) of the book.
|
||||
/// </summary>
|
||||
public List<IsbnEntity> ISBNs { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
//public List<ContributorIdModel> ContributorIds { get; set; } = [];
|
||||
public List<BookContributorEntity> BookContributors { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the pieces of artwork of the book, each tracked independently with its own enrichment state.
|
||||
/// </summary>
|
||||
public List<BookArtworkEntity> BookArtwork { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of ratings for this book.
|
||||
|
||||
@@ -56,4 +56,68 @@ public interface IBookRepository : IRepository<BookEntity>,
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the number of books needing their metadata enriched, or an error.</returns>
|
||||
Task<Result<int>> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
|
||||
/// <param name="lastPath">The path of the last retrieved book, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
|
||||
/// <param name="pageSize">The maximum number of books to retrieve.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a page of books needing their artwork resolved, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<BookEntity>>> GetBooksNeedingArtworkAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of books of the media library identified by <paramref name="libraryId"/> that need their artwork resolved.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are counted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the number of books needing their artwork resolved, or an error.</returns>
|
||||
Task<Result<int>> GetBooksNeedingArtworkCountAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Resets the enrichment state of the books stored at the provided <paramref name="paths"/> in the media library identified by
|
||||
/// <paramref name="libraryId"/>, so that they are re-enriched, because their content changed since the last scan.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are reset.</param>
|
||||
/// <param name="paths">The file system paths of the books whose enrichment state is reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>,
|
||||
/// so that they are re-enriched, because the metadata provider configuration of the library changed.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Resets the artwork status of all the artwork of the books of the media library identified by <paramref name="libraryId"/>,
|
||||
/// so that they are re-resolved, because the artwork provider configuration of the library changed.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose artwork is reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> ResetArtworkStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display names of the author of the books identified by the provided <paramref name="bookIds"/>,
|
||||
/// keyed by the Id of the book, or <see langword="null"/> when a book has no author.
|
||||
/// </summary>
|
||||
/// <param name="bookIds">The unique identifiers of the books whose authors are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns>
|
||||
Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book to delete.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteAsync(Guid bookId, CancellationToken cancellationToken);
|
||||
}
|
||||
+37
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for media contributors.
|
||||
/// </summary>
|
||||
public interface IMediaContributorRepository : IRepository<MediaContributorEntity>,
|
||||
IInsertRepositoryAction<MediaContributorEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the media contributor whose display name matches the provided <paramref name="displayName"/>, or creates and inserts a new one
|
||||
/// when no contributor with that name exists yet, guaranteeing a single contributor per person.
|
||||
/// </summary>
|
||||
/// <param name="displayName">The name by which the contributor is popularly known.</param>
|
||||
/// <param name="legalName">The optional legal name of the contributor.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the existing or newly created <see cref="MediaContributorEntity"/>, or an error.</returns>
|
||||
Task<Result<MediaContributorEntity>> FindOrCreateByDisplayNameAsync(string displayName, string? legalName, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media contributors identified by the provided <paramref name="ids"/>.
|
||||
/// </summary>
|
||||
/// <param name="ids">The unique identifiers of the media contributors to retrieve.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the retrieved <see cref="MediaContributorEntity"/>s, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<MediaContributorEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken);
|
||||
}
|
||||
+9
@@ -46,6 +46,15 @@ public interface ILibraryScanStagingResultsRepository : IRepository<LibraryScanS
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a page of staging results that need hashing, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<HashedFileSystemFileDto>>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the paths of the changed staging results, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<string>>> GetChangedPathsAsync(Guid scanId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the content hashes of the provided media library scan staging results.
|
||||
/// </summary>
|
||||
|
||||
@@ -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
|
||||
/// </summary>
|
||||
IBookRepository BookRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media contributor repository.
|
||||
/// </summary>
|
||||
IMediaContributorRepository MediaContributorRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the directory scan fingerprint repository.
|
||||
/// </summary>
|
||||
|
||||
@@ -21,4 +21,11 @@ public interface IFileHashService
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A collection of the hashed files, along with their hashes.</returns>
|
||||
Task<List<HashedFileSystemFileDto>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFileDto> files, Func<Task> callback, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Computes the content hash of the file stored at <paramref name="filePath"/>, by sampling chunks from it.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path of the file to hash.</param>
|
||||
/// <returns>The content hash of the file.</returns>
|
||||
ulong ComputeFileHash(string filePath);
|
||||
}
|
||||
+5
-6
@@ -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<DateTime>.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
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+41
-4
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the metadata fields of <paramref name="domainEntity"/> onto the existing <paramref name="entity"/>,
|
||||
/// without touching the enrichment tracking columns, which are managed directly by the enrichment jobs.
|
||||
/// </summary>
|
||||
/// <param name="entity">The repository entity onto which the metadata is applied.</param>
|
||||
/// <param name="domainEntity">The domain entity whose metadata is applied.</param>
|
||||
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();
|
||||
}
|
||||
}
|
||||
+3
-10
@@ -19,14 +19,12 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B
|
||||
public static class BookMetadataDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Applies the metadata of <paramref name="metadata"/> to <paramref name="book"/>, marking its metadata as enriched by the provided <paramref name="providerName"/>.
|
||||
/// Applies the metadata of <paramref name="metadata"/> to <paramref name="book"/>.
|
||||
/// </summary>
|
||||
/// <param name="book">The domain book to which the metadata is applied.</param>
|
||||
/// <param name="metadata">The metadata to be applied.</param>
|
||||
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
|
||||
/// <param name="lastUpdateUtc">The date and time when the metadata was enriched.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public static Result<Success> ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc)
|
||||
public static Result<Success> 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<string>.FromNullable(metadata.BarnesAndNobleId),
|
||||
Optional<string>.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;
|
||||
}
|
||||
}
|
||||
+81
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler<LibraryMediaItemDeletedDomainEvent>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IBookArtworkService _bookArtworkService;
|
||||
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="bookArtworkService">Injected service for storing the artwork of the books.</param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while deleting the media library item.</param>
|
||||
public LibraryMediaItemDeletedDomainEventHandler(IUnitOfWork unitOfWork, IBookArtworkService bookArtworkService, ILogger<LibraryMediaItemDeletedDomainEventHandler> logger)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_bookArtworkService = bookArtworkService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the event raised when a media library item is no longer present in the media library scan snapshot.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
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<BookEntity?> 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<LibraryEntity?> 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<IReadOnlyDictionary<Guid, string?>> 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<Deleted> 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<Deleted> 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);
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -326,9 +326,7 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
|
||||
.WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
|
||||
role.RuleFor(r => r!.Category)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty)
|
||||
.MaximumLength(50)
|
||||
.WithError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong);
|
||||
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.DTO.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a media contributor role.
|
||||
/// Data transfer object for the role of a media contributor in a media item.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the role assigned to the media contributor.</param>
|
||||
/// <param name="Category">The category of the role.</param>
|
||||
/// <param name="Name">The display name of the role assigned to the media contributor.</param>
|
||||
/// <param name="Category">The canonical category of the role.</param>
|
||||
[DebuggerDisplay("Name: {Name}, Category: {Category}")]
|
||||
public record MediaContributorRoleDto(
|
||||
string? Name,
|
||||
string? Category
|
||||
MediaContributorRoleCategory? Category
|
||||
);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="BookArtworkEntity"/> entity.
|
||||
/// </summary>
|
||||
public class BookArtworkConfiguration : IEntityTypeConfiguration<BookArtworkEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="BookArtworkEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<BookArtworkEntity> 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<string>()
|
||||
.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<string>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -152,27 +152,15 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
||||
builder.Property(book => book.UpdatedOnUtc)
|
||||
.HasColumnOrder(31);
|
||||
|
||||
//builder.HasMany<ContributorIdModel>()
|
||||
//.WithMany()
|
||||
//.UsingEntity<Dictionary<string, object>>(
|
||||
// "BookContributors",
|
||||
// j => j.HasOne<ContributorIdModel>().WithMany().HasForeignKey("ContributorId"),
|
||||
// j => j.HasOne<BookModel>().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<BookEntity>
|
||||
builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus });
|
||||
}
|
||||
}
|
||||
|
||||
//public class ContributorConfiguration : IEntityTypeConfiguration<ContributorIdModel>
|
||||
//{
|
||||
// public void Configure(EntityTypeBuilder<ContributorIdModel> builder)
|
||||
// {
|
||||
// builder.ToTable("Contributors");
|
||||
// builder.HasKey(c => c.Id);
|
||||
// builder.Property(c => c.Id).ValueGeneratedNever();
|
||||
// }
|
||||
//}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="BookContributorEntity"/> entity.
|
||||
/// </summary>
|
||||
public class BookContributorConfiguration : IEntityTypeConfiguration<BookContributorEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="BookContributorEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<BookContributorEntity> 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<string>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,16 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
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<LibraryEntity>
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="MediaContributorEntity"/> entity.
|
||||
/// </summary>
|
||||
public class MediaContributorConfiguration : IEntityTypeConfiguration<MediaContributorEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="MediaContributorEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<MediaContributorEntity> 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();
|
||||
}
|
||||
}
|
||||
+1566
File diff suppressed because it is too large.
Load diff
+256
@@ -0,0 +1,256 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsIndependentMetadataAndArtworkEnrichment : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<DateTime>(
|
||||
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<Guid>(
|
||||
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<DateTime>(
|
||||
name: "CreatedOnUtc",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(DateTime),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 11)
|
||||
.OldAnnotation("Relational:ColumnOrder", 9);
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "CreatedBy",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 12)
|
||||
.OldAnnotation("Relational:ColumnOrder", 10);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "ArtworkProvidersConfigurationFingerprint",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
maxLength: 64,
|
||||
nullable: true)
|
||||
.Annotation("Relational:ColumnOrder", 10);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "MetadataProvidersConfigurationFingerprint",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
maxLength: 64,
|
||||
nullable: true)
|
||||
.Annotation("Relational:ColumnOrder", 9);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "BookArtwork",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
ArtworkType = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
|
||||
Ordinal = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
FileName = table.Column<string>(type: "TEXT", maxLength: 2048, nullable: true),
|
||||
ContentHash = table.Column<ulong>(type: "INTEGER", nullable: false),
|
||||
Status = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
Provider = table.Column<string>(type: "TEXT", maxLength: 100, nullable: true),
|
||||
LastUpdateUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(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<Guid>(type: "TEXT", nullable: false),
|
||||
BookId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
MediaContributorId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
RoleName = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
|
||||
RoleCategory = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(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<Guid>(type: "TEXT", nullable: false),
|
||||
DisplayName = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false, collation: "NOCASE"),
|
||||
LegalName = table.Column<string>(type: "TEXT", maxLength: 255, nullable: true),
|
||||
Biography = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
|
||||
DateOfBirth = table.Column<DateOnly>(type: "TEXT", nullable: true),
|
||||
DateOfDeath = table.Column<DateOnly>(type: "TEXT", nullable: true),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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<DateTime>(
|
||||
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<Guid>(
|
||||
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<DateTime>(
|
||||
name: "CreatedOnUtc",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(DateTime),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 9)
|
||||
.OldAnnotation("Relational:ColumnOrder", 11);
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "CreatedBy",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 10)
|
||||
.OldAnnotation("Relational:ColumnOrder", 12);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "CoverImagePath",
|
||||
table: "Books",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<Guid>("MediaContributorId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("RoleCategory")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<string>("RoleName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("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<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("Biography")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateOnly?>("DateOfBirth")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateOnly?>("DateOfDeath")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1)
|
||||
.UseCollation("NOCASE");
|
||||
|
||||
b.Property<string>("LegalName")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime?>("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<Guid>("LibraryId")
|
||||
@@ -270,6 +376,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("ArtworkProvidersConfigurationFingerprint")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<bool>("CanDownloadMetadataFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
@@ -283,11 +394,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.ValueGeneratedOnAdd()
|
||||
@@ -304,6 +415,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("MetadataProvidersConfigurationFingerprint")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<bool>("ShouldSaveMetadataInMediaDirectories")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
@@ -320,11 +436,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
.HasColumnOrder(14);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
.HasColumnOrder(13);
|
||||
|
||||
b.Property<Guid>("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<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("ArtworkType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<string>("FileName")
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("LastUpdateUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<int>("Ordinal")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("Provider")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<DateTime?>("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<Guid>("Id")
|
||||
@@ -535,9 +721,6 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(28);
|
||||
|
||||
b.Property<string>("CoverImagePath")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("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");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
|
||||
/// <param name="lastPath">The path of the last retrieved book, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
|
||||
/// <param name="pageSize">The maximum number of books to retrieve.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a page of books needing their artwork resolved, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<BookEntity>>> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of books of the media library identified by <paramref name="libraryId"/> that need their artwork resolved.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are counted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the number of books needing their artwork resolved, or an error.</returns>
|
||||
public async Task<Result<int>> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the enrichment state of the books stored at the provided <paramref name="paths"/> in the media library identified by
|
||||
/// <paramref name="libraryId"/>, so that they are re-enriched, because their content changed since the last scan.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are reset.</param>
|
||||
/// <param name="paths">The file system paths of the books whose enrichment state is reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> ResetEnrichmentStateForPathsAsync(Guid libraryId, IReadOnlyCollection<string> 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<BookArtworkEntity>()
|
||||
.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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>,
|
||||
/// so that they are re-enriched, because the metadata provider configuration of the library changed.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose books are reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the artwork status of all the artwork of the books of the media library identified by <paramref name="libraryId"/>,
|
||||
/// so that they are re-resolved, because the artwork provider configuration of the library changed.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose artwork is reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> ResetArtworkStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
await _luminaDbContext.Set<BookArtworkEntity>()
|
||||
.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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display names of the author of the books identified by the provided <paramref name="bookIds"/>,
|
||||
/// keyed by the Id of the book, or <see langword="null"/> when a book has no author.
|
||||
/// </summary>
|
||||
/// <param name="bookIds">The unique identifiers of the books whose authors are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken)
|
||||
{
|
||||
List<AuthorRow> authorRows = await _luminaDbContext.BookContributors
|
||||
.Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.RoleCategory == MediaContributorRoleCategory.Author)
|
||||
.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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The author row of a book, joining the participation of an author contributor in a book with the display name of the contributor.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book.</param>
|
||||
/// <param name="DisplayName">The display name of the author contributor.</param>
|
||||
private sealed record AuthorRow(Guid BookId, string DisplayName);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book to delete.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Deleted>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a book.
|
||||
/// </summary>
|
||||
|
||||
+24
@@ -145,6 +145,30 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR
|
||||
return page.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the paths of the changed staging results, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<string>>> 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<string> paths = await connection.QueryAsync<string>(command).ConfigureAwait(false);
|
||||
return paths.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the content hashes of the provided media library scan staging results.
|
||||
/// </summary>
|
||||
|
||||
+89
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for media contributors.
|
||||
/// </summary>
|
||||
internal sealed class MediaContributorRepository : IMediaContributorRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaContributorRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public MediaContributorRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new media contributor.
|
||||
/// </summary>
|
||||
/// <param name="contributor">The media contributor to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Created>> InsertAsync(MediaContributorEntity contributor, CancellationToken cancellationToken)
|
||||
{
|
||||
_luminaDbContext.MediaContributors.Add(contributor);
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media contributor whose display name matches the provided <paramref name="displayName"/>, or creates and inserts a new one
|
||||
/// when no contributor with that name exists yet, guaranteeing a single contributor per person.
|
||||
/// </summary>
|
||||
/// <param name="displayName">The name by which the contributor is popularly known.</param>
|
||||
/// <param name="legalName">The optional legal name of the contributor.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the existing or newly created <see cref="MediaContributorEntity"/>, or an error.</returns>
|
||||
public async Task<Result<MediaContributorEntity>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media contributors identified by the provided <paramref name="ids"/>.
|
||||
/// </summary>
|
||||
/// <param name="ids">The unique identifiers of the media contributors to retrieve.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the retrieved <see cref="MediaContributorEntity"/>s, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.MediaContributors
|
||||
.Where(contributor => ids.Contains(contributor.Id))
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -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<LibraryMetadataProviderConfigurationEntity> LibraryMetadataProviderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<LibraryArtworkProviderConfigurationEntity> LibraryArtworkProviderConfigurations { get; set; } = null!;
|
||||
public virtual DbSet<ThemeEntity> Themes { get; set; } = null!;
|
||||
public virtual DbSet<MediaContributorEntity> MediaContributors { get; set; } = null!;
|
||||
public virtual DbSet<BookContributorEntity> BookContributors { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the directory scan fingerprint repository.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the status of the artwork enrichment of a book artwork.
|
||||
/// </summary>
|
||||
public enum ArtworkStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// The artwork of the book has not been resolved yet.
|
||||
/// </summary>
|
||||
Pending,
|
||||
|
||||
/// <summary>
|
||||
/// The artwork of the book has been successfully resolved.
|
||||
/// </summary>
|
||||
Enriched,
|
||||
|
||||
/// <summary>
|
||||
/// The artwork resolution of the book failed.
|
||||
/// </summary>
|
||||
Failed
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the canonical category of the role of a media contributor in a media item.
|
||||
/// The category normalizes the free-form role names returned by the metadata providers, so that roles
|
||||
/// that describe the same kind of contribution, like "Author" and "Writer", are never treated as distinct.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum MediaContributorRoleCategory
|
||||
{
|
||||
/// <summary>
|
||||
/// The role does not fall into any of the known categories.
|
||||
/// </summary>
|
||||
Other,
|
||||
|
||||
/// <summary>
|
||||
/// The contributor created the media item, like a book, a movie, or a piece of music.
|
||||
/// </summary>
|
||||
Author,
|
||||
|
||||
/// <summary>
|
||||
/// The contributor translated the media item into another language.
|
||||
/// </summary>
|
||||
Translator,
|
||||
|
||||
/// <summary>
|
||||
/// The contributor created the illustrations of the media item.
|
||||
/// </summary>
|
||||
Illustrator,
|
||||
|
||||
/// <summary>
|
||||
/// The contributor published the media item.
|
||||
/// </summary>
|
||||
Publisher,
|
||||
|
||||
/// <summary>
|
||||
/// The contributor narrated the media item.
|
||||
/// </summary>
|
||||
Narrator
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum ArtworkType
|
||||
{
|
||||
/// <summary>
|
||||
/// The main artwork of the media library item, like the cover of a book.
|
||||
/// </summary>
|
||||
Cover
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Media contributor error types.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanArtworkEnrichmentJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanProviderConfigurationInvalidationJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+19
-16
@@ -6,11 +6,13 @@ using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Id}: {Name}")]
|
||||
public class MediaContributor : AggregateRoot<MediaContributorId>
|
||||
@@ -20,11 +22,6 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
|
||||
/// </summary>
|
||||
public MediaContributorName Name { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the role of the contributor.
|
||||
/// </summary>
|
||||
public MediaContributorRole Role { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the biography of the contributor.
|
||||
/// </summary>
|
||||
@@ -45,19 +42,19 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the contributor.</param>
|
||||
/// <param name="name">The name of the contributor.</param>
|
||||
/// <param name="role">The role of the contributor.</param>
|
||||
/// <param name="biography">The optional biography of the contributor.</param>
|
||||
/// <param name="dateOfBirth">The optional date of birth of the contributor.</param>
|
||||
/// <param name="dateOfBirth">The optional date of death of the contributor.</param>
|
||||
/// <param name="dateOfDeath">The optional date of death of the contributor.</param>
|
||||
private MediaContributor(
|
||||
MediaContributorId id,
|
||||
MediaContributorName name,
|
||||
MediaContributorRole role,
|
||||
Optional<string> biography,
|
||||
Optional<DateOnly> dateOfBirth,
|
||||
Optional<DateOnly> dateOfDeath) : base(id)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
Role = role;
|
||||
Biography = biography;
|
||||
DateOfBirth = dateOfBirth;
|
||||
DateOfDeath = dateOfDeath;
|
||||
}
|
||||
@@ -69,9 +66,12 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
|
||||
/// <returns>The created <see cref="MediaContributor"/> instance.</returns>
|
||||
public static Result<MediaContributor> Create(MediaContributorName name)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
throw new NotImplementedException();
|
||||
//return new MediaContributor(id, name);
|
||||
return new MediaContributor(
|
||||
MediaContributorId.CreateUnique(),
|
||||
name,
|
||||
Optional<string>.None(),
|
||||
Optional<DateOnly>.None(),
|
||||
Optional<DateOnly>.None());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -79,14 +79,17 @@ public class MediaContributor : AggregateRoot<MediaContributorId>
|
||||
/// </summary>
|
||||
/// <param name="id">The unique identifier of the contributor.</param>
|
||||
/// <param name="name">The name of the contributor.</param>
|
||||
/// <param name="biography">The optional biography of the contributor.</param>
|
||||
/// <param name="dateOfBirth">The optional date of birth of the contributor.</param>
|
||||
/// <param name="dateOfDeath">The optional date of death of the contributor.</param>
|
||||
/// <returns>The created <see cref="MediaContributor"/> instance.</returns>
|
||||
public static Result<MediaContributor> Create(
|
||||
MediaContributorId id,
|
||||
MediaContributorName name,
|
||||
MediaContributorRole role,
|
||||
Optional<string> biography,
|
||||
Optional<DateOnly> dateOfBirth,
|
||||
Optional<DateOnly> dateOfDeath)
|
||||
{
|
||||
return new MediaContributor(id, name, role, dateOfBirth, dateOfDeath);
|
||||
return new MediaContributor(id, name, biography, dateOfBirth, dateOfDeath);
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -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
|
||||
/// <returns>The created <see cref="MediaContributorName"/> instance.</returns>
|
||||
public static Result<MediaContributorName> Create(string displayName, Optional<string> legalName)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
if (string.IsNullOrWhiteSpace(displayName))
|
||||
return Errors.MediaContributors.MediaContributorNameCannotBeEmpty;
|
||||
|
||||
return new MediaContributorName(displayName, legalName);
|
||||
}
|
||||
|
||||
|
||||
+24
-16
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{DisplayName}")]
|
||||
public sealed class MediaContributorRole : ValueObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the value representing this object.
|
||||
/// Gets the display name of the role.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
public string DisplayName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the category of this object.
|
||||
/// Gets the canonical category of the role.
|
||||
/// </summary>
|
||||
public string Category { get; }
|
||||
public MediaContributorRoleCategory Category { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaContributorRole"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The value representing this object.</param>
|
||||
/// <param name="category">The category of this object.</param>
|
||||
private MediaContributorRole(string name, string category)
|
||||
/// <param name="displayName">The display name of the role.</param>
|
||||
/// <param name="category">The canonical category of the role.</param>
|
||||
private MediaContributorRole(string displayName, MediaContributorRoleCategory category)
|
||||
{
|
||||
Name = name;
|
||||
DisplayName = displayName;
|
||||
Category = category;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="MediaContributorRole"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// Creates a new instance of the <see cref="MediaContributorRole"/> class, from a display <paramref name="displayName"/> and its canonical <paramref name="category"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">The value representing this object.</param>
|
||||
/// <param name="category">The category of this object.</param>
|
||||
/// <param name="displayName">The display name of the role.</param>
|
||||
/// <param name="category">The canonical category of the role.</param>
|
||||
/// <returns>The created <see cref="MediaContributorRole"/> instance.</returns>
|
||||
public static MediaContributorRole Create(string name, string category)
|
||||
public static Result<MediaContributorRole> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -51,7 +59,7 @@ public sealed class MediaContributorRole : ValueObject
|
||||
/// <returns>A list of items defining the equality.</returns>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Name;
|
||||
yield return DisplayName;
|
||||
yield return Category;
|
||||
}
|
||||
}
|
||||
+8
-55
@@ -38,21 +38,6 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
/// </summary>
|
||||
public string Path { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status of the metadata enrichment of the book.
|
||||
/// </summary>
|
||||
public MetadataStatus MetadataStatus { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the date and time when the metadata of the book was last enriched, if applicable.
|
||||
/// </summary>
|
||||
public Optional<DateTime> LastMetadataUpdateUtc { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the plugin that enriched the metadata of the book, if applicable.
|
||||
/// </summary>
|
||||
public Optional<string> MetadataProvider { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the format of the book (e.g., Hardcover, Paperback), if applicable.
|
||||
/// </summary>
|
||||
@@ -118,11 +103,6 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
/// </summary>
|
||||
public Optional<string> AppleBooksId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file system path of the cover image of the book, if applicable.
|
||||
/// </summary>
|
||||
public Optional<string> CoverImagePath { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of ISBN (International Standard Book Number) of the book.
|
||||
/// </summary>
|
||||
@@ -191,9 +171,6 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
LibraryId = libraryId;
|
||||
Path = path;
|
||||
Metadata = metadata;
|
||||
MetadataStatus = MetadataStatus.Pending;
|
||||
LastMetadataUpdateUtc = Optional<DateTime>.None();
|
||||
MetadataProvider = Optional<string>.None();
|
||||
Format = format;
|
||||
Edition = edition;
|
||||
VolumeNumber = volumeNumber;
|
||||
@@ -207,7 +184,6 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
GoogleBooksId = googleBooksId;
|
||||
BarnesAndNobleId = barnesAndNobleId;
|
||||
AppleBooksId = appleBooksId;
|
||||
CoverImagePath = Optional<string>.None();
|
||||
CreatedOnUtc = createdOnUtc;
|
||||
UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null;
|
||||
_isbns = isbns;
|
||||
@@ -368,36 +344,18 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the metadata of the book as enriched by the provided <paramref name="providerName"/>.
|
||||
/// Replaces the media contributors of the book with the provided <paramref name="contributors"/>, identified by their unique identifiers.
|
||||
/// </summary>
|
||||
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
|
||||
/// <param name="lastUpdateUtc">The date and time when the metadata of the book was enriched.</param>
|
||||
public void MarkMetadataAsEnriched(string providerName, DateTime lastUpdateUtc)
|
||||
/// <param name="contributors">The unique identifiers of the media contributors of the book.</param>
|
||||
public void UpdateContributors(IReadOnlyCollection<MediaContributorId> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the metadata enrichment of the book as failed.
|
||||
/// </summary>
|
||||
public void MarkMetadataAsFailed()
|
||||
{
|
||||
MetadataStatus = MetadataStatus.Failed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the file system path of the cover image of the book.
|
||||
/// </summary>
|
||||
/// <param name="coverImagePath">The file system path of the cover image of the book.</param>
|
||||
public void SetBookCoverImagePath(string coverImagePath)
|
||||
{
|
||||
CoverImagePath = coverImagePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the enriched <paramref name="metadata"/> and the related fields to the book, marking its metadata as enriched by the provided <paramref name="providerName"/>.
|
||||
/// Applies the enriched <paramref name="metadata"/> and the related fields to the book.
|
||||
/// </summary>
|
||||
/// <param name="metadata">The enriched metadata of the book.</param>
|
||||
/// <param name="format">The optional format of the book.</param>
|
||||
@@ -415,8 +373,6 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
/// <param name="appleBooksId">The optional Apple Books ID of the book.</param>
|
||||
/// <param name="isbns">The list of ISBNs of the book.</param>
|
||||
/// <param name="ratings">The list of ratings for the book.</param>
|
||||
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
|
||||
/// <param name="lastUpdateUtc">The date and time when the metadata was enriched.</param>
|
||||
public void ApplyEnrichedMetadata(
|
||||
WrittenContentMetadata metadata,
|
||||
Optional<BookFormat> format,
|
||||
@@ -433,9 +389,7 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
Optional<string> barnesAndNobleId,
|
||||
Optional<string> appleBooksId,
|
||||
List<Isbn> isbns,
|
||||
List<BookRating> ratings,
|
||||
string providerName,
|
||||
DateTime lastUpdateUtc)
|
||||
List<BookRating> ratings)
|
||||
{
|
||||
Metadata = metadata;
|
||||
Format = format;
|
||||
@@ -456,6 +410,5 @@ public sealed class Book : AggregateRoot<BookId>
|
||||
_isbns.AddRange(isbns);
|
||||
_ratings.Clear();
|
||||
_ratings.AddRange(ratings);
|
||||
MarkMetadataAsEnriched(providerName, lastUpdateUtc);
|
||||
}
|
||||
}
|
||||
+16
-5
@@ -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<IMediaLibraryScanProviderConfigurationInvalidationJob>(libraryId);
|
||||
IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob);
|
||||
mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob);
|
||||
IMediaLibraryScanArtworkEnrichmentJob mediaLibraryScanArtworkEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(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;
|
||||
|
||||
@@ -99,7 +99,9 @@ public static class InfrastructureLayerServices
|
||||
services.AddTransient<IMediaLibraryScanDiffJob, MediaLibraryScanDiffJob>();
|
||||
services.AddTransient<IMediaLibraryScanHashJob, MediaLibraryScanHashJob>();
|
||||
services.AddTransient<IMediaLibraryScanResultsSaveJob, MediaLibraryScanResultsSaveJob>();
|
||||
services.AddTransient<IMediaLibraryScanProviderConfigurationInvalidationJob, MediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
services.AddTransient<IMediaLibraryScanMetadataEnrichmentJob, MediaLibraryScanMetadataEnrichmentJob>();
|
||||
services.AddTransient<IMediaLibraryScanArtworkEnrichmentJob, MediaLibraryScanArtworkEnrichmentJob>();
|
||||
|
||||
|
||||
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
|
||||
|
||||
+412
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<MediaLibraryScanArtworkEnrichmentJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while resolving the artwork.</param>
|
||||
public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanArtworkEnrichmentJob> logger)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<LibraryEntity?> 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<IArtworkProvider> artworkProviders = [];
|
||||
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
|
||||
{
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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<IArtworkProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
|
||||
.GetKeyedServices<IArtworkProvider>(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<IBookArtworkService>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
Result<int> 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<Success> 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<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
|
||||
IReadOnlyList<BookEntity> 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<IReadOnlyDictionary<Guid, string?>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the cover artwork of the provided <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, 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.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="authorsDisplayNamesByBookId">The display names of the authors of the books of the current page, keyed by the Id of the book.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary<Guid, string?> 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<string> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
|
||||
/// returning the artwork of the first provider that returns it.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The resolved artwork and the provider that supplied it, or <see langword="null"/> when no provider returned usable artwork.</returns>
|
||||
private static async Task<ResolvedArtwork?> ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cover artwork entity for the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book the artwork belongs to.</param>
|
||||
/// <param name="status">The status of the artwork enrichment.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork, if the artwork has been resolved.</param>
|
||||
/// <param name="contentHash">The content hash of the stored artwork.</param>
|
||||
/// <param name="provider">The name of the plugin that resolved the artwork, if applicable.</param>
|
||||
/// <param name="lastUpdateUtc">The date and time when the artwork was resolved, if applicable.</param>
|
||||
/// <returns>The created cover artwork entity.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The artwork resolved for a book, along with the provider that supplied it.
|
||||
/// </summary>
|
||||
/// <param name="Artwork">The resolved artwork of the book.</param>
|
||||
/// <param name="ProviderName">The name of the provider that supplied the artwork.</param>
|
||||
private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName);
|
||||
}
|
||||
+105
-119
@@ -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
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
|
||||
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<LibraryEntity?> 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<IArtworkProvider> artworkProviders = [];
|
||||
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
|
||||
{
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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<IArtworkProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
|
||||
.GetKeyedServices<IArtworkProvider>(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<IBookArtworkService>();
|
||||
|
||||
// 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<string, MediaContributorEntity> 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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enriches the metadata and the artwork of the provided <paramref name="bookEntity"/>, using the provided metadata and artwork providers in their configured order.
|
||||
/// Enriches the metadata of the provided <paramref name="bookEntity"/>, using the provided metadata providers in their configured order,
|
||||
/// linking the media contributors discovered while enriching to the book.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose metadata and artwork are enriched.</param>
|
||||
/// <param name="bookEntity">The book whose metadata is enriched.</param>
|
||||
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="bookRepository">The repository used to persist the enriched book.</param>
|
||||
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
|
||||
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken)
|
||||
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> 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<Book> 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<Updated> 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<Updated> 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<BookContributorEntity> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the media contributor with the name of the provided <paramref name="contributor"/>, 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.
|
||||
/// </summary>
|
||||
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
|
||||
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
|
||||
/// <param name="contributor">The contributor to find or create.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The found or created media contributor.</returns>
|
||||
private async Task<MediaContributorEntity> FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken)
|
||||
{
|
||||
string displayName = contributor.Name!.DisplayName!;
|
||||
string normalizedDisplayName = displayName.ToLowerInvariant();
|
||||
|
||||
if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor))
|
||||
return cachedContributor;
|
||||
|
||||
Result<MediaContributorEntity> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -299,8 +322,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
|
||||
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The applied metadata, or <see langword="null"/> when no provider returned usable metadata.</returns>
|
||||
private static async Task<BookMetadataDto?> TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
|
||||
/// <returns>The applied metadata and the provider that supplied it, or <see langword="null"/> when no provider returned usable metadata.</returns>
|
||||
private static async Task<ResolvedMetadata?> TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> 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<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow);
|
||||
Result<Success> 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
|
||||
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
|
||||
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The applied aggregated metadata, or <see langword="null"/> when no provider returned usable metadata.</returns>
|
||||
private static async Task<BookMetadataDto?> AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
|
||||
/// <returns>The applied aggregated metadata and the providers that contributed to it, or <see langword="null"/> when no provider returned usable metadata.</returns>
|
||||
private static async Task<ResolvedMetadata?> AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
|
||||
{
|
||||
BookMetadataDto? mergedMetadata = null;
|
||||
List<string> contributingProviders = [];
|
||||
@@ -358,52 +381,8 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
if (mergedMetadata is null)
|
||||
return null;
|
||||
|
||||
Result<Success> applyMetadataResult = book.ApplyMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)), DateTime.UtcNow);
|
||||
return applyMetadataResult.IsFailure ? null : mergedMetadata;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the <paramref name="book"/> from the <paramref name="artworkProviders"/>, in their configured order, storing the artwork of the first provider that returns it.
|
||||
/// </summary>
|
||||
/// <param name="book">The book whose artwork is enriched.</param>
|
||||
/// <param name="appliedMetadata">The metadata applied to the book, used to build the directory of the book artwork.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private static async Task EnrichBookArtworkAsync(Book book, BookMetadataDto appliedMetadata, IReadOnlyList<IArtworkProvider> 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<string> 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<Success> applyMetadataResult = book.ApplyMetadata(mergedMetadata);
|
||||
return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -455,4 +434,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The metadata resolved for a book, along with the providers that supplied it.
|
||||
/// </summary>
|
||||
/// <param name="Metadata">The resolved metadata of the book.</param>
|
||||
/// <param name="ProviderName">The name of the provider, or the providers, that supplied the metadata.</param>
|
||||
private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName);
|
||||
}
|
||||
+183
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : MediaLibraryScanJob, IMediaLibraryScanProviderConfigurationInvalidationJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// 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.
|
||||
/// </param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while invalidating the enrichment state.</param>
|
||||
public MediaLibraryScanProviderConfigurationInvalidationJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> logger)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(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<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
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<Success> 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<LibraryEntity?> 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<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getMetadataConfigurationsResult.IsFailure)
|
||||
throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description);
|
||||
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> 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<UserSettingsEntity?> 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<Updated> 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<Updated> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<MediaLibraryScanJobProgress> 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;
|
||||
}
|
||||
}
|
||||
+13
@@ -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<IReadOnlyList<string>> 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<Updated> 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<Updated> 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)
|
||||
{
|
||||
|
||||
+64
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class ProviderConfigurationFingerprint
|
||||
{
|
||||
/// <summary>
|
||||
/// Computes the fingerprint of the metadata provider configuration of a media library.
|
||||
/// </summary>
|
||||
/// <param name="configurations">The metadata provider configurations of the media library.</param>
|
||||
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the books is aggregated from multiple providers, when fields are missing.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the media library permits downloading data from the web.</param>
|
||||
/// <returns>The fingerprint of the metadata provider configuration.</returns>
|
||||
public static string ComputeMetadataFingerprint(IReadOnlyList<LibraryMetadataProviderConfigurationEntity> 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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the fingerprint of the artwork provider configuration of a media library.
|
||||
/// </summary>
|
||||
/// <param name="configurations">The artwork provider configurations of the media library.</param>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the media library permits downloading data from the web.</param>
|
||||
/// <returns>The fingerprint of the artwork provider configuration.</returns>
|
||||
public static string ComputeArtworkFingerprint(IReadOnlyList<LibraryArtworkProviderConfigurationEntity> 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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the fingerprint of the provided canonical representation, by hashing it.
|
||||
/// </summary>
|
||||
/// <param name="canonicalRepresentation">The canonical representation of the configuration.</param>
|
||||
/// <returns>The fingerprint of the canonical representation.</returns>
|
||||
private static string ComputeFingerprint(string canonicalRepresentation)
|
||||
{
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(canonicalRepresentation);
|
||||
ulong hash = XxHash64.HashToUInt64(bytes);
|
||||
return hash.ToString("X16", CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,21 @@ internal class FileHashService : IFileHashService
|
||||
return outputFiles;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the content hash of the file stored at <paramref name="filePath"/>, by sampling chunks from it.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path of the file to hash.</param>
|
||||
/// <returns>The content hash of the file.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes content hash using memory-mapped sampling.
|
||||
/// </summary>
|
||||
|
||||
+5
-5
@@ -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<AddBookEndpoint, AddBookRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "author",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Author
|
||||
)
|
||||
),
|
||||
new(
|
||||
@@ -109,7 +110,7 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "illustrator",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Illustrator
|
||||
)
|
||||
)
|
||||
],
|
||||
@@ -252,7 +253,7 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "author",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Author
|
||||
)
|
||||
),
|
||||
new(
|
||||
@@ -262,7 +263,7 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "illustrator",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Illustrator
|
||||
)
|
||||
)
|
||||
],
|
||||
@@ -391,7 +392,6 @@ public class AddLibraryEndpointSummary : Summary<AddBookEndpoint, AddBookRequest
|
||||
"RoleNameCannotBeEmpty",
|
||||
"RoleNameMustBeMaximum50CharactersLong",
|
||||
"RoleCategoryCannotBeEmpty",
|
||||
"RoleCategoryMustBeMaximum50CharactersLong",
|
||||
"RatingsListCannotBeNull",
|
||||
"RatingValueMustBePositive",
|
||||
"RatingValueCannotBeGreaterThanMaxValue",
|
||||
|
||||
+5
-4
@@ -7,6 +7,7 @@ using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.B
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -122,7 +123,7 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "author",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Author
|
||||
)
|
||||
),
|
||||
new(
|
||||
@@ -132,7 +133,7 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "illustrator",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Illustrator
|
||||
)
|
||||
)
|
||||
],
|
||||
@@ -229,7 +230,7 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "author",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Author
|
||||
)
|
||||
),
|
||||
new(
|
||||
@@ -239,7 +240,7 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest
|
||||
),
|
||||
Role: new MediaContributorRoleDto(
|
||||
Name: "illustrator",
|
||||
Category: "book"
|
||||
Category: MediaContributorRoleCategory.Illustrator
|
||||
)
|
||||
)
|
||||
],
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>حفظ بيانات الفحص...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>إبطال التخصيب القديم...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>جاري حل العمل الفني...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>الفحص</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Scandaten werden gespeichert...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Ungültigmachen veralteter Anreicherungen...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Artwork wird aufgelöst...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Scannen</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Saving scan data...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Invalidating stale enrichment...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Resolving artwork...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Scan</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Guardando datos del escaneo...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Invalidando el enriquecimiento obsoleto...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Resolviendo la carátula...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Escanear</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Sauvegarde des données de scan en cours...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Invalidation de l'enrichissement obsolète...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Résolution de l'illustration...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Scanner</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Salvataggio dei dati di scansione...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Invalidazione dell'arricchimento obsoleto...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Risoluzione della copertina...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Scansiona</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>スキャンデータを保存中...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>古い補完を無効化しています...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>アートワークを取得しています...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>スキャン</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Saving scan data...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Invalidating stale enrichment...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Resolving artwork...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Scan</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Se salvează datele de scanare...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Se invalidează îmbogățirea învechită...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Se rezolvă coperta...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Scanează</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Збереження даних сканування...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>Інвалідація застарілого збагачення...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>Вирішення зображення...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>Сканувати</value>
|
||||
</data>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>正在保存扫描数据...</value>
|
||||
</data>
|
||||
<data name="InvalidatingStaleEnrichment" xml:space="preserve">
|
||||
<value>正在使过期的补全失效...</value>
|
||||
</data>
|
||||
<data name="ResolvingArtwork" xml:space="preserve">
|
||||
<value>正在获取封面图...</value>
|
||||
</data>
|
||||
<data name="Scan" xml:space="preserve">
|
||||
<value>扫描</value>
|
||||
</data>
|
||||
|
||||
@@ -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"]',
|
||||
|
||||
+60
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookContributorEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookContributorEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="BookContributorEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the participation.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book the contributor participated in.</param>
|
||||
/// <param name="mediaContributorId">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="roleName">Optional. The display name of the role the contributor played in the book.</param>
|
||||
/// <param name="roleCategory">Optional. The canonical category of the role the contributor played in the book.</param>
|
||||
/// <returns>The created <see cref="BookContributorEntity"/>.</returns>
|
||||
public BookContributorEntity Create(
|
||||
Guid? id = null,
|
||||
Guid? bookId = null,
|
||||
Guid? mediaContributorId = null,
|
||||
string? roleName = null,
|
||||
MediaContributorRoleCategory? roleCategory = null)
|
||||
{
|
||||
return new BookContributorEntity
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
BookId = bookId ?? Guid.NewGuid(),
|
||||
MediaContributorId = mediaContributorId ?? Guid.NewGuid(),
|
||||
RoleName = roleName ?? _faker.Lorem.Word(),
|
||||
RoleCategory = roleCategory ?? _faker.PickRandom<MediaContributorRoleCategory>(),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="BookContributorEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="BookContributorEntity"/> instances.</returns>
|
||||
public List<BookContributorEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributorEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaContributorEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the media contributor.</param>
|
||||
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
|
||||
/// <param name="legalName">Optional. The legal name of the contributor.</param>
|
||||
/// <param name="biography">Optional. The biography of the contributor.</param>
|
||||
/// <param name="dateOfBirth">Optional. The date of birth of the contributor.</param>
|
||||
/// <param name="dateOfDeath">Optional. The date of death of the contributor.</param>
|
||||
/// <returns>The created <see cref="MediaContributorEntity"/>.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MediaContributorEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaContributorEntity"/> instances.</returns>
|
||||
public List<MediaContributorEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -30,6 +30,8 @@ public class LibraryEntityFixture
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
|
||||
/// <param name="metadataProvidersConfigurationFingerprint">Optional. The fingerprint of the metadata provider configuration of the media library.</param>
|
||||
/// <param name="artworkProvidersConfigurationFingerprint">Optional. The fingerprint of the artwork provider configuration of the media library.</param>
|
||||
/// <returns>The created media library entity.</returns>
|
||||
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<LibraryEntity>()
|
||||
.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,
|
||||
|
||||
+73
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="BookArtworkEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookArtworkEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="BookArtworkEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the artwork.</param>
|
||||
/// <param name="bookId">Optional. The Id of the book the artwork belongs to.</param>
|
||||
/// <param name="artworkType">Optional. The type of the artwork.</param>
|
||||
/// <param name="ordinal">Optional. The ordinal of the artwork within its type.</param>
|
||||
/// <param name="fileName">Optional. The relative file name of the stored artwork.</param>
|
||||
/// <param name="contentHash">Optional. The content hash of the stored artwork.</param>
|
||||
/// <param name="status">Optional. The status of the artwork enrichment.</param>
|
||||
/// <param name="provider">Optional. The name of the plugin that resolved the artwork.</param>
|
||||
/// <param name="lastUpdateUtc">Optional. The date and time when the artwork was last resolved.</param>
|
||||
/// <returns>The created <see cref="BookArtworkEntity"/>.</returns>
|
||||
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<ArtworkStatus>(),
|
||||
Provider = provider ?? _faker.Company.CompanyName(),
|
||||
LastUpdateUtc = lastUpdateUtc ?? _faker.Date.Recent(),
|
||||
CreatedOnUtc = _faker.Date.Past(),
|
||||
CreatedBy = Guid.NewGuid(),
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="BookArtworkEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="BookArtworkEntity"/> instances.</returns>
|
||||
public List<BookArtworkEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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<MediaContributorRoleCategory>());
|
||||
|
||||
Faker<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
|
||||
.CustomInstantiator(f => new MediaContributorNameDto(
|
||||
|
||||
+5
-4
@@ -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
|
||||
/// <param name="roleCategory">Optional. The category of the role.</param>
|
||||
/// <returns>The created <see cref="MediaContributorDto"/>.</returns>
|
||||
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<MediaContributorRoleCategory>()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+4
-3
@@ -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
|
||||
/// <param name="category">Optional. The category of the role.</param>
|
||||
/// <returns>The created <see cref="MediaContributorRoleDto"/>.</returns>
|
||||
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<MediaContributorRoleCategory>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+2
-1
@@ -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<MediaContributorRoleCategory>());
|
||||
|
||||
Faker<MediaContributorNameDto> mediaContributorName = new Faker<MediaContributorNameDto>()
|
||||
.CustomInstantiator(f => new MediaContributorNameDto(
|
||||
|
||||
+2
-1
@@ -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<MediaContributorRoleCategory>()))],
|
||||
[new BookRatingDto(_faker.Random.Decimal(1m, 5m), 5m, BookRatingSource.Goodreads, _faker.Random.Int(1, 1000))],
|
||||
metadataStatus ?? _faker.PickRandom<MetadataStatus>(),
|
||||
_faker.Date.Recent().ToUniversalTime(),
|
||||
|
||||
+60
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaContributor"/> domain aggregate.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorFixture
|
||||
{
|
||||
private readonly MediaContributorIdFixture _mediaContributorIdFixture = new();
|
||||
private readonly MediaContributorNameFixture _mediaContributorNameFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MediaContributor"/> domain aggregate.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the contributor.</param>
|
||||
/// <param name="name">Optional. The name of the contributor.</param>
|
||||
/// <param name="biography">Optional. The biography of the contributor.</param>
|
||||
/// <param name="dateOfBirth">Optional. The date of birth of the contributor.</param>
|
||||
/// <param name="dateOfDeath">Optional. The date of death of the contributor.</param>
|
||||
/// <returns>The created <see cref="MediaContributor"/> domain aggregate.</returns>
|
||||
public MediaContributor Create(
|
||||
MediaContributorId? id = null,
|
||||
MediaContributorName? name = null,
|
||||
Optional<string>? biography = null,
|
||||
Optional<DateOnly>? dateOfBirth = null,
|
||||
Optional<DateOnly>? dateOfDeath = null)
|
||||
{
|
||||
Result<MediaContributor> result = MediaContributor.Create(
|
||||
id ?? _mediaContributorIdFixture.Create(),
|
||||
name ?? _mediaContributorNameFixture.Create(),
|
||||
biography ?? Optional<string>.None(),
|
||||
dateOfBirth ?? Optional<DateOnly>.None(),
|
||||
dateOfDeath ?? Optional<DateOnly>.None());
|
||||
|
||||
if (result.IsFailure)
|
||||
throw new InvalidOperationException("Failed to create MediaContributor: " + string.Join(", ", result.Errors));
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MediaContributor"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaContributor"/> instances.</returns>
|
||||
public List<MediaContributor> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -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
|
||||
/// <param name="name">Optional. The name of the role. If not provided, a random name is generated.</param>
|
||||
/// <param name="category">Optional. The category of the role. If not provided, a random category is generated.</param>
|
||||
/// <returns>The created <see cref="MediaContributorRole"/>.</returns>
|
||||
public MediaContributorRole Create(string? name = null, 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<MediaContributorRoleCategory>()).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
-18
@@ -1473,24 +1473,6 @@ public class AddBookEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>
|
||||
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()
|
||||
{
|
||||
|
||||
+2
-1
@@ -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)],
|
||||
|
||||
+4
-8
@@ -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<Success> result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow);
|
||||
Result<Success> 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<Success> result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow);
|
||||
Result<Success> 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);
|
||||
}
|
||||
}
|
||||
+218
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="LibraryMediaItemDeletedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class LibraryMediaItemDeletedDomainEventHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ILibraryRepository _mockLibraryRepository;
|
||||
private readonly IBookArtworkService _mockBookArtworkService;
|
||||
private readonly ILogger<LibraryMediaItemDeletedDomainEventHandler> _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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryMediaItemDeletedDomainEventHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public LibraryMediaItemDeletedDomainEventHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
|
||||
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
_mockLogger = Substitute.For<ILogger<LibraryMediaItemDeletedDomainEventHandler>>();
|
||||
|
||||
_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<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Result.Deleted);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenNoBookExistsAtPath_ShouldDoNothing()
|
||||
{
|
||||
// Arrange
|
||||
LibraryId libraryId = _libraryIdFixture.Create();
|
||||
_mockBookRepository.GetByPathAsync(libraryId.Value, "/books/deleted.epub", Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(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<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>());
|
||||
await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Error.Failure("Artwork.DeleteFailed", "Failed to delete the stored artwork"));
|
||||
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.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<EventualConsistencyException>(
|
||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(Result.From<BookEntity?>(book));
|
||||
_mockLibraryRepository.GetByIdAsync(libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockBookArtworkService.DeleteBookArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(Result.Deleted);
|
||||
Error error = Error.Failure("Database.Error", "Failed to delete the book");
|
||||
_mockBookRepository.DeleteAsync(book.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
LibraryMediaItemDeletedDomainEvent domainEvent = new(
|
||||
Guid.NewGuid(),
|
||||
libraryId,
|
||||
MediaLibraryScanCompositeId.Create(_scanIdFixture.Create(), _userIdFixture.Create()),
|
||||
book.Path,
|
||||
DateTime.UtcNow);
|
||||
|
||||
// Act
|
||||
EventualConsistencyException exception = await Assert.ThrowsAsync<EventualConsistencyException>(
|
||||
() => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(error, exception.EventualConsistencyError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
-14
@@ -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<Error> result = _validator.TestValidate(bookCommand);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError()
|
||||
{
|
||||
|
||||
+2
-1
@@ -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
|
||||
|
||||
+2
-1
@@ -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);
|
||||
|
||||
+2
-1
@@ -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"
|
||||
);
|
||||
|
||||
+236
@@ -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<IReadOnlyList<BookEntity>> 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<int> 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<LuminaDbContext>().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<Updated> 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<LuminaDbContext>().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<Updated> 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<LuminaDbContext>().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<Updated> result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Updated, result.Value);
|
||||
BookArtworkEntity? resetArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id);
|
||||
Assert.NotNull(resetArtwork);
|
||||
Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status);
|
||||
BookArtworkEntity? keptArtwork = await context.Set<BookArtworkEntity>().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<IReadOnlyDictionary<Guid, string?>> 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<Deleted> result = await _sut.DeleteAsync(book.Id, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
EntityEntry<BookEntity>? deletedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
|
||||
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == book.Id);
|
||||
Assert.NotNull(deletedBook);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError()
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
|
||||
}
|
||||
}
|
||||
+115
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaContributorRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaContributorRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly MediaContributorRepository _sut;
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaContributorRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public MediaContributorRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_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<MediaContributorEntity> 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<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindOrCreateByDisplayNameAsync_WhenContributorDoesNotExist_ShouldCreateAndAddANewContributor()
|
||||
{
|
||||
// Arrange
|
||||
string displayName = "Frank Herbert";
|
||||
|
||||
// Act
|
||||
Result<MediaContributorEntity> 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<MediaContributorEntity>? addedContributor = _mockContext.ChangeTracker.Entries<MediaContributorEntity>()
|
||||
.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<MediaContributorEntity> 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<MediaContributorEntity>());
|
||||
}
|
||||
|
||||
[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<IReadOnlyList<MediaContributorEntity>> 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);
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
+33
-10
@@ -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<string>.Some("Jane Doe Smith"));
|
||||
MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
Optional<string> biography = Optional<string>.Some("A well-known author.");
|
||||
Optional<DateOnly> dateOfBirth = Optional<DateOnly>.Some(new DateOnly(1980, 1, 1));
|
||||
Optional<DateOnly> dateOfDeath = Optional<DateOnly>.None();
|
||||
|
||||
// Act
|
||||
Result<MediaContributor> result = MediaContributor.Create(id, name, role, dateOfBirth, dateOfDeath);
|
||||
Result<MediaContributor> 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<string>.None());
|
||||
MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew");
|
||||
|
||||
// Act
|
||||
Result<MediaContributor> result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, role, Optional<DateOnly>.None(), Optional<DateOnly>.None());
|
||||
Result<MediaContributor> result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, Optional<string>.None(), Optional<DateOnly>.None(), Optional<DateOnly>.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<string>.None());
|
||||
|
||||
// Act & Assert
|
||||
Assert.Throws<NotImplementedException>(() => MediaContributor.Create(name));
|
||||
// Act
|
||||
Result<MediaContributor> 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"));
|
||||
}
|
||||
}
|
||||
+26
-11
@@ -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<MediaContributorRole> 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<MediaContributorRole> result = MediaContributorRole.Create(" ", MediaContributorRoleCategory.Author);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equals_WithSameValues_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "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);
|
||||
|
||||
+44
-14
@@ -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);
|
||||
}
|
||||
}
|
||||
+17
-4
@@ -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<IMediaLibraryScanDiffJob>();
|
||||
TestScanJob hashJob = CreateJob<IMediaLibraryScanHashJob>();
|
||||
TestScanJob saveJob = CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
TestScanJob invalidationJob = CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
TestScanJob enrichmentJob = CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
TestScanJob artworkEnrichmentJob = CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
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<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -77,7 +84,9 @@ public class BookLibraryTypeScannerTests
|
||||
CreateJob<IMediaLibraryScanDiffJob>();
|
||||
CreateJob<IMediaLibraryScanHashJob>();
|
||||
CreateJob<IMediaLibraryScanResultsSaveJob>();
|
||||
CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>();
|
||||
CreateJob<IMediaLibraryScanMetadataEnrichmentJob>();
|
||||
CreateJob<IMediaLibraryScanArtworkEnrichmentJob>();
|
||||
BookLibraryTypeScanner sut = new(_mockJobFactory);
|
||||
|
||||
// Act
|
||||
@@ -88,7 +97,9 @@ public class BookLibraryTypeScannerTests
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
|
||||
_mockJobFactory.Received(1).CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
|
||||
}
|
||||
|
||||
private TestScanJob CreateJob<TJob>() where TJob : class, IMediaLibraryScanJob
|
||||
@@ -111,7 +122,9 @@ public class BookLibraryTypeScannerTests
|
||||
IMediaLibraryScanDiffJob,
|
||||
IMediaLibraryScanHashJob,
|
||||
IMediaLibraryScanResultsSaveJob,
|
||||
IMediaLibraryScanMetadataEnrichmentJob
|
||||
IMediaLibraryScanProviderConfigurationInvalidationJob,
|
||||
IMediaLibraryScanMetadataEnrichmentJob,
|
||||
IMediaLibraryScanArtworkEnrichmentJob
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
|
||||
+299
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
|
||||
/// </summary>
|
||||
[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<MediaLibraryScanArtworkEnrichmentJob> _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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanArtworkEnrichmentJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanArtworkEnrichmentJob>>();
|
||||
|
||||
_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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [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<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [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<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((ArtworkDto?)null);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
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<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="artworkPluginId">The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="artworkProvider">The artwork provider to resolve.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the books.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider.
|
||||
/// </summary>
|
||||
/// <param name="book">The book whose artwork the job must resolve.</param>
|
||||
/// <param name="artworkPluginId">The Id of the plugin configured as artwork provider for the library.</param>
|
||||
private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId)
|
||||
{
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
}
|
||||
+122
-165
@@ -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<MediaLibraryScanMetadataEnrichmentJob> _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<IUnitOfWork>();
|
||||
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
|
||||
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
|
||||
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
@@ -125,7 +133,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -145,8 +153,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.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<IMetadataProvider>();
|
||||
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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.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<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(authorEntity));
|
||||
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(translatorEntity));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any<string?>(), Arg.Any<CancellationToken>());
|
||||
|
||||
// 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<IMetadataProvider>();
|
||||
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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([
|
||||
_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)
|
||||
]));
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
.Returns(Result.From(2));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([firstBook, secondBook]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<BookEntity>(entity => entity.MetadataStatus == MetadataStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.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<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.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<string?>(), Arg.Any<CancellationToken>())
|
||||
.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<BookEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
|
||||
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.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<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_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<string>(),
|
||||
Arg.Any<string>(),
|
||||
"First Title",
|
||||
Arg.Any<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).UpdateAsync(
|
||||
Arg.Is<BookEntity>(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"),
|
||||
Arg.Any<CancellationToken>());
|
||||
// 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<string?>(), Arg.Any<CancellationToken>());
|
||||
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<IMetadataProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.RequiresWebAccess.Returns(false);
|
||||
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_bookMetadataDtoFixture.Create(title: "Local Title"));
|
||||
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Web Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.RequiresWebAccess.Returns(true);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.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<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_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<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
@@ -570,8 +529,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Updated);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
}
|
||||
+291
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
|
||||
/// </summary>
|
||||
[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<MediaLibraryScanProviderConfigurationInvalidationJob> _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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJobTests"/> class.
|
||||
/// </summary>
|
||||
public MediaLibraryScanProviderConfigurationInvalidationJobTests()
|
||||
{
|
||||
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
|
||||
_mockServiceScope = Substitute.For<IServiceScope>();
|
||||
_mockServiceProvider = Substitute.For<IServiceProvider>();
|
||||
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_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<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProviderConfigurationInvalidationJob>>();
|
||||
|
||||
_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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>())
|
||||
.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<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>())
|
||||
.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<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
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<LibraryMetadataProviderConfigurationEntity> metadataConfigurations = _metadataConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
|
||||
List<LibraryArtworkProviderConfigurationEntity> 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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.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<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
|
||||
{
|
||||
// Arrange
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.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<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job reads the provided library and its provider configurations.
|
||||
/// </summary>
|
||||
/// <param name="library">The media library the job must read.</param>
|
||||
/// <param name="metadataConfigurations">The metadata provider configurations of the media library.</param>
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library.</param>
|
||||
private void SetupLibraryAndConfigurations(LibraryEntity library, List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
SetupConfigurations(metadataConfigurations, artworkConfigurations);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the provider configuration repositories and the user settings repository used by the job.
|
||||
/// </summary>
|
||||
/// <param name="metadataConfigurations">The metadata provider configurations of the media library, if already created by the caller.</param>
|
||||
/// <param name="artworkConfigurations">The artwork provider configurations of the media library, if already created by the caller.</param>
|
||||
private void SetupConfigurations(List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
|
||||
{
|
||||
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
|
||||
metadataConfigurations ?? [
|
||||
_metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
|
||||
_metadataConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
|
||||
]));
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
|
||||
artworkConfigurations ?? [
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
|
||||
]));
|
||||
|
||||
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
|
||||
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
|
||||
}
|
||||
}
|
||||
+34
@@ -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<IUnitOfWork>();
|
||||
_mockSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
|
||||
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["deleted.pdf"]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
|
||||
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
@@ -105,18 +113,44 @@ public class MediaLibraryScanResultsSaveJobTests
|
||||
// Assert
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryMediaItemDeletedDomainEvent>(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Is<IReadOnlyCollection<string>>(paths => paths.Any(path => path == "changed.pdf")), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt()
|
||||
{
|
||||
// Arrange
|
||||
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<string>>([]));
|
||||
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Updated));
|
||||
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
|
||||
@@ -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]
|
||||
|
||||
+2
-1
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user