Adds the media library artwork aggregation services, enrichers, and their provider contracts

This commit is contained in:
BinaryAlley committed 2026-10-09 01:59:00 +03:00
1 parent 00376c8313
commit 9e118864c3
33 files changed
+4621 -1118

No files matched your search

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