mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the media library artwork aggregation services, enrichers, and their provider contracts
This commit is contained in:
1 parent
00376c8313
commit
9e118864c3
33 files changed
+4621
-1118
No files matched your search
+91
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a piece of artwork of a music library item, like the cover of an album or the image of an artist.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("OwnerType: {OwnerType} OwnerId: {OwnerId} Type: {ArtworkType} Ordinal: {Ordinal}")]
|
||||
public class MusicArtworkEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the artwork.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the music library item that owns the artwork.
|
||||
/// </summary>
|
||||
public required MusicArtworkOwnerType OwnerType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the music library item that owns the artwork.
|
||||
/// </summary>
|
||||
public required Guid OwnerId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the artwork.
|
||||
/// </summary>
|
||||
public required ArtworkType ArtworkType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered.
|
||||
/// </summary>
|
||||
public required int Ordinal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the relative file name of the stored artwork, if the artwork has been resolved.
|
||||
/// </summary>
|
||||
public string? FileName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the content hash of the stored artwork, used to detect whether a re-resolved artwork differs from the stored one.
|
||||
/// </summary>
|
||||
public ulong ContentHash { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the status of the artwork enrichment.
|
||||
/// </summary>
|
||||
public required ArtworkStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the plugin that resolved the artwork, if applicable.
|
||||
/// </summary>
|
||||
public string? Provider { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time when the artwork was last resolved, if applicable.
|
||||
/// </summary>
|
||||
public DateTime? LastUpdateUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
+49
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for the artwork of the music library items.
|
||||
/// </summary>
|
||||
public interface IMusicArtworkRepository : IRepository<MusicArtworkEntity>,
|
||||
IInsertRangeRepositoryAction<MusicArtworkEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the pieces of artwork owned by the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicArtworkEntity"/>, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<MusicArtworkEntity>>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the pieces of artwork owned by the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by <paramref name="libraryId"/>, so that they are re-resolved.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The status is reset because the artwork provider configuration of the library changed.
|
||||
/// </remarks>
|
||||
/// <param name="libraryId">The Id of the media library whose artwork is reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
}
|
||||
+61
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IMusicArtworkService
|
||||
{
|
||||
/// <summary>
|
||||
/// Stores the <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <param name="releaseTypeName">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.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork of the album from the internal media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="releaseTypeName">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.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Result<Deleted> DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null);
|
||||
|
||||
/// <summary>
|
||||
/// Stores the <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork of the artist from the internal media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName);
|
||||
}
|
||||
+1
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="MusicArtworkEntity"/> entity.
|
||||
/// </summary>
|
||||
public class MusicArtworkConfiguration : IEntityTypeConfiguration<MusicArtworkEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="MusicArtworkEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<MusicArtworkEntity> 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<string>()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnOrder(1);
|
||||
builder.Property(musicArtwork => musicArtwork.OwnerId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
builder.Property(musicArtwork => musicArtwork.ArtworkType)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.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<string>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for the artwork of the music library items.
|
||||
/// </summary>
|
||||
internal sealed class MusicArtworkRepository : IMusicArtworkRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public MusicArtworkRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a range of pieces of artwork of music library items.
|
||||
/// </summary>
|
||||
/// <param name="artwork">The pieces of artwork to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Task<Result<Created>> InsertRangeAsync(IReadOnlyCollection<MusicArtworkEntity> artwork, CancellationToken cancellationToken)
|
||||
{
|
||||
if (artwork.Count > 0)
|
||||
_luminaDbContext.MusicArtwork.AddRange(artwork);
|
||||
return Task.FromResult<Result<Created>>(Result.Created);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the pieces of artwork owned by the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicArtworkEntity"/>, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<MusicArtworkEntity>>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken)
|
||||
{
|
||||
IReadOnlyList<MusicArtworkEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes all the pieces of artwork owned by the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Deleted>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library whose artwork is reset.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Updated>> 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<Guid> artistIds = await _luminaDbContext.Artists
|
||||
.Where(artist => artist.LibraryId == libraryId)
|
||||
.Select(artist => artist.Id)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<Guid> albumIds = await _luminaDbContext.Albums
|
||||
.Where(album => album.LibraryId == libraryId)
|
||||
.Select(album => album.Id)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
List<Guid> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the type of the music library item that owns a piece of artwork.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum MusicArtworkOwnerType
|
||||
{
|
||||
/// <summary>
|
||||
/// The artwork belongs to an artist.
|
||||
/// </summary>
|
||||
Artist,
|
||||
|
||||
/// <summary>
|
||||
/// The artwork belongs to an album.
|
||||
/// </summary>
|
||||
Album,
|
||||
|
||||
/// <summary>
|
||||
/// The artwork belongs to a track.
|
||||
/// </summary>
|
||||
Track
|
||||
}
|
||||
+457
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the artwork of an album into the internal media directory, under a per-album directory, and returns its relative path.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
|
||||
/// <param name="pathService">Injected service for handling file system paths.</param>
|
||||
/// <param name="httpClientFactory">Injected factory used to create the HTTP clients that download the remote artwork.</param>
|
||||
/// <param name="mediaSettingsOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
|
||||
public MusicArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions<MediaSettingsDto> mediaSettingsOptions)
|
||||
{
|
||||
_environmentContext = environmentContext;
|
||||
_pathService = pathService;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_mediaSettings = mediaSettingsOptions.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <param name="releaseTypeName">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.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
public async Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null)
|
||||
{
|
||||
Result<string> artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
|
||||
if (artworkDirectoryPathResult.IsFailure)
|
||||
return artworkDirectoryPathResult.Errors;
|
||||
return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
public async Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<string> artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
|
||||
if (artworkDirectoryPathResult.IsFailure)
|
||||
return artworkDirectoryPathResult.Errors;
|
||||
return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the local source of the <paramref name="artwork"/>, stores it into <paramref name="artworkDirectoryPath"/>, and cleans up the temporary download of a remote artwork.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory the artwork is stored into.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
private async Task<Result<string>> 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<ArtworkSourceResult> 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.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork of the album from the internal media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="releaseTypeName">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.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Deleted> DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null)
|
||||
{
|
||||
Result<string> artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
|
||||
if (artworkDirectoryPathResult.IsFailure)
|
||||
return artworkDirectoryPathResult.Errors;
|
||||
return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork of the artist from the internal media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName)
|
||||
{
|
||||
Result<string> artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
|
||||
if (artworkDirectoryPathResult.IsFailure)
|
||||
return artworkDirectoryPathResult.Errors;
|
||||
return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the files directly contained in <paramref name="artworkDirectoryPath"/>, leaving the subdirectories, such as the album directories of an artist, untouched.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory whose files are deleted.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private Result<Deleted> DeleteArtworkInDirectory(string artworkDirectoryPath)
|
||||
{
|
||||
Result<FileSystemPathId> 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<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value);
|
||||
if (directoryExistsResult.IsFailure)
|
||||
return directoryExistsResult.Errors;
|
||||
if (!directoryExistsResult.Value)
|
||||
return Result.Deleted;
|
||||
|
||||
Result<IEnumerable<FileSystemPathId>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the artwork file at <paramref name="sourcePath"/> into <paramref name="artworkDirectoryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory the artwork is stored into.</param>
|
||||
/// <param name="artworkType">The type of the artwork being stored.</param>
|
||||
/// <param name="ordinal">The ordinal of the artwork within its type.</param>
|
||||
/// <param name="sourcePath">The file system path of the artwork file to store.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
private async Task<Result<string>> StoreArtworkAsync(string artworkDirectoryPath, ArtworkType artworkType, int ordinal, string sourcePath, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<FileSystemPathId> sourcePathIdResult = FileSystemPathId.Create(sourcePath);
|
||||
if (sourcePathIdResult.IsFailure)
|
||||
return sourcePathIdResult.Errors;
|
||||
|
||||
Result<bool> 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<ImageType> 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<Success> ensureDirectoryResult = EnsureDirectory(artworkDirectoryPath);
|
||||
if (ensureDirectoryResult.IsFailure)
|
||||
return ensureDirectoryResult.Errors;
|
||||
|
||||
Result<FileSystemPathId> artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath);
|
||||
if (artworkDirectoryPathIdResult.IsFailure)
|
||||
return artworkDirectoryPathIdResult.Errors;
|
||||
|
||||
// Copy the artwork file from the source location.
|
||||
Result<FileSystemPathId> 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<FileSystemPathId> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file name stem of an artwork, derived from its type and ordinal.
|
||||
/// </summary>
|
||||
/// <param name="artworkType">The type of the artwork.</param>
|
||||
/// <param name="ordinal">The ordinal of the artwork within its type.</param>
|
||||
/// <returns>The file name stem of the artwork.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the local file system path of the <paramref name="artwork"/>, downloading it to a temporary file when it is remote.
|
||||
/// </summary>
|
||||
/// <param name="artwork">The artwork whose source path is resolved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the resolved local source of the artwork, or an error.</returns>
|
||||
private async Task<Result<ArtworkSourceResult>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="releaseTypeName">The name of the release type directory the album is stored under on disk, or <see langword="null"/> to store the artwork directly under the artist directory.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the file system path of the album artwork directory, or an error.</returns>
|
||||
private Result<string> BuildAlbumArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName)
|
||||
{
|
||||
Result<string> 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<string> albumParentPathResult = artistPathResult;
|
||||
if (!string.IsNullOrWhiteSpace(releaseTypeName))
|
||||
{
|
||||
Result<PathSegment> releaseTypeSegmentResult = _pathService.SanitizeSegment(releaseTypeName);
|
||||
if (releaseTypeSegmentResult.IsFailure)
|
||||
return releaseTypeSegmentResult.Errors;
|
||||
Result<string> releaseTypePathResult = _pathService.CombinePath(artistPathResult.Value, releaseTypeSegmentResult.Value.Name);
|
||||
if (releaseTypePathResult.IsFailure)
|
||||
return releaseTypePathResult.Errors;
|
||||
albumParentPathResult = releaseTypePathResult;
|
||||
}
|
||||
|
||||
Result<PathSegment> albumSegmentResult = _pathService.SanitizeSegment($"{albumTitle}-{albumId}");
|
||||
if (albumSegmentResult.IsFailure)
|
||||
return albumSegmentResult.Errors;
|
||||
return _pathService.CombinePath(albumParentPathResult.Value, albumSegmentResult.Value.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the file system path of the artist artwork directory, or an error.</returns>
|
||||
private Result<string> BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
|
||||
{
|
||||
Result<string> libraryPathResult = BuildLibraryArtworkDirectoryPath(libraryId, libraryName);
|
||||
if (libraryPathResult.IsFailure)
|
||||
return libraryPathResult.Errors;
|
||||
|
||||
Result<PathSegment> artistSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName);
|
||||
if (artistSegmentResult.IsFailure)
|
||||
return artistSegmentResult.Errors;
|
||||
return _pathService.CombinePath(libraryPathResult.Value, artistSegmentResult.Value.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory of a music media library, under the internal media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <param name="libraryName">The name of the media library.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the file system path of the media library directory, or an error.</returns>
|
||||
private Result<string> BuildLibraryArtworkDirectoryPath(Guid libraryId, string libraryName)
|
||||
{
|
||||
Result<string> mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory);
|
||||
if (mediaRootPathResult.IsFailure)
|
||||
return mediaRootPathResult.Errors;
|
||||
Result<string> musicPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.MusicDirectory);
|
||||
if (musicPathResult.IsFailure)
|
||||
return musicPathResult.Errors;
|
||||
|
||||
Result<PathSegment> librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}");
|
||||
if (librarySegmentResult.IsFailure)
|
||||
return librarySegmentResult.Errors;
|
||||
return _pathService.CombinePath(musicPathResult.Value, librarySegmentResult.Value.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the directory at <paramref name="directoryPath"/>, along with its missing parents.
|
||||
/// </summary>
|
||||
/// <param name="directoryPath">The file system path of the directory to create.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private Result<Success> EnsureDirectory(string directoryPath)
|
||||
{
|
||||
Result<FileSystemPathId> directoryPathIdResult = FileSystemPathId.Create(directoryPath);
|
||||
if (directoryPathIdResult.IsFailure)
|
||||
return directoryPathIdResult.Errors;
|
||||
|
||||
Result<bool> 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<Success> createParentResult = EnsureDirectory(parentDirectoryPath);
|
||||
if (createParentResult.IsFailure)
|
||||
return createParentResult.Errors;
|
||||
}
|
||||
|
||||
Result<FileSystemPathId> parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath);
|
||||
if (parentDirectoryPathIdResult.IsFailure)
|
||||
return parentDirectoryPathIdResult.Errors;
|
||||
|
||||
Result<FileSystemPathId> createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath));
|
||||
if (createDirectoryResult.IsFailure)
|
||||
return createDirectoryResult.Errors;
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes the resolved local source of the artwork.
|
||||
/// </summary>
|
||||
/// <param name="Path">The file system path of the resolved source.</param>
|
||||
/// <param name="IsTemporary">Whether the resolved source is a temporary file that must be cleaned up after it is stored.</param>
|
||||
private sealed record ArtworkSourceResult(string Path, bool IsTemporary);
|
||||
}
|
||||
+677
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Artwork enricher for the media library items of the music media library type, using the artwork providers configured for the media library.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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<MusicMediaLibraryScanArtworkEnricher> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// The media library type that this artwork enricher supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedLibraryType => LibraryType.Music;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while resolving the artwork.</param>
|
||||
public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger<MusicMediaLibraryScanArtworkEnricher> logger)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the artists and the albums of the provided media library, using the artwork providers configured for it.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library whose artwork is resolved.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan.</param>
|
||||
/// <param name="userId">The unique identifier of the user that initiated the media library scan.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId);
|
||||
|
||||
// Load the media library, whose name is used to build the 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<LibraryEntity?> 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<UserSettingsEntity?> 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<IArtworkProvider> artworkProviders = [];
|
||||
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
|
||||
{
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkConfigurationsResult.IsFailure)
|
||||
_logger.LogWarning("Failed to read the artwork provider configurations.");
|
||||
else
|
||||
{
|
||||
foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
|
||||
{
|
||||
List<IArtworkProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
|
||||
.GetKeyedServices<IArtworkProvider>(configuration.PluginId)
|
||||
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.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<IArtworkProvider> artistProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider<ArtistMetadataLookupDto>)];
|
||||
IReadOnlyList<IArtworkProvider> albumProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider<AlbumMetadataLookupDto>)];
|
||||
|
||||
IMusicArtworkService? musicArtworkService = asyncServiceScope.ServiceProvider.GetService<IMusicArtworkService>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
int totalArtistsToEnrich = 0;
|
||||
if (artistProviders.Count > 0)
|
||||
{
|
||||
Result<int> 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<int> 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<Success> 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<Success> 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<Success> publishFinalProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, totalItemsToEnrich, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishFinalProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the artists of the provided media library whose artwork has not been resolved yet, page by page.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library whose artists are enriched.</param>
|
||||
/// <param name="artworkProviders">The artists artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="musicArtworkService">The service used to store the artwork of the artists.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the artists belong to.</param>
|
||||
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.</param>
|
||||
/// <param name="unitOfWork">The unit of work used to persist the artwork of the artists.</param>
|
||||
/// <param name="reportItemProcessedAsync">The callback invoked after each artist is processed, to advance the progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
private async Task EnrichArtistsAsync(LibraryId libraryId, IReadOnlyList<IArtworkProvider> artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func<Task> reportItemProcessedAsync, CancellationToken cancellationToken)
|
||||
{
|
||||
string? lastName = null;
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
Result<IReadOnlyList<ArtistEntity>> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkAsync(libraryId.Value, lastName, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtistsPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getArtistsPageResult.FirstError.Description);
|
||||
IReadOnlyList<ArtistEntity> 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<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
|
||||
lastName = artistsPage[^1].Name;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the albums of the provided media library whose artwork has not been resolved yet, page by page.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library whose albums are enriched.</param>
|
||||
/// <param name="artworkProviders">The album artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="musicArtworkService">The service used to store the artwork of the albums.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the albums belong to.</param>
|
||||
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.</param>
|
||||
/// <param name="unitOfWork">The unit of work used to persist the artwork of the albums.</param>
|
||||
/// <param name="reportItemProcessedAsync">The callback invoked after each album is processed, to advance the progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
private async Task EnrichAlbumsAsync(LibraryId libraryId, IReadOnlyList<IArtworkProvider> artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func<Task> 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<Guid> albumsRemainingUnresolved = [];
|
||||
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
Result<IReadOnlyList<AlbumEntity>> getAlbumsPageResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkAsync(libraryId.Value, albumsRemainingUnresolved, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getAlbumsPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getAlbumsPageResult.FirstError.Description);
|
||||
IReadOnlyList<AlbumEntity> 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<IReadOnlyDictionary<Guid, string>> 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<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
|
||||
unitOfWork.ClearTrackedEntities();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the provided <paramref name="artistEntity"/> from the <paramref name="artworkProviders"/>, storing the artwork resolved from the providers, in their order.
|
||||
/// </summary>
|
||||
/// <param name="artistEntity">The artist whose artwork is resolved.</param>
|
||||
/// <param name="firstTrackPath">The file system path of one track of the artist, used to locate its directory.</param>
|
||||
/// <param name="artworkProviders">The artist artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="musicArtworkService">The service used to store the artwork of the artist.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.</param>
|
||||
/// <param name="unitOfWork">The unit of work used to persist the artwork of the artist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns><see langword="true"/> when the artist reached a terminal artwork state, otherwise <see langword="false"/>.</returns>
|
||||
private async Task<bool> EnrichArtistArtworkAsync(ArtistEntity artistEntity, string firstTrackPath, IReadOnlyList<IArtworkProvider> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the provided <paramref name="albumEntity"/> from the <paramref name="artworkProviders"/>, storing the artwork resolved from the providers, in their order.
|
||||
/// </summary>
|
||||
/// <param name="albumEntity">The album whose artwork is resolved.</param>
|
||||
/// <param name="firstTrackPath">The file system path of one track of the album, used to locate its directory.</param>
|
||||
/// <param name="artworkProviders">The album artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="musicArtworkService">The service used to store the artwork of the album.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="canResolveWithoutMusicBrainzIds">Whether a provider that does not require the web can resolve the artwork without any MusicBrainz identifier.</param>
|
||||
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.</param>
|
||||
/// <param name="unitOfWork">The unit of work used to persist the artwork of the album.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns><see langword="true"/> when the album reached a terminal artwork state, otherwise <see langword="false"/>.</returns>
|
||||
private async Task<bool> EnrichAlbumArtworkAsync(AlbumEntity albumEntity, string firstTrackPath, IReadOnlyList<IArtworkProvider> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the media item described by <paramref name="artworkLookup"/> from the <paramref name="artworkProviders"/>, in their order, replacing the stored artwork of the item.
|
||||
/// </summary>
|
||||
/// <param name="artworkLookup">The lookup describing the media item whose artwork is resolved.</param>
|
||||
/// <param name="ownerType">The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerDescription">The description of the owner, used to report the issues encountered.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="musicArtworkService">The service used to store the artwork of the owner.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="deleteStoredArtwork">The action that deletes the artwork of the owner from the internal media directory.</param>
|
||||
/// <param name="saveArtworkAsync">The action that stores a piece of artwork of the owner into the internal media directory.</param>
|
||||
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.</param>
|
||||
/// <param name="unitOfWork">The unit of work used to persist the artwork of the owner.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns><see langword="true"/> when the owner reached a terminal artwork state, otherwise <see langword="false"/>.</returns>
|
||||
private async Task<bool> EnrichArtworkAsync(MetadataLookupDto artworkLookup, MusicArtworkOwnerType ownerType, Guid ownerId, string ownerDescription, IReadOnlyList<IArtworkProvider> artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, Func<Result<Deleted>> deleteStoredArtwork, Func<ArtworkDto, CancellationToken, Task<Result<string>>> 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<Deleted> 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<Deleted> 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<MusicArtworkEntity> artworkEntities = [];
|
||||
|
||||
if (resolution.Artworks.Count > 0)
|
||||
{
|
||||
foreach (ResolvedArtwork resolvedArtwork in resolution.Artworks)
|
||||
{
|
||||
ArtworkDto artwork = resolvedArtwork.Artwork;
|
||||
Result<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the provided pieces of <paramref name="artworkEntities"/> of a music library item.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">The unit of work used to persist the artwork.</param>
|
||||
/// <param name="artworkEntities">The pieces of artwork to persist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
private async Task PersistArtworkAsync(IUnitOfWork unitOfWork, List<MusicArtworkEntity> artworkEntities, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<Created> 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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the temporary files of the provided <paramref name="artworks"/>, used when the resolved artwork is not stored, so the temporary files do not linger.
|
||||
/// </summary>
|
||||
/// <param name="artworks">The resolved artworks whose temporary files are deleted.</param>
|
||||
private static void DeleteTemporaryArtworks(IEnumerable<ArtworkDto> 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.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the media item described by <paramref name="lookup"/> from the <paramref name="artworkProviders"/>,
|
||||
/// either aggregating the providers when <paramref name="shouldAggregateArtworkWhenMissing"/> is set, or using the first provider that supplies artwork otherwise.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="ownerDescription">The description of the owner, used to report the issues encountered.</param>
|
||||
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork of every provider is combined, or only the first provider that supplies artwork is used.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>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.</returns>
|
||||
private async Task<ArtworkResolution> ResolveArtworkAsync(MetadataLookupDto lookup, IReadOnlyList<IArtworkProvider> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the media item described by <paramref name="lookup"/> from the first <paramref name="artworkProviders"/> provider that supplies some, in their order.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="ownerDescription">The description of the owner, used to report the issues encountered.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The resolved artwork, each with the provider that supplied it, and whether a provider answered at all.</returns>
|
||||
private async Task<ArtworkResolution> ResolveFirstArtworkAsync(MetadataLookupDto lookup, IReadOnlyList<IArtworkProvider> artworkProviders, string ownerDescription, CancellationToken cancellationToken)
|
||||
{
|
||||
bool hasResolved = false;
|
||||
bool hasFailed = false;
|
||||
foreach (IArtworkProvider provider in artworkProviders)
|
||||
{
|
||||
IReadOnlyList<ArtworkDto> 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<ResolvedArtwork> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the media item described by <paramref name="lookup"/> from every <paramref name="artworkProviders"/> provider, in their order,
|
||||
/// combining them so that a provider only fills the artwork the providers before it did not supply.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in the order they are consulted.</param>
|
||||
/// <param name="ownerDescription">The description of the owner, used to report the issues encountered.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The resolved artwork, each with the provider that supplied it, and whether a provider answered at all.</returns>
|
||||
private async Task<ArtworkResolution> ResolveAggregatedArtworkAsync(MetadataLookupDto lookup, IReadOnlyList<IArtworkProvider> artworkProviders, string ownerDescription, CancellationToken cancellationToken)
|
||||
{
|
||||
bool hasResolved = false;
|
||||
bool hasFailed = false;
|
||||
List<ResolvedArtwork> resolvedArtworks = [];
|
||||
HashSet<(ArtworkType Type, int Ordinal)> resolvedKeys = [];
|
||||
foreach (IArtworkProvider provider in artworkProviders)
|
||||
{
|
||||
IReadOnlyList<ArtworkDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a piece of artwork of the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
|
||||
/// </summary>
|
||||
/// <param name="ownerId">The Id of the music library item the artwork belongs to.</param>
|
||||
/// <param name="ownerType">The type of the music library item the artwork belongs to.</param>
|
||||
/// <param name="artworkType">The type of the artwork.</param>
|
||||
/// <param name="ordinal">The ordinal of the artwork within its type.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork, if the artwork has been resolved.</param>
|
||||
/// <param name="contentHash">The content hash of the stored artwork.</param>
|
||||
/// <param name="status">The status of the artwork enrichment.</param>
|
||||
/// <param name="provider">The name of the plugin that resolved the artwork, if applicable.</param>
|
||||
/// <returns>The created artwork entity.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library being scanned.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
|
||||
if (scanJobProgressResult.IsFailure)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The artwork resolved for a music library item, each with the provider that supplied it, and whether a provider answered at all.
|
||||
/// </summary>
|
||||
/// <param name="Artworks">The resolved artworks of the item, each with the provider that supplied it.</param>
|
||||
/// <param name="HasResolved">Whether at least one provider answered, confirming that any absence of artwork is real rather than a failure.</param>
|
||||
private sealed record ArtworkResolution(IReadOnlyList<ResolvedArtwork> Artworks, bool HasResolved);
|
||||
|
||||
/// <summary>
|
||||
/// A piece of artwork of a music library item, together with the provider that supplied it.
|
||||
/// </summary>
|
||||
/// <param name="Artwork">The resolved artwork.</param>
|
||||
/// <param name="ProviderName">The name of the provider that supplied the artwork.</param>
|
||||
private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName);
|
||||
}
|
||||
+31
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining the artwork enrichment of the media library items of a specific media library type.
|
||||
/// </summary>
|
||||
internal interface IMediaLibraryScanArtworkEnricher
|
||||
{
|
||||
/// <summary>
|
||||
/// The media library type that this artwork enricher supports.
|
||||
/// </summary>
|
||||
LibraryType SupportedLibraryType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the media library items of the provided media library, using the artwork providers configured for it.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library whose artwork is resolved.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan.</param>
|
||||
/// <param name="userId">The unique identifier of the user that initiated the media library scan.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken);
|
||||
}
|
||||
+15
-316
@@ -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
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for resolving the artwork of the media library items, using the artwork providers configured for the media library.
|
||||
/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched.
|
||||
/// The enrichment itself is delegated to the artwork enricher of the media library type.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob
|
||||
{
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILogger<MediaLibraryScanArtworkEnrichmentJob> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
|
||||
@@ -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.
|
||||
/// </param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while resolving the artwork.</param>
|
||||
public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanArtworkEnrichmentJob> logger)
|
||||
public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<LibraryEntity?> 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<LibraryEntity?> 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<IArtworkProvider> artworkProviders = [];
|
||||
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
|
||||
{
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkConfigurationsResult.IsFailure)
|
||||
_logger.LogWarning("Failed to read the artwork provider configurations.");
|
||||
else
|
||||
{
|
||||
foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
|
||||
{
|
||||
List<IArtworkProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
|
||||
.GetKeyedServices<IArtworkProvider>(configuration.PluginId)
|
||||
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
|
||||
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
|
||||
if (configuredProviders.Count == 0)
|
||||
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
|
||||
artworkProviders.AddRange(configuredProviders);
|
||||
}
|
||||
}
|
||||
}
|
||||
IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider
|
||||
.GetServices<IMediaLibraryScanArtworkEnricher>()
|
||||
.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<IBookArtworkService>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksToEnrichCountResult.IsFailure)
|
||||
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
||||
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsFailure)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedBooksCount = 0;
|
||||
|
||||
// Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size.
|
||||
string? lastPath = null;
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
Result<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
|
||||
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
|
||||
if (booksPage.Count == 0)
|
||||
break;
|
||||
|
||||
// Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory.
|
||||
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
|
||||
if (getAuthorsResult.IsFailure)
|
||||
throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
|
||||
|
||||
foreach (BookEntity bookEntity in booksPage)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Check if enough time has passed since 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<Success> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the cover artwork of the provided <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
|
||||
/// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="authorsDisplayNamesByBookId">The display names of the authors of the books of the current page, keyed by the Id of the book.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary<Guid, string?> authorsDisplayNamesByBookId, CancellationToken cancellationToken)
|
||||
{
|
||||
// When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped.
|
||||
if (bookArtworkService is null || artworkProviders.Count == 0)
|
||||
return;
|
||||
|
||||
ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
|
||||
if (resolvedArtwork is null)
|
||||
{
|
||||
// No artwork provider returned usable artwork, 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<string> saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false);
|
||||
if (saveArtworkResult.IsFailure)
|
||||
{
|
||||
// A failing artwork storage must not prevent the book from being tracked as failed to resolve.
|
||||
if (existingCoverArtwork is null)
|
||||
bookEntity.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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
|
||||
/// returning the artwork of the first provider that returns it.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The resolved artwork and the provider that supplied it, or <see langword="null"/> when no provider returned usable artwork.</returns>
|
||||
private static async Task<ResolvedArtwork?> ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, CancellationToken cancellationToken)
|
||||
{
|
||||
BookMetadataLookupDto artworkLookup = new(
|
||||
LibraryId: bookEntity.LibraryId,
|
||||
Path: bookEntity.Path,
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null,
|
||||
OpenLibraryId: bookEntity.OpenLibraryId,
|
||||
Title: bookEntity.Title,
|
||||
Author: null,
|
||||
LanguageCode: bookEntity.LanguageCode
|
||||
);
|
||||
|
||||
foreach (IArtworkProvider provider in artworkProviders)
|
||||
{
|
||||
ArtworkDto? artwork = null;
|
||||
try
|
||||
{
|
||||
artwork = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A failing artwork provider must not prevent the other providers from being tried.
|
||||
}
|
||||
|
||||
if (artwork is null)
|
||||
continue;
|
||||
|
||||
// A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
|
||||
if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
|
||||
continue;
|
||||
|
||||
return new ResolvedArtwork(artwork, provider.Name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cover artwork entity for the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book the artwork belongs to.</param>
|
||||
/// <param name="status">The status of the artwork enrichment.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork, if the artwork has been resolved.</param>
|
||||
/// <param name="contentHash">The content hash of the stored artwork.</param>
|
||||
/// <param name="provider">The name of the plugin that resolved the artwork, if applicable.</param>
|
||||
/// <param name="lastUpdateUtc">The date and time when the artwork was resolved, if applicable.</param>
|
||||
/// <returns>The created cover artwork entity.</returns>
|
||||
private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc)
|
||||
{
|
||||
return new BookArtworkEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookId,
|
||||
ArtworkType = ArtworkType.Cover,
|
||||
Ordinal = 0,
|
||||
FileName = fileName,
|
||||
ContentHash = contentHash,
|
||||
Status = status,
|
||||
Provider = provider,
|
||||
LastUpdateUtc = lastUpdateUtc,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
|
||||
if (scanJobProgressResult.IsFailure)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The artwork resolved for a book, along with the provider that supplied it.
|
||||
/// </summary>
|
||||
/// <param name="Artwork">The resolved artwork of the book.</param>
|
||||
/// <param name="ProviderName">The name of the provider that supplied the artwork.</param>
|
||||
private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName);
|
||||
}
|
||||
+378
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Artwork enricher for the media library items of the books media library type, using the artwork providers configured for the media library.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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<BooksMediaLibraryScanArtworkEnricher> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// The media library type that this artwork enricher supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedLibraryType => LibraryType.Book;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
|
||||
/// <param name="logger">Injected logger used to report the issues encountered while resolving the artwork.</param>
|
||||
public BooksMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger<BooksMediaLibraryScanArtworkEnricher> logger)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the books of the provided media library, using the artwork providers configured for it.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library whose artwork is resolved.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan.</param>
|
||||
/// <param name="userId">The unique identifier of the user that initiated the media library scan.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId);
|
||||
|
||||
// Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
|
||||
// whether the providers that require access to the web are used during the enrichment.
|
||||
string libraryName = string.Empty;
|
||||
bool canDownloadMetadataFromWeb = false;
|
||||
if (unitOfWork.LibraryRepository is not null)
|
||||
{
|
||||
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
_logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
|
||||
else
|
||||
{
|
||||
libraryName = getLibraryResult.Value.Title;
|
||||
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
|
||||
}
|
||||
}
|
||||
|
||||
// Get the artwork providers configured for the media library, in their configured order, that support the media library type.
|
||||
// The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding.
|
||||
List<IArtworkProvider> artworkProviders = [];
|
||||
if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
|
||||
{
|
||||
Result<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getArtworkConfigurationsResult.IsFailure)
|
||||
_logger.LogWarning("Failed to read the artwork provider configurations.");
|
||||
else
|
||||
{
|
||||
foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
|
||||
{
|
||||
List<IArtworkProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
|
||||
.GetKeyedServices<IArtworkProvider>(configuration.PluginId)
|
||||
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
|
||||
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
|
||||
if (configuredProviders.Count == 0)
|
||||
_logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
|
||||
artworkProviders.AddRange(configuredProviders);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely.
|
||||
if (artworkProviders.Count > 0)
|
||||
{
|
||||
IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService<IBookArtworkService>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksToEnrichCountResult.IsFailure)
|
||||
throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
|
||||
int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
|
||||
|
||||
// Set the initial progress of the scan job.
|
||||
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, 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<IReadOnlyList<BookEntity>> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(libraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getBooksPageResult.IsFailure)
|
||||
throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
|
||||
IReadOnlyList<BookEntity> booksPage = getBooksPageResult.Value;
|
||||
if (booksPage.Count == 0)
|
||||
break;
|
||||
|
||||
// Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory.
|
||||
Result<IReadOnlyDictionary<Guid, string?>> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
|
||||
if (getAuthorsResult.IsFailure)
|
||||
throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
|
||||
|
||||
foreach (BookEntity bookEntity in booksPage)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Check if enough time has passed since 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<Success> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the cover artwork of the provided <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
|
||||
/// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the book.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="authorsDisplayNamesByBookId">The display names of the authors of the books of the current page, keyed by the Id of the book.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private static async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary<Guid, string?> authorsDisplayNamesByBookId, CancellationToken cancellationToken)
|
||||
{
|
||||
// When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped.
|
||||
if (bookArtworkService is null || artworkProviders.Count == 0)
|
||||
return;
|
||||
|
||||
ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
|
||||
// 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<string> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the artwork of the <paramref name="bookEntity"/> from the <paramref name="artworkProviders"/>, in their configured order,
|
||||
/// returning the artwork of the first provider that returns it.
|
||||
/// </summary>
|
||||
/// <param name="bookEntity">The book whose artwork is resolved.</param>
|
||||
/// <param name="artworkProviders">The artwork providers, in their configured order.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The resolved artwork and the provider that supplied it, or <see langword="null"/> when no provider returned usable artwork.</returns>
|
||||
private static async Task<ResolvedArtwork?> ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList<IArtworkProvider> artworkProviders, CancellationToken cancellationToken)
|
||||
{
|
||||
BookMetadataLookupDto artworkLookup = new(
|
||||
LibraryId: bookEntity.LibraryId,
|
||||
Path: bookEntity.Path,
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null,
|
||||
OpenLibraryId: bookEntity.OpenLibraryId,
|
||||
Title: bookEntity.Title,
|
||||
Author: null,
|
||||
LanguageCode: bookEntity.LanguageCode
|
||||
);
|
||||
|
||||
foreach (IArtworkProvider provider in artworkProviders)
|
||||
{
|
||||
IReadOnlyList<ArtworkDto> 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<ArtworkDto> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a cover artwork entity for the book identified by <paramref name="bookId"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book the artwork belongs to.</param>
|
||||
/// <param name="status">The status of the artwork enrichment.</param>
|
||||
/// <param name="fileName">The relative file name of the stored artwork, if the artwork has been resolved.</param>
|
||||
/// <param name="contentHash">The content hash of the stored artwork.</param>
|
||||
/// <param name="provider">The name of the plugin that resolved the artwork, if applicable.</param>
|
||||
/// <param name="lastUpdateUtc">The date and time when the artwork was resolved, if applicable.</param>
|
||||
/// <returns>The created cover artwork entity.</returns>
|
||||
private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc)
|
||||
{
|
||||
return new BookArtworkEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookId,
|
||||
ArtworkType = ArtworkType.Cover,
|
||||
Ordinal = 0,
|
||||
FileName = fileName,
|
||||
ContentHash = contentHash,
|
||||
Status = status,
|
||||
Provider = provider,
|
||||
LastUpdateUtc = lastUpdateUtc,
|
||||
CreatedOnUtc = DateTime.UtcNow,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="domainEventPublisher">The service used to publish the progress update.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library being scanned.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static async Task<Result<Success>> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
|
||||
if (scanJobProgressResult.IsFailure)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The artwork resolved for a book, along with the provider that supplied it.
|
||||
/// </summary>
|
||||
/// <param name="Artworks">The resolved artworks of the book.</param>
|
||||
/// <param name="ProviderName">The name of the provider that supplied the artwork.</param>
|
||||
private sealed record ResolvedArtwork(IReadOnlyList<ArtworkDto> Artworks, string ProviderName);
|
||||
}
|
||||
+4
-2
@@ -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<FileSystemPathId> renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}");
|
||||
Result<FileSystemPathId> 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
|
||||
|
||||
@@ -29,10 +29,10 @@ public interface IArtworkProvider
|
||||
bool RequiresWebAccess { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork of the media item described by <paramref name="lookup"/>.
|
||||
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the media item, or <see langword="null"/> when no artwork was found.</returns>
|
||||
Task<ArtworkDto?> GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken);
|
||||
/// <returns>The artworks of the media item, or an empty collection when no artwork was found.</returns>
|
||||
Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -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<TLookup> : IArtworkProvider
|
||||
where TLookup : MetadataLookupDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the artwork of the media item described by <paramref name="lookup"/>.
|
||||
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the media item, or <see langword="null"/> when no artwork was found.</returns>
|
||||
Task<ArtworkDto?> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken);
|
||||
/// <returns>The artworks of the media item, or an empty collection when no artwork was found.</returns>
|
||||
Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artwork of the media item described by <paramref name="lookup"/>.
|
||||
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artwork of the media item, or <see langword="null"/> when no artwork was found or the lookup is of another runtime type.</returns>
|
||||
async Task<ArtworkDto?> IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
/// <returns>The artworks of the media item, or an empty collection when no artwork was found or the lookup is of another runtime type.</returns>
|
||||
async Task<IReadOnlyList<ArtworkDto>> 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) : [];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
/// </summary>
|
||||
IReadOnlyList<LibraryType> SupportedLibraryTypes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type of the metadata lookup this provider accepts, used to select the provider that matches a given lookup.
|
||||
/// </summary>
|
||||
Type LookupType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
|
||||
/// </summary>
|
||||
|
||||
@@ -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<TLookup, TMetadata> : IMetadataProvider
|
||||
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
|
||||
Task<TMetadata?> GetMetadataAsync(TLookup lookup, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the type of the metadata lookup this provider accepts.
|
||||
/// </summary>
|
||||
Type IMetadataProvider.LookupType => typeof(TLookup);
|
||||
|
||||
/// <summary>
|
||||
/// Searches for the metadata of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to search for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The collection of metadata candidates found for the media item.</returns>
|
||||
/// <returns>The collection of metadata candidates found for the media item, or an empty collection when the lookup is of another runtime type.</returns>
|
||||
async Task<IReadOnlyList<MetadataDto>> 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) : [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -48,9 +54,9 @@ public interface IMetadataProvider<TLookup, TMetadata> : IMetadataProvider
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the metadata for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
|
||||
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found or the lookup is of another runtime type.</returns>
|
||||
async Task<MetadataDto?> 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;
|
||||
}
|
||||
}
|
||||
+82
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MusicArtworkEntity"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtworkEntityFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="MusicArtworkEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">Optional. The Id of the artwork.</param>
|
||||
/// <param name="ownerType">Optional. The type of the music library item that owns the artwork.</param>
|
||||
/// <param name="ownerId">Optional. The Id of the music library item that owns the artwork.</param>
|
||||
/// <param name="artworkType">Optional. The type of the artwork.</param>
|
||||
/// <param name="ordinal">Optional. The ordinal of the artwork within its type.</param>
|
||||
/// <param name="fileName">Optional. The relative file name of the stored artwork.</param>
|
||||
/// <param name="contentHash">Optional. The content hash of the stored artwork.</param>
|
||||
/// <param name="status">Optional. The status of the artwork enrichment.</param>
|
||||
/// <param name="provider">Optional. The name of the plugin that resolved the artwork.</param>
|
||||
/// <param name="lastUpdateUtc">Optional. The date and time when the artwork was last resolved.</param>
|
||||
/// <param name="includeFileName">Whether the file name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeProvider">Whether the provider should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLastUpdateUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="MusicArtworkEntity"/>.</returns>
|
||||
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<MusicArtworkOwnerType>(),
|
||||
OwnerId = ownerId ?? Guid.NewGuid(),
|
||||
ArtworkType = artworkType ?? _faker.PickRandom<ArtworkType>(),
|
||||
Ordinal = ordinal ?? _faker.Random.Int(0, 5),
|
||||
FileName = includeFileName ? (fileName ?? _faker.System.FilePath()) : null,
|
||||
ContentHash = contentHash ?? (ulong)_faker.Random.ULong(),
|
||||
Status = status ?? _faker.PickRandom<ArtworkStatus>(),
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="MusicArtworkEntity"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MusicArtworkEntity"/> instances.</returns>
|
||||
public List<MusicArtworkEntity> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+1
@@ -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;
|
||||
|
||||
+763
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="MusicArtworkService"/> class.
|
||||
/// </summary>
|
||||
[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<MediaSettingsDto> _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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkServiceTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
|
||||
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
_mockHttpClientFactory.CreateClient(Arg.Any<string>()).Returns(new HttpClient(_stubHttpMessageHandler));
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
_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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), "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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "artwork.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), expectedFileName)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName))));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName: "Unknown", albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = CreateTempImageFile();
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.None));
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(pathId => pathId.Path.StartsWith(Path.GetTempPath())),
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
_stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []);
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> 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<string> 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(pathId => pathId.Path == sourcePath),
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
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<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = CreateTempImageFile();
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type"));
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.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<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return name == $"{libraryName}-{libraryId}"
|
||||
? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
|
||||
: Errors.FileSystemManagement.InvalidPath;
|
||||
});
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>()).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<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistName, albumTitle);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
|
||||
_mockFileProviderService.Received(1).DeleteFile(bookletFileId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path service so that building the artwork directory paths succeeds.
|
||||
/// </summary>
|
||||
private void MockPathBuilding()
|
||||
{
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork is stored into the given directory.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
|
||||
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<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
|
||||
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the album is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <returns>The expected file system path of the album artwork directory.</returns>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temporary image file and returns its path.
|
||||
/// </summary>
|
||||
/// <param name="smallImageBytes">The size of the temporary image file, in bytes.</param>
|
||||
/// <returns>The file system path of the created temporary image file.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
|
||||
/// </summary>
|
||||
/// <param name="linkPath">The file system path of the link to create.</param>
|
||||
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
|
||||
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -65,7 +65,7 @@ public class BookArtworkServiceTests
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
_mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler));
|
||||
_mockHttpClientFactory.CreateClient(Arg.Any<string>()).Returns(new HttpClient(_stubHttpMessageHandler));
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
@@ -98,9 +98,9 @@ public class BookArtworkServiceTests
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), 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<FileSystemPathId>(), "cover.jpeg")
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
@@ -113,7 +113,7 @@ public class BookArtworkServiceTests
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
true);
|
||||
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg");
|
||||
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
@@ -264,8 +264,8 @@ public class BookArtworkServiceTests
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "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<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
@@ -521,7 +521,7 @@ public class BookArtworkServiceTests
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
|
||||
|
||||
// Act
|
||||
|
||||
+15
-14
@@ -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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> 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<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Empty(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
+2
-2
@@ -120,8 +120,8 @@ public class BookArtworkServiceSecurityTests
|
||||
string capturedDestinationPath = string.Empty;
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Do<FileSystemPathId>(destination => capturedDestinationPath = destination.Path), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg"))));
|
||||
|
||||
// Act
|
||||
char separator = Path.DirectorySeparatorChar;
|
||||
|
||||
+155
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkConfiguration"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MusicArtworkConfigurationTests : IDisposable
|
||||
{
|
||||
private readonly LuminaDbContext _context;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkConfigurationTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkConfigurationTests()
|
||||
{
|
||||
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().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<IProperty> 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<IIndex> 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<IIndex> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
}
|
||||
}
|
||||
+187
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkRepository"/> class.
|
||||
/// </summary>
|
||||
[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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
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<LuminaDbContext>().UseSqlite(_connection).Options);
|
||||
_context.Database.EnsureCreated();
|
||||
_sut = new MusicArtworkRepository(_context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InsertRangeAsync_WhenCalledWithArtwork_ShouldAddThemToContextAndReturnCreated()
|
||||
{
|
||||
// Arrange
|
||||
List<MusicArtworkEntity> artwork = _musicArtworkEntityFixture.CreateMany(3);
|
||||
|
||||
// Act
|
||||
Result<Created> 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<Created> 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<IReadOnlyList<MusicArtworkEntity>> 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<IReadOnlyList<MusicArtworkEntity>> 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<Deleted> result = await _sut.DeleteByOwnerAsync(ownerType, ownerId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
List<MusicArtworkEntity> 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<Deleted> 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<Updated> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the database context and its underlying connection.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Dispose();
|
||||
_connection.Dispose();
|
||||
}
|
||||
}
|
||||
+252
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicArtworkService"/> class.
|
||||
/// </summary>
|
||||
[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<MediaSettingsDto> _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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicArtworkServiceTests"/> class.
|
||||
/// </summary>
|
||||
public MusicArtworkServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
|
||||
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
_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<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveAlbumArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
MockPathBuilding();
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> 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<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[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<FileSystemPathId>()).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<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> 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<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteAlbumArtwork_WhenBuildingTheDirectoryPathFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path service so that building the artwork directory paths succeeds.
|
||||
/// </summary>
|
||||
private void MockPathBuilding()
|
||||
{
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork is stored into the given directory.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
|
||||
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<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
|
||||
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the album is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <returns>The expected file system path of the album artwork directory.</returns>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
+604
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="MusicMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
[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<ArtistMetadataLookupDto> _artistProvider;
|
||||
private readonly TestArtworkProvider<AlbumMetadataLookupDto> _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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanArtworkEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public MusicMediaLibraryScanArtworkEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockArtistRepository = Substitute.For<IArtistRepository>();
|
||||
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
|
||||
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
|
||||
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
|
||||
_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<ArtistMetadataLookupDto> { Name = "Artist Provider", RequiresWebAccess = false };
|
||||
_albumProvider = new TestArtworkProvider<AlbumMetadataLookupDto> { Name = "Album Provider", RequiresWebAccess = false };
|
||||
|
||||
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.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<IUnitOfWork>(_ => _mockUnitOfWork);
|
||||
services.AddScoped<IDomainEventPublisher>(_ => _mockDomainEventPublisher);
|
||||
services.AddSingleton(_mockMusicArtworkService);
|
||||
services.AddSingleton(_mockFileHashService);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_artistPluginId, _artistProvider);
|
||||
services.AddKeyedSingleton<IArtworkProvider>(_albumPluginId, _albumProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
_sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanArtworkEnricher>.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<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<UserSettingsEntity?>.Success(null));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([]));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(new Dictionary<Guid, string>()));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<IReadOnlyList<ArtworkDto>>([_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<IReadOnlyList<ArtworkDto>>([_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<string>(),
|
||||
artist.Name,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(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<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumProviderReturnsArtwork_ShouldStoreAndPersistEnrichedAlbumArtwork()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupAlbums(album);
|
||||
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_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<string>(),
|
||||
Arg.Any<string>(),
|
||||
album.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>(),
|
||||
Arg.Any<string?>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(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<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheProviderAnswersWithNoArtwork_ShouldMarkTheArtistNotAvailable()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
&& entities.First().Status == ArtworkStatus.NotAvailable
|
||||
&& entities.First().FileName == null
|
||||
&& entities.First().Provider == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure."));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheArtistFailed()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.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<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldLeaveTheArtistUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>())
|
||||
.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<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenClearingTheStoredArtworkRecordsFails_ShouldLeaveTheArtistUnresolved()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.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<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<IReadOnlyList<ArtworkDto>>([_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<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumCountCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAlbumsPageCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheTrackPathsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupArtists(artist);
|
||||
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(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<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library owned by the test user.
|
||||
/// </summary>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
|
||||
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Music,
|
||||
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork provider configuration reader with one enabled configuration per test plugin.
|
||||
/// </summary>
|
||||
private void SetupConfiguration()
|
||||
{
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
|
||||
[
|
||||
_artworkConfigurationFixture.Create(_libraryId.Value, _artistPluginId, 0),
|
||||
_artworkConfigurationFixture.Create(_libraryId.Value, _albumPluginId, 1)
|
||||
]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artist reader with a single page holding the provided artists.
|
||||
/// </summary>
|
||||
/// <param name="artists">The artists of the page.</param>
|
||||
private void SetupArtists(params ArtistEntity[] artists)
|
||||
{
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(artists.Length));
|
||||
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<ArtistEntity>>(artists),
|
||||
Result.From<IReadOnlyList<ArtistEntity>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the album reader with a single page holding the provided albums.
|
||||
/// </summary>
|
||||
/// <param name="albums">The albums of the page.</param>
|
||||
private void SetupAlbums(params AlbumEntity[] albums)
|
||||
{
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(albums.Length));
|
||||
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<AlbumEntity>>(albums),
|
||||
Result.From<IReadOnlyList<AlbumEntity>>([]));
|
||||
Dictionary<Guid, string> trackPaths = albums.ToDictionary(album => album.Id, album => "/music/artist/album/track.flac");
|
||||
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(trackPaths));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork storage and persistence so that an item is stored successfully.
|
||||
/// </summary>
|
||||
private void SetupSuccessArtworkStorage()
|
||||
{
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>(), Arg.Any<string?>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
|
||||
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic artwork provider for a specific lookup type, used instead of a substitute because the default implementation of
|
||||
/// <see cref="IArtworkProvider.GetArtworkAsync(MetadataLookupDto, CancellationToken)"/> cannot be intercepted reliably.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLookup">The type of the lookup the provider accepts.</typeparam>
|
||||
private sealed class TestArtworkProvider<TLookup> : IArtworkProvider<TLookup> where TLookup : MetadataLookupDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the display name of the artwork provider.
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media library types this artwork provider supports.
|
||||
/// </summary>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes { get; set; } = [LibraryType.Music];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
|
||||
/// </summary>
|
||||
public bool RequiresWebAccess { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the callback that supplies the artwork of a media item.
|
||||
/// </summary>
|
||||
public Func<TLookup, CancellationToken, Task<IReadOnlyList<ArtworkDto>>> OnGetArtworkAsync { get; set; } = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of times the provider was asked for artwork.
|
||||
/// </summary>
|
||||
public int CallCount { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
|
||||
/// </summary>
|
||||
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The artworks of the media item, or an empty collection when no artwork was found.</returns>
|
||||
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
CallCount++;
|
||||
return OnGetArtworkAsync(lookup, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
-733
@@ -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<MediaLibraryScanArtworkEnrichmentJob> _mockLogger;
|
||||
private readonly MediaLibraryScanArtworkEnrichmentJob _sut;
|
||||
private readonly ScanIdFixture _scanIdFixture = new();
|
||||
private readonly UserIdFixture _userIdFixture = new();
|
||||
private readonly LibraryIdFixture _libraryIdFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly ScanId _scanId;
|
||||
private readonly UserId _userId;
|
||||
private readonly LibraryId _libraryId;
|
||||
@@ -79,23 +60,27 @@ public class MediaLibraryScanArtworkEnrichmentJobTests
|
||||
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
|
||||
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_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<IMediaLibraryScanArtworkEnricher>();
|
||||
_mockArtworkEnricher.SupportedLibraryType.Returns(LibraryType.Music);
|
||||
_mockArtworkEnricher.EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanArtworkEnricher>))
|
||||
.Returns(new IMediaLibraryScanArtworkEnricher[] { _mockArtworkEnricher });
|
||||
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ValueTask.CompletedTask);
|
||||
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
|
||||
|
||||
_mockLogger = Substitute.For<ILogger<MediaLibraryScanArtworkEnrichmentJob>>();
|
||||
|
||||
_scanId = _scanIdFixture.Create();
|
||||
_userId = _userIdFixture.Create();
|
||||
_libraryId = _libraryIdFixture.Create();
|
||||
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory, _mockLogger)
|
||||
_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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", title: "Test Title");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(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<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
|
||||
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(123ul);
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
// the book already has a stored cover with the same content hash as the resolved artwork
|
||||
book.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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// the identical artwork is not copied again, so the artwork storage service is not called and the stored file name is kept
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((ArtworkDto?)null);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
SetupSingleBookPage(book, artworkPluginId);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
BookArtworkEntity coverArtwork = Assert.Single(book.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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
|
||||
{
|
||||
// Arrange
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
|
||||
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenReadingArtworkProviderConfigurationsFails_ShouldLogWarningAndSkipEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.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<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheConfiguredArtworkProviderIsNotRegistered_ShouldLogWarningAndSkipEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
Guid artworkPluginId = Guid.NewGuid();
|
||||
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_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<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldSkipArtworkProvidersThatRequireWebAccess()
|
||||
{
|
||||
// Arrange
|
||||
Guid webPluginId = Guid.NewGuid();
|
||||
Guid localPluginId = Guid.NewGuid();
|
||||
IArtworkProvider webProvider = Substitute.For<IArtworkProvider>();
|
||||
webProvider.Name.Returns("Web Provider");
|
||||
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
webProvider.RequiresWebAccess.Returns(true);
|
||||
IArtworkProvider localProvider = Substitute.For<IArtworkProvider>();
|
||||
localProvider.Name.Returns("Local Provider");
|
||||
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
localProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/local-cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/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<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, webPluginId, 1),
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, localPluginId, 2)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to count the books that need artwork"));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the books that need artwork"));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Database.Error", "Failed to get the author display names"));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns((ArtworkDto?)null);
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
|
||||
SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService);
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
|
||||
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Storage.Error", "Failed to store the artwork"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Storage.Error", "Failed to store the artwork"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.RequiresWebAccess.Returns(true);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash(Arg.Any<string>()).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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// 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<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
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<IArtworkProvider>();
|
||||
artworkProvider.Name.Returns("Artwork Provider");
|
||||
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/cover.jpg").Returns(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<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?>()));
|
||||
|
||||
// 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<ArtworkDto>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<IArtworkProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<ArtworkDto?>(new InvalidOperationException("The artwork provider failed")));
|
||||
IArtworkProvider secondProvider = Substitute.For<IArtworkProvider>();
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/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<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1),
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// 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<IArtworkProvider>();
|
||||
firstProvider.Name.Returns("First Provider");
|
||||
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
firstProvider.RequiresWebAccess.Returns(false);
|
||||
firstProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://example.com/cover.jpg"));
|
||||
IArtworkProvider secondProvider = Substitute.For<IArtworkProvider>();
|
||||
secondProvider.Name.Returns("Second Provider");
|
||||
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
secondProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_artworkDtoFixture.Create(localPath: "/some/second-cover.jpg"));
|
||||
|
||||
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
|
||||
IFileHashService mockFileHashService = Substitute.For<IFileHashService>();
|
||||
mockFileHashService.ComputeFileHash("/some/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<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1),
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, secondPluginId, 2)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(new Dictionary<Guid, string?> { [book.Id] = "Frank Herbert" }));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
// 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<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
IMediaLibraryScanJob mockChildJob = Substitute.For<IMediaLibraryScanJob>();
|
||||
mockChildJob.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
|
||||
.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<CancellationToken>());
|
||||
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wires a real service provider with the given artwork provider and services, so that the job resolves them from the dependency injection container.
|
||||
/// </summary>
|
||||
/// <param name="artworkPluginId">The Id of the plugin providing the artwork.</param>
|
||||
/// <param name="artworkProvider">The artwork provider to resolve.</param>
|
||||
/// <param name="bookArtworkService">The service used to store the artwork of the books.</param>
|
||||
/// <param name="fileHashService">The service used to hash the artwork.</param>
|
||||
private void SetupRealServiceProvider(Guid artworkPluginId, IArtworkProvider artworkProvider, IBookArtworkService bookArtworkService, IFileHashService fileHashService)
|
||||
{
|
||||
ServiceCollection services = new();
|
||||
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
|
||||
services.AddSingleton(_mockUnitOfWork);
|
||||
services.AddSingleton(_mockDomainEventPublisher);
|
||||
services.AddSingleton(bookArtworkService);
|
||||
services.AddSingleton(fileHashService);
|
||||
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
|
||||
ServiceProvider realServiceProvider = services.BuildServiceProvider();
|
||||
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
|
||||
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given artwork provider.
|
||||
/// </summary>
|
||||
/// <param name="book">The book whose artwork the job must resolve.</param>
|
||||
/// <param name="artworkPluginId">The Id of the plugin configured as artwork provider for the library.</param>
|
||||
private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId)
|
||||
{
|
||||
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true)));
|
||||
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
|
||||
|
||||
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([
|
||||
_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)
|
||||
]));
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
await _mockArtworkEnricher.DidNotReceive().EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>());
|
||||
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
|
||||
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+482
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BooksMediaLibraryScanArtworkEnricher"/> class.
|
||||
/// </summary>
|
||||
[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<BooksMediaLibraryScanArtworkEnricher> _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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanArtworkEnricherTests"/> class.
|
||||
/// </summary>
|
||||
public BooksMediaLibraryScanArtworkEnricherTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
|
||||
_mockArtworkProvider = Substitute.For<IArtworkProvider>();
|
||||
_mockArtworkProvider.Name.Returns("Test Provider");
|
||||
_mockArtworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
|
||||
_mockArtworkProvider.RequiresWebAccess.Returns(true);
|
||||
|
||||
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
|
||||
_mockFileHashService = Substitute.For<IFileHashService>();
|
||||
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
|
||||
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
|
||||
_mockLogger = Substitute.For<ILogger<BooksMediaLibraryScanArtworkEnricher>>();
|
||||
|
||||
// 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<IArtworkProvider>(_pluginId, _mockArtworkProvider);
|
||||
_serviceProvider = services.BuildServiceProvider();
|
||||
_sut = new BooksMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), _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<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.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<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<MetadataLookupDto>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBookHasArtwork_ShouldStoreAndPersistEnrichedArtwork()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_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<string>(),
|
||||
Arg.Any<string>(),
|
||||
book.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>());
|
||||
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<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenAProviderAnswersWithNoArtwork_ShouldMarkTheBookFailed()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
SetupBooks(book);
|
||||
SetupSuccessStore();
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([]));
|
||||
|
||||
// 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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException<IReadOnlyList<ArtworkDto>>(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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_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<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
|
||||
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<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
|
||||
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_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<Guid>(), Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnrichAsync_WhenTheAuthorsCannotBeRead_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
SetupLibrary();
|
||||
SetupConfiguration();
|
||||
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]));
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(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<MetadataLookupDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
|
||||
.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<InvalidOperationException>(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<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the media library reader with a library owned by the test user.
|
||||
/// </summary>
|
||||
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
|
||||
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
|
||||
{
|
||||
LibraryEntity library = _libraryEntityFixture.Create(
|
||||
id: _libraryId.Value,
|
||||
libraryType: LibraryType.Book,
|
||||
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
|
||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(library));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork provider configuration reader with a single enabled configuration for the test plugin.
|
||||
/// </summary>
|
||||
private void SetupConfiguration()
|
||||
{
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationFixture.Create(_libraryId.Value, _pluginId, 0)]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the book reader with a single page holding the provided books.
|
||||
/// </summary>
|
||||
/// <param name="books">The books of the page.</param>
|
||||
private void SetupBooks(params BookEntity[] books)
|
||||
{
|
||||
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(books.Length));
|
||||
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Result.From<IReadOnlyList<BookEntity>>(books),
|
||||
Result.From<IReadOnlyList<BookEntity>>([]));
|
||||
Dictionary<Guid, string?> authors = books.ToDictionary(book => book.Id, book => (string?)"Frank Herbert");
|
||||
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(authors));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the artwork storage so that a book stores its artwork successfully.
|
||||
/// </summary>
|
||||
private void SetupSuccessStore()
|
||||
{
|
||||
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/books/cover.jpg"));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, otherFileId]));
|
||||
|
||||
+6
-6
@@ -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<ArtworkDto> 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<ArtworkDto> result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Empty(result);
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -34,16 +34,16 @@ public class IArtworkProviderGenericTests
|
||||
IArtworkProvider baseProvider = provider;
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken);
|
||||
IReadOnlyList<ArtworkDto> 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<ArtworkDto> 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;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Task<ArtworkDto?> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
ReceivedLookup = lookup;
|
||||
ReceivedCancellationToken = cancellationToken;
|
||||
return Task.FromResult<ArtworkDto?>(_artwork);
|
||||
return Task.FromResult<IReadOnlyList<ArtworkDto>>([_artwork]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-12
@@ -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<MetadataDto> result = await baseProvider.GetSearchResultsAsync(otherLookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAsync<InvalidCastException>(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<InvalidCastException>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test double for the typed metadata provider interface that records the forwarded arguments.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user