From 9e118864c3cf39b7c1530d2388907d28f2922521 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 9 Oct 2026 01:59:00 +0300 Subject: [PATCH] Adds the media library artwork aggregation services, enrichers, and their provider contracts --- .../MusicLibrary/MusicArtworkEntity.cs | 91 +++ .../MusicLibrary/IMusicArtworkRepository.cs | 49 ++ .../Artwork/IMusicArtworkService.cs | 61 ++ .../BookLibrary/Books/BookResponse.cs | 1 + .../MusicArtworkConfiguration.cs | 78 ++ .../MusicLibrary/MusicArtworkRepository.cs | 109 +++ .../AudioLibrary/MusicArtworkOwnerType.cs | 27 + .../Artwork/MusicArtworkService.cs | 457 +++++++++++ .../MusicMediaLibraryScanArtworkEnricher.cs | 677 ++++++++++++++++ .../IMediaLibraryScanArtworkEnricher.cs | 31 + .../MediaLibraryScanArtworkEnrichmentJob.cs | 331 +------- .../BooksMediaLibraryScanArtworkEnricher.cs | 378 +++++++++ .../BookLibrary/Artwork/BookArtworkService.cs | 6 +- .../Core/Metadata/IArtworkProvider.cs | 6 +- .../Core/Metadata/IArtworkProviderGeneric.cs | 15 +- .../Core/Metadata/IMetadataProvider.cs | 6 + .../Core/Metadata/IMetadataProviderGeneric.cs | 14 +- .../MusicLibrary/MusicArtworkEntityFixture.cs | 82 ++ .../BookLibrary/Books/BookResponseFixture.cs | 1 + .../Artwork/MusicArtworkServiceTests.cs | 763 ++++++++++++++++++ .../Artwork/BookArtworkServiceTests.cs | 22 +- .../Core/CalibreArtworkProviderTests.cs | 29 +- .../BookArtworkServiceSecurityTests.cs | 4 +- .../MusicArtworkConfigurationTests.cs | 155 ++++ .../MusicArtworkRepositoryTests.cs | 187 +++++ .../Artwork/MusicArtworkServiceTests.cs | 252 ++++++ ...sicMediaLibraryScanArtworkEnricherTests.cs | 604 ++++++++++++++ ...diaLibraryScanArtworkEnrichmentJobTests.cs | 761 +---------------- ...oksMediaLibraryScanArtworkEnricherTests.cs | 482 +++++++++++ .../Artwork/BookArtworkServiceTests.cs | 2 +- .../Core/CalibreArtworkProviderTests.cs | 12 +- .../Metadata/IArtworkProviderGenericTests.cs | 14 +- .../Metadata/IMetadataProviderGenericTests.cs | 32 +- 33 files changed, 4621 insertions(+), 1118 deletions(-) create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs create mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs create mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs new file mode 100644 index 00000000..db880c8b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a piece of artwork of a music library item, like the cover of an album or the image of an artist. +/// +/// +/// A music library item can have multiple pieces of artwork of different types, and multiple instances of the same type +/// (like the front cover, the back cover and the booklet pages of an album), each tracked independently so that a change +/// of one artwork does not require the others to be re-fetched. +/// +[DebuggerDisplay("OwnerType: {OwnerType} OwnerId: {OwnerId} Type: {ArtworkType} Ordinal: {Ordinal}")] +public class MusicArtworkEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the artwork. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the type of the music library item that owns the artwork. + /// + public required MusicArtworkOwnerType OwnerType { get; set; } + + /// + /// Gets or sets the Id of the music library item that owns the artwork. + /// + public required Guid OwnerId { get; set; } + + /// + /// Gets or sets the type of the artwork. + /// + public required ArtworkType ArtworkType { get; set; } + + /// + /// Gets or sets the ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered. + /// + public required int Ordinal { get; set; } + + /// + /// Gets or sets the relative file name of the stored artwork, if the artwork has been resolved. + /// + public string? FileName { get; set; } + + /// + /// Gets or sets the content hash of the stored artwork, used to detect whether a re-resolved artwork differs from the stored one. + /// + public ulong ContentHash { get; set; } + + /// + /// Gets or sets the status of the artwork enrichment. + /// + public required ArtworkStatus Status { get; set; } + + /// + /// Gets or sets the name of the plugin that resolved the artwork, if applicable. + /// + public string? Provider { get; set; } + + /// + /// Gets or sets the date and time when the artwork was last resolved, if applicable. + /// + public DateTime? LastUpdateUtc { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs new file mode 100644 index 00000000..2d1686e8 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; + +/// +/// Interface for the repository for the artwork of the music library items. +/// +public interface IMusicArtworkRepository : IRepository, + IInsertRangeRepositoryAction +{ + /// + /// Gets the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken); + + /// + /// Deletes all the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken); + + /// + /// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by , so that they are re-resolved. + /// + /// + /// The status is reset because the artwork provider configuration of the library changed. + /// + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs new file mode 100644 index 00000000..1754343c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Interface for the service for storing the artwork of a music library item, an album or an artist, into the internal media directory and serving its relative path. +/// +public interface IMusicArtworkService +{ + /// + /// Stores the of the album into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null); + + /// + /// Deletes the stored artwork of the album from the internal media directory. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An representing either a successful operation, or an error. + Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null); + + /// + /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken); + + /// + /// Deletes the stored artwork of the artist from the internal media directory. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// An representing either a successful operation, or an error. + Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName); +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs index 97d9a8e3..b8111399 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -3,6 +3,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.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs new file mode 100644 index 00000000..50853c1b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class MusicArtworkConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("MusicArtwork"); + builder.HasKey(musicArtwork => musicArtwork.Id); + builder.Property(musicArtwork => musicArtwork.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(musicArtwork => musicArtwork.OwnerType) + .IsRequired() + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(1); + builder.Property(musicArtwork => musicArtwork.OwnerId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(musicArtwork => musicArtwork.ArtworkType) + .IsRequired() + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(3); + builder.Property(musicArtwork => musicArtwork.Ordinal) + .IsRequired() + .HasColumnOrder(4); + builder.Property(musicArtwork => musicArtwork.FileName) + .HasMaxLength(2048) + .HasColumnOrder(5); + builder.Property(musicArtwork => musicArtwork.ContentHash) + .HasColumnOrder(6); + builder.Property(musicArtwork => musicArtwork.Status) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(7); + builder.Property(musicArtwork => musicArtwork.Provider) + .HasMaxLength(100) + .HasColumnOrder(8); + builder.Property(musicArtwork => musicArtwork.LastUpdateUtc) + .HasColumnOrder(9); + + // audit + builder.Property(musicArtwork => musicArtwork.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(10); + + builder.Property(musicArtwork => musicArtwork.CreatedBy) + .IsRequired() + .HasColumnOrder(11); + + builder.Property(musicArtwork => musicArtwork.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(12); + + builder.Property(musicArtwork => musicArtwork.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(13); + + builder.HasIndex(musicArtwork => new { musicArtwork.OwnerType, musicArtwork.OwnerId, musicArtwork.ArtworkType, musicArtwork.Ordinal }) + .IsUnique(); + builder.HasIndex(musicArtwork => musicArtwork.Status); + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs new file mode 100644 index 00000000..ceb8f38e --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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.MusicLibrary; + +/// +/// Repository for the artwork of the music library items. +/// +internal sealed class MusicArtworkRepository : IMusicArtworkRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public MusicArtworkRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a range of pieces of artwork of music library items. + /// + /// The pieces of artwork to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public Task> InsertRangeAsync(IReadOnlyCollection artwork, CancellationToken cancellationToken) + { + if (artwork.Count > 0) + _luminaDbContext.MusicArtwork.AddRange(artwork); + return Task.FromResult>(Result.Created); + } + + /// + /// Gets the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) + { + IReadOnlyList artwork = await _luminaDbContext.MusicArtwork + .AsNoTracking() + .Where(musicArtwork => musicArtwork.OwnerType == ownerType && musicArtwork.OwnerId == ownerId) + .OrderBy(musicArtwork => musicArtwork.ArtworkType) + .ThenBy(musicArtwork => musicArtwork.Ordinal) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From(artwork); + } + + /// + /// Deletes all the pieces of artwork owned by the music library item of the provided identified by . + /// + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken) + { + await _luminaDbContext.MusicArtwork + .Where(musicArtwork => musicArtwork.OwnerType == ownerType && musicArtwork.OwnerId == ownerId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + return Result.Deleted; + } + + /// + /// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by . + /// + /// The Id of the media library whose artwork is reset. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + // The artwork table is shared by all the music library item types, so the owners of the artwork of this library are collected per type. + List artistIds = await _luminaDbContext.Artists + .Where(artist => artist.LibraryId == libraryId) + .Select(artist => artist.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List albumIds = await _luminaDbContext.Albums + .Where(album => album.LibraryId == libraryId) + .Select(album => album.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List trackIds = await _luminaDbContext.Tracks + .Where(track => track.LibraryId == libraryId) + .Select(track => track.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + await _luminaDbContext.MusicArtwork + .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && artistIds.Contains(musicArtwork.OwnerId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album && albumIds.Contains(musicArtwork.OwnerId)) + || (musicArtwork.OwnerType == MusicArtworkOwnerType.Track && trackIds.Contains(musicArtwork.OwnerId))) + .ExecuteUpdateAsync(setters => setters.SetProperty(musicArtwork => musicArtwork.Status, ArtworkStatus.Pending), cancellationToken).ConfigureAwait(false); + return Result.Updated; + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs new file mode 100644 index 00000000..29ed3503 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; + +/// +/// Enumeration for the type of the music library item that owns a piece of artwork. +/// +[DebuggerDisplay("{ToString()}")] +public enum MusicArtworkOwnerType +{ + /// + /// The artwork belongs to an artist. + /// + Artist, + + /// + /// The artwork belongs to an album. + /// + Album, + + /// + /// The artwork belongs to a track. + /// + Track +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs new file mode 100644 index 00000000..28ccb723 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs @@ -0,0 +1,457 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.Utilities; +using Lumina.Infrastructure.Common.Networking; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Stores the artwork of an album into the internal media directory, under a per-album directory, and returns its relative path. +/// +internal sealed class MusicArtworkService : IMusicArtworkService +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _environmentContext; + private readonly IPathService _pathService; + private readonly IHttpClientFactory _httpClientFactory; + private readonly MediaSettingsDto _mediaSettings; + + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for environment contextual services. + /// Injected service for handling file system paths. + /// Injected factory used to create the HTTP clients that download the remote artwork. + /// Injected service for retrieving . + public MusicArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions mediaSettingsOptions) + { + _environmentContext = environmentContext; + _pathService = pathService; + _httpClientFactory = httpClientFactory; + _mediaSettings = mediaSettingsOptions.Value; + } + + /// + /// Stores the of the album into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null) + { + Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); + } + + /// + /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken) + { + Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the local source of the , stores it into , and cleans up the temporary download of a remote artwork. + /// + /// The file system path of the directory the artwork is stored into. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + private async Task> SaveArtworkAsync(string artworkDirectoryPath, ArtworkDto artwork, CancellationToken cancellationToken) + { + // Resolve the local file path of the artwork, downloading it to a temporary file when it is remote. + Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false); + if (resolveSourceResult.IsFailure) + return resolveSourceResult.Errors; + string sourcePath = resolveSourceResult.Value.Path; + + try + { + return await StoreArtworkAsync(artworkDirectoryPath, artwork.Type, artwork.Ordinal, sourcePath, cancellationToken).ConfigureAwait(false); + } + finally + { + // Remove the temporary source of the artwork, whether it was downloaded for a remote artwork or produced by a provider, never a file of the user. + if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath)) + { + try + { + File.Delete(sourcePath); + } + catch (IOException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + catch (UnauthorizedAccessException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + } + } + } + + /// + /// Deletes the stored artwork of the album from the internal media directory. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. + /// An representing either a successful operation, or an error. + public Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null) + { + Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); + } + + /// + /// Deletes the stored artwork of the artist from the internal media directory. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// An representing either a successful operation, or an error. + public Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName) + { + Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); + } + + /// + /// Deletes the files directly contained in , leaving the subdirectories, such as the album directories of an artist, untouched. + /// + /// The file system path of the directory whose files are deleted. + /// An representing either a successful operation, or an error. + private Result DeleteArtworkInDirectory(string artworkDirectoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + // When nothing was stored for the owner yet, its directory does not exist, so there is nothing to delete. + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; + if (!directoryExistsResult.Value) + return Result.Deleted; + + Result> getFilesResult = _environmentContext.FileProviderService.GetFilePaths(directoryPathIdResult.Value, true); + if (getFilesResult.IsFailure) + return getFilesResult.Errors; + + foreach (FileSystemPathId filePathId in getFilesResult.Value) + _environmentContext.FileProviderService.DeleteFile(filePathId); + + return Result.Deleted; + } + + /// + /// Stores the artwork file at into . + /// + /// The file system path of the directory the artwork is stored into. + /// The type of the artwork being stored. + /// The ordinal of the artwork within its type. + /// The file system path of the artwork file to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + private async Task> StoreArtworkAsync(string artworkDirectoryPath, ArtworkType artworkType, int ordinal, string sourcePath, CancellationToken cancellationToken) + { + Result sourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (sourcePathIdResult.IsFailure) + return sourcePathIdResult.Errors; + + Result fileExistsResult = _environmentContext.FileProviderService.FileExists(sourcePathIdResult.Value); + if (fileExistsResult.IsFailure) + return fileExistsResult.Errors; + if (!fileExistsResult.Value) + return Errors.FileSystemManagement.FileNotFound; + + // Reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine. + if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint)) + return Errors.FileSystemManagement.InvalidPath; + + // Reject the artwork when it exceeds the maximum allowed size. + FileInfo sourceFileInfo = new(sourcePath); + if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + + // Make sure the file is an actual supported image. + Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageTypeResult.IsFailure) + return imageTypeResult.Errors; + if (imageTypeResult.Value == ImageType.None) + return Errors.Library.CoverFileMustBeAnImage; + + Result ensureDirectoryResult = EnsureDirectory(artworkDirectoryPath); + if (ensureDirectoryResult.IsFailure) + return ensureDirectoryResult.Errors; + + Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath); + if (artworkDirectoryPathIdResult.IsFailure) + return artworkDirectoryPathIdResult.Errors; + + // Copy the artwork file from the source location. + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true); + if (copyFileResult.IsFailure) + return copyFileResult.Errors; + + // Rename the copied file to the standard naming, derived from the type and the ordinal of the artwork. + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"{BuildArtworkFileStem(artworkType, ordinal)}.{imageTypeResult.Value.ToFileExtension()}"); + if (renameFileResult.IsFailure) + return renameFileResult.Errors; + + // Get the internal relative path for the copied file. + string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..]; + if (!relativePath.StartsWith(_pathService.PathSeparator)) + relativePath = $"{_pathService.PathSeparator}{relativePath}"; + return relativePath; + } + + /// + /// Builds the file name stem of an artwork, derived from its type and ordinal. + /// + /// The type of the artwork. + /// The ordinal of the artwork within its type. + /// The file name stem of the artwork. + private static string BuildArtworkFileStem(ArtworkType artworkType, int ordinal) + { + string stem = artworkType switch + { + ArtworkType.Cover => "cover", + ArtworkType.Front => "front", + ArtworkType.Back => "back", + ArtworkType.Booklet => "booklet", + ArtworkType.Medium => "medium", + ArtworkType.Tray => "tray", + ArtworkType.Spine => "spine", + ArtworkType.Obi => "obi", + ArtworkType.Sticker => "sticker", + ArtworkType.Poster => "poster", + ArtworkType.Liner => "liner", + ArtworkType.Watermark => "watermark", + ArtworkType.Backdrop => "backdrop", + ArtworkType.Banner => "banner", + ArtworkType.Logo => "logo", + ArtworkType.Thumb => "thumb", + _ => "other" + }; + return ordinal > 0 ? $"{stem}-{ordinal}" : stem; + } + + /// + /// Resolves the local file system path of the , downloading it to a temporary file when it is remote. + /// + /// The artwork whose source path is resolved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the resolved local source of the artwork, or an error. + private async Task> ResolveArtworkSourceAsync(ArtworkDto artwork, CancellationToken cancellationToken) + { + if (!string.IsNullOrWhiteSpace(artwork.LocalPath)) + return new ArtworkSourceResult(artwork.LocalPath, IsTemporary: artwork.IsTemporary); + + if (string.IsNullOrWhiteSpace(artwork.RemoteUrl)) + return Errors.FileSystemManagement.FileNotFound; + + // Download the remote artwork into a temporary file, aborting when it exceeds the allowed size. + using HttpClient httpClient = _httpClientFactory.CreateClient(NamedHttpClients.ARTWORK_DOWNLOAD); + string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); + bool downloaded = false; + try + { + using HttpResponseMessage response = await httpClient.GetAsync(artwork.RemoteUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + return Errors.FileSystemManagement.FileNotFound; + + await using Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using FileStream fileStream = new(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true); + + byte[] buffer = new byte[81920]; + long totalRead = 0; + int bytesRead; + while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + totalRead += bytesRead; + if (totalRead > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + downloaded = true; + return new ArtworkSourceResult(tempPath, IsTemporary: true); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return Errors.FileSystemManagement.FileNotFound; + } + finally + { + // Remove the partially downloaded temporary file when the download failed. + if (!downloaded && File.Exists(tempPath)) + File.Delete(tempPath); + } + } + + /// + /// Builds the file system path of the directory of the album artwork, under the internal media directory. + /// The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The name of the release type directory the album is stored under on disk, or to store the artwork directly under the artist directory. + /// An containing either the file system path of the album artwork directory, or an error. + private Result BuildAlbumArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName) + { + Result artistPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + if (artistPathResult.IsFailure) + return artistPathResult.Errors; + + // The release type directory groups the releases of an artist that share a title but are different releases, like the album and the single of the same songs. + Result albumParentPathResult = artistPathResult; + if (!string.IsNullOrWhiteSpace(releaseTypeName)) + { + Result releaseTypeSegmentResult = _pathService.SanitizeSegment(releaseTypeName); + if (releaseTypeSegmentResult.IsFailure) + return releaseTypeSegmentResult.Errors; + Result releaseTypePathResult = _pathService.CombinePath(artistPathResult.Value, releaseTypeSegmentResult.Value.Name); + if (releaseTypePathResult.IsFailure) + return releaseTypePathResult.Errors; + albumParentPathResult = releaseTypePathResult; + } + + Result albumSegmentResult = _pathService.SanitizeSegment($"{albumTitle}-{albumId}"); + if (albumSegmentResult.IsFailure) + return albumSegmentResult.Errors; + return _pathService.CombinePath(albumParentPathResult.Value, albumSegmentResult.Value.Name); + } + + /// + /// Builds the file system path of the directory of the artist artwork, under the internal media directory. + /// The artwork of the albums of the artist is stored in the subdirectories of this directory. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// An containing either the file system path of the artist artwork directory, or an error. + private Result BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + { + Result libraryPathResult = BuildLibraryArtworkDirectoryPath(libraryId, libraryName); + if (libraryPathResult.IsFailure) + return libraryPathResult.Errors; + + Result artistSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName); + if (artistSegmentResult.IsFailure) + return artistSegmentResult.Errors; + return _pathService.CombinePath(libraryPathResult.Value, artistSegmentResult.Value.Name); + } + + /// + /// Builds the file system path of the directory of a music media library, under the internal media directory. + /// + /// The Id of the media library. + /// The name of the media library. + /// An containing either the file system path of the media library directory, or an error. + private Result BuildLibraryArtworkDirectoryPath(Guid libraryId, string libraryName) + { + Result mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory); + if (mediaRootPathResult.IsFailure) + return mediaRootPathResult.Errors; + Result musicPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.MusicDirectory); + if (musicPathResult.IsFailure) + return musicPathResult.Errors; + + Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}"); + if (librarySegmentResult.IsFailure) + return librarySegmentResult.Errors; + return _pathService.CombinePath(musicPathResult.Value, librarySegmentResult.Value.Name); + } + + /// + /// Creates the directory at , along with its missing parents. + /// + /// The file system path of the directory to create. + /// An representing either a successful operation, or an error. + private Result EnsureDirectory(string directoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(directoryPath); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; + if (directoryExistsResult.Value) + return Result.Success; + + string? parentDirectoryPath = Path.GetDirectoryName(directoryPath); + if (!string.IsNullOrEmpty(parentDirectoryPath) && !string.Equals(parentDirectoryPath, directoryPath, StringComparison.Ordinal)) + { + Result createParentResult = EnsureDirectory(parentDirectoryPath); + if (createParentResult.IsFailure) + return createParentResult.Errors; + } + + Result parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath); + if (parentDirectoryPathIdResult.IsFailure) + return parentDirectoryPathIdResult.Errors; + + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath)); + if (createDirectoryResult.IsFailure) + return createDirectoryResult.Errors; + return Result.Success; + } + + /// + /// Describes the resolved local source of the artwork. + /// + /// The file system path of the resolved source. + /// Whether the resolved source is a temporary file that must be cleaned up after it is stored. + private sealed record ArtworkSourceResult(string Path, bool IsTemporary); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs new file mode 100644 index 00000000..862e4455 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs @@ -0,0 +1,677 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using 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.Audio.Music; + +/// +/// Artwork enricher for the media library items of the music media library type, using the artwork providers configured for the media library. +/// +/// +/// The artwork of an artist and of an album is tracked per type and ordinal, so that a change of one piece of artwork does not require the others to be re-fetched. +/// +internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanArtworkEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 200; // The number of artists or albums that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// The media library type that this artwork enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Music; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while resolving the artwork. + public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Resolves the artwork of the artists and the albums of the provided media library, using the artwork providers configured for it. + /// + /// The unique identifier of the media library whose artwork is resolved. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Load the media library, whose name is used to build the directories of the artwork, and whose setting determines whether the providers that require access to the web are used during the enrichment. + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // Read whether the artwork of the items of the user is aggregated from multiple providers, when it is missing. + bool shouldAggregateArtworkWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the artwork will not be aggregated across providers."); + else + shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? 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 enrichment from proceeding. + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music) + && (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.Music); + artworkProviders.AddRange(configuredProviders); + } + } + } + + // When no artwork provider is available, the items must not be marked as failed to resolve, so the enrichment is skipped entirely. + if (artworkProviders.Count == 0) + { + _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value); + return; + } + + // The providers are split by the lookup they accept, keeping the configured rank order in which they were gathered. + IReadOnlyList artistProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider)]; + IReadOnlyList albumProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider)]; + + IMusicArtworkService? musicArtworkService = asyncServiceScope.ServiceProvider.GetService(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + int totalArtistsToEnrich = 0; + if (artistProviders.Count > 0) + { + Result getArtistsToEnrichCountResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtistsToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getArtistsToEnrichCountResult.FirstError.Description); + totalArtistsToEnrich = getArtistsToEnrichCountResult.Value; + } + + int totalAlbumsToEnrich = 0; + if (albumProviders.Count > 0) + { + Result getAlbumsToEnrichCountResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getAlbumsToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getAlbumsToEnrichCountResult.FirstError.Description); + totalAlbumsToEnrich = getAlbumsToEnrichCountResult.Value; + } + + int totalItemsToEnrich = totalArtistsToEnrich + totalAlbumsToEnrich; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedItemsCount = 0; + + // Reports that a single artist or album was processed, publishing the progress at most once per interval. + async Task ReportItemProcessedAsync() + { + int processedItems = Interlocked.Increment(ref processedItemsCount); + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + Result publishItemProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, processedItems, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishItemProgressResult.IsFailure) + throw new InvalidOperationException(publishItemProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + if (artistProviders.Count > 0) + await EnrichArtistsAsync(libraryId, artistProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false); + + if (albumProviders.Count > 0) + await EnrichAlbumsAsync(libraryId, albumProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false); + + // The enrichment finished, force the progress to reach its total, so that a throttled update cannot leave it incomplete. + Result publishFinalProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, totalItemsToEnrich, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishFinalProgressResult.IsFailure) + throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description); + } + + /// + /// Resolves the artwork of the artists of the provided media library whose artwork has not been resolved yet, page by page. + /// + /// The unique identifier of the media library whose artists are enriched. + /// The artists artwork providers, in the order they are consulted. + /// The service used to store the artwork of the artists. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the artists belong to. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the artists. + /// The callback invoked after each artist is processed, to advance the progress. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task EnrichArtistsAsync(LibraryId libraryId, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func reportItemProcessedAsync, CancellationToken cancellationToken) + { + string? lastName = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkAsync(libraryId.Value, lastName, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getArtistsPageResult.IsFailure) + throw new InvalidOperationException(getArtistsPageResult.FirstError.Description); + IReadOnlyList artistsPage = getArtistsPageResult.Value; + if (artistsPage.Count == 0) + break; + + foreach (ArtistEntity artistEntity in artistsPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + // The first track of the artist, in a deterministic order, describes the artist in the artwork lookup and locates its directory on the file system. + string firstTrackPath = artistEntity.Albums.SelectMany(album => album.Tracks).Select(track => track.Path).OrderBy(path => path).FirstOrDefault() ?? string.Empty; + await EnrichArtistArtworkAsync(artistEntity, firstTrackPath, artworkProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); + await reportItemProcessedAsync().ConfigureAwait(false); + } + + // Persist the resolved artwork of this page, then detach it from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + unitOfWork.ClearTrackedEntities(); + + lastName = artistsPage[^1].Name; + } + } + + /// + /// Resolves the artwork of the albums of the provided media library whose artwork has not been resolved yet, page by page. + /// + /// The unique identifier of the media library whose albums are enriched. + /// The album artwork providers, in the order they are consulted. + /// The service used to store the artwork of the albums. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the albums belong to. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the albums. + /// The callback invoked after each album is processed, to advance the progress. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task EnrichAlbumsAsync(LibraryId libraryId, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func reportItemProcessedAsync, CancellationToken cancellationToken) + { + // A provider that does not require the web, like the one that reads the files of the user, can resolve the artwork without any MusicBrainz identifier. + bool canResolveWithoutMusicBrainzIds = artworkProviders.Any(provider => !provider.RequiresWebAccess); + + // The albums that were attempted but remain unresolved are tracked and excluded from the following pages, so that a page that made no album reach a terminal state cannot make the pagination loop forever. + List albumsRemainingUnresolved = []; + + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getAlbumsPageResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkAsync(libraryId.Value, albumsRemainingUnresolved, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getAlbumsPageResult.IsFailure) + throw new InvalidOperationException(getAlbumsPageResult.FirstError.Description); + IReadOnlyList albumsPage = getAlbumsPageResult.Value; + if (albumsPage.Count == 0) + break; + + // Load the path of one track of each album of this page, in one query, since it is used to locate the album directory on the file system. + Result> getTrackPathsResult = await unitOfWork.AlbumRepository.GetFirstTrackPathsByAlbumIdsAsync([.. albumsPage.Select(album => album.Id)], cancellationToken).ConfigureAwait(false); + if (getTrackPathsResult.IsFailure) + throw new InvalidOperationException(getTrackPathsResult.FirstError.Description); + + foreach (AlbumEntity albumEntity in albumsPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + string firstTrackPath = getTrackPathsResult.Value.TryGetValue(albumEntity.Id, out string? trackPath) ? trackPath : string.Empty; + bool isTerminal = await EnrichAlbumArtworkAsync(albumEntity, firstTrackPath, artworkProviders, musicArtworkService, fileHashService, libraryName, canResolveWithoutMusicBrainzIds, shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); + if (!isTerminal) + albumsRemainingUnresolved.Add(albumEntity.Id); + await reportItemProcessedAsync().ConfigureAwait(false); + } + + // Persist the enriched albums of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + unitOfWork.ClearTrackedEntities(); + } + } + + /// + /// Resolves the artwork of the provided from the , storing the artwork resolved from the providers, in their order. + /// + /// The artist whose artwork is resolved. + /// The file system path of one track of the artist, used to locate its directory. + /// The artist artwork providers, in the order they are consulted. + /// The service used to store the artwork of the artist. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the artist belongs to. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the artist. + /// Cancellation token that can be used to stop the execution. + /// when the artist reached a terminal artwork state, otherwise . + private async Task EnrichArtistArtworkAsync(ArtistEntity artistEntity, string firstTrackPath, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken) + { + ArtistMetadataLookupDto artworkLookup = new( + LibraryId: artistEntity.LibraryId, + Path: firstTrackPath, + MusicBrainzArtistId: artistEntity.MusicBrainzArtistId, + Name: artistEntity.Name); + + string artistName = artistEntity.Name; + + return await EnrichArtworkAsync( + artworkLookup, + MusicArtworkOwnerType.Artist, + artistEntity.Id, + artistName, + artworkProviders, + musicArtworkService, + fileHashService, + () => musicArtworkService!.DeleteArtistArtwork(artistEntity.LibraryId, libraryName, artistName), + (artwork, token) => musicArtworkService!.SaveArtistArtworkAsync(artistEntity.LibraryId, libraryName, artistName, artwork, token), + shouldAggregateArtworkWhenMissing, + unitOfWork, + cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the artwork of the provided from the , storing the artwork resolved from the providers, in their order. + /// + /// The album whose artwork is resolved. + /// The file system path of one track of the album, used to locate its directory. + /// The album artwork providers, in the order they are consulted. + /// The service used to store the artwork of the album. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the album belongs to. + /// Whether a provider that does not require the web can resolve the artwork without any MusicBrainz identifier. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the album. + /// Cancellation token that can be used to stop the execution. + /// when the album reached a terminal artwork state, otherwise . + private async Task EnrichAlbumArtworkAsync(AlbumEntity albumEntity, string firstTrackPath, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool canResolveWithoutMusicBrainzIds, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken) + { + // Without any MusicBrainz identifier, only a provider that reads the files of the user can resolve the artwork, so the album is left for a following scan otherwise. + if (albumEntity.MusicBrainzReleaseId is null && albumEntity.MusicBrainzReleaseGroupId is null && !canResolveWithoutMusicBrainzIds) + return false; + + AlbumMetadataLookupDto artworkLookup = new( + LibraryId: albumEntity.LibraryId, + Path: firstTrackPath, + MusicBrainzReleaseGroupId: albumEntity.MusicBrainzReleaseGroupId, + MusicBrainzReleaseId: albumEntity.MusicBrainzReleaseId, + Title: albumEntity.Title, + ArtistName: albumEntity.Artist?.Name, + ReleaseYear: albumEntity.OriginalReleaseYear, + TrackCount: albumEntity.TotalTracks); + + string artistName = albumEntity.Artist?.Name ?? string.Empty; + + // The release type directory groups the artwork of the releases of the artist that share a title, so the album, the single and the live release of the same songs do not collide. + // It is read from the file system, because the structure on disk is the source of truth of the release type of an album. + string? releaseTypeName = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath); + + return await EnrichArtworkAsync( + artworkLookup, + MusicArtworkOwnerType.Album, + albumEntity.Id, + albumEntity.Title, + artworkProviders, + musicArtworkService, + fileHashService, + () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName), + (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, token, releaseTypeName), + shouldAggregateArtworkWhenMissing, + unitOfWork, + cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the artwork of the media item described by from the , in their order, replacing the stored artwork of the item. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The type of the music library item that owns the artwork. + /// The Id of the music library item that owns the artwork. + /// The description of the owner, used to report the issues encountered. + /// The artwork providers, in the order they are consulted. + /// The service used to store the artwork of the owner. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The action that deletes the artwork of the owner from the internal media directory. + /// The action that stores a piece of artwork of the owner into the internal media directory. + /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used. + /// The unit of work used to persist the artwork of the owner. + /// Cancellation token that can be used to stop the execution. + /// when the owner reached a terminal artwork state, otherwise . + private async Task EnrichArtworkAsync(MetadataLookupDto artworkLookup, MusicArtworkOwnerType ownerType, Guid ownerId, string ownerDescription, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, Func> deleteStoredArtwork, Func>> saveArtworkAsync, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken) + { + if (musicArtworkService is null || unitOfWork.MusicArtworkRepository is null) + return false; + + ArtworkResolution resolution = await ResolveArtworkAsync(artworkLookup, artworkProviders, ownerDescription, shouldAggregateArtworkWhenMissing, cancellationToken).ConfigureAwait(false); + + // Replace the stored artwork of the owner as a whole, so that a piece of artwork that no longer exists at the source does not linger. + Result deleteStoredArtworkResult = deleteStoredArtwork(); + if (deleteStoredArtworkResult.IsFailure) + { + _logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription); + DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork)); + return false; + } + Result deleteEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false); + if (deleteEntitiesResult.IsFailure) + { + _logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription); + DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork)); + return false; + } + + List artworkEntities = []; + + if (resolution.Artworks.Count > 0) + { + foreach (ResolvedArtwork resolvedArtwork in resolution.Artworks) + { + ArtworkDto artwork = resolvedArtwork.Artwork; + Result saveArtworkResult = await saveArtworkAsync(artwork, cancellationToken).ConfigureAwait(false); + if (saveArtworkResult.IsFailure) + { + _logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription); + continue; + } + + string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\')); + ulong contentHash = fileHashService.ComputeFileHash(storedArtworkPath); + artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, artwork.Type, artwork.Ordinal, saveArtworkResult.Value, contentHash, ArtworkStatus.Enriched, resolvedArtwork.ProviderName)); + } + + // When every resolved piece of artwork failed to be stored, the owner is treated as failed to resolve, so that it is retried. + if (artworkEntities.Count == 0) + { + artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null)); + await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false); + return false; + } + } + else + { + // No artwork exists for the owner when a provider answered and found none, which is not a failure; it only failed when no provider could answer. + ArtworkStatus status = resolution.HasResolved ? ArtworkStatus.NotAvailable : ArtworkStatus.Failed; + artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, status, null)); + await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false); + return status == ArtworkStatus.NotAvailable; + } + + await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false); + return true; + } + + /// + /// Persists the provided pieces of of a music library item. + /// + /// The unit of work used to persist the artwork. + /// The pieces of artwork to persist. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + private async Task PersistArtworkAsync(IUnitOfWork unitOfWork, List artworkEntities, CancellationToken cancellationToken) + { + Result insertArtworkResult = await unitOfWork.MusicArtworkRepository.InsertRangeAsync(artworkEntities, cancellationToken).ConfigureAwait(false); + if (insertArtworkResult.IsFailure) + _logger.LogWarning("Failed to persist the resolved artwork of a music library item."); + } + + /// + /// Deletes the temporary files of the provided , used when the resolved artwork is not stored, so the temporary files do not linger. + /// + /// The resolved artworks whose temporary files are deleted. + private static void DeleteTemporaryArtworks(IEnumerable artworks) + { + foreach (ArtworkDto artwork in artworks) + { + if (!artwork.IsTemporary || string.IsNullOrWhiteSpace(artwork.LocalPath)) + continue; + try + { + if (File.Exists(artwork.LocalPath)) + File.Delete(artwork.LocalPath); + } + catch (IOException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + catch (UnauthorizedAccessException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + } + } + + /// + /// Resolves the artwork of the media item described by from the , + /// either aggregating the providers when is set, or using the first provider that supplies artwork otherwise. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The artwork providers, in the order they are consulted. + /// The description of the owner, used to report the issues encountered. + /// Whether the artwork of every provider is combined, or only the first provider that supplies artwork is used. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all, distinguishing a confirmed absence of artwork from a resolution failure. + private async Task ResolveArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, bool shouldAggregateArtworkWhenMissing, CancellationToken cancellationToken) + { + if (shouldAggregateArtworkWhenMissing) + return await ResolveAggregatedArtworkAsync(lookup, artworkProviders, ownerDescription, cancellationToken).ConfigureAwait(false); + return await ResolveFirstArtworkAsync(lookup, artworkProviders, ownerDescription, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the artwork of the media item described by from the first provider that supplies some, in their order. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The artwork providers, in the order they are consulted. + /// The description of the owner, used to report the issues encountered. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all. + private async Task ResolveFirstArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, CancellationToken cancellationToken) + { + bool hasResolved = false; + bool hasFailed = false; + foreach (IArtworkProvider provider in artworkProviders) + { + IReadOnlyList providerArtworks; + try + { + providerArtworks = await provider.GetArtworkAsync(lookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. + hasFailed = true; + _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription); + continue; + } + + hasResolved = true; + // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. + List usableArtworks = [.. providerArtworks + .Where(artwork => string.IsNullOrWhiteSpace(artwork.RemoteUrl) || provider.RequiresWebAccess) + .Select(artwork => new ResolvedArtwork(artwork, provider.Name))]; + if (usableArtworks.Count > 0) + return new ArtworkResolution(usableArtworks, HasResolved: true); + } + + // An empty result is only treated as a confirmed absence of artwork when at least one provider answered; when every provider failed, it is a failure. + return new ArtworkResolution([], HasResolved: hasResolved || !hasFailed); + } + + /// + /// Resolves the artwork of the media item described by from every provider, in their order, + /// combining them so that a provider only fills the artwork the providers before it did not supply. + /// + /// The lookup describing the media item whose artwork is resolved. + /// The artwork providers, in the order they are consulted. + /// The description of the owner, used to report the issues encountered. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all. + private async Task ResolveAggregatedArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, CancellationToken cancellationToken) + { + bool hasResolved = false; + bool hasFailed = false; + List resolvedArtworks = []; + HashSet<(ArtworkType Type, int Ordinal)> resolvedKeys = []; + foreach (IArtworkProvider provider in artworkProviders) + { + IReadOnlyList providerArtworks; + try + { + providerArtworks = await provider.GetArtworkAsync(lookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception exception) + { + // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics. + hasFailed = true; + _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription); + continue; + } + + hasResolved = true; + foreach (ArtworkDto artwork in providerArtworks) + { + // 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; + // The providers are consulted in their configured order, so a provider only fills the artwork the higher ranked ones did not supply, and a provider + // that holds just a part of the artwork of the item, like the local files of the user, is complemented by the providers that follow it. + if (resolvedKeys.Add((artwork.Type, artwork.Ordinal))) + resolvedArtworks.Add(new ResolvedArtwork(artwork, provider.Name)); + } + } + + // An empty result is only treated as a confirmed absence of artwork when at least one provider answered; when every provider failed, it is a failure. + return new ArtworkResolution(resolvedArtworks, HasResolved: hasResolved || !hasFailed); + } + + /// + /// Creates a piece of artwork of the music library item of the provided identified by . + /// + /// The Id of the music library item the artwork belongs to. + /// The type of the music library item the artwork belongs to. + /// The type of the artwork. + /// The ordinal of the artwork within its type. + /// The relative file name of the stored artwork, if the artwork has been resolved. + /// The content hash of the stored artwork. + /// The status of the artwork enrichment. + /// The name of the plugin that resolved the artwork, if applicable. + /// The created artwork entity. + private static MusicArtworkEntity CreateArtworkEntity(Guid ownerId, MusicArtworkOwnerType ownerType, ArtworkType artworkType, int ordinal, string? fileName, ulong contentHash, ArtworkStatus status, string? provider) + { + return new MusicArtworkEntity + { + Id = Guid.NewGuid(), + OwnerType = ownerType, + OwnerId = ownerId, + ArtworkType = artworkType, + Ordinal = ordinal, + FileName = fileName, + ContentHash = contentHash, + Status = status, + Provider = provider, + LastUpdateUtc = DateTime.UtcNow, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The artwork resolved for a music library item, each with the provider that supplied it, and whether a provider answered at all. + /// + /// The resolved artworks of the item, each with the provider that supplied it. + /// Whether at least one provider answered, confirming that any absence of artwork is real rather than a failure. + private sealed record ArtworkResolution(IReadOnlyList Artworks, bool HasResolved); + + /// + /// A piece of artwork of a music library item, together with the provider that supplied it. + /// + /// The resolved artwork. + /// The name of the provider that supplied the artwork. + private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs new file mode 100644 index 00000000..065c32f1 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Interface defining the artwork enrichment of the media library items of a specific media library type. +/// +internal interface IMediaLibraryScanArtworkEnricher +{ + /// + /// The media library type that this artwork enricher supports. + /// + LibraryType SupportedLibraryType { get; } + + /// + /// Resolves the artwork of the media library items of the provided media library, using the artwork providers configured for it. + /// + /// The unique identifier of the media library whose artwork is resolved. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs index 31d7f468..64b5506a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs @@ -1,25 +1,14 @@ #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.BookLibrary.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; @@ -29,13 +18,11 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// /// 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. +/// The enrichment itself is delegated to the artwork enricher of the media library type. /// internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob { - private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -44,11 +31,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob /// Injected factory for creating scopes in which services are requested. /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details. /// - /// Injected logger used to report the issues encountered while resolving the artwork. - public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger) + public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; - _logger = logger; } /// @@ -79,113 +64,22 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines - // whether the providers that require access to the web are used during the enrichment. - string libraryName = string.Empty; - bool canDownloadMetadataFromWeb = false; - if (unitOfWork.LibraryRepository is not null) - { - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: 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; - } - } + // Load the media library, whose type determines the artwork enricher to use. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found."); + LibraryType libraryType = getLibraryResult.Value.LibraryType; - // Get the artwork providers configured for the media library, in their configured order, that support the media library type. - // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding. - List artworkProviders = []; - if (unitOfWork.ArtworkProviderConfigurationRepository is not null) - { - Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getArtworkConfigurationsResult.IsFailure) - _logger.LogWarning("Failed to read the artwork provider configurations."); - else - { - foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) - { - List configuredProviders = [.. asyncServiceScope.ServiceProvider - .GetKeyedServices(configuration.PluginId) - .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) - && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; - if (configuredProviders.Count == 0) - _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); - artworkProviders.AddRange(configuredProviders); - } - } - } + IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider + .GetServices() + .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType); + if (artworkEnricher is null) + throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'."); - // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely. - if (artworkProviders.Count > 0) - { - IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); - IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false); - Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getBooksToEnrichCountResult.IsFailure) - throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); - int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - - // Set the initial progress of the scan job. - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - int processedBooksCount = 0; - - // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size. - string? lastPath = null; - while (true) - { - cancellationToken.ThrowIfCancellationRequested(); - - Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getBooksPageResult.IsFailure) - throw new InvalidOperationException(getBooksPageResult.FirstError.Description); - IReadOnlyList booksPage = getBooksPageResult.Value; - if (booksPage.Count == 0) - break; - - // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory. - Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false); - if (getAuthorsResult.IsFailure) - throw new InvalidOperationException(getAuthorsResult.FirstError.Description); - - foreach (BookEntity bookEntity in booksPage) - { - cancellationToken.ThrowIfCancellationRequested(); - - await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); - - // Check if enough time has passed since the 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. - Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - throw new InvalidOperationException(saveChangesResult.FirstError.Description); - 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); - + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) @@ -208,199 +102,4 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false); } } - - /// - /// Resolves the cover artwork of the provided from the , in their configured order, - /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book. - /// - /// The book whose artwork is resolved. - /// The artwork providers, in their configured order. - /// The service used to store the artwork of the book. - /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. - /// The name of the media library the book belongs to. - /// The display names of the authors of the books of the current page, keyed by the Id of the book. - /// Cancellation token that can be used to stop the execution. - private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken) - { - // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped. - if (bookArtworkService is null || artworkProviders.Count == 0) - return; - - ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false); - if (resolvedArtwork is null) - { - // No artwork provider returned usable artwork, so the cover artwork of the book is marked as failed to resolve. - BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); - if (coverArtwork is null) - bookEntity.Artwork.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.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); - - // When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one - // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it. - ulong contentHash = 0; - bool shouldStoreArtwork = true; - if (!string.IsNullOrWhiteSpace(resolvedArtwork.Artwork.LocalPath)) - { - contentHash = fileHashService.ComputeFileHash(resolvedArtwork.Artwork.LocalPath); - shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash; - } - - if (shouldStoreArtwork) - { - string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; - Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false); - if (saveArtworkResult.IsFailure) - { - // A failing artwork storage must not prevent the book from being tracked as failed to resolve. - if (existingCoverArtwork is null) - bookEntity.Artwork.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.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); - else - { - existingCoverArtwork.FileName = saveArtworkResult.Value; - existingCoverArtwork.ContentHash = contentHash; - existingCoverArtwork.Status = ArtworkStatus.Enriched; - existingCoverArtwork.Provider = resolvedArtwork.ProviderName; - existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedBy = Guid.NewGuid(); - } - } - else - { - // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched. - existingCoverArtwork!.Status = ArtworkStatus.Enriched; - existingCoverArtwork.Provider = resolvedArtwork.ProviderName; - existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; - existingCoverArtwork.UpdatedBy = Guid.NewGuid(); - } - } - - /// - /// Resolves the artwork of the from the , in their configured order, - /// returning the artwork of the first provider that returns it. - /// - /// The book whose artwork is resolved. - /// The artwork providers, in their configured order. - /// Cancellation token that can be used to stop the execution. - /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork. - private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken) - { - BookMetadataLookupDto artworkLookup = new( - LibraryId: bookEntity.LibraryId, - Path: bookEntity.Path, - Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, - OpenLibraryId: bookEntity.OpenLibraryId, - Title: bookEntity.Title, - Author: null, - LanguageCode: bookEntity.LanguageCode - ); - - foreach (IArtworkProvider provider in artworkProviders) - { - ArtworkDto? artwork = null; - try - { - artwork = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false); - } - catch (Exception) - { - // A failing artwork provider must not prevent the other providers from being tried. - } - - if (artwork is null) - continue; - - // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. - if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) - continue; - - return new ResolvedArtwork(artwork, provider.Name); - } - return null; - } - - /// - /// Creates a cover artwork entity for the book identified by . - /// - /// The Id of the book the artwork belongs to. - /// The status of the artwork enrichment. - /// The relative file name of the stored artwork, if the artwork has been resolved. - /// The content hash of the stored artwork. - /// The name of the plugin that resolved the artwork, if applicable. - /// The date and time when the artwork was resolved, if applicable. - /// The created cover artwork entity. - private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc) - { - return new BookArtworkEntity - { - Id = Guid.NewGuid(), - BookId = bookId, - ArtworkType = ArtworkType.Cover, - Ordinal = 0, - FileName = fileName, - ContentHash = contentHash, - Status = status, - Provider = provider, - LastUpdateUtc = lastUpdateUtc, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - }; - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); - if (scanJobProgressResult.IsFailure) - return scanJobProgressResult.Errors; - - await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( - Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - - return Result.Success; - } - - /// - /// The artwork resolved for a book, along with the provider that supplied it. - /// - /// The resolved artwork of the book. - /// The name of the provider that supplied the artwork. - private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs new file mode 100644 index 00000000..51953e6a --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs @@ -0,0 +1,378 @@ +#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.BookLibrary.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.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using 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.WrittenContent.Books; + +/// +/// Artwork enricher for the media library items of the books media library type, using the artwork providers configured for the media library. +/// +/// +/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched. +/// +internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanArtworkEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// The media library type that this artwork enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while resolving the artwork. + public BooksMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Resolves the artwork of the books of the provided media library, using the artwork providers configured for it. + /// + /// The unique identifier of the media library whose artwork is resolved. + /// The unique identifier of the media library scan. + /// The unique identifier of the user that initiated the media library scan. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!; + IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines + // whether the providers that require access to the web are used during the enrichment. + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // Get the artwork providers configured for the media library, in their configured order, that support the media library type. + // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding. + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + artworkProviders.AddRange(configuredProviders); + } + } + } + + // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely. + if (artworkProviders.Count > 0) + { + IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); + int totalBooksToEnrich = getBooksToEnrichCountResult.Value; + + // Set the initial progress of the scan job. + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size. + string? lastPath = null; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(libraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) + throw new InvalidOperationException(getBooksPageResult.FirstError.Description); + IReadOnlyList booksPage = getBooksPageResult.Value; + if (booksPage.Count == 0) + break; + + // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory. + Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false); + if (getAuthorsResult.IsFailure) + throw new InvalidOperationException(getAuthorsResult.FirstError.Description); + + foreach (BookEntity bookEntity in booksPage) + { + cancellationToken.ThrowIfCancellationRequested(); + + await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); + + // Check if enough time has passed since the last update. + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, 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. + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); + 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); + } + + /// + /// Resolves the cover artwork of the provided from the , in their configured order, + /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book. + /// + /// The book whose artwork is resolved. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one. + /// The name of the media library the book belongs to. + /// The display names of the authors of the books of the current page, keyed by the Id of the book. + /// Cancellation token that can be used to stop the execution. + private static async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken) + { + // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped. + if (bookArtworkService is null || artworkProviders.Count == 0) + return; + + ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false); + // The books media library type tracks a single cover, so only the cover returned by the provider is stored. + ArtworkDto? resolvedCover = resolvedArtwork?.Artworks.FirstOrDefault(artwork => artwork.Type == ArtworkType.Cover); + if (resolvedCover is null || resolvedArtwork is null) + { + // No artwork provider returned a usable cover, so the cover artwork of the book is marked as failed to resolve. + BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + if (coverArtwork is null) + bookEntity.Artwork.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.Artwork.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(resolvedCover.LocalPath)) + { + contentHash = fileHashService.ComputeFileHash(resolvedCover.LocalPath); + shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash; + } + + if (shouldStoreArtwork) + { + string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty; + Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedCover, 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.Artwork.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.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); + else + { + existingCoverArtwork.FileName = saveArtworkResult.Value; + existingCoverArtwork.ContentHash = contentHash; + existingCoverArtwork.Status = ArtworkStatus.Enriched; + existingCoverArtwork.Provider = resolvedArtwork.ProviderName; + existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + } + else + { + // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched. + existingCoverArtwork!.Status = ArtworkStatus.Enriched; + existingCoverArtwork.Provider = resolvedArtwork.ProviderName; + existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow; + existingCoverArtwork.UpdatedBy = Guid.NewGuid(); + } + } + + /// + /// Resolves the artwork of the from the , in their configured order, + /// returning the artwork of the first provider that returns it. + /// + /// The book whose artwork is resolved. + /// The artwork providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork. + private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken) + { + BookMetadataLookupDto artworkLookup = new( + LibraryId: bookEntity.LibraryId, + Path: bookEntity.Path, + Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, + OpenLibraryId: bookEntity.OpenLibraryId, + Title: bookEntity.Title, + Author: null, + LanguageCode: bookEntity.LanguageCode + ); + + foreach (IArtworkProvider provider in artworkProviders) + { + IReadOnlyList artworks = []; + try + { + artworks = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + // A failing artwork provider must not prevent the other providers from being tried. + } + + // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract. + IReadOnlyList usableArtworks = [.. artworks.Where(artwork => artwork.Type == ArtworkType.Cover && (string.IsNullOrWhiteSpace(artwork.RemoteUrl) || provider.RequiresWebAccess))]; + if (usableArtworks.Count == 0) + continue; + + return new ResolvedArtwork(usableArtworks, provider.Name); + } + return null; + } + + /// + /// Creates a cover artwork entity for the book identified by . + /// + /// The Id of the book the artwork belongs to. + /// The status of the artwork enrichment. + /// The relative file name of the stored artwork, if the artwork has been resolved. + /// The content hash of the stored artwork. + /// The name of the plugin that resolved the artwork, if applicable. + /// The date and time when the artwork was resolved, if applicable. + /// The created cover artwork entity. + private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc) + { + return new BookArtworkEntity + { + Id = Guid.NewGuid(), + BookId = bookId, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = fileName, + ContentHash = contentHash, + Status = status, + Provider = provider, + LastUpdateUtc = lastUpdateUtc, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private static async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork"); + if (scanJobProgressResult.IsFailure) + return scanJobProgressResult.Errors; + + await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent( + Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + + return Result.Success; + } + + /// + /// The artwork resolved for a book, along with the provider that supplied it. + /// + /// The resolved artworks of the book. + /// The name of the provider that supplied the artwork. + private sealed record ResolvedArtwork(IReadOnlyList Artworks, string ProviderName); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs index 1355aaff..33a82ee5 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs @@ -8,6 +8,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.Utilities; +using Lumina.Infrastructure.Common.Networking; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; @@ -240,7 +242,7 @@ internal sealed class BookArtworkService : IBookArtworkService return copyFileResult.Errors; // Rename the copied file to the standard naming. - Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}"); + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToFileExtension()}"); if (renameFileResult.IsFailure) return renameFileResult.Errors; @@ -266,7 +268,7 @@ internal sealed class BookArtworkService : IBookArtworkService return Errors.FileSystemManagement.FileNotFound; // Download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size. - using HttpClient httpClient = _httpClientFactory.CreateClient(); + using HttpClient httpClient = _httpClientFactory.CreateClient(NamedHttpClients.ARTWORK_DOWNLOAD); string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); bool downloaded = false; try diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs index 09b9250c..855fce9e 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs @@ -29,10 +29,10 @@ public interface IArtworkProvider bool RequiresWebAccess { get; } /// - /// Gets the artwork of the media item described by . + /// Gets the artworks of the media item described by . /// /// The lookup describing the media item to get the artwork for. /// Cancellation token that can be used to stop the execution. - /// The artwork of the media item, or when no artwork was found. - Task GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); + /// The artworks of the media item, or an empty collection when no artwork was found. + Task> GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); } diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs index ea296737..e1f3b94b 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -14,21 +15,21 @@ public interface IArtworkProvider : IArtworkProvider where TLookup : MetadataLookupDto { /// - /// Gets the artwork of the media item described by . + /// Gets the artworks of the media item described by . /// /// The lookup describing the media item to get the artwork for. /// Cancellation token that can be used to stop the execution. - /// The artwork of the media item, or when no artwork was found. - Task GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken); + /// The artworks of the media item, or an empty collection when no artwork was found. + Task> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken); /// - /// Gets the artwork of the media item described by . + /// Gets the artworks of the media item described by . /// /// The lookup describing the media item to get the artwork for. /// Cancellation token that can be used to stop the execution. - /// The artwork of the media item, or when no artwork was found or the lookup is of another runtime type. - async Task IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) + /// The artworks of the media item, or an empty collection when no artwork was found or the lookup is of another runtime type. + async Task> IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { - return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null; + return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : []; } } diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs index aef276fc..824f1ce4 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -23,6 +24,11 @@ public interface IMetadataProvider /// IReadOnlyList SupportedLibraryTypes { get; } + /// + /// Gets the type of the metadata lookup this provider accepts, used to select the provider that matches a given lookup. + /// + Type LookupType { get; } + /// /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. /// diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs index 980a4d9e..7ea2f873 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -32,15 +33,20 @@ public interface IMetadataProvider : IMetadataProvider /// The metadata of the media item, or when no metadata was found. Task GetMetadataAsync(TLookup lookup, CancellationToken cancellationToken); + /// + /// Gets the type of the metadata lookup this provider accepts. + /// + Type IMetadataProvider.LookupType => typeof(TLookup); + /// /// Searches for the metadata of the media item described by . /// /// The lookup describing the media item to search for. /// Cancellation token that can be used to stop the execution. - /// The collection of metadata candidates found for the media item. + /// The collection of metadata candidates found for the media item, or an empty collection when the lookup is of another runtime type. async Task> IMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { - return await GetSearchResultsAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); + return lookup is TLookup typedLookup ? await GetSearchResultsAsync(typedLookup, cancellationToken).ConfigureAwait(false) : []; } /// @@ -48,9 +54,9 @@ public interface IMetadataProvider : IMetadataProvider /// /// The lookup describing the media item to get the metadata for. /// Cancellation token that can be used to stop the execution. - /// The metadata of the media item, or when no metadata was found. + /// The metadata of the media item, or when no metadata was found or the lookup is of another runtime type. async Task IMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { - return await GetMetadataAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); + return lookup is TLookup typedLookup ? await GetMetadataAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null; } } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs new file mode 100644 index 00000000..753064fa --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +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.AudioLibrary.MusicLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the artwork. + /// Optional. The type of the music library item that owns the artwork. + /// Optional. The Id of the music library item that owns the artwork. + /// Optional. The type of the artwork. + /// Optional. The ordinal of the artwork within its type. + /// Optional. The relative file name of the stored artwork. + /// Optional. The content hash of the stored artwork. + /// Optional. The status of the artwork enrichment. + /// Optional. The name of the plugin that resolved the artwork. + /// Optional. The date and time when the artwork was last resolved. + /// Whether the file name should be included, or forced to . + /// Whether the provider should be included, or forced to . + /// Whether the last update date should be included, or forced to . + /// The created . + public MusicArtworkEntity Create( + Guid? id = null, + MusicArtworkOwnerType? ownerType = null, + Guid? ownerId = null, + ArtworkType? artworkType = null, + int? ordinal = null, + string? fileName = null, + ulong? contentHash = null, + ArtworkStatus? status = null, + string? provider = null, + DateTime? lastUpdateUtc = null, + bool includeFileName = true, + bool includeProvider = true, + bool includeLastUpdateUtc = true) + { + return new MusicArtworkEntity + { + Id = id ?? Guid.NewGuid(), + OwnerType = ownerType ?? _faker.PickRandom(), + OwnerId = ownerId ?? Guid.NewGuid(), + ArtworkType = artworkType ?? _faker.PickRandom(), + Ordinal = ordinal ?? _faker.Random.Int(0, 5), + FileName = includeFileName ? (fileName ?? _faker.System.FilePath()) : null, + ContentHash = contentHash ?? (ulong)_faker.Random.ULong(), + Status = status ?? _faker.PickRandom(), + Provider = includeProvider ? (provider ?? _faker.Company.CompanyName()) : null, + LastUpdateUtc = includeLastUpdateUtc ? (lastUpdateUtc ?? _faker.Date.Recent()) : null, + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = null, + UpdatedBy = null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs index 7226bbf4..6c6f41e5 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs @@ -7,6 +7,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.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.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs new file mode 100644 index 00000000..50f9f53d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -0,0 +1,763 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Infrastructure.Fixtures.Common.Setup; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkServiceTests +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly MusicArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + private readonly StubHttpMessageHandler _stubHttpMessageHandler = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + _mockHttpClientFactory.CreateClient(Arg.Any()).Returns(new HttpClient(_stubHttpMessageHandler)); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpg"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Theory] + [InlineData(ArtworkType.Cover, 0, "cover.jpg")] // the front cover uses the bare type name + [InlineData(ArtworkType.Back, 0, "back.jpg")] // the back cover uses the bare type name + [InlineData(ArtworkType.Medium, 0, "medium.jpg")] // a single medium uses the bare type name + [InlineData(ArtworkType.Booklet, 0, "booklet.jpg")] // the first booklet page uses the bare type name + [InlineData(ArtworkType.Booklet, 2, "booklet-2.jpg")] // a further booklet page is suffixed with its ordinal + [InlineData(ArtworkType.Liner, 1, "liner-1.jpg")] // a liner note page is suffixed with its ordinal + [InlineData(ArtworkType.Other, 0, "other.jpg")] // any other type falls back to the generic name + public async Task SaveAlbumArtworkAsync_WhenTheArtworkHasAType_ShouldNameTheFileAfterTheTypeAndOrdinal(ArtworkType artworkType, int ordinal, string expectedFileName) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "artwork.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), expectedFileName) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName)))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), expectedFileName); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtistNameIsMissing_ShouldUseUnknownForTheDirectorySegment() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName: "Unknown", albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).SanitizeSegment("Unknown"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // The environment does not support creating reparse points. + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage() + { + // Arrange + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[1024]); + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())), + Arg.Any(), + true); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(sourcePath)); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + MockPathBuilding(); + + // Act + async Task Act() + { + await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type")); + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Directory.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().RenameFile(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtistNameCannotBeSanitized_ShouldReturnInvalidPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string sourcePath = CreateTempImageFile(); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string musicPath = Path.Combine(mediaRoot, "music"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "music").Returns(Result.From(musicPath)); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return name == $"{libraryName}-{libraryId}" + ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)) + : Errors.FileSystemManagement.InvalidPath; + }); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg")); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([coverFileId, bookletFileId])); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(coverFileId); + _mockFileProviderService.Received(1).DeleteFile(bookletFileId); + } + + /// + /// Stubs the path service so that building the artwork directory paths succeeds. + /// + private void MockPathBuilding() + { + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + MockPathBuilding(); + + // Every directory except the artwork directory itself already exists, so that only the final directory is created. + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the album is stored into. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The expected file system path of the album artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName, + $"{albumTitle}-{albumId}"); + } + + /// + /// Creates a temporary image file and returns its path. + /// + /// The size of the temporary image file, in bytes. + /// The file system path of the created temporary image file. + private static string CreateTempImageFile(int smallImageBytes = 1024) + { + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[smallImageBytes]); + return sourcePath; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + Process process = Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 13b9f52b..5456488f 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -65,7 +65,7 @@ public class BookArtworkServiceTests _mockPathService.PathSeparator.Returns('\\'); _mockHttpClientFactory = Substitute.For(); - _mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler)); + _mockHttpClientFactory.CreateClient(Arg.Any()).Returns(new HttpClient(_stubHttpMessageHandler)); MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); _mockMediaSettingsOptions = Substitute.For>(); @@ -98,9 +98,9 @@ public class BookArtworkServiceTests _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(copiedFileId)); - string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg"); + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -113,7 +113,7 @@ public class BookArtworkServiceTests Arg.Is(pathId => pathId.Path == sourcePath), Arg.Any(), true); - _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpeg"); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpg"); } finally { @@ -140,10 +140,10 @@ public class BookArtworkServiceTests string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -264,8 +264,8 @@ public class BookArtworkServiceTests _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -327,10 +327,10 @@ public class BookArtworkServiceTests string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Result.From(renamedFileId)); // Act @@ -521,7 +521,7 @@ public class BookArtworkServiceTests MockArtworkDirectoryStubs(artworkDirectoryPath); _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); // Act diff --git a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs index e337b06b..d4e78cbe 100644 --- a/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs +++ b/tests/IntegrationTests/Lumina.Plugins.Calibre.IntegrationTests/Core/CalibreArtworkProviderTests.cs @@ -4,6 +4,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Plugins.Calibre.Core; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; @@ -34,12 +35,12 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.NotNull(result); - Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); - Assert.Null(result.RemoteUrl); + ArtworkDto artwork = Assert.Single(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), artwork.LocalPath); + Assert.Null(artwork.RemoteUrl); } finally { @@ -59,10 +60,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -85,10 +86,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -108,10 +109,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -130,10 +131,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { @@ -153,10 +154,10 @@ public class CalibreArtworkProviderTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } finally { diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs index 364d4351..169819d2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -120,8 +120,8 @@ public class BookArtworkServiceSecurityTests string capturedDestinationPath = string.Empty; _mockFileProviderService.CopyFile(Arg.Any(), Arg.Do(destination => capturedDestinationPath = destination.Path), true) .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg")))); - _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") - .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg")))); // Act char separator = Path.DirectorySeparatorChar; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs new file mode 100644 index 00000000..6987317f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/MusicArtworkConfigurationTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("MusicArtwork", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + IProperty ownerTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerType)); + IProperty ownerIdProperty = entityType.GetProperty(nameof(MusicArtworkEntity.OwnerId)); + IProperty artworkTypeProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ArtworkType)); + IProperty ordinalProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Ordinal)); + IProperty fileNameProperty = entityType.GetProperty(nameof(MusicArtworkEntity.FileName)); + IProperty contentHashProperty = entityType.GetProperty(nameof(MusicArtworkEntity.ContentHash)); + IProperty statusProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Status)); + IProperty providerProperty = entityType.GetProperty(nameof(MusicArtworkEntity.Provider)); + IProperty lastUpdateUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.LastUpdateUtc)); + + // Assert + Assert.False(ownerTypeProperty.IsNullable); + Assert.Equal(typeof(MusicArtworkOwnerType), ownerTypeProperty.ClrType); + Assert.Equal("TEXT", ownerTypeProperty.GetColumnType()); + Assert.Equal(50, ownerTypeProperty.GetMaxLength()); + Assert.False(ownerIdProperty.IsNullable); + Assert.False(artworkTypeProperty.IsNullable); + Assert.Equal(typeof(ArtworkType), artworkTypeProperty.ClrType); + Assert.Equal("TEXT", artworkTypeProperty.GetColumnType()); + Assert.Equal(50, artworkTypeProperty.GetMaxLength()); + Assert.False(ordinalProperty.IsNullable); + Assert.True(fileNameProperty.IsNullable); + Assert.Equal(2048, fileNameProperty.GetMaxLength()); + Assert.False(contentHashProperty.IsNullable); + Assert.False(statusProperty.IsNullable); + Assert.Equal(typeof(ArtworkStatus), statusProperty.ClrType); + Assert.Equal("TEXT", statusProperty.GetColumnType()); + Assert.Equal(20, statusProperty.GetMaxLength()); + Assert.True(providerProperty.IsNullable); + Assert.Equal(100, providerProperty.GetMaxLength()); + Assert.True(lastUpdateUtcProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueOwnerArtworkIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + IIndex uniqueIndex = Assert.Single(indexes, index => index.IsUnique); + Assert.Equal( + [nameof(MusicArtworkEntity.OwnerType), nameof(MusicArtworkEntity.OwnerId), nameof(MusicArtworkEntity.ArtworkType), nameof(MusicArtworkEntity.Ordinal)], + uniqueIndex.Properties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexOnStatus() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(MusicArtworkEntity.Status)])); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(MusicArtworkEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(MusicArtworkEntity.UpdatedBy)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.True(updatedOnUtcProperty.IsNullable); + Assert.True(updatedByProperty.IsNullable); + } + + /// + /// Disposes the database context. + /// + public void Dispose() + { + _context.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs new file mode 100644 index 00000000..4fb1496f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/MusicArtworkRepositoryTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +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.MusicLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkRepositoryTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly LuminaDbContext _context; + private readonly MusicArtworkRepository _sut; + private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkRepositoryTests() + { + // the repository deletes and updates in bulk, which translates to SQL, so it can only be exercised against a real SQLite database + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connection).Options); + _context.Database.EnsureCreated(); + _sut = new MusicArtworkRepository(_context); + } + + [Fact] + public async Task InsertRangeAsync_WhenCalledWithArtwork_ShouldAddThemToContextAndReturnCreated() + { + // Arrange + List artwork = _musicArtworkEntityFixture.CreateMany(3); + + // Act + Result result = await _sut.InsertRangeAsync(artwork, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await _context.SaveChangesAsync(); + Assert.Equal(3, await _context.MusicArtwork.CountAsync()); + } + + [Fact] + public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutAddingAnyArtwork() + { + // Act + Result result = await _sut.InsertRangeAsync([], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + await _context.SaveChangesAsync(); + Assert.Empty(await _context.MusicArtwork.ToListAsync()); + } + + [Fact] + public async Task GetByOwnerAsync_WhenCalled_ShouldReturnOnlyTheArtworkOfTheOwnerOrderedByTypeThenOrdinal() + { + // Arrange + MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album; + Guid ownerId = Guid.NewGuid(); + MusicArtworkEntity frontSecond = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 1); + MusicArtworkEntity frontFirst = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Front, ordinal: 0); + MusicArtworkEntity cover = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId, artworkType: ArtworkType.Cover, ordinal: 0); + MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: Guid.NewGuid()); + MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: ownerId); + _context.MusicArtwork.AddRange(frontSecond, frontFirst, cover, artworkOfAnotherOwner, artworkOfAnotherOwnerType); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByOwnerAsync(ownerType, ownerId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([cover.Id, frontFirst.Id, frontSecond.Id], result.Value.Select(artwork => artwork.Id)); + } + + [Fact] + public async Task GetByOwnerAsync_WhenTheOwnerHasNoArtwork_ShouldReturnAnEmptyCollection() + { + // Act + Result> result = await _sut.GetByOwnerAsync(MusicArtworkOwnerType.Track, Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task DeleteByOwnerAsync_WhenCalled_ShouldDeleteOnlyTheArtworkOfTheOwner() + { + // Arrange + MusicArtworkOwnerType ownerType = MusicArtworkOwnerType.Album; + Guid ownerId = Guid.NewGuid(); + MusicArtworkEntity artworkOfOwner = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: ownerId); + MusicArtworkEntity artworkOfAnotherOwner = _musicArtworkEntityFixture.Create(ownerType: ownerType, ownerId: Guid.NewGuid()); + MusicArtworkEntity artworkOfAnotherOwnerType = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: ownerId); + _context.MusicArtwork.AddRange(artworkOfOwner, artworkOfAnotherOwner, artworkOfAnotherOwnerType); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByOwnerAsync(ownerType, ownerId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + List remainingArtwork = await _context.MusicArtwork.ToListAsync(); + Assert.Equal(2, remainingArtwork.Count); + Assert.DoesNotContain(remainingArtwork, artwork => artwork.Id == artworkOfOwner.Id); + Assert.Contains(remainingArtwork, artwork => artwork.Id == artworkOfAnotherOwner.Id); + Assert.Contains(remainingArtwork, artwork => artwork.Id == artworkOfAnotherOwnerType.Id); + } + + [Fact] + public async Task DeleteByOwnerAsync_WhenNoArtworkExistsForTheOwner_ShouldReturnDeleted() + { + // Act + Result result = await _sut.DeleteByOwnerAsync(MusicArtworkOwnerType.Track, Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + } + + [Fact] + public async Task ResetStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkOfTheLibraryItemsToPending() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _context.Artists.AddRange(artist, artistOfAnotherLibrary); + _context.Albums.Add(album); + _context.Tracks.Add(track); + MusicArtworkEntity artistArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artist.Id, status: ArtworkStatus.Enriched); + MusicArtworkEntity albumArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Album, ownerId: album.Id, status: ArtworkStatus.Enriched); + MusicArtworkEntity trackArtwork = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Track, ownerId: track.Id, status: ArtworkStatus.Enriched); + MusicArtworkEntity artworkOfAnotherLibrary = _musicArtworkEntityFixture.Create(ownerType: MusicArtworkOwnerType.Artist, ownerId: artistOfAnotherLibrary.Id, status: ArtworkStatus.Enriched); + _context.MusicArtwork.AddRange(artistArtwork, albumArtwork, trackArtwork, artworkOfAnotherLibrary); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.ResetStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + // the bulk update bypasses the change tracker, so the tracked entities are detached before the stored values are read back + _context.ChangeTracker.Clear(); + Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(artistArtwork.Id))!.Status); + Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(albumArtwork.Id))!.Status); + Assert.Equal(ArtworkStatus.Pending, (await _context.MusicArtwork.FindAsync(trackArtwork.Id))!.Status); + Assert.Equal(ArtworkStatus.Enriched, (await _context.MusicArtwork.FindAsync(artworkOfAnotherLibrary.Id))!.Status); + } + + /// + /// Disposes the database context and its underlying connection. + /// + public void Dispose() + { + _context.Dispose(); + _connection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs new file mode 100644 index 00000000..f79aef01 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -0,0 +1,252 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicArtworkServiceTests +{ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly MusicArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + MockPathBuilding(); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound() + { + // Arrange + MockPathBuilding(); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + MockPathBuilding(); + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + } + + [Fact] + public void DeleteAlbumArtwork_WhenListingTheArtworkFilesFails_ShouldReturnTheError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files")); + + // Act + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Fact] + public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg")); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([coverFileId, bookletFileId])); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(coverFileId); + _mockFileProviderService.Received(1).DeleteFile(bookletFileId); + } + + [Fact] + public void DeleteAlbumArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError() + { + // Arrange + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album"); + + // Assert + Assert.True(result.IsFailure); + _mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any(), true); + } + + [Fact] + public void DeleteAlbumArtwork_WhenBuildingTheDirectoryPathFails_ShouldReturnTheError() + { + // Arrange + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + /// + /// Stubs the path service so that building the artwork directory paths succeeds. + /// + private void MockPathBuilding() + { + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + MockPathBuilding(); + + // Every directory except the artwork directory itself already exists, so that only the final directory is created. + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the album is stored into. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The expected file system path of the album artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName, + $"{albumTitle}-{albumId}"); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs new file mode 100644 index 00000000..4f1a823e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs @@ -0,0 +1,604 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaLibraryScanArtworkEnricherTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IMusicArtworkRepository _mockMusicArtworkRepository; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IMusicArtworkService _mockMusicArtworkService; + private readonly IFileHashService _mockFileHashService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly TestArtworkProvider _artistProvider; + private readonly TestArtworkProvider _albumProvider; + private readonly MusicMediaLibraryScanArtworkEnricher _sut; + private readonly ServiceProvider _serviceProvider; + private readonly Guid _artistPluginId = Guid.NewGuid(); + private readonly Guid _albumPluginId = Guid.NewGuid(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryScanArtworkEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockArtworkProviderConfigurationRepository = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockMusicArtworkRepository = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository); + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + + _artistProvider = new TestArtworkProvider { Name = "Artist Provider", RequiresWebAccess = false }; + _albumProvider = new TestArtworkProvider { Name = "Album Provider", RequiresWebAccess = false }; + + _mockMusicArtworkService = Substitute.For(); + _mockFileHashService = Substitute.For(); + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + + // the enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept, + // so a real container is used to honor the keyed registration of the typed providers. + ServiceCollection services = new(); + services.AddScoped(_ => _mockUnitOfWork); + services.AddScoped(_ => _mockDomainEventPublisher); + services.AddSingleton(_mockMusicArtworkService); + services.AddSingleton(_mockFileHashService); + services.AddKeyedSingleton(_artistPluginId, _artistProvider); + services.AddKeyedSingleton(_albumPluginId, _albumProvider); + _serviceProvider = services.BuildServiceProvider(); + + _sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + + // Default stubs that keep the happy path working, overridden per test where needed. + SetupLibrary(); + SetupConfiguration(); + _mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + _mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(0)); + _mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(0)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(new Dictionary())); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + SetupSuccessArtworkStorage(); + } + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnMusic() + { + // Act + LibraryType result = _sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Music, result); + } + + [Fact] + public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment() + { + // Arrange + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment() + { + // Arrange + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Provider.Error", "Failed to read the configurations")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + _artistProvider.RequiresWebAccess = true; + _albumProvider.RequiresWebAccess = true; + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + _artistProvider.RequiresWebAccess = true; + AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value); + SetupAlbums(album); + _albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + Assert.Equal(1, _albumProvider.CallCount); + Assert.Equal(0, _artistProvider.CallCount); + } + + [Fact] + public async Task EnrichAsync_WhenTheArtistProviderReturnsArtwork_ShouldStoreAndPersistEnrichedArtistArtwork() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync( + _libraryId.Value, + Arg.Any(), + artist.Name, + Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), + Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().OwnerType == MusicArtworkOwnerType.Artist + && entities.First().OwnerId == artist.Id + && entities.First().ArtworkType == ArtworkType.Cover + && entities.First().Ordinal == 0 + && entities.First().Status == ArtworkStatus.Enriched + && entities.First().Provider == "Artist Provider" + && entities.First().FileName == "/media/music/cover.jpg" + && entities.First().ContentHash == 123UL), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumProviderReturnsArtwork_ShouldStoreAndPersistEnrichedAlbumArtwork() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value); + SetupAlbums(album); + _albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync( + _libraryId.Value, + album.Id, + Arg.Any(), + Arg.Any(), + album.Title, + Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), + Arg.Any(), + Arg.Any()); + await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any()); + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().OwnerType == MusicArtworkOwnerType.Album + && entities.First().OwnerId == album.Id + && entities.First().Status == ArtworkStatus.Enriched + && entities.First().Provider == "Album Provider"), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheProviderAnswersWithNoArtwork_ShouldMarkTheArtistNotAvailable() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().Status == ArtworkStatus.NotAvailable + && entities.First().FileName == null + && entities.First().Provider == null), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheArtistFailed() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromException>(new HttpRequestException("Transient failure.")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheArtistFailed() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to store the artwork")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed), + Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldLeaveTheArtistUnresolved() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenClearingTheStoredArtworkRecordsFails_ShouldLeaveTheArtistUnresolved() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork records")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumHasNoMusicBrainzIdentifierAndNoLocalProvider_ShouldLeaveItUnresolved() + { + // Arrange + _albumProvider.RequiresWebAccess = true; + AlbumEntity album = _albumEntityFixture.Create( + libraryId: _libraryId.Value, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false); + SetupAlbums(album); + _albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + Assert.Equal(0, _albumProvider.CallCount); + await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumCountCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to count the albums")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheAlbumsPageCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the albums")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheTrackPathsCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value); + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([album])); + _mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the track paths")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value); + SetupArtists(artist); + _artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to save the changes")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + /// + /// Stubs the media library reader with a library owned by the test user. + /// + /// Whether the library allows downloading data from the web. + private void SetupLibrary(bool canDownloadMetadataFromWeb = true) + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + canDownloadMetadataFromWeb: canDownloadMetadataFromWeb); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the artwork provider configuration reader with one enabled configuration per test plugin. + /// + private void SetupConfiguration() + { + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>( + [ + _artworkConfigurationFixture.Create(_libraryId.Value, _artistPluginId, 0), + _artworkConfigurationFixture.Create(_libraryId.Value, _albumPluginId, 1) + ])); + } + + /// + /// Stubs the artist reader with a single page holding the provided artists. + /// + /// The artists of the page. + private void SetupArtists(params ArtistEntity[] artists) + { + _mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(artists.Length)); + _mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(artists), + Result.From>([])); + } + + /// + /// Stubs the album reader with a single page holding the provided albums. + /// + /// The albums of the page. + private void SetupAlbums(params AlbumEntity[] albums) + { + _mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(albums.Length)); + _mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(albums), + Result.From>([])); + Dictionary trackPaths = albums.ToDictionary(album => album.Id, album => "/music/artist/album/track.flac"); + _mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(trackPaths)); + } + + /// + /// Stubs the artwork storage and persistence so that an item is stored successfully. + /// + private void SetupSuccessArtworkStorage() + { + _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/music/cover.jpg")); + _mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/music/cover.jpg")); + _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); + _mockMusicArtworkRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockFileHashService.ComputeFileHash(Arg.Any()).Returns(123UL); + } + + /// + /// Deterministic artwork provider for a specific lookup type, used instead of a substitute because the default implementation of + /// cannot be intercepted reliably. + /// + /// The type of the lookup the provider accepts. + private sealed class TestArtworkProvider : IArtworkProvider where TLookup : MetadataLookupDto + { + /// + /// Gets or sets the display name of the artwork provider. + /// + public string Name { get; set; } = string.Empty; + + /// + /// Gets or sets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes { get; set; } = [LibraryType.Music]; + + /// + /// Gets or sets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess { get; set; } + + /// + /// Gets or sets the callback that supplies the artwork of a media item. + /// + public Func>> OnGetArtworkAsync { get; set; } = (_, _) => Task.FromResult>([]); + + /// + /// Gets the number of times the provider was asked for artwork. + /// + public int CallCount { get; private set; } + + /// + /// Gets the artworks of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artworks of the media item, or an empty collection when no artwork was found. + public Task> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken) + { + CallCount++; + return OnGetArtworkAsync(lookup, cancellationToken); + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs index 5a2e3bc1..1bcd1732 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJobTests.cs @@ -1,18 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Security; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -23,17 +13,13 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; -using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -50,19 +36,14 @@ public class MediaLibraryScanArtworkEnrichmentJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; - private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository; - private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaLibraryScanArtworkEnricher _mockArtworkEnricher; private readonly IDomainEventPublisher _mockDomainEventPublisher; - private readonly ILogger _mockLogger; private readonly MediaLibraryScanArtworkEnrichmentJob _sut; private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); - private readonly BookEntityFixture _bookEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); - private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); - private readonly ArtworkDtoFixture _artworkDtoFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; private readonly LibraryId _libraryId; @@ -79,23 +60,27 @@ public class MediaLibraryScanArtworkEnrichmentJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); - _mockArtworkConfigurationRepository = Substitute.For(); - _mockBookRepository = Substitute.For(); - _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); - _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // the job resolves the artwork enricher of the loaded library type from the service scope, so the music enricher must be available + _mockArtworkEnricher = Substitute.For(); + _mockArtworkEnricher.SupportedLibraryType.Returns(LibraryType.Music); + _mockArtworkEnricher.EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanArtworkEnricher[] { _mockArtworkEnricher }); + _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); - _mockLogger = Substitute.For>(); - _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); - _sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger) + _sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory) { ScanId = _scanId, UserId = _userId, @@ -104,729 +89,39 @@ public class MediaLibraryScanArtworkEnrichmentJobTests } [Fact] - public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndTrackTheCoverArtworkAsEnriched() + public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent() { // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - await mockBookArtworkService.Received(1).SaveBookArtworkAsync( - _libraryId.Value, - book.Id, - "My Library", - "Frank Herbert", - "Test Title", - Arg.Any(), - Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); - Assert.Equal(0, coverArtwork.Ordinal); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(123ul, coverArtwork.ContentHash); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.NotNull(coverArtwork.LastUpdateUtc); + await _mockArtworkEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } [Fact] - public async Task ExecuteAsync_WhenResolvedArtworkIsIdenticalToTheStoredOne_ShouldKeepTheStoredArtworkAndMarkItAsEnriched() + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - // the book already has a stored cover with the same content hash as the resolved artwork - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept - await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.NotNull(coverArtwork.LastUpdateUtc); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoProviderReturnsArtwork_ShouldMarkTheCoverArtworkAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns((ArtworkDto?)null); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); - Assert.Equal(0, coverArtwork.Ordinal); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Null(coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichmentWithoutMarkingBooksAsFailed() - { - // Arrange - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a library without artwork providers must not mark its books as failed to resolve, so the books are not even queried - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() - { - // Arrange - using CancellationTokenSource cancellationTokenSource = new(); - cancellationTokenSource.Cancel(); - - // Act - Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); - - // Assert - await Assert.ThrowsAnyAsync(() => operation); - Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenReadingArtworkProviderConfigurationsFails_ShouldLogWarningAndSkipEnrichment() - { - // Arrange - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to read the artwork provider configurations")); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a failure to read the artwork configurations is best-effort, so the enrichment is skipped without touching the books - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenTheConfiguredArtworkProviderIsNotRegistered_ShouldLogWarningAndSkipEnrichment() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - // the configuration references a plugin that is not registered in the dependency injection container - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1)])); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldSkipArtworkProvidersThatRequireWebAccess() - { - // Arrange - Guid webPluginId = Guid.NewGuid(); - Guid localPluginId = Guid.NewGuid(); - IArtworkProvider webProvider = Substitute.For(); - webProvider.Name.Returns("Web Provider"); - webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - webProvider.RequiresWebAccess.Returns(true); - IArtworkProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/local-cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/local-cover.jpg").Returns(111UL); - - ServiceCollection services = new(); - services.AddKeyedSingleton(webPluginId, webProvider); - services.AddKeyedSingleton(localPluginId, localProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - services.AddSingleton(mockFileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: false))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, webPluginId, 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, localPluginId, 2) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the provider that requires access to the web is skipped when the library does not permit web downloads - await webProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("Local Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenCountingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingTheBooksNeedingArtworkFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingTheAuthorDisplayNamesFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the author display names")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoProviderReturnsArtworkAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns((ArtworkDto?)null); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - IFileHashService mockFileHashService = Substitute.For(); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 123ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasNoExistingCover_ShouldTrackTheCoverAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(111UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Null(coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenStoringTheArtworkFailsAndTheBookHasAnExistingCover_ShouldMarkTheExistingCoverAsFailed() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Storage.Error", "Failed to store the artwork")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); - Assert.Equal("existing\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheResolvedArtworkIsRemote_ShouldComputeTheContentHashOfTheStoredArtwork() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.RequiresWebAccess.Returns(true); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash(Arg.Any()).Returns(999UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, artworkPluginId); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // for remote artwork, the content hash is computed on the stored copy, so it is only known after the artwork is stored - await mockBookArtworkService.Received(1).SaveBookArtworkAsync(_libraryId.Value, book.Id, "My Library", "Frank Herbert", Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(999ul, coverArtwork.ContentHash); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheBookHasAnExistingCoverAndTheArtworkDiffersFromIt_ShouldStoreItAndUpdateTheExistingCover() - { - // Arrange - Guid artworkPluginId = Guid.NewGuid(); - IArtworkProvider artworkProvider = Substitute.For(); - artworkProvider.Name.Returns("Artwork Provider"); - artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(222UL); - - SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); - // the book has no known ISBNs of its own, so the artwork lookup is built without an ISBN - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title", includeMetadata: false); - book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: "existing\\cover.jpeg", contentHash: 111ul, status: ArtworkStatus.Pending, provider: "Old Provider", lastUpdateUtc: DateTime.UtcNow.AddDays(-1))]; - SetupSingleBookPage(book, artworkPluginId); - // the author of the book is not known, so its artwork directory falls back to an empty author name - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary())); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await mockBookArtworkService.Received(1).SaveBookArtworkAsync( - _libraryId.Value, - book.Id, - "My Library", - string.Empty, - "Test Title", - Arg.Any(), - Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("\\media\\books\\Library\\Author\\Title\\cover.jpeg", coverArtwork.FileName); - Assert.Equal(222ul, coverArtwork.ContentHash); - Assert.Equal("Artwork Provider", coverArtwork.Provider); - Assert.NotNull(coverArtwork.LastUpdateUtc); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAnArtworkProviderThrows_ShouldTryTheNextProvider() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IArtworkProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The artwork provider failed"))); - IArtworkProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(333UL); - - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - services.AddKeyedSingleton(secondPluginId, secondProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - services.AddSingleton(mockFileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a failing artwork provider must not prevent the artwork of the other provider from being used - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("Second Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAProviderReturnsRemoteArtworkWithoutRequiringWebAccess_ShouldSkipItAndUseTheNextProvider() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IArtworkProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.RequiresWebAccess.Returns(false); - firstProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg")); - IArtworkProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) - .Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg")); - - IBookArtworkService mockBookArtworkService = Substitute.For(); - mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); - IFileHashService mockFileHashService = Substitute.For(); - mockFileHashService.ComputeFileHash("/some/second-cover.jpg").Returns(444UL); - - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - services.AddKeyedSingleton(secondPluginId, secondProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(mockBookArtworkService); - services.AddSingleton(mockFileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1), - _artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a provider that returns remote artwork must require web access, so its artwork is skipped and the next provider is used - BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); - Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); - Assert.Equal("Second Provider", coverArtwork.Provider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() - { - // Arrange - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - IMediaLibraryScanJob mockChildJob = Substitute.For(); - mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - _sut.AddChild(mockChildJob); - Guid id = Guid.NewGuid(); - object input = new(); - - // Act - await _sut.ExecuteAsync(id, input, CancellationToken.None); - - // Assert - await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - /// - /// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container. - /// - /// The Id of the plugin providing the artwork. - /// The artwork provider to resolve. - /// The service used to store the artwork of the books. - /// The service used to hash the artwork. - private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService) - { - ServiceCollection services = new(); - services.AddKeyedSingleton(artworkPluginId, artworkProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - services.AddSingleton(bookArtworkService); - services.AddSingleton(fileHashService); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - } - - /// - /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider. - /// - /// The book whose artwork the job must resolve. - /// The Id of the plugin configured as artwork provider for the library. - private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId) - { - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([ - _artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1) - ])); - _mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + await _mockArtworkEnricher.DidNotReceive().EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs new file mode 100644 index 00000000..952443a8 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricherTests.cs @@ -0,0 +1,482 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryScanArtworkEnricherTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IArtworkProvider _mockArtworkProvider; + private readonly IBookArtworkService _mockBookArtworkService; + private readonly IFileHashService _mockFileHashService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; + private readonly BooksMediaLibraryScanArtworkEnricher _sut; + private readonly ServiceProvider _serviceProvider; + private readonly Guid _pluginId = Guid.NewGuid(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryScanArtworkEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockArtworkProviderConfigurationRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + _mockArtworkProvider = Substitute.For(); + _mockArtworkProvider.Name.Returns("Test Provider"); + _mockArtworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + _mockArtworkProvider.RequiresWebAccess.Returns(true); + + _mockBookArtworkService = Substitute.For(); + _mockFileHashService = Substitute.For(); + _mockFileHashService.ComputeFileHash(Arg.Any()).Returns(123UL); + _mockDomainEventPublisher = Substitute.For(); + _mockLogger = Substitute.For>(); + + // The enricher resolves the keyed artwork providers from the scope of the service provider, so a real container is used to honor the keyed registration. + ServiceCollection services = new(); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(_mockBookArtworkService); + services.AddSingleton(_mockFileHashService); + services.AddKeyedSingleton(_pluginId, _mockArtworkProvider); + _serviceProvider = services.BuildServiceProvider(); + _sut = new BooksMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService(), _mockLogger); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + } + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnBook() + { + // Act + LibraryType result = _sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Book, result); + } + + [Fact] + public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment() + { + // Arrange + SetupLibrary(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment() + { + // Arrange + SetupLibrary(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Provider.Error", "Failed to read the configurations")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(true); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve() + { + // Arrange + SetupLibrary(canDownloadMetadataFromWeb: false); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(false); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockArtworkProvider.Received(1).GetArtworkAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheBookHasArtwork_ShouldStoreAndPersistEnrichedArtwork() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg", type: ArtworkType.Cover, ordinal: 0)])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( + book.LibraryId, + book.Id, + Arg.Any(), + Arg.Any(), + book.Title, + Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), + Arg.Any()); + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkType.Cover, artwork.ArtworkType); + Assert.Equal(0, artwork.Ordinal); + Assert.Equal(ArtworkStatus.Enriched, artwork.Status); + Assert.Equal("Test Provider", artwork.Provider); + Assert.Equal("/media/books/cover.jpg", artwork.FileName); + Assert.Equal(123UL, artwork.ContentHash); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenAProviderAnswersWithNoArtwork_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + Assert.Null(artwork.FileName); + Assert.Null(artwork.Provider); + } + + [Fact] + public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException>(new HttpRequestException("Transient failure."))); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + } + + [Fact] + public async Task EnrichAsync_WhenTheProviderReturnsRemoteArtworkButDoesNotRequireWebAccess_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + } + + [Fact] + public async Task EnrichAsync_WhenTheStoredArtworkIsIdentical_ShouldKeepItAndMarkItEnriched() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockArtworkProvider.RequiresWebAccess.Returns(false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + BookArtworkEntity existingArtwork = _bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, contentHash: 123UL, status: ArtworkStatus.Enriched); + book.Artwork = [existingArtwork]; + SetupBooks(book); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: "/media/books/local.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Enriched, artwork.Status); + Assert.Equal("Test Provider", artwork.Provider); + } + + [Fact] + public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheBookFailed() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Artwork.Error", "Failed to store the artwork")); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + BookArtworkEntity artwork = Assert.Single(book.Artwork); + Assert.Equal(ArtworkStatus.Failed, artwork.Status); + } + + [Fact] + public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to count the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheAuthorsCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()).Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book])); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the authors")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException() + { + // Arrange + SetupLibrary(); + SetupConfiguration(); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + SetupSuccessStore(); + _mockArtworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to save the changes")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + SetupLibrary(); + SetupConfiguration(); + SetupBooks(); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + /// + /// Stubs the media library reader with a library owned by the test user. + /// + /// Whether the library allows downloading data from the web. + private void SetupLibrary(bool canDownloadMetadataFromWeb = true) + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Book, + canDownloadMetadataFromWeb: canDownloadMetadataFromWeb); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the artwork provider configuration reader with a single enabled configuration for the test plugin. + /// + private void SetupConfiguration() + { + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([_artworkConfigurationFixture.Create(_libraryId.Value, _pluginId, 0)])); + } + + /// + /// Stubs the book reader with a single page holding the provided books. + /// + /// The books of the page. + private void SetupBooks(params BookEntity[] books) + { + _mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(books.Length)); + _mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(books), + Result.From>([])); + Dictionary authors = books.ToDictionary(book => book.Id, book => (string?)"Frank Herbert"); + _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>(authors)); + } + + /// + /// Stubs the artwork storage so that a book stores its artwork successfully. + /// + private void SetupSuccessStore() + { + _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("/media/books/cover.jpg")); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs index 2c2f28fd..7edeb01f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkServiceTests.cs @@ -144,7 +144,7 @@ public class BookArtworkServiceTests string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); MockArtworkDirectoryStubs(artworkDirectoryPath); - FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json")); _mockFileProviderService.GetFilePaths(Arg.Any(), true) .Returns(Result.From>([coverFileId, otherFileId])); diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs index f86d2c0d..0eafb831 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs @@ -57,29 +57,29 @@ public class CalibreArtworkProviderTests } [Fact] - public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull() + public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnEmpty() { // Arrange MetadataLookupDto lookup = _testMetadataLookupFixture.Create(); IArtworkProvider baseProvider = _sut; // Act - ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } [Fact] - public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnNull() + public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnEmpty() { // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " "); // Act - ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + IReadOnlyList result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); } } diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs index 2172609c..7f90de3f 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs @@ -34,16 +34,16 @@ public class IArtworkProviderGenericTests IArtworkProvider baseProvider = provider; // Act - ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken); + IReadOnlyList result = await baseProvider.GetArtworkAsync(lookup, cancellationToken); // Assert - Assert.Equal(expectedArtwork, result); + Assert.Equal([expectedArtwork], result); Assert.Same(lookup, provider.ReceivedLookup); Assert.Equal(cancellationToken, provider.ReceivedCancellationToken); } [Fact] - public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNull() + public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnEmpty() { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); @@ -51,10 +51,10 @@ public class IArtworkProviderGenericTests IArtworkProvider baseProvider = provider; // Act - ArtworkDto? result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None); + IReadOnlyList result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None); // Assert - Assert.Null(result); + Assert.Empty(result); Assert.Null(provider.ReceivedLookup); } @@ -95,11 +95,11 @@ public class IArtworkProviderGenericTests public bool RequiresWebAccess => false; /// - public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + public Task> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) { ReceivedLookup = lookup; ReceivedCancellationToken = cancellationToken; - return Task.FromResult(_artwork); + return Task.FromResult>([_artwork]); } } } diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs index d6413507..a014a6ee 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs @@ -64,7 +64,7 @@ public class IMetadataProviderGenericTests } [Fact] - public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() + public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnEmptyAndNotForward() { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); @@ -72,18 +72,15 @@ public class IMetadataProviderGenericTests IMetadataProvider baseProvider = provider; // Act - async Task Act() - { - await baseProvider.GetSearchResultsAsync(otherLookup, CancellationToken.None); - } + IReadOnlyList result = await baseProvider.GetSearchResultsAsync(otherLookup, CancellationToken.None); // Assert - await Assert.ThrowsAsync(Act); + Assert.Empty(result); Assert.Null(provider.ReceivedLookup); } [Fact] - public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() + public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNullAndNotForward() { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); @@ -91,16 +88,27 @@ public class IMetadataProviderGenericTests IMetadataProvider baseProvider = provider; // Act - async Task Act() - { - await baseProvider.GetMetadataAsync(otherLookup, CancellationToken.None); - } + MetadataDto? result = await baseProvider.GetMetadataAsync(otherLookup, CancellationToken.None); // Assert - await Assert.ThrowsAsync(Act); + Assert.Null(result); Assert.Null(provider.ReceivedLookup); } + [Fact] + public void LookupType_WhenReadThroughBaseInterface_ShouldReturnTypedLookupType() + { + // Arrange + TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false)); + IMetadataProvider baseProvider = provider; + + // Act + Type lookupType = baseProvider.LookupType; + + // Assert + Assert.Equal(typeof(BookMetadataLookupDto), lookupType); + } + /// /// Test double for the typed metadata provider interface that records the forwarded arguments. ///