diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs
new file mode 100644
index 00000000..db880c8b
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntity.cs
@@ -0,0 +1,91 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+
+///
+/// Repository entity for a piece of artwork of a music library item, like the cover of an album or the image of an artist.
+///
+///
+/// A music library item can have multiple pieces of artwork of different types, and multiple instances of the same type
+/// (like the front cover, the back cover and the booklet pages of an album), each tracked independently so that a change
+/// of one artwork does not require the others to be re-fetched.
+///
+[DebuggerDisplay("OwnerType: {OwnerType} OwnerId: {OwnerId} Type: {ArtworkType} Ordinal: {Ordinal}")]
+public class MusicArtworkEntity : IStorageEntity, IAuditableEntity
+{
+ ///
+ /// Gets the Id of the artwork.
+ ///
+ public required Guid Id { get; init; }
+
+ ///
+ /// Gets or sets the type of the music library item that owns the artwork.
+ ///
+ public required MusicArtworkOwnerType OwnerType { get; set; }
+
+ ///
+ /// Gets or sets the Id of the music library item that owns the artwork.
+ ///
+ public required Guid OwnerId { get; set; }
+
+ ///
+ /// Gets or sets the type of the artwork.
+ ///
+ public required ArtworkType ArtworkType { get; set; }
+
+ ///
+ /// Gets or sets the ordinal of the artwork within its type, so that multiple artworks of the same type can be ordered.
+ ///
+ public required int Ordinal { get; set; }
+
+ ///
+ /// Gets or sets the relative file name of the stored artwork, if the artwork has been resolved.
+ ///
+ public string? FileName { get; set; }
+
+ ///
+ /// Gets or sets the content hash of the stored artwork, used to detect whether a re-resolved artwork differs from the stored one.
+ ///
+ public ulong ContentHash { get; set; }
+
+ ///
+ /// Gets or sets the status of the artwork enrichment.
+ ///
+ public required ArtworkStatus Status { get; set; }
+
+ ///
+ /// Gets or sets the name of the plugin that resolved the artwork, if applicable.
+ ///
+ public string? Provider { get; set; }
+
+ ///
+ /// Gets or sets the date and time when the artwork was last resolved, if applicable.
+ ///
+ public DateTime? LastUpdateUtc { get; set; }
+
+ ///
+ /// Gets or sets the time and date when the entity was added.
+ ///
+ public required DateTime CreatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the Id of the user that created the entity.
+ ///
+ public required Guid CreatedBy { get; set; }
+
+ ///
+ /// Gets or sets the optional time and date when the entity was updated.
+ ///
+ public DateTime? UpdatedOnUtc { get; set; }
+
+ ///
+ /// Gets or sets the optional Id of the user that updated the entity.
+ ///
+ public required Guid? UpdatedBy { get; set; }
+}
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs
new file mode 100644
index 00000000..2d1686e8
--- /dev/null
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicArtworkRepository.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
+using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
+
+///
+/// Interface for the repository for the artwork of the music library items.
+///
+public interface IMusicArtworkRepository : IRepository,
+ IInsertRangeRepositoryAction
+{
+ ///
+ /// Gets the pieces of artwork owned by the music library item of the provided identified by .
+ ///
+ /// The type of the music library item that owns the artwork.
+ /// The Id of the music library item that owns the artwork.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken);
+
+ ///
+ /// Deletes all the pieces of artwork owned by the music library item of the provided identified by .
+ ///
+ /// The type of the music library item that owns the artwork.
+ /// The Id of the music library item that owns the artwork.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken);
+
+ ///
+ /// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by , so that they are re-resolved.
+ ///
+ ///
+ /// The status is reset because the artwork provider configuration of the library changed.
+ ///
+ /// The Id of the media library whose artwork is reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs
new file mode 100644
index 00000000..1754343c
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+
+///
+/// Interface for the service for storing the artwork of a music library item, an album or an artist, into the internal media directory and serving its relative path.
+///
+public interface IMusicArtworkService
+{
+ ///
+ /// Stores the of the album into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the album.
+ /// The name of the media library the album belongs to.
+ /// The name of the artist of the album.
+ /// The title of the album.
+ /// The artwork to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added.
+ /// An containing either the relative path of the stored artwork, or an error.
+ Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null);
+
+ ///
+ /// Deletes the stored artwork of the album from the internal media directory.
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the album.
+ /// The name of the media library the album belongs to.
+ /// The name of the artist of the album.
+ /// The title of the album.
+ /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added.
+ /// An representing either a successful operation, or an error.
+ Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null);
+
+ ///
+ /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the media library the artist belongs to.
+ /// The name of the artist.
+ /// The artwork to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken);
+
+ ///
+ /// Deletes the stored artwork of the artist from the internal media directory.
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the media library the artist belongs to.
+ /// The name of the artist.
+ /// An representing either a successful operation, or an error.
+ Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName);
+}
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs
index 97d9a8e3..b8111399 100644
--- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs
@@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
diff --git a/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs
new file mode 100644
index 00000000..50853c1b
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/MusicArtworkConfiguration.cs
@@ -0,0 +1,78 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+#endregion
+
+namespace Lumina.DataAccess.Common.Configuration;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class MusicArtworkConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("MusicArtwork");
+ builder.HasKey(musicArtwork => musicArtwork.Id);
+ builder.Property(musicArtwork => musicArtwork.Id)
+ .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
+ .HasColumnOrder(0);
+ builder.Property(musicArtwork => musicArtwork.OwnerType)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(50)
+ .HasColumnOrder(1);
+ builder.Property(musicArtwork => musicArtwork.OwnerId)
+ .IsRequired()
+ .HasColumnOrder(2);
+ builder.Property(musicArtwork => musicArtwork.ArtworkType)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(50)
+ .HasColumnOrder(3);
+ builder.Property(musicArtwork => musicArtwork.Ordinal)
+ .IsRequired()
+ .HasColumnOrder(4);
+ builder.Property(musicArtwork => musicArtwork.FileName)
+ .HasMaxLength(2048)
+ .HasColumnOrder(5);
+ builder.Property(musicArtwork => musicArtwork.ContentHash)
+ .HasColumnOrder(6);
+ builder.Property(musicArtwork => musicArtwork.Status)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(20)
+ .HasColumnOrder(7);
+ builder.Property(musicArtwork => musicArtwork.Provider)
+ .HasMaxLength(100)
+ .HasColumnOrder(8);
+ builder.Property(musicArtwork => musicArtwork.LastUpdateUtc)
+ .HasColumnOrder(9);
+
+ // audit
+ builder.Property(musicArtwork => musicArtwork.CreatedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(10);
+
+ builder.Property(musicArtwork => musicArtwork.CreatedBy)
+ .IsRequired()
+ .HasColumnOrder(11);
+
+ builder.Property(musicArtwork => musicArtwork.UpdatedOnUtc)
+ .HasDefaultValue(null)
+ .HasColumnOrder(12);
+
+ builder.Property(musicArtwork => musicArtwork.UpdatedBy)
+ .HasDefaultValue(null)
+ .HasColumnOrder(13);
+
+ builder.HasIndex(musicArtwork => new { musicArtwork.OwnerType, musicArtwork.OwnerId, musicArtwork.ArtworkType, musicArtwork.Ordinal })
+ .IsUnique();
+ builder.HasIndex(musicArtwork => musicArtwork.Status);
+ }
+}
diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs
new file mode 100644
index 00000000..ceb8f38e
--- /dev/null
+++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicArtworkRepository.cs
@@ -0,0 +1,109 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
+
+///
+/// Repository for the artwork of the music library items.
+///
+internal sealed class MusicArtworkRepository : IMusicArtworkRepository
+{
+ private readonly LuminaDbContext _luminaDbContext;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Entity Framework DbContext.
+ public MusicArtworkRepository(LuminaDbContext luminaDbContext)
+ {
+ _luminaDbContext = luminaDbContext;
+ }
+
+ ///
+ /// Adds a range of pieces of artwork of music library items.
+ ///
+ /// The pieces of artwork to add.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public Task> InsertRangeAsync(IReadOnlyCollection artwork, CancellationToken cancellationToken)
+ {
+ if (artwork.Count > 0)
+ _luminaDbContext.MusicArtwork.AddRange(artwork);
+ return Task.FromResult>(Result.Created);
+ }
+
+ ///
+ /// Gets the pieces of artwork owned by the music library item of the provided identified by .
+ ///
+ /// The type of the music library item that owns the artwork.
+ /// The Id of the music library item that owns the artwork.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either a collection of , or an error.
+ public async Task>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken)
+ {
+ IReadOnlyList artwork = await _luminaDbContext.MusicArtwork
+ .AsNoTracking()
+ .Where(musicArtwork => musicArtwork.OwnerType == ownerType && musicArtwork.OwnerId == ownerId)
+ .OrderBy(musicArtwork => musicArtwork.ArtworkType)
+ .ThenBy(musicArtwork => musicArtwork.Ordinal)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ return Result.From(artwork);
+ }
+
+ ///
+ /// Deletes all the pieces of artwork owned by the music library item of the provided identified by .
+ ///
+ /// The type of the music library item that owns the artwork.
+ /// The Id of the music library item that owns the artwork.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> DeleteByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken)
+ {
+ await _luminaDbContext.MusicArtwork
+ .Where(musicArtwork => musicArtwork.OwnerType == ownerType && musicArtwork.OwnerId == ownerId)
+ .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
+ return Result.Deleted;
+ }
+
+ ///
+ /// Resets the artwork enrichment status of all the pieces of artwork owned by the music library items of the media library identified by .
+ ///
+ /// The Id of the media library whose artwork is reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> ResetStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken)
+ {
+ // The artwork table is shared by all the music library item types, so the owners of the artwork of this library are collected per type.
+ List artistIds = await _luminaDbContext.Artists
+ .Where(artist => artist.LibraryId == libraryId)
+ .Select(artist => artist.Id)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ List albumIds = await _luminaDbContext.Albums
+ .Where(album => album.LibraryId == libraryId)
+ .Select(album => album.Id)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ List trackIds = await _luminaDbContext.Tracks
+ .Where(track => track.LibraryId == libraryId)
+ .Select(track => track.Id)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+
+ await _luminaDbContext.MusicArtwork
+ .Where(musicArtwork => (musicArtwork.OwnerType == MusicArtworkOwnerType.Artist && artistIds.Contains(musicArtwork.OwnerId))
+ || (musicArtwork.OwnerType == MusicArtworkOwnerType.Album && albumIds.Contains(musicArtwork.OwnerId))
+ || (musicArtwork.OwnerType == MusicArtworkOwnerType.Track && trackIds.Contains(musicArtwork.OwnerId)))
+ .ExecuteUpdateAsync(setters => setters.SetProperty(musicArtwork => musicArtwork.Status, ArtworkStatus.Pending), cancellationToken).ConfigureAwait(false);
+ return Result.Updated;
+ }
+}
diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs
new file mode 100644
index 00000000..29ed3503
--- /dev/null
+++ b/src/Lumina.Domain.SharedKernel/Common/Enums/AudioLibrary/MusicArtworkOwnerType.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+
+///
+/// Enumeration for the type of the music library item that owns a piece of artwork.
+///
+[DebuggerDisplay("{ToString()}")]
+public enum MusicArtworkOwnerType
+{
+ ///
+ /// The artwork belongs to an artist.
+ ///
+ Artist,
+
+ ///
+ /// The artwork belongs to an album.
+ ///
+ Album,
+
+ ///
+ /// The artwork belongs to a track.
+ ///
+ Track
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs
new file mode 100644
index 00000000..28ccb723
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs
@@ -0,0 +1,457 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
+using Lumina.Infrastructure.Common.Utilities;
+using Lumina.Infrastructure.Common.Networking;
+using Microsoft.Extensions.Options;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+
+///
+/// Stores the artwork of an album into the internal media directory, under a per-album directory, and returns its relative path.
+///
+internal sealed class MusicArtworkService : IMusicArtworkService
+{
+ private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
+
+ private readonly IEnvironmentContext _environmentContext;
+ private readonly IPathService _pathService;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly MediaSettingsDto _mediaSettings;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected facade service for environment contextual services.
+ /// Injected service for handling file system paths.
+ /// Injected factory used to create the HTTP clients that download the remote artwork.
+ /// Injected service for retrieving .
+ public MusicArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions mediaSettingsOptions)
+ {
+ _environmentContext = environmentContext;
+ _pathService = pathService;
+ _httpClientFactory = httpClientFactory;
+ _mediaSettings = mediaSettingsOptions.Value;
+ }
+
+ ///
+ /// Stores the of the album into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the album.
+ /// The name of the media library the album belongs to.
+ /// The name of the artist of the album.
+ /// The title of the album.
+ /// The artwork to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added.
+ /// An containing either the relative path of the stored artwork, or an error.
+ public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null)
+ {
+ Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
+ if (artworkDirectoryPathResult.IsFailure)
+ return artworkDirectoryPathResult.Errors;
+ return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Stores the of the artist into the internal media directory, and returns the relative path of the stored artwork.
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the media library the artist belongs to.
+ /// The name of the artist.
+ /// The artwork to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken)
+ {
+ Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
+ if (artworkDirectoryPathResult.IsFailure)
+ return artworkDirectoryPathResult.Errors;
+ return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resolves the local source of the , stores it into , and cleans up the temporary download of a remote artwork.
+ ///
+ /// The file system path of the directory the artwork is stored into.
+ /// The artwork to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ private async Task> SaveArtworkAsync(string artworkDirectoryPath, ArtworkDto artwork, CancellationToken cancellationToken)
+ {
+ // Resolve the local file path of the artwork, downloading it to a temporary file when it is remote.
+ Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false);
+ if (resolveSourceResult.IsFailure)
+ return resolveSourceResult.Errors;
+ string sourcePath = resolveSourceResult.Value.Path;
+
+ try
+ {
+ return await StoreArtworkAsync(artworkDirectoryPath, artwork.Type, artwork.Ordinal, sourcePath, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ // Remove the temporary source of the artwork, whether it was downloaded for a remote artwork or produced by a provider, never a file of the user.
+ if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath))
+ {
+ try
+ {
+ File.Delete(sourcePath);
+ }
+ catch (IOException)
+ {
+ // A failed cleanup of the temporary file must not mask the result of the operation.
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // A failed cleanup of the temporary file must not mask the result of the operation.
+ }
+ }
+ }
+ }
+
+ ///
+ /// Deletes the stored artwork of the album from the internal media directory.
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the album.
+ /// The name of the media library the album belongs to.
+ /// The name of the artist of the album.
+ /// The title of the album.
+ /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added.
+ /// An representing either a successful operation, or an error.
+ public Result DeleteAlbumArtwork(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null)
+ {
+ Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName);
+ if (artworkDirectoryPathResult.IsFailure)
+ return artworkDirectoryPathResult.Errors;
+ return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value);
+ }
+
+ ///
+ /// Deletes the stored artwork of the artist from the internal media directory.
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the media library the artist belongs to.
+ /// The name of the artist.
+ /// An representing either a successful operation, or an error.
+ public Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName)
+ {
+ Result artworkDirectoryPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
+ if (artworkDirectoryPathResult.IsFailure)
+ return artworkDirectoryPathResult.Errors;
+ return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value);
+ }
+
+ ///
+ /// Deletes the files directly contained in , leaving the subdirectories, such as the album directories of an artist, untouched.
+ ///
+ /// The file system path of the directory whose files are deleted.
+ /// An representing either a successful operation, or an error.
+ private Result DeleteArtworkInDirectory(string artworkDirectoryPath)
+ {
+ Result directoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath);
+ if (directoryPathIdResult.IsFailure)
+ return directoryPathIdResult.Errors;
+
+ // When nothing was stored for the owner yet, its directory does not exist, so there is nothing to delete.
+ Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value);
+ if (directoryExistsResult.IsFailure)
+ return directoryExistsResult.Errors;
+ if (!directoryExistsResult.Value)
+ return Result.Deleted;
+
+ Result> getFilesResult = _environmentContext.FileProviderService.GetFilePaths(directoryPathIdResult.Value, true);
+ if (getFilesResult.IsFailure)
+ return getFilesResult.Errors;
+
+ foreach (FileSystemPathId filePathId in getFilesResult.Value)
+ _environmentContext.FileProviderService.DeleteFile(filePathId);
+
+ return Result.Deleted;
+ }
+
+ ///
+ /// Stores the artwork file at into .
+ ///
+ /// The file system path of the directory the artwork is stored into.
+ /// The type of the artwork being stored.
+ /// The ordinal of the artwork within its type.
+ /// The file system path of the artwork file to store.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the relative path of the stored artwork, or an error.
+ private async Task> StoreArtworkAsync(string artworkDirectoryPath, ArtworkType artworkType, int ordinal, string sourcePath, CancellationToken cancellationToken)
+ {
+ Result sourcePathIdResult = FileSystemPathId.Create(sourcePath);
+ if (sourcePathIdResult.IsFailure)
+ return sourcePathIdResult.Errors;
+
+ Result fileExistsResult = _environmentContext.FileProviderService.FileExists(sourcePathIdResult.Value);
+ if (fileExistsResult.IsFailure)
+ return fileExistsResult.Errors;
+ if (!fileExistsResult.Value)
+ return Errors.FileSystemManagement.FileNotFound;
+
+ // Reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine.
+ if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint))
+ return Errors.FileSystemManagement.InvalidPath;
+
+ // Reject the artwork when it exceeds the maximum allowed size.
+ FileInfo sourceFileInfo = new(sourcePath);
+ if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES)
+ return Errors.FileSystemManagement.FileTooLarge;
+
+ // Make sure the file is an actual supported image.
+ Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false);
+ if (imageTypeResult.IsFailure)
+ return imageTypeResult.Errors;
+ if (imageTypeResult.Value == ImageType.None)
+ return Errors.Library.CoverFileMustBeAnImage;
+
+ Result ensureDirectoryResult = EnsureDirectory(artworkDirectoryPath);
+ if (ensureDirectoryResult.IsFailure)
+ return ensureDirectoryResult.Errors;
+
+ Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath);
+ if (artworkDirectoryPathIdResult.IsFailure)
+ return artworkDirectoryPathIdResult.Errors;
+
+ // Copy the artwork file from the source location.
+ Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true);
+ if (copyFileResult.IsFailure)
+ return copyFileResult.Errors;
+
+ // Rename the copied file to the standard naming, derived from the type and the ordinal of the artwork.
+ Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"{BuildArtworkFileStem(artworkType, ordinal)}.{imageTypeResult.Value.ToFileExtension()}");
+ if (renameFileResult.IsFailure)
+ return renameFileResult.Errors;
+
+ // Get the internal relative path for the copied file.
+ string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..];
+ if (!relativePath.StartsWith(_pathService.PathSeparator))
+ relativePath = $"{_pathService.PathSeparator}{relativePath}";
+ return relativePath;
+ }
+
+ ///
+ /// Builds the file name stem of an artwork, derived from its type and ordinal.
+ ///
+ /// The type of the artwork.
+ /// The ordinal of the artwork within its type.
+ /// The file name stem of the artwork.
+ private static string BuildArtworkFileStem(ArtworkType artworkType, int ordinal)
+ {
+ string stem = artworkType switch
+ {
+ ArtworkType.Cover => "cover",
+ ArtworkType.Front => "front",
+ ArtworkType.Back => "back",
+ ArtworkType.Booklet => "booklet",
+ ArtworkType.Medium => "medium",
+ ArtworkType.Tray => "tray",
+ ArtworkType.Spine => "spine",
+ ArtworkType.Obi => "obi",
+ ArtworkType.Sticker => "sticker",
+ ArtworkType.Poster => "poster",
+ ArtworkType.Liner => "liner",
+ ArtworkType.Watermark => "watermark",
+ ArtworkType.Backdrop => "backdrop",
+ ArtworkType.Banner => "banner",
+ ArtworkType.Logo => "logo",
+ ArtworkType.Thumb => "thumb",
+ _ => "other"
+ };
+ return ordinal > 0 ? $"{stem}-{ordinal}" : stem;
+ }
+
+ ///
+ /// Resolves the local file system path of the , downloading it to a temporary file when it is remote.
+ ///
+ /// The artwork whose source path is resolved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the resolved local source of the artwork, or an error.
+ private async Task> ResolveArtworkSourceAsync(ArtworkDto artwork, CancellationToken cancellationToken)
+ {
+ if (!string.IsNullOrWhiteSpace(artwork.LocalPath))
+ return new ArtworkSourceResult(artwork.LocalPath, IsTemporary: artwork.IsTemporary);
+
+ if (string.IsNullOrWhiteSpace(artwork.RemoteUrl))
+ return Errors.FileSystemManagement.FileNotFound;
+
+ // Download the remote artwork into a temporary file, aborting when it exceeds the allowed size.
+ using HttpClient httpClient = _httpClientFactory.CreateClient(NamedHttpClients.ARTWORK_DOWNLOAD);
+ string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}");
+ bool downloaded = false;
+ try
+ {
+ using HttpResponseMessage response = await httpClient.GetAsync(artwork.RemoteUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ if (!response.IsSuccessStatusCode)
+ return Errors.FileSystemManagement.FileNotFound;
+
+ await using Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ await using FileStream fileStream = new(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true);
+
+ byte[] buffer = new byte[81920];
+ long totalRead = 0;
+ int bytesRead;
+ while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
+ {
+ totalRead += bytesRead;
+ if (totalRead > MAX_ARTWORK_SIZE_BYTES)
+ return Errors.FileSystemManagement.FileTooLarge;
+ await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false);
+ }
+ downloaded = true;
+ return new ArtworkSourceResult(tempPath, IsTemporary: true);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception)
+ {
+ return Errors.FileSystemManagement.FileNotFound;
+ }
+ finally
+ {
+ // Remove the partially downloaded temporary file when the download failed.
+ if (!downloaded && File.Exists(tempPath))
+ File.Delete(tempPath);
+ }
+ }
+
+ ///
+ /// Builds the file system path of the directory of the album artwork, under the internal media directory.
+ /// The artwork of the album is stored under the directory of its release type, mirroring the structure of the scanned files.
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the album.
+ /// The name of the media library the album belongs to.
+ /// The name of the artist of the album.
+ /// The title of the album.
+ /// The name of the release type directory the album is stored under on disk, or to store the artwork directly under the artist directory.
+ /// An containing either the file system path of the album artwork directory, or an error.
+ private Result BuildAlbumArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName)
+ {
+ Result artistPathResult = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName);
+ if (artistPathResult.IsFailure)
+ return artistPathResult.Errors;
+
+ // The release type directory groups the releases of an artist that share a title but are different releases, like the album and the single of the same songs.
+ Result albumParentPathResult = artistPathResult;
+ if (!string.IsNullOrWhiteSpace(releaseTypeName))
+ {
+ Result releaseTypeSegmentResult = _pathService.SanitizeSegment(releaseTypeName);
+ if (releaseTypeSegmentResult.IsFailure)
+ return releaseTypeSegmentResult.Errors;
+ Result releaseTypePathResult = _pathService.CombinePath(artistPathResult.Value, releaseTypeSegmentResult.Value.Name);
+ if (releaseTypePathResult.IsFailure)
+ return releaseTypePathResult.Errors;
+ albumParentPathResult = releaseTypePathResult;
+ }
+
+ Result albumSegmentResult = _pathService.SanitizeSegment($"{albumTitle}-{albumId}");
+ if (albumSegmentResult.IsFailure)
+ return albumSegmentResult.Errors;
+ return _pathService.CombinePath(albumParentPathResult.Value, albumSegmentResult.Value.Name);
+ }
+
+ ///
+ /// Builds the file system path of the directory of the artist artwork, under the internal media directory.
+ /// The artwork of the albums of the artist is stored in the subdirectories of this directory.
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the media library the artist belongs to.
+ /// The name of the artist.
+ /// An containing either the file system path of the artist artwork directory, or an error.
+ private Result BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
+ {
+ Result libraryPathResult = BuildLibraryArtworkDirectoryPath(libraryId, libraryName);
+ if (libraryPathResult.IsFailure)
+ return libraryPathResult.Errors;
+
+ Result artistSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(artistName) ? "Unknown" : artistName);
+ if (artistSegmentResult.IsFailure)
+ return artistSegmentResult.Errors;
+ return _pathService.CombinePath(libraryPathResult.Value, artistSegmentResult.Value.Name);
+ }
+
+ ///
+ /// Builds the file system path of the directory of a music media library, under the internal media directory.
+ ///
+ /// The Id of the media library.
+ /// The name of the media library.
+ /// An containing either the file system path of the media library directory, or an error.
+ private Result BuildLibraryArtworkDirectoryPath(Guid libraryId, string libraryName)
+ {
+ Result mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory);
+ if (mediaRootPathResult.IsFailure)
+ return mediaRootPathResult.Errors;
+ Result musicPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.MusicDirectory);
+ if (musicPathResult.IsFailure)
+ return musicPathResult.Errors;
+
+ Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}");
+ if (librarySegmentResult.IsFailure)
+ return librarySegmentResult.Errors;
+ return _pathService.CombinePath(musicPathResult.Value, librarySegmentResult.Value.Name);
+ }
+
+ ///
+ /// Creates the directory at , along with its missing parents.
+ ///
+ /// The file system path of the directory to create.
+ /// An representing either a successful operation, or an error.
+ private Result EnsureDirectory(string directoryPath)
+ {
+ Result directoryPathIdResult = FileSystemPathId.Create(directoryPath);
+ if (directoryPathIdResult.IsFailure)
+ return directoryPathIdResult.Errors;
+
+ Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value);
+ if (directoryExistsResult.IsFailure)
+ return directoryExistsResult.Errors;
+ if (directoryExistsResult.Value)
+ return Result.Success;
+
+ string? parentDirectoryPath = Path.GetDirectoryName(directoryPath);
+ if (!string.IsNullOrEmpty(parentDirectoryPath) && !string.Equals(parentDirectoryPath, directoryPath, StringComparison.Ordinal))
+ {
+ Result createParentResult = EnsureDirectory(parentDirectoryPath);
+ if (createParentResult.IsFailure)
+ return createParentResult.Errors;
+ }
+
+ Result parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath);
+ if (parentDirectoryPathIdResult.IsFailure)
+ return parentDirectoryPathIdResult.Errors;
+
+ Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath));
+ if (createDirectoryResult.IsFailure)
+ return createDirectoryResult.Errors;
+ return Result.Success;
+ }
+
+ ///
+ /// Describes the resolved local source of the artwork.
+ ///
+ /// The file system path of the resolved source.
+ /// Whether the resolved source is a temporary file that must be cleaned up after it is stored.
+ private sealed record ArtworkSourceResult(string Path, bool IsTemporary);
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs
new file mode 100644
index 00000000..862e4455
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs
@@ -0,0 +1,677 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.Plugins;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Security;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
+
+///
+/// Artwork enricher for the media library items of the music media library type, using the artwork providers configured for the media library.
+///
+///
+/// The artwork of an artist and of an album is tracked per type and ordinal, so that a change of one piece of artwork does not require the others to be re-fetched.
+///
+internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanArtworkEnricher
+{
+ private const int ENRICHMENT_PAGE_SIZE = 200; // The number of artists or albums that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
+ private readonly IServiceScopeFactory _serviceScopeFactory;
+ private readonly ILogger _logger;
+
+ ///
+ /// The media library type that this artwork enricher supports.
+ ///
+ public LibraryType SupportedLibraryType => LibraryType.Music;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating scopes in which services are requested.
+ /// Injected logger used to report the issues encountered while resolving the artwork.
+ public MusicMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Resolves the artwork of the artists and the albums of the provided media library, using the artwork providers configured for it.
+ ///
+ /// The unique identifier of the media library whose artwork is resolved.
+ /// The unique identifier of the media library scan.
+ /// The unique identifier of the user that initiated the media library scan.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken)
+ {
+ await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
+ IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!;
+ IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
+
+ MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId);
+
+ // Load the media library, whose name is used to build the directories of the artwork, and whose setting determines whether the providers that require access to the web are used during the enrichment.
+ string libraryName = string.Empty;
+ bool canDownloadMetadataFromWeb = false;
+ if (unitOfWork.LibraryRepository is not null)
+ {
+ Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
+ _logger.LogWarning("Failed to read the media library, the artwork will not be stored and the providers requiring the web will not be used.");
+ else
+ {
+ libraryName = getLibraryResult.Value.Title;
+ canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
+ }
+ }
+
+ // Read whether the artwork of the items of the user is aggregated from multiple providers, when it is missing.
+ bool shouldAggregateArtworkWhenMissing = false;
+ if (unitOfWork.UserSettingsRepository is not null)
+ {
+ Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId.Value, cancellationToken).ConfigureAwait(false);
+ if (getUserSettingsResult.IsFailure)
+ _logger.LogWarning("Failed to read the user settings, the artwork will not be aggregated across providers.");
+ else
+ shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false;
+ }
+
+ // Get the artwork providers configured for the media library, in their configured order, that support the media library type.
+ // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding.
+ List artworkProviders = [];
+ if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
+ {
+ Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getArtworkConfigurationsResult.IsFailure)
+ _logger.LogWarning("Failed to read the artwork provider configurations.");
+ else
+ {
+ foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
+ {
+ List configuredProviders = [.. asyncServiceScope.ServiceProvider
+ .GetKeyedServices(configuration.PluginId)
+ .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
+ && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
+ if (configuredProviders.Count == 0)
+ _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
+ artworkProviders.AddRange(configuredProviders);
+ }
+ }
+ }
+
+ // When no artwork provider is available, the items must not be marked as failed to resolve, so the enrichment is skipped entirely.
+ if (artworkProviders.Count == 0)
+ {
+ _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
+ return;
+ }
+
+ // The providers are split by the lookup they accept, keeping the configured rank order in which they were gathered.
+ IReadOnlyList artistProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider)];
+ IReadOnlyList albumProviders = [.. artworkProviders.Where(provider => provider is IArtworkProvider)];
+
+ IMusicArtworkService? musicArtworkService = asyncServiceScope.ServiceProvider.GetService();
+ IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!;
+
+ int totalArtistsToEnrich = 0;
+ if (artistProviders.Count > 0)
+ {
+ Result getArtistsToEnrichCountResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getArtistsToEnrichCountResult.IsFailure)
+ throw new InvalidOperationException(getArtistsToEnrichCountResult.FirstError.Description);
+ totalArtistsToEnrich = getArtistsToEnrichCountResult.Value;
+ }
+
+ int totalAlbumsToEnrich = 0;
+ if (albumProviders.Count > 0)
+ {
+ Result getAlbumsToEnrichCountResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getAlbumsToEnrichCountResult.IsFailure)
+ throw new InvalidOperationException(getAlbumsToEnrichCountResult.FirstError.Description);
+ totalAlbumsToEnrich = getAlbumsToEnrichCountResult.Value;
+ }
+
+ int totalItemsToEnrich = totalArtistsToEnrich + totalAlbumsToEnrich;
+
+ // Set the initial progress of the scan job.
+ Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsFailure)
+ throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
+
+ DateTime lastUpdateTime = DateTime.UtcNow;
+ int minUpdateIntervalMs = 100;
+ int processedItemsCount = 0;
+
+ // Reports that a single artist or album was processed, publishing the progress at most once per interval.
+ async Task ReportItemProcessedAsync()
+ {
+ int processedItems = Interlocked.Increment(ref processedItemsCount);
+ DateTime now = DateTime.UtcNow;
+ if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
+ {
+ Result publishItemProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, processedItems, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishItemProgressResult.IsFailure)
+ throw new InvalidOperationException(publishItemProgressResult.FirstError.Description);
+ lastUpdateTime = now;
+ }
+ }
+
+ if (artistProviders.Count > 0)
+ await EnrichArtistsAsync(libraryId, artistProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false);
+
+ if (albumProviders.Count > 0)
+ await EnrichAlbumsAsync(libraryId, albumProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false);
+
+ // The enrichment finished, force the progress to reach its total, so that a throttled update cannot leave it incomplete.
+ Result publishFinalProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, totalItemsToEnrich, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishFinalProgressResult.IsFailure)
+ throw new InvalidOperationException(publishFinalProgressResult.FirstError.Description);
+ }
+
+ ///
+ /// Resolves the artwork of the artists of the provided media library whose artwork has not been resolved yet, page by page.
+ ///
+ /// The unique identifier of the media library whose artists are enriched.
+ /// The artists artwork providers, in the order they are consulted.
+ /// The service used to store the artwork of the artists.
+ /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
+ /// The name of the media library the artists belong to.
+ /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.
+ /// The unit of work used to persist the artwork of the artists.
+ /// The callback invoked after each artist is processed, to advance the progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ private async Task EnrichArtistsAsync(LibraryId libraryId, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func reportItemProcessedAsync, CancellationToken cancellationToken)
+ {
+ string? lastName = null;
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Result> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingArtworkAsync(libraryId.Value, lastName, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
+ if (getArtistsPageResult.IsFailure)
+ throw new InvalidOperationException(getArtistsPageResult.FirstError.Description);
+ IReadOnlyList artistsPage = getArtistsPageResult.Value;
+ if (artistsPage.Count == 0)
+ break;
+
+ foreach (ArtistEntity artistEntity in artistsPage)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ // The first track of the artist, in a deterministic order, describes the artist in the artwork lookup and locates its directory on the file system.
+ string firstTrackPath = artistEntity.Albums.SelectMany(album => album.Tracks).Select(track => track.Path).OrderBy(path => path).FirstOrDefault() ?? string.Empty;
+ await EnrichArtistArtworkAsync(artistEntity, firstTrackPath, artworkProviders, musicArtworkService, fileHashService, libraryName, shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false);
+ await reportItemProcessedAsync().ConfigureAwait(false);
+ }
+
+ // Persist the resolved artwork of this page, then detach it from the change tracker, keeping the peak memory bounded regardless of the library size.
+ Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ throw new InvalidOperationException(saveChangesResult.FirstError.Description);
+ unitOfWork.ClearTrackedEntities();
+
+ lastName = artistsPage[^1].Name;
+ }
+ }
+
+ ///
+ /// Resolves the artwork of the albums of the provided media library whose artwork has not been resolved yet, page by page.
+ ///
+ /// The unique identifier of the media library whose albums are enriched.
+ /// The album artwork providers, in the order they are consulted.
+ /// The service used to store the artwork of the albums.
+ /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
+ /// The name of the media library the albums belong to.
+ /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.
+ /// The unit of work used to persist the artwork of the albums.
+ /// The callback invoked after each album is processed, to advance the progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ private async Task EnrichAlbumsAsync(LibraryId libraryId, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, Func reportItemProcessedAsync, CancellationToken cancellationToken)
+ {
+ // A provider that does not require the web, like the one that reads the files of the user, can resolve the artwork without any MusicBrainz identifier.
+ bool canResolveWithoutMusicBrainzIds = artworkProviders.Any(provider => !provider.RequiresWebAccess);
+
+ // The albums that were attempted but remain unresolved are tracked and excluded from the following pages, so that a page that made no album reach a terminal state cannot make the pagination loop forever.
+ List albumsRemainingUnresolved = [];
+
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Result> getAlbumsPageResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingArtworkAsync(libraryId.Value, albumsRemainingUnresolved, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
+ if (getAlbumsPageResult.IsFailure)
+ throw new InvalidOperationException(getAlbumsPageResult.FirstError.Description);
+ IReadOnlyList albumsPage = getAlbumsPageResult.Value;
+ if (albumsPage.Count == 0)
+ break;
+
+ // Load the path of one track of each album of this page, in one query, since it is used to locate the album directory on the file system.
+ Result> getTrackPathsResult = await unitOfWork.AlbumRepository.GetFirstTrackPathsByAlbumIdsAsync([.. albumsPage.Select(album => album.Id)], cancellationToken).ConfigureAwait(false);
+ if (getTrackPathsResult.IsFailure)
+ throw new InvalidOperationException(getTrackPathsResult.FirstError.Description);
+
+ foreach (AlbumEntity albumEntity in albumsPage)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ string firstTrackPath = getTrackPathsResult.Value.TryGetValue(albumEntity.Id, out string? trackPath) ? trackPath : string.Empty;
+ bool isTerminal = await EnrichAlbumArtworkAsync(albumEntity, firstTrackPath, artworkProviders, musicArtworkService, fileHashService, libraryName, canResolveWithoutMusicBrainzIds, shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false);
+ if (!isTerminal)
+ albumsRemainingUnresolved.Add(albumEntity.Id);
+ await reportItemProcessedAsync().ConfigureAwait(false);
+ }
+
+ // Persist the enriched albums of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
+ Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ throw new InvalidOperationException(saveChangesResult.FirstError.Description);
+ unitOfWork.ClearTrackedEntities();
+ }
+ }
+
+ ///
+ /// Resolves the artwork of the provided from the , storing the artwork resolved from the providers, in their order.
+ ///
+ /// The artist whose artwork is resolved.
+ /// The file system path of one track of the artist, used to locate its directory.
+ /// The artist artwork providers, in the order they are consulted.
+ /// The service used to store the artwork of the artist.
+ /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
+ /// The name of the media library the artist belongs to.
+ /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.
+ /// The unit of work used to persist the artwork of the artist.
+ /// Cancellation token that can be used to stop the execution.
+ /// when the artist reached a terminal artwork state, otherwise .
+ private async Task EnrichArtistArtworkAsync(ArtistEntity artistEntity, string firstTrackPath, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken)
+ {
+ ArtistMetadataLookupDto artworkLookup = new(
+ LibraryId: artistEntity.LibraryId,
+ Path: firstTrackPath,
+ MusicBrainzArtistId: artistEntity.MusicBrainzArtistId,
+ Name: artistEntity.Name);
+
+ string artistName = artistEntity.Name;
+
+ return await EnrichArtworkAsync(
+ artworkLookup,
+ MusicArtworkOwnerType.Artist,
+ artistEntity.Id,
+ artistName,
+ artworkProviders,
+ musicArtworkService,
+ fileHashService,
+ () => musicArtworkService!.DeleteArtistArtwork(artistEntity.LibraryId, libraryName, artistName),
+ (artwork, token) => musicArtworkService!.SaveArtistArtworkAsync(artistEntity.LibraryId, libraryName, artistName, artwork, token),
+ shouldAggregateArtworkWhenMissing,
+ unitOfWork,
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resolves the artwork of the provided from the , storing the artwork resolved from the providers, in their order.
+ ///
+ /// The album whose artwork is resolved.
+ /// The file system path of one track of the album, used to locate its directory.
+ /// The album artwork providers, in the order they are consulted.
+ /// The service used to store the artwork of the album.
+ /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
+ /// The name of the media library the album belongs to.
+ /// Whether a provider that does not require the web can resolve the artwork without any MusicBrainz identifier.
+ /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.
+ /// The unit of work used to persist the artwork of the album.
+ /// Cancellation token that can be used to stop the execution.
+ /// when the album reached a terminal artwork state, otherwise .
+ private async Task EnrichAlbumArtworkAsync(AlbumEntity albumEntity, string firstTrackPath, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, string libraryName, bool canResolveWithoutMusicBrainzIds, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken)
+ {
+ // Without any MusicBrainz identifier, only a provider that reads the files of the user can resolve the artwork, so the album is left for a following scan otherwise.
+ if (albumEntity.MusicBrainzReleaseId is null && albumEntity.MusicBrainzReleaseGroupId is null && !canResolveWithoutMusicBrainzIds)
+ return false;
+
+ AlbumMetadataLookupDto artworkLookup = new(
+ LibraryId: albumEntity.LibraryId,
+ Path: firstTrackPath,
+ MusicBrainzReleaseGroupId: albumEntity.MusicBrainzReleaseGroupId,
+ MusicBrainzReleaseId: albumEntity.MusicBrainzReleaseId,
+ Title: albumEntity.Title,
+ ArtistName: albumEntity.Artist?.Name,
+ ReleaseYear: albumEntity.OriginalReleaseYear,
+ TrackCount: albumEntity.TotalTracks);
+
+ string artistName = albumEntity.Artist?.Name ?? string.Empty;
+
+ // The release type directory groups the artwork of the releases of the artist that share a title, so the album, the single and the live release of the same songs do not collide.
+ // It is read from the file system, because the structure on disk is the source of truth of the release type of an album.
+ string? releaseTypeName = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(firstTrackPath);
+
+ return await EnrichArtworkAsync(
+ artworkLookup,
+ MusicArtworkOwnerType.Album,
+ albumEntity.Id,
+ albumEntity.Title,
+ artworkProviders,
+ musicArtworkService,
+ fileHashService,
+ () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName),
+ (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, token, releaseTypeName),
+ shouldAggregateArtworkWhenMissing,
+ unitOfWork,
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resolves the artwork of the media item described by from the , in their order, replacing the stored artwork of the item.
+ ///
+ /// The lookup describing the media item whose artwork is resolved.
+ /// The type of the music library item that owns the artwork.
+ /// The Id of the music library item that owns the artwork.
+ /// The description of the owner, used to report the issues encountered.
+ /// The artwork providers, in the order they are consulted.
+ /// The service used to store the artwork of the owner.
+ /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
+ /// The action that deletes the artwork of the owner from the internal media directory.
+ /// The action that stores a piece of artwork of the owner into the internal media directory.
+ /// Whether the artwork is aggregated from multiple providers, when it is missing, or only the first provider that supplies it is used.
+ /// The unit of work used to persist the artwork of the owner.
+ /// Cancellation token that can be used to stop the execution.
+ /// when the owner reached a terminal artwork state, otherwise .
+ private async Task EnrichArtworkAsync(MetadataLookupDto artworkLookup, MusicArtworkOwnerType ownerType, Guid ownerId, string ownerDescription, IReadOnlyList artworkProviders, IMusicArtworkService? musicArtworkService, IFileHashService fileHashService, Func> deleteStoredArtwork, Func>> saveArtworkAsync, bool shouldAggregateArtworkWhenMissing, IUnitOfWork unitOfWork, CancellationToken cancellationToken)
+ {
+ if (musicArtworkService is null || unitOfWork.MusicArtworkRepository is null)
+ return false;
+
+ ArtworkResolution resolution = await ResolveArtworkAsync(artworkLookup, artworkProviders, ownerDescription, shouldAggregateArtworkWhenMissing, cancellationToken).ConfigureAwait(false);
+
+ // Replace the stored artwork of the owner as a whole, so that a piece of artwork that no longer exists at the source does not linger.
+ Result deleteStoredArtworkResult = deleteStoredArtwork();
+ if (deleteStoredArtworkResult.IsFailure)
+ {
+ _logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
+ DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
+ return false;
+ }
+ Result deleteEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
+ if (deleteEntitiesResult.IsFailure)
+ {
+ _logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
+ DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
+ return false;
+ }
+
+ List artworkEntities = [];
+
+ if (resolution.Artworks.Count > 0)
+ {
+ foreach (ResolvedArtwork resolvedArtwork in resolution.Artworks)
+ {
+ ArtworkDto artwork = resolvedArtwork.Artwork;
+ Result saveArtworkResult = await saveArtworkAsync(artwork, cancellationToken).ConfigureAwait(false);
+ if (saveArtworkResult.IsFailure)
+ {
+ _logger.LogWarning("Failed to store the {ArtworkType} artwork of the {OwnerType} '{OwnerDescription}'.", artwork.Type, ownerType, ownerDescription);
+ continue;
+ }
+
+ string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\'));
+ ulong contentHash = fileHashService.ComputeFileHash(storedArtworkPath);
+ artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, artwork.Type, artwork.Ordinal, saveArtworkResult.Value, contentHash, ArtworkStatus.Enriched, resolvedArtwork.ProviderName));
+ }
+
+ // When every resolved piece of artwork failed to be stored, the owner is treated as failed to resolve, so that it is retried.
+ if (artworkEntities.Count == 0)
+ {
+ artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null));
+ await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false);
+ return false;
+ }
+ }
+ else
+ {
+ // No artwork exists for the owner when a provider answered and found none, which is not a failure; it only failed when no provider could answer.
+ ArtworkStatus status = resolution.HasResolved ? ArtworkStatus.NotAvailable : ArtworkStatus.Failed;
+ artworkEntities.Add(CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, status, null));
+ await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false);
+ return status == ArtworkStatus.NotAvailable;
+ }
+
+ await PersistArtworkAsync(unitOfWork, artworkEntities, cancellationToken).ConfigureAwait(false);
+ return true;
+ }
+
+ ///
+ /// Persists the provided pieces of of a music library item.
+ ///
+ /// The unit of work used to persist the artwork.
+ /// The pieces of artwork to persist.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ private async Task PersistArtworkAsync(IUnitOfWork unitOfWork, List artworkEntities, CancellationToken cancellationToken)
+ {
+ Result insertArtworkResult = await unitOfWork.MusicArtworkRepository.InsertRangeAsync(artworkEntities, cancellationToken).ConfigureAwait(false);
+ if (insertArtworkResult.IsFailure)
+ _logger.LogWarning("Failed to persist the resolved artwork of a music library item.");
+ }
+
+ ///
+ /// Deletes the temporary files of the provided , used when the resolved artwork is not stored, so the temporary files do not linger.
+ ///
+ /// The resolved artworks whose temporary files are deleted.
+ private static void DeleteTemporaryArtworks(IEnumerable artworks)
+ {
+ foreach (ArtworkDto artwork in artworks)
+ {
+ if (!artwork.IsTemporary || string.IsNullOrWhiteSpace(artwork.LocalPath))
+ continue;
+ try
+ {
+ if (File.Exists(artwork.LocalPath))
+ File.Delete(artwork.LocalPath);
+ }
+ catch (IOException)
+ {
+ // A failed cleanup of the temporary file must not mask the result of the operation.
+ }
+ catch (UnauthorizedAccessException)
+ {
+ // A failed cleanup of the temporary file must not mask the result of the operation.
+ }
+ }
+ }
+
+ ///
+ /// Resolves the artwork of the media item described by from the ,
+ /// either aggregating the providers when is set, or using the first provider that supplies artwork otherwise.
+ ///
+ /// The lookup describing the media item whose artwork is resolved.
+ /// The artwork providers, in the order they are consulted.
+ /// The description of the owner, used to report the issues encountered.
+ /// Whether the artwork of every provider is combined, or only the first provider that supplies artwork is used.
+ /// Cancellation token that can be used to stop the execution.
+ /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all, distinguishing a confirmed absence of artwork from a resolution failure.
+ private async Task ResolveArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, bool shouldAggregateArtworkWhenMissing, CancellationToken cancellationToken)
+ {
+ if (shouldAggregateArtworkWhenMissing)
+ return await ResolveAggregatedArtworkAsync(lookup, artworkProviders, ownerDescription, cancellationToken).ConfigureAwait(false);
+ return await ResolveFirstArtworkAsync(lookup, artworkProviders, ownerDescription, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resolves the artwork of the media item described by from the first provider that supplies some, in their order.
+ ///
+ /// The lookup describing the media item whose artwork is resolved.
+ /// The artwork providers, in the order they are consulted.
+ /// The description of the owner, used to report the issues encountered.
+ /// Cancellation token that can be used to stop the execution.
+ /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all.
+ private async Task ResolveFirstArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, CancellationToken cancellationToken)
+ {
+ bool hasResolved = false;
+ bool hasFailed = false;
+ foreach (IArtworkProvider provider in artworkProviders)
+ {
+ IReadOnlyList providerArtworks;
+ try
+ {
+ providerArtworks = await provider.GetArtworkAsync(lookup, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception exception)
+ {
+ // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
+ hasFailed = true;
+ _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
+ continue;
+ }
+
+ hasResolved = true;
+ // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
+ List usableArtworks = [.. providerArtworks
+ .Where(artwork => string.IsNullOrWhiteSpace(artwork.RemoteUrl) || provider.RequiresWebAccess)
+ .Select(artwork => new ResolvedArtwork(artwork, provider.Name))];
+ if (usableArtworks.Count > 0)
+ return new ArtworkResolution(usableArtworks, HasResolved: true);
+ }
+
+ // An empty result is only treated as a confirmed absence of artwork when at least one provider answered; when every provider failed, it is a failure.
+ return new ArtworkResolution([], HasResolved: hasResolved || !hasFailed);
+ }
+
+ ///
+ /// Resolves the artwork of the media item described by from every provider, in their order,
+ /// combining them so that a provider only fills the artwork the providers before it did not supply.
+ ///
+ /// The lookup describing the media item whose artwork is resolved.
+ /// The artwork providers, in the order they are consulted.
+ /// The description of the owner, used to report the issues encountered.
+ /// Cancellation token that can be used to stop the execution.
+ /// The resolved artwork, each with the provider that supplied it, and whether a provider answered at all.
+ private async Task ResolveAggregatedArtworkAsync(MetadataLookupDto lookup, IReadOnlyList artworkProviders, string ownerDescription, CancellationToken cancellationToken)
+ {
+ bool hasResolved = false;
+ bool hasFailed = false;
+ List resolvedArtworks = [];
+ HashSet<(ArtworkType Type, int Ordinal)> resolvedKeys = [];
+ foreach (IArtworkProvider provider in artworkProviders)
+ {
+ IReadOnlyList providerArtworks;
+ try
+ {
+ providerArtworks = await provider.GetArtworkAsync(lookup, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception exception)
+ {
+ // A failing artwork provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
+ hasFailed = true;
+ _logger.LogWarning(exception, "The artwork provider '{ProviderName}' failed while resolving the artwork of '{OwnerDescription}'.", provider.Name, ownerDescription);
+ continue;
+ }
+
+ hasResolved = true;
+ foreach (ArtworkDto artwork in providerArtworks)
+ {
+ // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
+ if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
+ continue;
+ // The providers are consulted in their configured order, so a provider only fills the artwork the higher ranked ones did not supply, and a provider
+ // that holds just a part of the artwork of the item, like the local files of the user, is complemented by the providers that follow it.
+ if (resolvedKeys.Add((artwork.Type, artwork.Ordinal)))
+ resolvedArtworks.Add(new ResolvedArtwork(artwork, provider.Name));
+ }
+ }
+
+ // An empty result is only treated as a confirmed absence of artwork when at least one provider answered; when every provider failed, it is a failure.
+ return new ArtworkResolution(resolvedArtworks, HasResolved: hasResolved || !hasFailed);
+ }
+
+ ///
+ /// Creates a piece of artwork of the music library item of the provided identified by .
+ ///
+ /// The Id of the music library item the artwork belongs to.
+ /// The type of the music library item the artwork belongs to.
+ /// The type of the artwork.
+ /// The ordinal of the artwork within its type.
+ /// The relative file name of the stored artwork, if the artwork has been resolved.
+ /// The content hash of the stored artwork.
+ /// The status of the artwork enrichment.
+ /// The name of the plugin that resolved the artwork, if applicable.
+ /// The created artwork entity.
+ private static MusicArtworkEntity CreateArtworkEntity(Guid ownerId, MusicArtworkOwnerType ownerType, ArtworkType artworkType, int ordinal, string? fileName, ulong contentHash, ArtworkStatus status, string? provider)
+ {
+ return new MusicArtworkEntity
+ {
+ Id = Guid.NewGuid(),
+ OwnerType = ownerType,
+ OwnerId = ownerId,
+ ArtworkType = artworkType,
+ Ordinal = ordinal,
+ FileName = fileName,
+ ContentHash = contentHash,
+ Status = status,
+ Provider = provider,
+ LastUpdateUtc = DateTime.UtcNow,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = Guid.Empty,
+ UpdatedBy = null
+ };
+ }
+
+ ///
+ /// Publishes a job progress update.
+ ///
+ /// The service used to publish the progress update.
+ /// The unique identifier of the media library being scanned.
+ /// The composite unique identifier of a media library scan.
+ /// The current job progress.
+ /// The total job progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
+ {
+ Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
+ if (scanJobProgressResult.IsFailure)
+ return scanJobProgressResult.Errors;
+
+ await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
+ Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
+
+ return Result.Success;
+ }
+
+ ///
+ /// The artwork resolved for a music library item, each with the provider that supplied it, and whether a provider answered at all.
+ ///
+ /// The resolved artworks of the item, each with the provider that supplied it.
+ /// Whether at least one provider answered, confirming that any absence of artwork is real rather than a failure.
+ private sealed record ArtworkResolution(IReadOnlyList Artworks, bool HasResolved);
+
+ ///
+ /// A piece of artwork of a music library item, together with the provider that supplied it.
+ ///
+ /// The resolved artwork.
+ /// The name of the provider that supplied the artwork.
+ private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName);
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs
new file mode 100644
index 00000000..065c32f1
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanArtworkEnricher.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
+
+///
+/// Interface defining the artwork enrichment of the media library items of a specific media library type.
+///
+internal interface IMediaLibraryScanArtworkEnricher
+{
+ ///
+ /// The media library type that this artwork enricher supports.
+ ///
+ LibraryType SupportedLibraryType { get; }
+
+ ///
+ /// Resolves the artwork of the media library items of the provided media library, using the artwork providers configured for it.
+ ///
+ /// The unique identifier of the media library whose artwork is resolved.
+ /// The unique identifier of the media library scan.
+ /// The unique identifier of the user that initiated the media library scan.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs
index 31d7f468..64b5506a 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanArtworkEnrichmentJob.cs
@@ -1,25 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
-using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
-using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
-using Lumina.Application.Common.Infrastructure.Security;
-using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
-using Lumina.Contracts.DTO.Common;
-using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
-using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
using System;
-using System.Collections.Generic;
-using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -29,13 +18,11 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
///
/// Media library scan job for resolving the artwork of the media library items, using the artwork providers configured for the media library.
-/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched.
+/// The enrichment itself is delegated to the artwork enricher of the media library type.
///
internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanArtworkEnrichmentJob
{
- private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
private readonly IServiceScopeFactory _serviceScopeFactory;
- private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
@@ -44,11 +31,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
/// Injected factory for creating scopes in which services are requested.
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
///
- /// Injected logger used to report the issues encountered while resolving the artwork.
- public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ public MediaLibraryScanArtworkEnrichmentJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
- _logger = logger;
}
///
@@ -79,113 +64,22 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
- // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
- // whether the providers that require access to the web are used during the enrichment.
- string libraryName = string.Empty;
- bool canDownloadMetadataFromWeb = false;
- if (unitOfWork.LibraryRepository is not null)
- {
- Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
- if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
- _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
- else
- {
- libraryName = getLibraryResult.Value.Title;
- canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
- }
- }
+ // Load the media library, whose type determines the artwork enricher to use.
+ Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
+ throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
+ LibraryType libraryType = getLibraryResult.Value.LibraryType;
- // Get the artwork providers configured for the media library, in their configured order, that support the media library type.
- // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding.
- List artworkProviders = [];
- if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
- {
- Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
- if (getArtworkConfigurationsResult.IsFailure)
- _logger.LogWarning("Failed to read the artwork provider configurations.");
- else
- {
- foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
- {
- List configuredProviders = [.. asyncServiceScope.ServiceProvider
- .GetKeyedServices(configuration.PluginId)
- .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
- && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
- if (configuredProviders.Count == 0)
- _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
- artworkProviders.AddRange(configuredProviders);
- }
- }
- }
+ IMediaLibraryScanArtworkEnricher? artworkEnricher = asyncServiceScope.ServiceProvider
+ .GetServices()
+ .FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
+ if (artworkEnricher is null)
+ throw new InvalidOperationException($"No artwork enricher exists for media library type '{libraryType}'.");
- // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely.
- if (artworkProviders.Count > 0)
- {
- IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService();
- IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!;
+ await artworkEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
- Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
- if (getBooksToEnrichCountResult.IsFailure)
- throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
- int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
-
- // Set the initial progress of the scan job.
- Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
- if (publishJobProgressResult.IsFailure)
- throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
-
- DateTime lastUpdateTime = DateTime.UtcNow;
- int minUpdateIntervalMs = 100;
- int processedBooksCount = 0;
-
- // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size.
- string? lastPath = null;
- while (true)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
- if (getBooksPageResult.IsFailure)
- throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
- IReadOnlyList booksPage = getBooksPageResult.Value;
- if (booksPage.Count == 0)
- break;
-
- // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory.
- Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
- if (getAuthorsResult.IsFailure)
- throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
-
- foreach (BookEntity bookEntity in booksPage)
- {
- cancellationToken.ThrowIfCancellationRequested();
-
- await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false);
-
- // Check if enough time has passed since the last update.
- DateTime now = DateTime.UtcNow;
- if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
- {
- // Increment the number of processed elements progress.
- publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
- if (publishJobProgressResult.IsFailure)
- throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
- lastUpdateTime = now;
- }
- }
-
- // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
- Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
- if (saveChangesResult.IsFailure)
- throw new InvalidOperationException(saveChangesResult.FirstError.Description);
- unitOfWork.ClearTrackedEntities();
-
- lastPath = booksPage[^1].Path;
- }
- }
- else
- _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", LibraryId.Value);
-
+ // Increment the number of completed jobs progress.
+ await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
// When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed.
if (Children.Count == 0)
@@ -208,199 +102,4 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
}
}
-
- ///
- /// Resolves the cover artwork of the provided from the , in their configured order,
- /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book.
- ///
- /// The book whose artwork is resolved.
- /// The artwork providers, in their configured order.
- /// The service used to store the artwork of the book.
- /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
- /// The name of the media library the book belongs to.
- /// The display names of the authors of the books of the current page, keyed by the Id of the book.
- /// Cancellation token that can be used to stop the execution.
- private async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken)
- {
- // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped.
- if (bookArtworkService is null || artworkProviders.Count == 0)
- return;
-
- ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
- if (resolvedArtwork is null)
- {
- // No artwork provider returned usable artwork, so the cover artwork of the book is marked as failed to resolve.
- BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
- if (coverArtwork is null)
- bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
- else
- {
- coverArtwork.Status = ArtworkStatus.Failed;
- coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
- coverArtwork.UpdatedBy = Guid.NewGuid();
- }
- return;
- }
-
- BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
-
- // When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
- // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it.
- ulong contentHash = 0;
- bool shouldStoreArtwork = true;
- if (!string.IsNullOrWhiteSpace(resolvedArtwork.Artwork.LocalPath))
- {
- contentHash = fileHashService.ComputeFileHash(resolvedArtwork.Artwork.LocalPath);
- shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash;
- }
-
- if (shouldStoreArtwork)
- {
- string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
- Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedArtwork.Artwork, cancellationToken).ConfigureAwait(false);
- if (saveArtworkResult.IsFailure)
- {
- // A failing artwork storage must not prevent the book from being tracked as failed to resolve.
- if (existingCoverArtwork is null)
- bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
- else
- {
- existingCoverArtwork.Status = ArtworkStatus.Failed;
- existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
- existingCoverArtwork.UpdatedBy = Guid.NewGuid();
- }
- return;
- }
-
- // For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one.
- if (contentHash == 0)
- {
- string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\'));
- contentHash = fileHashService.ComputeFileHash(storedArtworkPath);
- }
-
- if (existingCoverArtwork is null)
- bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
- else
- {
- existingCoverArtwork.FileName = saveArtworkResult.Value;
- existingCoverArtwork.ContentHash = contentHash;
- existingCoverArtwork.Status = ArtworkStatus.Enriched;
- existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
- existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
- existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
- existingCoverArtwork.UpdatedBy = Guid.NewGuid();
- }
- }
- else
- {
- // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched.
- existingCoverArtwork!.Status = ArtworkStatus.Enriched;
- existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
- existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
- existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
- existingCoverArtwork.UpdatedBy = Guid.NewGuid();
- }
- }
-
- ///
- /// Resolves the artwork of the from the , in their configured order,
- /// returning the artwork of the first provider that returns it.
- ///
- /// The book whose artwork is resolved.
- /// The artwork providers, in their configured order.
- /// Cancellation token that can be used to stop the execution.
- /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork.
- private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken)
- {
- BookMetadataLookupDto artworkLookup = new(
- LibraryId: bookEntity.LibraryId,
- Path: bookEntity.Path,
- Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null,
- OpenLibraryId: bookEntity.OpenLibraryId,
- Title: bookEntity.Title,
- Author: null,
- LanguageCode: bookEntity.LanguageCode
- );
-
- foreach (IArtworkProvider provider in artworkProviders)
- {
- ArtworkDto? artwork = null;
- try
- {
- artwork = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false);
- }
- catch (Exception)
- {
- // A failing artwork provider must not prevent the other providers from being tried.
- }
-
- if (artwork is null)
- continue;
-
- // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
- if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess)
- continue;
-
- return new ResolvedArtwork(artwork, provider.Name);
- }
- return null;
- }
-
- ///
- /// Creates a cover artwork entity for the book identified by .
- ///
- /// The Id of the book the artwork belongs to.
- /// The status of the artwork enrichment.
- /// The relative file name of the stored artwork, if the artwork has been resolved.
- /// The content hash of the stored artwork.
- /// The name of the plugin that resolved the artwork, if applicable.
- /// The date and time when the artwork was resolved, if applicable.
- /// The created cover artwork entity.
- private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc)
- {
- return new BookArtworkEntity
- {
- Id = Guid.NewGuid(),
- BookId = bookId,
- ArtworkType = ArtworkType.Cover,
- Ordinal = 0,
- FileName = fileName,
- ContentHash = contentHash,
- Status = status,
- Provider = provider,
- LastUpdateUtc = lastUpdateUtc,
- CreatedOnUtc = DateTime.UtcNow,
- CreatedBy = Guid.Empty,
- UpdatedBy = null
- };
- }
-
- ///
- /// Publishes a job progress update.
- ///
- /// The service used to publish the progress update.
- /// The composite unique identifier of a media library scan.
- /// The current job progress.
- /// The total job progress.
- /// Cancellation token that can be used to stop the execution.
- /// An representing either a successful operation, or an error.
- private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
- {
- Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
- if (scanJobProgressResult.IsFailure)
- return scanJobProgressResult.Errors;
-
- await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
- Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
-
- return Result.Success;
- }
-
- ///
- /// The artwork resolved for a book, along with the provider that supplied it.
- ///
- /// The resolved artwork of the book.
- /// The name of the provider that supplied the artwork.
- private sealed record ResolvedArtwork(ArtworkDto Artwork, string ProviderName);
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs
new file mode 100644
index 00000000..51953e6a
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanArtworkEnricher.cs
@@ -0,0 +1,378 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Entities.Plugins;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Security;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
+
+///
+/// Artwork enricher for the media library items of the books media library type, using the artwork providers configured for the media library.
+///
+///
+/// The artwork is tracked per book, per type and ordinal, so that a change of one artwork does not require the others to be re-fetched.
+///
+internal sealed class BooksMediaLibraryScanArtworkEnricher : IMediaLibraryScanArtworkEnricher
+{
+ private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
+ private readonly IServiceScopeFactory _serviceScopeFactory;
+ private readonly ILogger _logger;
+
+ ///
+ /// The media library type that this artwork enricher supports.
+ ///
+ public LibraryType SupportedLibraryType => LibraryType.Book;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating scopes in which services are requested.
+ /// Injected logger used to report the issues encountered while resolving the artwork.
+ public BooksMediaLibraryScanArtworkEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Resolves the artwork of the books of the provided media library, using the artwork providers configured for it.
+ ///
+ /// The unique identifier of the media library whose artwork is resolved.
+ /// The unique identifier of the media library scan.
+ /// The unique identifier of the user that initiated the media library scan.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken)
+ {
+ await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
+ IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!;
+ IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
+
+ MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId);
+
+ // Load the media library, whose name is used to build the directory of the book artwork, and whose setting determines
+ // whether the providers that require access to the web are used during the enrichment.
+ string libraryName = string.Empty;
+ bool canDownloadMetadataFromWeb = false;
+ if (unitOfWork.LibraryRepository is not null)
+ {
+ Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
+ _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used.");
+ else
+ {
+ libraryName = getLibraryResult.Value.Title;
+ canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
+ }
+ }
+
+ // Get the artwork providers configured for the media library, in their configured order, that support the media library type.
+ // The artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the enrichment from proceeding.
+ List artworkProviders = [];
+ if (unitOfWork.ArtworkProviderConfigurationRepository is not null)
+ {
+ Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getArtworkConfigurationsResult.IsFailure)
+ _logger.LogWarning("Failed to read the artwork provider configurations.");
+ else
+ {
+ foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
+ {
+ List configuredProviders = [.. asyncServiceScope.ServiceProvider
+ .GetKeyedServices(configuration.PluginId)
+ .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
+ && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
+ if (configuredProviders.Count == 0)
+ _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
+ artworkProviders.AddRange(configuredProviders);
+ }
+ }
+ }
+
+ // When no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely.
+ if (artworkProviders.Count > 0)
+ {
+ IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService();
+ IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!;
+
+ Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getBooksToEnrichCountResult.IsFailure)
+ throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description);
+ int totalBooksToEnrich = getBooksToEnrichCountResult.Value;
+
+ // Set the initial progress of the scan job.
+ Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsFailure)
+ throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
+
+ DateTime lastUpdateTime = DateTime.UtcNow;
+ int minUpdateIntervalMs = 100;
+ int processedBooksCount = 0;
+
+ // Process the books that need their artwork resolved in pages, keeping the peak memory bounded regardless of the library size.
+ string? lastPath = null;
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingArtworkAsync(libraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
+ if (getBooksPageResult.IsFailure)
+ throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
+ IReadOnlyList booksPage = getBooksPageResult.Value;
+ if (booksPage.Count == 0)
+ break;
+
+ // Load the display names of the authors of the books of this page, in one query, since they are used to build the artwork directory.
+ Result> getAuthorsResult = await unitOfWork.BookRepository.GetAuthorsDisplayNamesByBookIdsAsync([.. booksPage.Select(bookEntity => bookEntity.Id)], cancellationToken).ConfigureAwait(false);
+ if (getAuthorsResult.IsFailure)
+ throw new InvalidOperationException(getAuthorsResult.FirstError.Description);
+
+ foreach (BookEntity bookEntity in booksPage)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false);
+
+ // Check if enough time has passed since the last update.
+ DateTime now = DateTime.UtcNow;
+ if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
+ {
+ // Increment the number of processed elements progress.
+ publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false);
+ if (publishJobProgressResult.IsFailure)
+ throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
+ lastUpdateTime = now;
+ }
+ }
+
+ // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size.
+ Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ throw new InvalidOperationException(saveChangesResult.FirstError.Description);
+ unitOfWork.ClearTrackedEntities();
+
+ lastPath = booksPage[^1].Path;
+ }
+ }
+ else
+ _logger.LogWarning("No artwork provider is configured for the media library with Id '{LibraryId}', the artwork enrichment will be skipped.", libraryId.Value);
+ }
+
+ ///
+ /// Resolves the cover artwork of the provided from the , in their configured order,
+ /// storing the artwork of the first provider that returns it, and tracking the enrichment state of the artwork on the book.
+ ///
+ /// The book whose artwork is resolved.
+ /// The artwork providers, in their configured order.
+ /// The service used to store the artwork of the book.
+ /// The service used to hash the artwork, to detect whether the resolved artwork differs from the stored one.
+ /// The name of the media library the book belongs to.
+ /// The display names of the authors of the books of the current page, keyed by the Id of the book.
+ /// Cancellation token that can be used to stop the execution.
+ private static async Task EnrichBookArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, IFileHashService fileHashService, string libraryName, IReadOnlyDictionary authorsDisplayNamesByBookId, CancellationToken cancellationToken)
+ {
+ // When no artwork provider is available, the book must not be marked as failed to resolve, so the enrichment is skipped.
+ if (bookArtworkService is null || artworkProviders.Count == 0)
+ return;
+
+ ResolvedArtwork? resolvedArtwork = await ResolveArtworkAsync(bookEntity, artworkProviders, cancellationToken).ConfigureAwait(false);
+ // The books media library type tracks a single cover, so only the cover returned by the provider is stored.
+ ArtworkDto? resolvedCover = resolvedArtwork?.Artworks.FirstOrDefault(artwork => artwork.Type == ArtworkType.Cover);
+ if (resolvedCover is null || resolvedArtwork is null)
+ {
+ // No artwork provider returned a usable cover, so the cover artwork of the book is marked as failed to resolve.
+ BookArtworkEntity? coverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
+ if (coverArtwork is null)
+ bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
+ else
+ {
+ coverArtwork.Status = ArtworkStatus.Failed;
+ coverArtwork.UpdatedOnUtc = DateTime.UtcNow;
+ coverArtwork.UpdatedBy = Guid.NewGuid();
+ }
+ return;
+ }
+
+ BookArtworkEntity? existingCoverArtwork = bookEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0);
+
+ // When the artwork comes from a local file, its content hash can be computed before storing it, so that an artwork identical to the stored one
+ // is not copied again. For remote artwork, the content hash of the stored artwork is computed after storing it.
+ ulong contentHash = 0;
+ bool shouldStoreArtwork = true;
+ if (!string.IsNullOrWhiteSpace(resolvedCover.LocalPath))
+ {
+ contentHash = fileHashService.ComputeFileHash(resolvedCover.LocalPath);
+ shouldStoreArtwork = existingCoverArtwork is null || contentHash != existingCoverArtwork.ContentHash;
+ }
+
+ if (shouldStoreArtwork)
+ {
+ string authorName = authorsDisplayNamesByBookId.TryGetValue(bookEntity.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
+ Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(bookEntity.LibraryId, bookEntity.Id, libraryName, authorName, bookEntity.Title, resolvedCover, cancellationToken).ConfigureAwait(false);
+ if (saveArtworkResult.IsFailure)
+ {
+ // A failing artwork storage must not prevent the book from being tracked as failed to resolve.
+ if (existingCoverArtwork is null)
+ bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null));
+ else
+ {
+ existingCoverArtwork.Status = ArtworkStatus.Failed;
+ existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
+ existingCoverArtwork.UpdatedBy = Guid.NewGuid();
+ }
+ return;
+ }
+
+ // For remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one.
+ if (contentHash == 0)
+ {
+ string storedArtworkPath = Path.Combine(AppContext.BaseDirectory, saveArtworkResult.Value.TrimStart('/', '\\'));
+ contentHash = fileHashService.ComputeFileHash(storedArtworkPath);
+ }
+
+ if (existingCoverArtwork is null)
+ bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow));
+ else
+ {
+ existingCoverArtwork.FileName = saveArtworkResult.Value;
+ existingCoverArtwork.ContentHash = contentHash;
+ existingCoverArtwork.Status = ArtworkStatus.Enriched;
+ existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
+ existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
+ existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
+ existingCoverArtwork.UpdatedBy = Guid.NewGuid();
+ }
+ }
+ else
+ {
+ // The resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched.
+ existingCoverArtwork!.Status = ArtworkStatus.Enriched;
+ existingCoverArtwork.Provider = resolvedArtwork.ProviderName;
+ existingCoverArtwork.LastUpdateUtc = DateTime.UtcNow;
+ existingCoverArtwork.UpdatedOnUtc = DateTime.UtcNow;
+ existingCoverArtwork.UpdatedBy = Guid.NewGuid();
+ }
+ }
+
+ ///
+ /// Resolves the artwork of the from the , in their configured order,
+ /// returning the artwork of the first provider that returns it.
+ ///
+ /// The book whose artwork is resolved.
+ /// The artwork providers, in their configured order.
+ /// Cancellation token that can be used to stop the execution.
+ /// The resolved artwork and the provider that supplied it, or when no provider returned usable artwork.
+ private static async Task ResolveArtworkAsync(BookEntity bookEntity, IReadOnlyList artworkProviders, CancellationToken cancellationToken)
+ {
+ BookMetadataLookupDto artworkLookup = new(
+ LibraryId: bookEntity.LibraryId,
+ Path: bookEntity.Path,
+ Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null,
+ OpenLibraryId: bookEntity.OpenLibraryId,
+ Title: bookEntity.Title,
+ Author: null,
+ LanguageCode: bookEntity.LanguageCode
+ );
+
+ foreach (IArtworkProvider provider in artworkProviders)
+ {
+ IReadOnlyList artworks = [];
+ try
+ {
+ artworks = await provider.GetArtworkAsync(artworkLookup, cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception)
+ {
+ // A failing artwork provider must not prevent the other providers from being tried.
+ }
+
+ // A provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract.
+ IReadOnlyList usableArtworks = [.. artworks.Where(artwork => artwork.Type == ArtworkType.Cover && (string.IsNullOrWhiteSpace(artwork.RemoteUrl) || provider.RequiresWebAccess))];
+ if (usableArtworks.Count == 0)
+ continue;
+
+ return new ResolvedArtwork(usableArtworks, provider.Name);
+ }
+ return null;
+ }
+
+ ///
+ /// Creates a cover artwork entity for the book identified by .
+ ///
+ /// The Id of the book the artwork belongs to.
+ /// The status of the artwork enrichment.
+ /// The relative file name of the stored artwork, if the artwork has been resolved.
+ /// The content hash of the stored artwork.
+ /// The name of the plugin that resolved the artwork, if applicable.
+ /// The date and time when the artwork was resolved, if applicable.
+ /// The created cover artwork entity.
+ private static BookArtworkEntity CreateCoverArtworkEntity(Guid bookId, ArtworkStatus status, string? fileName, ulong contentHash, string? provider, DateTime? lastUpdateUtc)
+ {
+ return new BookArtworkEntity
+ {
+ Id = Guid.NewGuid(),
+ BookId = bookId,
+ ArtworkType = ArtworkType.Cover,
+ Ordinal = 0,
+ FileName = fileName,
+ ContentHash = contentHash,
+ Status = status,
+ Provider = provider,
+ LastUpdateUtc = lastUpdateUtc,
+ CreatedOnUtc = DateTime.UtcNow,
+ CreatedBy = Guid.Empty,
+ UpdatedBy = null
+ };
+ }
+
+ ///
+ /// Publishes a job progress update.
+ ///
+ /// The service used to publish the progress update.
+ /// The unique identifier of the media library being scanned.
+ /// The composite unique identifier of a media library scan.
+ /// The current job progress.
+ /// The total job progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ private static async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
+ {
+ Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ResolvingArtwork");
+ if (scanJobProgressResult.IsFailure)
+ return scanJobProgressResult.Errors;
+
+ await domainEventPublisher.PublishAsync(new LibraryScanJobProgressChangedDomainEvent(
+ Guid.NewGuid(), libraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
+
+ return Result.Success;
+ }
+
+ ///
+ /// The artwork resolved for a book, along with the provider that supplied it.
+ ///
+ /// The resolved artworks of the book.
+ /// The name of the provider that supplied the artwork.
+ private sealed record ResolvedArtwork(IReadOnlyList Artworks, string ProviderName);
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs
index 1355aaff..33a82ee5 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs
@@ -8,6 +8,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
+using Lumina.Infrastructure.Common.Utilities;
+using Lumina.Infrastructure.Common.Networking;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
@@ -240,7 +242,7 @@ internal sealed class BookArtworkService : IBookArtworkService
return copyFileResult.Errors;
// Rename the copied file to the standard naming.
- Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}");
+ Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToFileExtension()}");
if (renameFileResult.IsFailure)
return renameFileResult.Errors;
@@ -266,7 +268,7 @@ internal sealed class BookArtworkService : IBookArtworkService
return Errors.FileSystemManagement.FileNotFound;
// Download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size.
- using HttpClient httpClient = _httpClientFactory.CreateClient();
+ using HttpClient httpClient = _httpClientFactory.CreateClient(NamedHttpClients.ARTWORK_DOWNLOAD);
string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}");
bool downloaded = false;
try
diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs
index 09b9250c..855fce9e 100644
--- a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs
+++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs
@@ -29,10 +29,10 @@ public interface IArtworkProvider
bool RequiresWebAccess { get; }
///
- /// Gets the artwork of the media item described by .
+ /// Gets the artworks of the media item described by .
///
/// The lookup describing the media item to get the artwork for.
/// Cancellation token that can be used to stop the execution.
- /// The artwork of the media item, or when no artwork was found.
- Task GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken);
+ /// The artworks of the media item, or an empty collection when no artwork was found.
+ Task> GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken);
}
diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs
index ea296737..e1f3b94b 100644
--- a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs
+++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -14,21 +15,21 @@ public interface IArtworkProvider : IArtworkProvider
where TLookup : MetadataLookupDto
{
///
- /// Gets the artwork of the media item described by .
+ /// Gets the artworks of the media item described by .
///
/// The lookup describing the media item to get the artwork for.
/// Cancellation token that can be used to stop the execution.
- /// The artwork of the media item, or when no artwork was found.
- Task GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken);
+ /// The artworks of the media item, or an empty collection when no artwork was found.
+ Task> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken);
///
- /// Gets the artwork of the media item described by .
+ /// Gets the artworks of the media item described by .
///
/// The lookup describing the media item to get the artwork for.
/// Cancellation token that can be used to stop the execution.
- /// The artwork of the media item, or when no artwork was found or the lookup is of another runtime type.
- async Task IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
+ /// The artworks of the media item, or an empty collection when no artwork was found or the lookup is of another runtime type.
+ async Task> IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
{
- return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null;
+ return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : [];
}
}
diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs
index aef276fc..824f1ce4 100644
--- a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs
+++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -23,6 +24,11 @@ public interface IMetadataProvider
///
IReadOnlyList SupportedLibraryTypes { get; }
+ ///
+ /// Gets the type of the metadata lookup this provider accepts, used to select the provider that matches a given lookup.
+ ///
+ Type LookupType { get; }
+
///
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
///
diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs
index 980a4d9e..7ea2f873 100644
--- a/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs
+++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
+using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -32,15 +33,20 @@ public interface IMetadataProvider : IMetadataProvider
/// The metadata of the media item, or when no metadata was found.
Task GetMetadataAsync(TLookup lookup, CancellationToken cancellationToken);
+ ///
+ /// Gets the type of the metadata lookup this provider accepts.
+ ///
+ Type IMetadataProvider.LookupType => typeof(TLookup);
+
///
/// Searches for the metadata of the media item described by .
///
/// The lookup describing the media item to search for.
/// Cancellation token that can be used to stop the execution.
- /// The collection of metadata candidates found for the media item.
+ /// The collection of metadata candidates found for the media item, or an empty collection when the lookup is of another runtime type.
async Task> IMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
{
- return await GetSearchResultsAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false);
+ return lookup is TLookup typedLookup ? await GetSearchResultsAsync(typedLookup, cancellationToken).ConfigureAwait(false) : [];
}
///
@@ -48,9 +54,9 @@ public interface IMetadataProvider : IMetadataProvider
///
/// The lookup describing the media item to get the metadata for.
/// Cancellation token that can be used to stop the execution.
- /// The metadata of the media item, or when no metadata was found.
+ /// The metadata of the media item, or when no metadata was found or the lookup is of another runtime type.
async Task IMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken)
{
- return await GetMetadataAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false);
+ return lookup is TLookup typedLookup ? await GetMetadataAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null;
}
}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs
new file mode 100644
index 00000000..753064fa
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/MusicArtworkEntityFixture.cs
@@ -0,0 +1,82 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicArtworkEntityFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the artwork.
+ /// Optional. The type of the music library item that owns the artwork.
+ /// Optional. The Id of the music library item that owns the artwork.
+ /// Optional. The type of the artwork.
+ /// Optional. The ordinal of the artwork within its type.
+ /// Optional. The relative file name of the stored artwork.
+ /// Optional. The content hash of the stored artwork.
+ /// Optional. The status of the artwork enrichment.
+ /// Optional. The name of the plugin that resolved the artwork.
+ /// Optional. The date and time when the artwork was last resolved.
+ /// Whether the file name should be included, or forced to .
+ /// Whether the provider should be included, or forced to .
+ /// Whether the last update date should be included, or forced to .
+ /// The created .
+ public MusicArtworkEntity Create(
+ Guid? id = null,
+ MusicArtworkOwnerType? ownerType = null,
+ Guid? ownerId = null,
+ ArtworkType? artworkType = null,
+ int? ordinal = null,
+ string? fileName = null,
+ ulong? contentHash = null,
+ ArtworkStatus? status = null,
+ string? provider = null,
+ DateTime? lastUpdateUtc = null,
+ bool includeFileName = true,
+ bool includeProvider = true,
+ bool includeLastUpdateUtc = true)
+ {
+ return new MusicArtworkEntity
+ {
+ Id = id ?? Guid.NewGuid(),
+ OwnerType = ownerType ?? _faker.PickRandom(),
+ OwnerId = ownerId ?? Guid.NewGuid(),
+ ArtworkType = artworkType ?? _faker.PickRandom(),
+ Ordinal = ordinal ?? _faker.Random.Int(0, 5),
+ FileName = includeFileName ? (fileName ?? _faker.System.FilePath()) : null,
+ ContentHash = contentHash ?? (ulong)_faker.Random.ULong(),
+ Status = status ?? _faker.PickRandom(),
+ Provider = includeProvider ? (provider ?? _faker.Company.CompanyName()) : null,
+ LastUpdateUtc = includeLastUpdateUtc ? (lastUpdateUtc ?? _faker.Date.Recent()) : null,
+ CreatedOnUtc = _faker.Date.Past(),
+ CreatedBy = Guid.NewGuid(),
+ UpdatedOnUtc = null,
+ UpdatedBy = null
+ };
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs
index 7226bbf4..6c6f41e5 100644
--- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs
@@ -7,6 +7,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs
new file mode 100644
index 00000000..50f9f53d
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs
@@ -0,0 +1,763 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
+using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
+using Lumina.Contracts.Fixtures.Core.DTO.Common;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
+using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
+using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
+using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Infrastructure.Fixtures.Common.Setup;
+using Microsoft.Extensions.Options;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.IntegrationTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicArtworkServiceTests
+{
+ private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
+
+ private readonly IEnvironmentContext _mockEnvironmentContext;
+ private readonly IFileTypeService _mockFileTypeService;
+ private readonly IFileProviderService _mockFileProviderService;
+ private readonly IDirectoryProviderService _mockDirectoryProviderService;
+ private readonly IPathService _mockPathService;
+ private readonly IHttpClientFactory _mockHttpClientFactory;
+ private readonly IOptions _mockMediaSettingsOptions;
+ private readonly MusicArtworkService _sut;
+ private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
+ private readonly PathSegmentFixture _pathSegmentFixture = new();
+ private readonly ArtworkDtoFixture _artworkDtoFixture = new();
+ private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
+ private readonly StubHttpMessageHandler _stubHttpMessageHandler = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public MusicArtworkServiceTests()
+ {
+ _mockEnvironmentContext = Substitute.For();
+ _mockFileTypeService = Substitute.For();
+ _mockFileProviderService = Substitute.For();
+ _mockDirectoryProviderService = Substitute.For();
+ _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
+ _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
+ _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
+
+ _mockPathService = Substitute.For();
+ _mockPathService.PathSeparator.Returns('\\');
+
+ _mockHttpClientFactory = Substitute.For();
+ _mockHttpClientFactory.CreateClient(Arg.Any()).Returns(new HttpClient(_stubHttpMessageHandler));
+
+ MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music");
+ _mockMediaSettingsOptions = Substitute.For>();
+ _mockMediaSettingsOptions.Value.Returns(mediaSettings);
+
+ _sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+
+ string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
+ FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath);
+ _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg")
+ .Returns(Result.From(renamedFileId));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
+ _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpg");
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Theory]
+ [InlineData(ArtworkType.Cover, 0, "cover.jpg")] // the front cover uses the bare type name
+ [InlineData(ArtworkType.Back, 0, "back.jpg")] // the back cover uses the bare type name
+ [InlineData(ArtworkType.Medium, 0, "medium.jpg")] // a single medium uses the bare type name
+ [InlineData(ArtworkType.Booklet, 0, "booklet.jpg")] // the first booklet page uses the bare type name
+ [InlineData(ArtworkType.Booklet, 2, "booklet-2.jpg")] // a further booklet page is suffixed with its ordinal
+ [InlineData(ArtworkType.Liner, 1, "liner-1.jpg")] // a liner note page is suffixed with its ordinal
+ [InlineData(ArtworkType.Other, 0, "other.jpg")] // any other type falls back to the generic name
+ public async Task SaveAlbumArtworkAsync_WhenTheArtworkHasAType_ShouldNameTheFileAfterTheTypeAndOrdinal(ArtworkType artworkType, int ordinal, string expectedFileName)
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "artwork.jpg"))));
+ _mockFileProviderService.RenameFile(Arg.Any(), expectedFileName)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName))));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ _mockFileProviderService.Received(1).RenameFile(Arg.Any(), expectedFileName);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenArtistNameIsMissing_ShouldUseUnknownForTheDirectorySegment()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName: "Unknown", albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+ _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg")
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ _mockPathService.Received(1).SanitizeSegment("Unknown");
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath()
+ {
+ // Arrange
+ string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}");
+ Directory.CreateDirectory(targetDirectory);
+ string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}");
+ if (!TryCreateJunction(linkPath, targetDirectory))
+ {
+ Directory.Delete(targetDirectory, true);
+ return; // The environment does not support creating reparse points.
+ }
+
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ MockPathBuilding();
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
+ _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true);
+ }
+ finally
+ {
+ if (OperatingSystem.IsWindows())
+ Directory.Delete(linkPath, true);
+ else
+ File.Delete(linkPath);
+ Directory.Delete(targetDirectory, true);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge()
+ {
+ // Arrange
+ string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1);
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ MockPathBuilding();
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
+ await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any());
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage()
+ {
+ // Arrange
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.None));
+ MockPathBuilding();
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError);
+ _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork()
+ {
+ // Arrange
+ _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[1024]);
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+ _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg")
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ _mockFileProviderService.Received(1).CopyFile(
+ Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())),
+ Arg.Any(),
+ true);
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound()
+ {
+ // Arrange
+ _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []);
+ MockPathBuilding();
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge()
+ {
+ // Arrange
+ _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]);
+ MockPathBuilding();
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+ _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg")
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.True(File.Exists(sourcePath));
+ _mockFileProviderService.Received(1).CopyFile(
+ Arg.Is(pathId => pathId.Path == sourcePath),
+ Arg.Any(),
+ true);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation()
+ {
+ // Arrange
+ using CancellationTokenSource cancellationTokenSource = new();
+ cancellationTokenSource.Cancel();
+ MockPathBuilding();
+
+ // Act
+ async Task Act()
+ {
+ await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), cancellationTokenSource.Token);
+ }
+
+ // Assert
+ await Assert.ThrowsAnyAsync(Act);
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenImageTypeDetectionFails_ShouldReturnTheError()
+ {
+ // Arrange
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Error.Failure("FileSystem.Error", "Failed to detect the image type"));
+ MockPathBuilding();
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal("FileSystem.Error", result.FirstError.Code);
+ _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenCreatingTheArtworkDirectoryFails_ShouldReturnTheError()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+ _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any())
+ .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory"));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal("Directory.Error", result.FirstError.Code);
+ _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenDirectoryExistenceCheckFails_ShouldReturnTheError()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+ _mockDirectoryProviderService.DirectoryExists(Arg.Any())
+ .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory"));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal("Directory.Error", result.FirstError.Code);
+ _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenCopyingTheArtworkFails_ShouldReturnTheError()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork"));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal("FileSystem.Error", result.FirstError.Code);
+ _mockFileProviderService.DidNotReceive().RenameFile(Arg.Any(), Arg.Any());
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenRenamingTheCopiedArtworkFails_ShouldReturnTheError()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle);
+ MockArtworkDirectoryStubs(artworkDirectoryPath);
+ _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true)
+ .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
+ _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg")
+ .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork"));
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal("FileSystem.Error", result.FirstError.Code);
+ }
+ finally
+ {
+ File.Delete(sourcePath);
+ }
+ }
+
+ [Fact]
+ public async Task SaveAlbumArtworkAsync_WhenArtistNameCannotBeSanitized_ShouldReturnInvalidPath()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ string libraryName = "Test Library";
+ string artistName = "Test Artist";
+ string albumTitle = "Test Album";
+
+ string sourcePath = CreateTempImageFile();
+ try
+ {
+ _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true));
+ _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(ImageType.JPEG));
+
+ string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
+ string musicPath = Path.Combine(mediaRoot, "music");
+ _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
+ _mockPathService.CombinePath(mediaRoot, "music").Returns(Result.From(musicPath));
+ _mockPathService.CombinePath(Arg.Any(), Arg.Any())
+ .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1))));
+ _mockPathService.SanitizeSegment(Arg.Any())
+ .Returns(callInfo =>
+ {
+ string name = callInfo.Arg();
+ return name == $"{libraryName}-{libraryId}"
+ ? Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false))
+ : Errors.FileSystemManagement.InvalidPath;
+ });
+
+ // Act
+ Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
+ _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any