Merge pull request #180 from BinaryAlley/feature/independent-metadata-and-artwork-enrichment

Feature/independent metadata and artwork enrichment
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-27 07:25:06 -07:00
commit 459dab07fe
128 files changed
+6750 -631

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>
@@ -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; }
}
@@ -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; }
}
@@ -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
);
@@ -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
);
@@ -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>
@@ -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; }
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -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
);
}
@@ -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();
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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();
}
}
@@ -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>
@@ -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>
@@ -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
}
@@ -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));
}
}
@@ -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
{
}
@@ -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
{
}
@@ -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);
}
}
@@ -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);
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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>();
@@ -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);
}
@@ -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);
}
@@ -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;
}
}
@@ -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)
{
@@ -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>
@@ -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",
@@ -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
)
)
],
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Plugins;
/// <summary>
/// Data transfer object for an artwork provider configured for a media library.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class LibraryArtworkProviderDto
{
/// <summary>
/// Gets or sets the unique identifier of the plugin providing the artwork.
/// </summary>
public Guid PluginId { get; set; }
/// <summary>
/// Gets or sets the display name of the artwork provider.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets whether the artwork provider is enabled for the media library.
/// </summary>
public bool IsEnabled { get; set; }
/// <summary>
/// Gets or sets the rank of the artwork provider, determining the order in which providers are tried.
/// </summary>
public int Rank { get; set; }
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Library.Management;
/// <summary>
/// Represents the request for retrieving the artwork providers of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose artwork providers are retrieved.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetArtworkProvidersRequest(
Guid LibraryId
);
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Plugins;
/// <summary>
/// Represents a request to reorder the artwork providers of a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public class ReorderLibraryArtworkProvidersRequest
{
/// <summary>
/// Gets or sets the Id of the media library whose artwork providers are reordered.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the plugin Ids in the new order, from highest to lowest rank.
/// </summary>
public List<Guid> PluginIds { get; set; } = [];
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Plugins;
/// <summary>
/// Represents a request to enable or disable an artwork provider for a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
public class SetLibraryArtworkProviderEnabledRequest
{
/// <summary>
/// Gets or sets the Id of the media library whose artwork provider is enabled or disabled.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the plugin providing the artwork.
/// </summary>
public Guid PluginId { get; set; }
/// <summary>
/// Gets or sets whether the artwork provider should be enabled for the media library.
/// </summary>
public bool IsEnabled { get; set; }
}
@@ -24,5 +24,8 @@ public static partial class ApiRoutes
public const string GET_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers";
public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "libraries/{libraryId}/metadata-providers/{pluginId}/enabled";
public const string REORDER_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers/reorder";
public const string GET_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers";
public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers/reorder";
}
}
@@ -25,5 +25,8 @@ public static partial class WebRoutes
public const string GET_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-metadata-providers/{libraryId}";
public const string SET_METADATA_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-metadata-provider-enabled";
public const string REORDER_METADATA_PROVIDERS = "{culture}/libraries/manage/api-reorder-metadata-providers";
public const string GET_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-artwork-providers/{libraryId}";
public const string SET_ARTWORK_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-artwork-provider-enabled";
public const string REORDER_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-reorder-artwork-providers";
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetArtworkProviders;
/// <summary>
/// API endpoint for the <c>/{culture}/libraries/manage/api-get-artwork-providers/{libraryId}</c> route.
/// </summary>
public class GetArtworkProvidersEndpoint : BaseEndpoint<GetArtworkProvidersRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtworkProvidersEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetArtworkProvidersEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS);
DontAutoTag();
Options(options => options.WithTags("Libraries"));
}
/// <summary>
/// Retrieves the artwork providers of a media library.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose artwork providers are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetArtworkProvidersRequest request, CancellationToken cancellationToken)
{
LibraryArtworkProviderDto[] response = await _apiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(ApiRoutes.Libraries.GET_LIBRARY_ARTWORK_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetArtworkProviders;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetArtworkProvidersEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtworkProvidersEndpointSummary : Summary<GetArtworkProvidersEndpoint, GetArtworkProvidersRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtworkProvidersEndpointSummary"/> class.
/// </summary>
public GetArtworkProvidersEndpointSummary()
{
Summary = "Retrieves the artwork providers of a media library.";
Description = "Retrieves the artwork providers of the media library identified by the request.";
RequestParam(r => r.LibraryId, "The unique identifier of the media library whose artwork providers are retrieved.");
Response(200, "The artwork providers of the media library are returned.", example: new SuccessResponse<LibraryArtworkProviderDto[]>(true, default));
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
/// <summary>
/// API endpoint for the <c>/{culture}/libraries/manage/api-reorder-artwork-providers</c> route.
/// </summary>
public class ReorderArtworkProvidersEndpoint : BaseEndpoint<ReorderLibraryArtworkProvidersRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public ReorderArtworkProvidersEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.PUT);
Routes(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS);
DontAutoTag();
Options(options => options.WithTags("Libraries"));
EnableAntiforgery();
}
/// <summary>
/// Reorders the artwork providers of a media library.
/// </summary>
/// <param name="request">The request containing the Id of the media library and the plugin Ids in the new order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, ReorderLibraryArtworkProvidersRequest>(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
/// <summary>
/// Class used for providing a textual description for the <see cref="ReorderArtworkProvidersEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderArtworkProvidersEndpointSummary : Summary<ReorderArtworkProvidersEndpoint, ReorderLibraryArtworkProvidersRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpointSummary"/> class.
/// </summary>
public ReorderArtworkProvidersEndpointSummary()
{
Summary = "Reorders the artwork providers of a media library.";
Description = "Reorders the artwork providers of the media library identified by the request, in the provided order.";
RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required.");
ExampleRequest = new ReorderLibraryArtworkProvidersRequest
{
LibraryId = Guid.NewGuid(),
PluginIds = [Guid.NewGuid(), Guid.NewGuid()]
};
Response(200, "The artwork providers of the media library are reordered.", example: new SuccessResponse(true));
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
/// <summary>
/// API endpoint for the <c>/{culture}/libraries/manage/api-set-artwork-provider-enabled</c> route.
/// </summary>
public class SetArtworkProviderEnabledEndpoint : BaseEndpoint<SetLibraryArtworkProviderEnabledRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public SetArtworkProviderEnabledEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.PUT);
Routes(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED);
DontAutoTag();
Options(options => options.WithTags("Libraries"));
EnableAntiforgery();
}
/// <summary>
/// Enables or disables an artwork provider of a media library.
/// </summary>
/// <param name="request">The request containing the Ids of the media library and of the plugin, and whether the provider is enabled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, SetLibraryArtworkProviderEnabledRequest>(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetArtworkProviderEnabledEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetArtworkProviderEnabledEndpointSummary : Summary<SetArtworkProviderEnabledEndpoint, SetLibraryArtworkProviderEnabledRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpointSummary"/> class.
/// </summary>
public SetArtworkProviderEnabledEndpointSummary()
{
Summary = "Enables or disables an artwork provider of a media library.";
Description = "Enables or disables the artwork provider of the media library identified by the request.";
RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required.");
RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required.");
RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library, or not. Required.");
ExampleRequest = new SetLibraryArtworkProviderEnabledRequest
{
LibraryId = Guid.NewGuid(),
PluginId = Guid.NewGuid(),
IsEnabled = true
};
Response(200, "The artwork provider of the media library is enabled or disabled.", example: new SuccessResponse(true));
}
}
@@ -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>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>مزوّدو البيانات الوصفية المستخدمون لإثراء عناصر هذه المكتبة، بالترتيب الذي يتم تجريبهم به.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Die Metadatenanbieter, die verwendet werden, um die Elemente dieser Bibliothek anzureichern, in der Reihenfolge, in der sie versucht werden.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>The metadata providers used to enrich the items of this library, in the order they are tried.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Los proveedores de metadatos utilizados para enriquecer los elementos de esta biblioteca, en el orden en que se prueban.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Les fournisseurs de métadonnées utilisés pour enrichir les éléments de cette bibliothèque, dans l'ordre où ils sont essayés.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>I fornitori di metadati utilizzati per arricchire gli elementi di questa libreria, nell'ordine in cui vengono provati.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>このライブラリのアイテムを補完するために使用されるメタデータプロバイダーを、試行する順序で指定します。</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>The metadata providers used to enrich the items of this library, in the order they are tried.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Furnizorii de metadate folosiți pentru a îmbogăți elementele acestei biblioteci, în ordinea în care sunt încercați.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Постачальники метаданих, які використовуються для збагачення елементів цієї бібліотеки, у порядку, в якому вони випробовуються.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>用于丰富此库项目内容的元数据提供程序,按其尝试顺序排列。</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -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"]',
@@ -222,6 +222,22 @@
</table>
<small class="form-label text-disabled form-description">@_localizer["DescriptionMetadataProviders"]</small>
</div>
<h3 class="text-light-two">@_localizer["ArtworkProviders"]</h3>
<div class="form-row">
<table id="artwork-providers-table" class="w-100">
<thead>
<tr>
<th class="w-50">@_localizer["Name"]</th>
<th class="w-15 text-center">@_localizer["Enabled"]</th>
<th class="w-35 text-center">@_localizer["Order"]</th>
</tr>
</thead>
<tbody>
<!-- artwork providers will be populated here -->
</tbody>
</table>
<small class="form-label text-disabled form-description">@_localizer["DescriptionArtworkProviders"]</small>
</div>
}
<div class="form-row">
<button type="submit" class="confirm-button w-100px">@_localizer["Save"]</button>
@@ -435,6 +451,77 @@
}
};
const artworkProvidersTable = document.getElementById('artwork-providers-table');
const artworkProvidersTbody = artworkProvidersTable ? artworkProvidersTable.querySelector('tbody') : null;
// loads the artwork providers configured for the library, when editing an existing library
async function loadArtworkProvidersAsync() {
if (!id || !artworkProvidersTbody) return;
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })'
.replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side
const response = await callApiGetAsync(url);
if (response && response.length > 0) {
artworkProvidersTbody.innerHTML = response.map((provider, index) => renderArtworkProviderRow(provider, index, response.length)).join('');
}
}
// renders an artwork provider row of the library
function renderArtworkProviderRow(provider, index, count) {
return `
<tr data-provider-plugin-id="${provider.pluginId}">
<td>${provider.name}</td>
<td class="text-center">
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden artwork-provider-enabled" ${provider.isEnabled ? 'checked' : ''} />
<span class="enlightenment-checkbox"></span>
</label>
</td>
<td class="text-center">
<button type="button" class="artwork-provider-move-up confirm-button f-12 h-20px" ${index === 0 ? 'disabled' : ''}>@_localizer["MoveUp"]</button>
<button type="button" class="artwork-provider-move-down abort-button f-12 h-20px" ${index === count - 1 ? 'disabled' : ''}>@_localizer["MoveDown"]</button>
</td>
</tr>`;
}
// on artwork provider move button click, reorders the providers and persists the new order
async function handleArtworkProviderReorderAsync(e) {
const button = e.target.closest('.artwork-provider-move-up, .artwork-provider-move-down');
if (!button || !artworkProvidersTbody) return;
const row = button.closest('tr');
if (button.classList.contains('artwork-provider-move-up')) {
const previousRow = row.previousElementSibling;
if (previousRow) artworkProvidersTbody.insertBefore(row, previousRow);
} else {
const nextRow = row.nextElementSibling;
if (nextRow) artworkProvidersTbody.insertBefore(nextRow, row);
}
await saveArtworkProviderOrderAsync();
}
// persists the current order of the artwork providers of the library
async function saveArtworkProviderOrderAsync() {
if (!id || !artworkProvidersTbody) return;
const pluginIds = Array.from(artworkProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]'))
.map(row => row.getAttribute('data-provider-plugin-id'));
const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS)', { libraryId: id, pluginIds: pluginIds });
if (result.success) {
notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS);
}
}
// on artwork provider enabled checkbox change, persists the new state
async function handleArtworkProviderEnabledChangeAsync(e) {
if (e.target.matches('.artwork-provider-enabled')) {
const row = e.target.closest('tr');
const pluginId = row.getAttribute('data-provider-plugin-id');
const isEnabled = e.target.checked;
const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled });
if (!result.success) {
e.target.checked = !isEnabled;
}
}
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
@@ -448,6 +535,10 @@
metadataProvidersTbody.addEventListener('click', handleMetadataProviderReorderAsync);
metadataProvidersTbody.addEventListener('change', handleMetadataProviderEnabledChangeAsync);
}
if (artworkProvidersTbody) {
artworkProvidersTbody.addEventListener('click', handleArtworkProviderReorderAsync);
artworkProvidersTbody.addEventListener('change', handleArtworkProviderEnabledChangeAsync);
}
// register cleanup for these listeners
cleanupFunctions.push(() => {
@@ -463,11 +554,16 @@
metadataProvidersTbody.removeEventListener('click', handleMetadataProviderReorderAsync);
metadataProvidersTbody.removeEventListener('change', handleMetadataProviderEnabledChangeAsync);
}
if (artworkProvidersTbody) {
artworkProvidersTbody.removeEventListener('click', handleArtworkProviderReorderAsync);
artworkProvidersTbody.removeEventListener('change', handleArtworkProviderEnabledChangeAsync);
}
});
// load the metadata providers when editing an existing library
// load the metadata and artwork providers when editing an existing library
if (id) {
loadMetadataProvidersAsync();
loadArtworkProvidersAsync();
}
// store all cleanups for this view on window object using the scriptId
@@ -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())];
}
}
@@ -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())];
}
}
@@ -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,
@@ -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())];
}
}
@@ -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(
@@ -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>
@@ -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>
@@ -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(
@@ -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(),
@@ -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())];
}
}
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more