Adds independent metadata and artwork enrichment

Splits the single combined enrichment phase of the media library scan into
independent, modular jobs, so that the metadata and the artwork of a book
are enriched separately and only when their respective triggers fire.

- Adds the MediaContributorRoleCategory enum (Other first, then Author,
  Translator, Illustrator, Publisher and Narrator) and makes the role
  category canonical, so that roles describing the same kind of
  contribution are never treated as distinct.
- Realizes the media contributor bounded context: a MediaContributor is a
  person, unique by display name, without a role. The role moves to the
  per-work participation (BookContributors), so that a single contributor
  can play multiple roles. Contributors are created and linked by the
  metadata enrichment job, and exposed to subsequent jobs.
- Makes the Book aggregate pure: the enrichment tracking state (metadata
  status, providers, timestamps and covers) no longer lives on the domain
  aggregate, but stays in the Books table, managed directly by the jobs.
- Models artwork generically as a BookArtwork child table (type, ordinal,
  content hash, status and provider), so that each piece of artwork is
  tracked independently and a change of one does not require the others to
  be re-fetched.
- Splits the scan DAG into ResultsSave, ProviderConfigurationInvalidation,
  MetadataEnrichment and ArtworkEnrichment jobs. The invalidation job
  fingerprints the provider configuration of a library and resets the
  enrichment state of the affected channel when it changed. The artwork job
  resolves the missing artwork, hashing it to detect identical covers and
  skip re-copying. Content-changed books are reset by the results save job.
- Deletes the book and its stored artwork when the file disappears from the
  library.
- Adds the migration creating the new tables, backfilling the existing
  covers into the artwork table, and adding the configuration fingerprints.
- Localizes the new scan job stages, and fixes the invalidation job wiping
  the library content locations by persisting the fingerprints through the
  change tracker instead of the repository update action.
This commit is contained in:
BinaryAlley committed 2026-08-27 14:41:49 +03:00
1 parent 4ee2976806
commit 565fe68239
98 files changed
+5845 -630

No files matched your search

@@ -1,10 +1,12 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
@@ -14,6 +16,9 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -39,6 +44,9 @@ public class BookRepositoryTests
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly IsbnEntityFixture _isbnEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new();
@@ -528,4 +536,232 @@ public class BookRepositoryTests
Assert.Single(retrievedBook.Ratings);
Assert.Equal(4.5M, retrievedBook.Ratings.First().Value);
}
[Fact]
public async Task GetBooksNeedingArtworkAsync_WhenCalled_ShouldReturnOnlyBooksWithoutAnEnrichedCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity bookWithoutCover = _bookEntityFixture.Create();
bookWithoutCover.LibraryId = libraryId;
bookWithoutCover.Path = "/books/a.epub";
bookWithoutCover.BookArtwork = [];
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
bookWithEnrichedCover.LibraryId = libraryId;
bookWithEnrichedCover.Path = "/books/b.epub";
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookWithFailedCover = _bookEntityFixture.Create();
bookWithFailedCover.LibraryId = libraryId;
bookWithFailedCover.Path = "/books/c.epub";
bookWithFailedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<BookEntity>> result = await _sut.GetBooksNeedingArtworkAsync(libraryId, null, 10, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Contains(result.Value, book => book.Id == bookWithoutCover.Id);
Assert.Contains(result.Value, book => book.Id == bookWithFailedCover.Id);
}
[Fact]
public async Task GetBooksNeedingArtworkCountAsync_WhenCalled_ShouldCountOnlyBooksWithoutAnEnrichedCover()
{
// Arrange
Guid libraryId = Guid.NewGuid();
BookEntity bookWithoutCover = _bookEntityFixture.Create();
bookWithoutCover.LibraryId = libraryId;
bookWithoutCover.BookArtwork = [];
BookEntity bookWithEnrichedCover = _bookEntityFixture.Create();
bookWithEnrichedCover.LibraryId = libraryId;
bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [];
_mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
Result<int> result = await _sut.GetBooksNeedingArtworkCountAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1, result.Value);
}
[Fact]
public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths()
{
// Arrange
// the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity changedBook = _bookEntityFixture.Create();
changedBook.LibraryId = libraryId;
changedBook.Path = "/books/changed.epub";
changedBook.MetadataStatus = MetadataStatus.Enriched;
changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity unchangedBook = _bookEntityFixture.Create();
unchangedBook.LibraryId = libraryId;
unchangedBook.Path = "/books/unchanged.epub";
unchangedBook.MetadataStatus = MetadataStatus.Enriched;
unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.AddRange(changedBook, unchangedBook);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id);
Assert.NotNull(resetBook);
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status);
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id);
Assert.NotNull(keptBook);
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
}
[Fact]
public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary()
{
// Arrange
// the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity enrichedBook = _bookEntityFixture.Create();
enrichedBook.LibraryId = libraryId;
enrichedBook.MetadataStatus = MetadataStatus.Enriched;
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched;
context.Books.AddRange(enrichedBook, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id);
Assert.NotNull(resetBook);
Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus);
BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id);
Assert.NotNull(keptBook);
Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus);
}
[Fact]
public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks()
{
// Arrange
// the reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
LuminaDbContext context = new(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite(anchorConnection.ConnectionString).Options);
context.Database.EnsureCreated();
BookRepository sut = new(context);
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create();
bookOfAnotherLibrary.LibraryId = Guid.NewGuid();
bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)];
context.Books.AddRange(book, bookOfAnotherLibrary);
await context.SaveChangesAsync();
// Act
Result<Updated> result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
BookArtworkEntity? resetArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id);
Assert.NotNull(resetArtwork);
Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status);
BookArtworkEntity? keptArtwork = await context.Set<BookArtworkEntity>().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id);
Assert.NotNull(keptArtwork);
Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status);
}
[Fact]
public async Task GetAuthorsDisplayNamesByBookIdsAsync_WhenCalled_ShouldReturnTheAuthorDisplayNames()
{
// Arrange
BookEntity firstBook = _bookEntityFixture.Create();
BookEntity secondBook = _bookEntityFixture.Create();
BookEntity bookWithoutAuthor = _bookEntityFixture.Create();
_mockContext.Books.AddRange(firstBook, secondBook, bookWithoutAuthor);
await _mockContext.SaveChangesAsync();
MediaContributorEntity author = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
MediaContributorEntity translator = _mediaContributorEntityFixture.Create(displayName: "Jane Translator");
_mockContext.MediaContributors.AddRange(author, translator);
await _mockContext.SaveChangesAsync();
_mockContext.BookContributors.AddRange(
_bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, roleName: "Author", roleCategory: MediaContributorRoleCategory.Author),
_bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator));
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyDictionary<Guid, string?>> result = await _sut.GetAuthorsDisplayNamesByBookIdsAsync([firstBook.Id, secondBook.Id, bookWithoutAuthor.Id], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// only the author contributor of the first book is returned; the book with no author is not included
Assert.Single(result.Value);
Assert.Equal("Frank Herbert", result.Value[firstBook.Id]);
}
[Fact]
public async Task DeleteAsync_WhenBookExists_ShouldRemoveItAndReturnDeleted()
{
// Arrange
BookEntity book = _bookEntityFixture.Create();
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteAsync(book.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
EntityEntry<BookEntity>? deletedBook = _mockContext.ChangeTracker.Entries<BookEntity>()
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == book.Id);
Assert.NotNull(deletedBook);
}
[Fact]
public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError()
{
// Act
Result<Deleted> result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError);
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.MediaContributors;
/// <summary>
/// Contains unit tests for the <see cref="MediaContributorRepository"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly MediaContributorRepository _sut;
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaContributorRepositoryTests"/> class.
/// </summary>
public MediaContributorRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new MediaContributorRepository(_mockContext);
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenContributorExists_ShouldReturnTheExistingContributor()
{
// Arrange
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Stephen King");
_mockContext.MediaContributors.Add(existingContributor);
await _mockContext.SaveChangesAsync();
// Act
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("stephen king", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
// the comparison is case-insensitive, so the existing contributor is returned and no new one is created
Assert.Equal(existingContributor.Id, result.Value.Id);
Assert.Equal("Stephen King", result.Value.DisplayName);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenContributorDoesNotExist_ShouldCreateAndAddANewContributor()
{
// Arrange
string displayName = "Frank Herbert";
// Act
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync(displayName, "Franklin Patrick Herbert", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(displayName, result.Value.DisplayName);
Assert.Equal("Franklin Patrick Herbert", result.Value.LegalName);
EntityEntry<MediaContributorEntity>? addedContributor = _mockContext.ChangeTracker.Entries<MediaContributorEntity>()
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == result.Value.Id);
Assert.NotNull(addedContributor);
}
[Fact]
public async Task FindOrCreateByDisplayNameAsync_WhenContributorWithSameNameExistsInDifferentCase_ShouldNotCreateADuplicate()
{
// Arrange
MediaContributorEntity existingContributor = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert");
_mockContext.MediaContributors.Add(existingContributor);
await _mockContext.SaveChangesAsync();
// Act
Result<MediaContributorEntity> result = await _sut.FindOrCreateByDisplayNameAsync("FRANK HERBERT", "Franklin Patrick Herbert", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(existingContributor.Id, result.Value.Id);
Assert.Equal(existingContributor.DisplayName, result.Value.DisplayName);
Assert.Single(_mockContext.ChangeTracker.Entries<MediaContributorEntity>());
}
[Fact]
public async Task GetByIdsAsync_WhenCalled_ShouldReturnOnlyTheContributorsWithTheProvidedIds()
{
// Arrange
MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create();
MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create();
MediaContributorEntity thirdContributor = _mediaContributorEntityFixture.Create();
_mockContext.MediaContributors.AddRange(firstContributor, secondContributor, thirdContributor);
await _mockContext.SaveChangesAsync();
// Act
Result<IReadOnlyList<MediaContributorEntity>> result = await _sut.GetByIdsAsync([firstContributor.Id, thirdContributor.Id], CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Contains(result.Value, contributor => contributor.Id == firstContributor.Id);
Assert.Contains(result.Value, contributor => contributor.Id == thirdContributor.Id);
}
}
@@ -47,7 +47,7 @@ public class LuminaDbContextTests : IDisposable
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
Assert.Equal(25, tableNames.Length);
Assert.Equal(28, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
@@ -73,6 +73,9 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("BookRatings", tableNames);
Assert.Contains("BookISBNs", tableNames);
Assert.Contains("Themes", tableNames);
Assert.Contains("MediaContributors", tableNames);
Assert.Contains("BookContributors", tableNames);
Assert.Contains("BookArtwork", tableNames);
}
[Fact]