Adds the music library scanning pipeline, its scanner, scan jobs, and path structure

This commit is contained in:
BinaryAlley committed 2026-10-09 20:53:00 +03:00
1 parent 9e118864c3
commit 35ac1dbdcb
38 files changed
+5119 -1150

No files matched your search

@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for discovering music file system items.
/// </summary>
public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanJob
{
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
/// <summary>
/// Interface for the media library scan job for extracting the metadata of the discovered music file system items,
/// reading it from the embedded tags of the files and falling back to the structure of the media library on disk.
/// </summary>
public interface IMusicMetadataExtractionJob : IMediaLibraryScanJob
{
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
/// <summary>
/// Interface defining a media library scanner for a music media library type.
/// </summary>
public interface IMusicLibraryTypeScanner : IMediaTypeScanner
{
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
/// <summary>
/// Media library scanner for a music media library type.
/// </summary>
internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner
{
private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
/// <summary>
/// The media library type that this media library scanner supports.
/// </summary>
public LibraryType SupportedLibraryType { get; } = LibraryType.Music;
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryTypeScanner"/> class.
/// </summary>
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
public MusicLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
{
_mediaScanJobFactory = mediaScanJobFactory;
}
/// <summary>
/// Creates the media library scan jobs for the provided media library.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
/// <returns>A collection of media library scan jobs.</returns>
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId)
{
// Declare the list of jobs that this scanner requires.
IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IMusicFileSystemDiscoveryJob>(libraryId);
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
IMusicMetadataExtractionJob musicMetadataExtractionJob = _mediaScanJobFactory.CreateJob<IMusicMetadataExtractionJob>(libraryId);
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
// Establish the hierarchical relationships between jobs.
fileSystemDiscoveryJob.AddChild(mediaLibraryScanDiffJob);
mediaLibraryScanDiffJob.AddParent(fileSystemDiscoveryJob);
mediaLibraryScanDiffJob.AddChild(mediaLibraryScanHashJob);
mediaLibraryScanHashJob.AddParent(mediaLibraryScanDiffJob);
mediaLibraryScanHashJob.AddChild(musicMetadataExtractionJob);
musicMetadataExtractionJob.AddParent(mediaLibraryScanHashJob);
// The metadata extraction job reads the embedded tags of the discovered music files, falling back to the structure of the media library
// on disk, and stages the extracted metadata, so that the results save job can materialize the artists, albums and tracks from it.
musicMetadataExtractionJob.AddChild(mediaLibraryScanResultsSaveJob);
mediaLibraryScanResultsSaveJob.AddParent(musicMetadataExtractionJob);
// The enrichment of the media library items is split into independent, modular jobs that run sequentially: the provider configuration
// invalidation job invalidates the enrichment state of the items whose metadata or artwork providers changed since the last scan, the
// metadata enrichment job enriches the metadata and links the media contributors, and the artwork enrichment job resolves the artwork.
// The artwork enrichment job is always the last job in the directed acyclic job graph, running after the metadata enrichment job.
IMediaLibraryScanProviderConfigurationInvalidationJob mediaLibraryScanProviderConfigurationInvalidationJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanProviderConfigurationInvalidationJob>(libraryId);
IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanMetadataEnrichmentJob>(libraryId);
IMediaLibraryScanArtworkEnrichmentJob mediaLibraryScanArtworkEnrichmentJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanArtworkEnrichmentJob>(libraryId);
mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanProviderConfigurationInvalidationJob);
mediaLibraryScanProviderConfigurationInvalidationJob.AddParent(mediaLibraryScanResultsSaveJob);
mediaLibraryScanProviderConfigurationInvalidationJob.AddChild(mediaLibraryScanMetadataEnrichmentJob);
mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanProviderConfigurationInvalidationJob);
mediaLibraryScanMetadataEnrichmentJob.AddChild(mediaLibraryScanArtworkEnrichmentJob);
mediaLibraryScanArtworkEnrichmentJob.AddParent(mediaLibraryScanMetadataEnrichmentJob);
// Return the top level jobs that will be triggered when the scan will be started.
yield return fileSystemDiscoveryJob;
}
}
@@ -32,7 +32,7 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Created> SetDefaultDirectories(string rootPath)
{
// make sure the root path exists
// Make sure the root path exists.
Result<FileSystemPathId> rootPathIdResult = FileSystemPathId.Create(rootPath);
if (rootPathIdResult.IsFailure)
return rootPathIdResult.Errors;
@@ -45,6 +45,10 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService
if (createBooksDirectoryResult.IsFailure)
return createBooksDirectoryResult.Errors;
Result<Created> createMusicDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "music");
if (createMusicDirectoryResult.IsFailure)
return createMusicDirectoryResult.Errors;
return Result.Created;
}
@@ -68,7 +72,7 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService
if (directoryExistsResult.IsFailure)
return directoryExistsResult.Errors;
// only create it if it doesn't already exist
// Only create it if it doesn't already exist.
if (!directoryExistsResult.Value)
{
Result<FileSystemPathId> createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName);
@@ -54,22 +54,22 @@ public class FileTypeService : IFileTypeService
/// <returns>An <see cref="Result{TValue}"/> containing the type of image or an error.</returns>
public async Task<Result<ImageType>> GetImageTypeAsync(FileSystemPathId path, CancellationToken cancellationToken)
{
// check if the user has access permissions to the provided path
// Check if the user has access permissions to the provided path.
if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents))
return Errors.Permission.UnauthorizedAccess;
Memory<byte> buffer = new byte[BUFFER_SIZE];
using FileSystemStream stream = _fileSystem.FileStream.New(path.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
// check if the file's length is less than the buffer size
// Check if the file's length is less than the buffer size.
if (stream.Length < BUFFER_SIZE)
return ImageType.None;
// read only the first bytes of the file, equal to the buffer size
// Read only the first bytes of the file, equal to the buffer size.
await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
byte[] firstBytes = buffer[..BUFFER_SIZE].ToArray();
// check if its a known image type, based on header bytes
// Check if its a known image type, based on header bytes.
ImageType type = IdentifyHeader(firstBytes);
if (type != ImageType.None)
return type;
// no known image header types were found, check other methods
// No known image header types were found, check other methods.
string content = Encoding.UTF8.GetString(buffer.ToArray());
if (IsSvg(content, path.Path))
return ImageType.SVG;
@@ -87,20 +87,20 @@ public class FileTypeService : IFileTypeService
/// <returns><see langword="true"/> if the file is a SVG image, <see langword="false"/> otherwise.</returns>
private bool IsSvg(string initialContent, string path)
{
// check if it starts with <svg
// Check if it starts with <svg.
if (initialContent.StartsWith("<svg", StringComparison.OrdinalIgnoreCase))
return true;
// check if it starts with <?xml
// Check if it starts with <?xml.
if (initialContent.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase))
{
// Read more content from the file
// Read more content from the file.
using FileSystemStream stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
byte[] svgBuffer = new byte[1000];
#pragma warning disable CA2022 // Avoid inexact read with 'Stream.Read'
stream.Read(svgBuffer, 0, 1000);
#pragma warning restore CA2022 // Avoid inexact read with 'Stream.Read'
string extendedContent = Encoding.UTF8.GetString(svgBuffer);
// check if the extended content contains <svg
// Check if the extended content contains <svg.
return extendedContent.Contains("<svg", StringComparison.OrdinalIgnoreCase);
}
return false;
@@ -136,10 +136,15 @@ public class FileTypeService : IFileTypeService
return ImageType.TIFF; // TIFF
if (new byte[] { 255, 216, 255, 224 }.SequenceEqual(firstBytes[..4]))
return ImageType.JPEG; // JPEG
if (new byte[] { 255, 216, 255, 225 }.SequenceEqual(firstBytes[..4]))
return ImageType.JPEG_CANON; // JPEG CANON
if (new byte[] { 255, 216, 255, 226 }.SequenceEqual(firstBytes[..4]))
// Any JPEG starts with the start-of-image marker FF D8 followed by FF and a marker byte. The marker that follows varies
// (E0 JFIF, E1 Exif, DB quantization table, C2 progressive, EE Adobe, FE comment, ...), so every JPEG is accepted here and
// only classified into its known variants, rather than being rejected for using a marker that is not explicitly listed.
if (firstBytes[0] == 255 && firstBytes[1] == 216 && firstBytes[2] == 255)
{
if (firstBytes[3] == 225)
return ImageType.JPEG_CANON; // JPEG CANON
return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN
}
if (new byte[] { 0x00, 0x11, 0x02, 0xFF }.SequenceEqual(firstBytes[..4]))
return ImageType.PICT; // PICT
if (new byte[] { 0x00, 0x00, 0x01, 0x00 }.SequenceEqual(firstBytes[..4]))
@@ -47,8 +47,8 @@ public interface ILibraryPathTemplateService
/// <param name="relativePath">The path of the media library item, relative to the root of its content location.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the derived metadata, or an error. A successful result whose value is <see langword="null"/>
/// An <see cref="Result{TValue}"/> containing either the derived metadata, or an error. A successful result whose value has no value
/// means the path does not match the template.
/// </returns>
Result<ParsedLibraryPath?> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator);
Result<Optional<ParsedLibraryPath>> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator);
}
@@ -96,13 +96,13 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
/// <param name="relativePath">The path of the media library item, relative to the root of its content location.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the derived metadata, or an error. A successful result whose value is <see langword="null"/>
/// An <see cref="Result{TValue}"/> containing either the derived metadata, or an error. A successful result whose value has no value
/// means the path does not match the template.
/// </returns>
public Result<ParsedLibraryPath?> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator)
public Result<Optional<ParsedLibraryPath>> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator)
{
if (string.IsNullOrWhiteSpace(relativePath) || template.IsEmpty)
return Result<ParsedLibraryPath?>.Success(null);
return Result<Optional<ParsedLibraryPath>>.Success(Optional<ParsedLibraryPath>.None());
Result<Success> validationResult = Validate(libraryType, template);
if (validationResult.IsFailure)
@@ -114,14 +114,14 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
Regex pattern = GetCompiledPattern(template, definitions, pathSeparator);
Match match = pattern.Match(relativePath);
if (!match.Success)
return Result<ParsedLibraryPath?>.Success(null);
return Result<Optional<ParsedLibraryPath>>.Success(Optional<ParsedLibraryPath>.None());
Dictionary<LibraryPathPartKind, string> values = [];
foreach (LibraryPathPart part in template.Parts)
{
if (part.Kind == LibraryPathPartKind.Literal || part.Kind == LibraryPathPartKind.Separator)
continue;
// a kind can legitimately appear more than once, like the title and the author appearing both in the directory and in the file name,
// A kind can legitimately appear more than once, like the title and the author appearing both in the directory and in the file name,
// so the first non-empty capture is kept.
if (values.ContainsKey(part.Kind))
continue;
@@ -132,7 +132,7 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
if (!string.IsNullOrWhiteSpace(value))
values[part.Kind] = value;
}
return Result<ParsedLibraryPath?>.Success(ParsedLibraryPath.Create(values));
return Result<Optional<ParsedLibraryPath>>.Success(Optional<ParsedLibraryPath>.Some(ParsedLibraryPath.Create(values)));
}
/// <summary>
@@ -212,7 +212,7 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
string prefix = part.Representation[..placeholder.Index];
string suffix = part.Representation[(placeholder.Index + placeholder.Length)..];
Group width = placeholder.Groups["width"];
// a fixed width narrows the capture to an exact number of digits, otherwise the base pattern of the value type is used.
// A fixed width narrows the capture to an exact number of digits, otherwise the base pattern of the value type is used.
string valuePattern = width.Success ? $@"\d{{{width.Value.Length}}}" : GetValuePattern(definition.ValueType);
return Regex.Escape(prefix) + $"(?<{part.Kind}>{valuePattern})" + Regex.Escape(suffix);
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners;
using Microsoft.Extensions.DependencyInjection;
using System;
@@ -32,7 +33,7 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
{
return libraryType switch
{
// implemented scanners
// Implemented scanners.
LibraryType.Book => _serviceProvider.GetRequiredService<IBookLibraryTypeScanner>(),
LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."),
LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."),
@@ -55,7 +56,7 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
LibraryType.InterviewVideo => throw new NotImplementedException("InterviewVideo scanner is not implemented."),
LibraryType.CoverSongVideo => throw new NotImplementedException("CoverSongVideo scanner is not implemented."),
LibraryType.PodcastVideo => throw new NotImplementedException("PodcastVideo scanner is not implemented."),
LibraryType.Music => throw new NotImplementedException("Music scanner is not implemented."),
LibraryType.Music => _serviceProvider.GetRequiredService<IMusicLibraryTypeScanner>(),
LibraryType.Audiobook => throw new NotImplementedException("Audiobook scanner is not implemented."),
LibraryType.LiveRecordingAudio => throw new NotImplementedException("LiveRecordingAudio scanner is not implemented."),
LibraryType.InterviewAudio => throw new NotImplementedException("InterviewAudio scanner is not implemented."),
@@ -68,7 +69,7 @@ internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
LibraryType.Collection => throw new NotImplementedException("Collection scanner is not implemented."),
LibraryType.Subtitles => throw new NotImplementedException("Subtitles scanner is not implemented."),
LibraryType.Lyrics => throw new NotImplementedException("Lyrics scanner is not implemented."),
// catch-all for unknown or unsupported types
// Catch-all for unknown or unsupported types.
_ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.")
};
}
@@ -0,0 +1,205 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
/// <summary>
/// Merges the music metadata returned by multiple metadata providers into a single metadata, giving priority to the first provider that provides a value for each field.
/// </summary>
internal static class MusicMetadataAggregator
{
/// <summary>
/// Merges <paramref name="first"/> with <paramref name="second"/>, keeping the first non-empty value of each scalar field, and the union of the collection fields.
/// </summary>
/// <param name="first">The first artist metadata to merge, whose values have priority.</param>
/// <param name="second">The second artist metadata, filling the fields that the first metadata lacks.</param>
/// <returns>The merged artist metadata.</returns>
public static ArtistMetadataDto Merge(ArtistMetadataDto first, ArtistMetadataDto second)
{
return new ArtistMetadataDto(
First(first.Name, second.Name),
First(first.SortName, second.SortName),
First(first.Disambiguation, second.Disambiguation),
First(first.Type, second.Type),
First(first.Gender, second.Gender),
First(first.Country, second.Country),
First(first.Area, second.Area),
First(first.BeginArea, second.BeginArea),
First(first.EndArea, second.EndArea),
First(first.LifeSpanBegin, second.LifeSpanBegin),
First(first.LifeSpanEnd, second.LifeSpanEnd),
first.IsEnded || second.IsEnded,
First(first.Website, second.Website),
First(first.MusicBrainzArtistId, second.MusicBrainzArtistId),
Union(first.Ipis, second.Ipis, ipi => ipi),
Union(first.Isnis, second.Isnis, isni => isni),
Union(first.Aliases, second.Aliases, alias => alias.Name),
Union(first.Genres, second.Genres, genre => genre.Name),
Union(first.Tags, second.Tags, tag => tag.Name),
Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()),
Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}"));
}
/// <summary>
/// Merges <paramref name="first"/> with <paramref name="second"/>, keeping the first non-empty value of each scalar field, and the union of the collection fields.
/// </summary>
/// <param name="first">The first album metadata to merge, whose values have priority.</param>
/// <param name="second">The second album metadata, filling the fields that the first metadata lacks.</param>
/// <returns>The merged album metadata.</returns>
public static AlbumMetadataDto Merge(AlbumMetadataDto first, AlbumMetadataDto second)
{
return new AlbumMetadataDto(
First(first.Title, second.Title),
First(first.OriginalTitle, second.OriginalTitle),
First(first.Description, second.Description),
First(first.Disambiguation, second.Disambiguation),
MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo),
First(first.Language, second.Language),
First(first.OriginalLanguage, second.OriginalLanguage),
Union(first.Tags, second.Tags, tag => tag.Name),
Union(first.Genres, second.Genres, genre => genre.Name),
First(first.Script, second.Script),
first.ReleaseTypes is { Count: > 0 } ? first.ReleaseTypes : second.ReleaseTypes,
First(first.ReleaseStatus, second.ReleaseStatus),
First(first.MediaFormat, second.MediaFormat),
First(first.Packaging, second.Packaging),
First(first.TotalDiscs, second.TotalDiscs),
First(first.TotalTracks, second.TotalTracks),
First(first.Barcode, second.Barcode),
Union(first.CatalogNumbers, second.CatalogNumbers, catalogNumber => catalogNumber),
First(first.Label, second.Label),
First(first.ASIN, second.ASIN),
First(first.MusicBrainzReleaseId, second.MusicBrainzReleaseId),
First(first.MusicBrainzReleaseGroupId, second.MusicBrainzReleaseGroupId),
First(first.MusicBrainzReleaseArtistId, second.MusicBrainzReleaseArtistId),
Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}"),
Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()),
First(first.ReleaseTitle, second.ReleaseTitle));
}
/// <summary>
/// Merges <paramref name="first"/> with <paramref name="second"/>, keeping the first non-empty value of each scalar field, and the union of the collection fields.
/// </summary>
/// <param name="first">The first audio metadata to merge, whose values have priority.</param>
/// <param name="second">The second audio metadata, filling the fields that the first metadata lacks.</param>
/// <returns>The merged audio metadata.</returns>
public static AudioMetadataDto Merge(AudioMetadataDto first, AudioMetadataDto second)
{
return new AudioMetadataDto(
First(first.Title, second.Title),
First(first.OriginalTitle, second.OriginalTitle),
First(first.Description, second.Description),
First(first.Disambiguation, second.Disambiguation),
MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo),
First(first.Language, second.Language),
First(first.OriginalLanguage, second.OriginalLanguage),
Union(first.Tags, second.Tags, tag => tag.Name),
Union(first.Genres, second.Genres, genre => genre.Name),
First(first.Script, second.Script),
First(first.Key, second.Key),
First(first.Bpm, second.Bpm),
first.IsVideo || second.IsVideo,
First(first.Work, second.Work),
Union(first.Isrcs, second.Isrcs, isrc => isrc.Value),
Union(first.Moods, second.Moods, mood => mood.Name),
First(first.DurationInSeconds, second.DurationInSeconds),
First(first.SampleRate, second.SampleRate),
First(first.Channels, second.Channels),
First(first.BitDepth, second.BitDepth),
First(first.AudioCodec, second.AudioCodec),
First(first.Bitrate, second.Bitrate),
First(first.MusicBrainzRecordingId, second.MusicBrainzRecordingId),
First(first.MusicBrainzTrackId, second.MusicBrainzTrackId),
Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}"),
Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()));
}
/// <summary>
/// Merges the release information of the two metadata, keeping the first non-null value of each field.
/// </summary>
/// <param name="first">The first release information, whose values have priority.</param>
/// <param name="second">The second release information, filling the fields that the first one lacks.</param>
/// <returns>The merged release information, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static ReleaseInfoDto? MergeReleaseInfo(ReleaseInfoDto? first, ReleaseInfoDto? second)
{
if (first is null && second is null)
return null;
DateOnly? originalReleaseDate = First(first?.OriginalReleaseDate, second?.OriginalReleaseDate);
int? originalReleaseYear = First(first?.OriginalReleaseYear, second?.OriginalReleaseYear);
DateOnly? reReleaseDate = First(first?.ReReleaseDate, second?.ReReleaseDate);
int? reReleaseYear = First(first?.ReReleaseYear, second?.ReReleaseYear);
// A release date and its year describe the same point in time, so the year is derived from the date whenever a date is known. Without this,
// a year from one provider could be combined with a date from another (for example a release year from the tags with the original release
// date from MusicBrainz), and the resulting inconsistent pair would be rejected when the metadata is applied.
if (originalReleaseDate is not null)
originalReleaseYear = originalReleaseDate.Value.Year;
if (reReleaseDate is not null)
reReleaseYear = reReleaseDate.Value.Year;
return new ReleaseInfoDto(
originalReleaseDate,
originalReleaseYear,
reReleaseDate,
reReleaseYear,
First(first?.ReleaseCountry, second?.ReleaseCountry),
First(first?.ReleaseVersion, second?.ReleaseVersion));
}
/// <summary>
/// Gets the first non-null value of the two values.
/// </summary>
/// <typeparam name="T">The type of the values.</typeparam>
/// <param name="first">The value with priority.</param>
/// <param name="second">The fallback value.</param>
/// <returns>The first non-null value, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static T? First<T>(T? first, T? second)
{
return first is not null && !IsEmpty(first) ? first : second;
}
/// <summary>
/// Determines whether the provided value is an empty string.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="value">The value to check.</param>
/// <returns><see langword="true"/> when the value is an empty string, otherwise <see langword="false"/>.</returns>
private static bool IsEmpty<T>(T? value)
{
return value is string text && string.IsNullOrWhiteSpace(text);
}
/// <summary>
/// Returns the union of the two collections, de-duplicated by the <paramref name="keySelector"/> key, keeping the items of the first collection on key conflicts.
/// </summary>
/// <typeparam name="T">The type of the collection items.</typeparam>
/// <param name="first">The first collection, whose items have priority.</param>
/// <param name="second">The second collection.</param>
/// <param name="keySelector">The function used to extract the de-duplication key of an item.</param>
/// <returns>The union of the two collections, or <see langword="null"/> when both are <see langword="null"/>.</returns>
private static List<T>? Union<T>(List<T>? first, List<T>? second, Func<T, string?> keySelector)
where T : class
{
if (first is null && second is null)
return null;
Dictionary<string, T> seen = new(StringComparer.OrdinalIgnoreCase);
List<T> result = [];
void AddRange(List<T>? items)
{
foreach (T item in items ?? [])
if (seen.TryAdd(keySelector(item) ?? string.Empty, item))
result.Add(item);
}
AddRange(first);
AddRange(second);
return result;
}
}
@@ -0,0 +1,332 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Media library scan job for discovering music file system items.
/// </summary>
internal sealed class MusicFileSystemDiscoveryJob : MediaLibraryScanJob, IMusicFileSystemDiscoveryJob
{
private const int STAGING_BATCH_SIZE = 1000; // The number of discovered files that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size.
private static readonly HashSet<string> s_audioExtensions = new(
[
".mp3", ".flac", ".m4a", ".aac", ".ogg", ".opus",
".wav", ".wma", ".aiff", ".aif", ".ape", ".wv",
".dsf", ".dff", ".mka"
],
StringComparer.OrdinalIgnoreCase
);
private readonly IServiceScopeFactory _serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="MusicFileSystemDiscoveryJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">
/// 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>
public MusicFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
/// <param name="id">The id of the media library scan job.</param>
/// <param name="input">The input data to be processed by this payload.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService<IFileProviderService>()!;
IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService<IDirectoryProviderService>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// Get the library from the repository.
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.");
// Convert it to a domain object.
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsFailure)
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
// When the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan.
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
{
Result<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await unitOfWork.DirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getFingerprintsResult.IsFailure)
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
fingerprintsByPath = getFingerprintsResult.Value;
}
// Set the initial progress of the scan job.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
DateTime lastHeartbeat = DateTime.UtcNow;
int processedContentLocations = 0;
List<LibraryScanStagingResultsEntity> stagingBatch = [];
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
// Get the files for each of the media library content locations.
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
cancellationToken.ThrowIfCancellationRequested();
await DiscoverContentLocationAsync(
contentLocation.Path,
fileProviderService,
directoryProviderService,
fingerprintsByPath is not null,
fingerprintsByPath,
stagingBatch,
fingerprintBatch,
unitOfWork.LibraryScanStagingResultsRepository,
unitOfWork.DirectoryScanFingerprintRepository,
cancellationToken).ConfigureAwait(false);
processedContentLocations++;
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
DateTime now = DateTime.UtcNow;
if (now - lastHeartbeat >= heartbeatInterval)
{
publishJobProgressResult = await PublishJobProgressAsync(
domainEventPublisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastHeartbeat = now;
}
}
// Flush any remaining discovered files and directory scan fingerprints that did not reach the batch size.
if (stagingBatch.Count > 0)
{
Result<Created> insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
throw new InvalidOperationException(insertResult.FirstError.Description);
}
if (fingerprintBatch.Count > 0)
{
Result<Updated> upsertResult = await unitOfWork.DirectoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertResult.IsFailure)
throw new InvalidOperationException(upsertResult.FirstError.Description);
}
// This job finished, increment the number of processed jobs progress.
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
catch (Exception exception)
{
Status = LibraryScanJobStatus.Failed;
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Discovers the music files of a content location of the media library, using a breadth-first traversal, and writes them in batches to the staging results.
/// </summary>
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
/// <param name="fileProviderService">The service used to enumerate the files of a directory.</param>
/// <param name="directoryProviderService">The service used to enumerate the subdirectories of a directory.</param>
/// <param name="shouldSkipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param>
/// <param name="fingerprintsByPath">The directory scan fingerprints of the library, mapped by the directory path. Can be <see langword="null"/> when the fast skip is disabled.</param>
/// <param name="stagingBatch">The batch of discovered files that is written to the staging results when it reaches the batch size.</param>
/// <param name="fingerprintBatch">The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.</param>
/// <param name="stagingResultsRepository">The repository used to write the discovered files to the staging results.</param>
/// <param name="directoryScanFingerprintRepository">The repository used to write the directory scan fingerprints to the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private async Task DiscoverContentLocationAsync(
string rootDirectoryPath,
IFileProviderService fileProviderService,
IDirectoryProviderService directoryProviderService,
bool shouldSkipUnchangedDirectories,
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
List<LibraryScanStagingResultsEntity> stagingBatch,
List<DirectoryScanFingerprintEntity> fingerprintBatch,
ILibraryScanStagingResultsRepository stagingResultsRepository,
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository,
CancellationToken cancellationToken)
{
Result<FileSystemPathId> rootPathResult = FileSystemPathId.Create(rootDirectoryPath);
if (rootPathResult.IsFailure)
return;
Queue<FileSystemPathId> directoryQueue = new();
directoryQueue.Enqueue(rootPathResult.Value);
// Use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory
// and could result in stack overflow on deeply nested directories.
while (directoryQueue.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
FileSystemPathId currentDirectory = directoryQueue.Dequeue();
// When the fast skip is enabled, skip the whole subtree of a directory whose last write time has not changed since the last scan.
if (shouldSkipUnchangedDirectories)
{
Result<Optional<DateTime>> getLastWriteTimeResult = directoryProviderService.GetLastWriteTime(currentDirectory);
DateTime currentLastWriteTimeUtc = getLastWriteTimeResult.IsSuccess && getLastWriteTimeResult.Value.HasValue
? getLastWriteTimeResult.Value.Value
: DateTime.MinValue;
if (fingerprintsByPath is not null &&
fingerprintsByPath.TryGetValue(currentDirectory.Path, out DirectoryScanFingerprintEntity? fingerprint) &&
fingerprint.LastWriteTimeUtc == currentLastWriteTimeUtc)
continue;
fingerprintBatch.Add(new DirectoryScanFingerprintEntity()
{
Id = Guid.NewGuid(),
LibraryId = LibraryId.Value,
Path = currentDirectory.Path,
LastWriteTimeUtc = currentLastWriteTimeUtc
});
// Flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has.
if (fingerprintBatch.Count >= STAGING_BATCH_SIZE)
{
Result<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
if (upsertFingerprintsResult.IsFailure)
throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description);
fingerprintBatch.Clear();
}
}
// Process the files of the current directory.
Result<IEnumerable<FileSystemPathId>> getFilesResult = fileProviderService.GetFilePaths(currentDirectory, true);
if (getFilesResult.IsSuccess)
{
foreach (FileSystemPathId filePath in getFilesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
if (!s_audioExtensions.Contains(Path.GetExtension(filePath.Path)))
continue;
long size = 0;
Result<long?> getSizeResult = fileProviderService.GetSize(filePath);
if (getSizeResult.IsSuccess && getSizeResult.Value.HasValue)
size = getSizeResult.Value.Value;
long ticks = 0;
Result<Optional<DateTime>> getFileLastWriteTimeResult = fileProviderService.GetLastWriteTime(filePath);
if (getFileLastWriteTimeResult.IsSuccess && getFileLastWriteTimeResult.Value.HasValue)
ticks = getFileLastWriteTimeResult.Value.Value.Ticks;
stagingBatch.Add(new LibraryScanStagingResultsEntity()
{
Id = Guid.NewGuid(),
LibraryScanId = ScanId.Value,
Path = filePath.Path,
Size = size,
Ticks = ticks,
ContentHash = 0,
PreviousContentHash = 0,
NeedsRehash = true,
IsNew = true
});
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
{
Result<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
stagingBatch.Clear();
}
}
}
// Process the subdirectories - each new subdirectory is added to the same queue, for later processing.
Result<IEnumerable<FileSystemPathId>> getSubdirectoriesResult = directoryProviderService.GetSubdirectoryPaths(currentDirectory, true);
if (getSubdirectoriesResult.IsSuccess)
{
foreach (FileSystemPathId subdirectory in getSubdirectoriesResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
directoryQueue.Enqueue(subdirectory);
}
}
}
}
/// <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, "DiscoveringFiles");
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;
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using System;
using System.IO;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Derives the structure of a music library on disk from the file system path of a music file.
/// </summary>
internal static class MusicLibraryPathStructure
{
/// <summary>
/// Matches the name of a directory that holds one disc of a multi-disc album, like "Disc 1" or "CD2".
/// </summary>
private static readonly Regex s_discDirectoryPattern = new(@"^(?:disk|disc|cd)\s*\d+$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>
/// Gets the on-disk directory of the album the track stored at <paramref name="trackPath"/> belongs to.
/// A multi-disc album nests its tracks in disc subdirectories, so the directory of a disc is skipped in favor of its parent.
/// </summary>
/// <param name="trackPath">The file system path of the track whose album directory is retrieved.</param>
/// <returns>The file system path of the album directory, or the directory of the track when it cannot be resolved.</returns>
public static string GetAlbumDirectory(string trackPath)
{
if (string.IsNullOrEmpty(trackPath))
return trackPath;
string? trackDirectory = Path.GetDirectoryName(trackPath);
if (string.IsNullOrEmpty(trackDirectory))
return trackPath;
if (!s_discDirectoryPattern.IsMatch(Path.GetFileName(trackDirectory)))
return trackDirectory;
string? albumDirectory = Path.GetDirectoryName(trackDirectory);
return string.IsNullOrEmpty(albumDirectory) ? trackDirectory : albumDirectory;
}
/// <summary>
/// Gets the name of the on-disk release type directory of the track stored at <paramref name="trackPath"/>, when the structure of the library
/// uses one. The directory is the parent of the album directory, and it is only used when its name is a known release type, so that the artist
/// directory of a flat library is not mistaken for a release type.
/// </summary>
/// <param name="trackPath">The file system path of the track whose release type directory is retrieved.</param>
/// <returns>The name of the on-disk release type directory, or <see langword="null"/> when the library does not use one.</returns>
public static string? GetReleaseTypeDirectoryName(string trackPath)
{
string albumDirectory = GetAlbumDirectory(trackPath);
string? releaseTypeDirectory = Path.GetDirectoryName(albumDirectory);
if (string.IsNullOrEmpty(releaseTypeDirectory))
return null;
string releaseTypeName = Path.GetFileName(releaseTypeDirectory);
return Enum.TryParse(releaseTypeName, ignoreCase: true, out MusicReleaseType _) ? releaseTypeName : null;
}
}
@@ -0,0 +1,312 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
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>
/// Materializer for the media library items of the music media library type.
/// </summary>
internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanItemMaterializer
{
private const string UNKNOWN_ARTIST_NAME = "Unknown Artist";
private const string UNKNOWN_ALBUM_TITLE = "Unknown Album";
/// <summary>
/// The media library type that this materializer supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Music;
/// <summary>
/// Resets the enrichment state of the tracks stored at the provided <paramref name="paths"/>, together with their albums and artists.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose tracks are reset.</param>
/// <param name="paths">The file system paths of the tracks whose enrichment state 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>> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
{
return await unitOfWork.TrackRepository.ResetEnrichmentStateForPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Materializes the artists, albums and tracks of the media library from the metadata staged for the media library scan.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose items are materialized.</param>
/// <param name="scanId">The Id of the media library scan whose results are materialized.</param>
/// <param name="paths">The file system paths of the media library scan snapshot.</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<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList<string> paths, CancellationToken cancellationToken)
{
// The staged metadata of the scan holds everything needed to materialize the music library items, grouped by artist and by release.
Result<IReadOnlyList<MusicLibraryScanItemMetadataEntity>> getStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.GetByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false);
if (getStagedMetadataResult.IsFailure)
return getStagedMetadataResult.Errors;
IReadOnlyList<MusicLibraryScanItemMetadataEntity> stagedMetadata = getStagedMetadataResult.Value;
if (stagedMetadata.Count == 0)
return Result.Success;
// Tracks that are already stored are never inserted again, so a re-scan of an unchanged file does not duplicate its track.
List<string> stagedPaths = [.. stagedMetadata.Select(stagedItem => stagedItem.Path)];
Result<IReadOnlyCollection<string>> getExistingPathsResult = await unitOfWork.TrackRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false);
if (getExistingPathsResult.IsFailure)
return getExistingPathsResult.Errors;
HashSet<string> existingPaths = [.. getExistingPathsResult.Value];
// The artists of a library are uniquely identified by their name, so they are grouped by it, otherwise two groups named alike would collide with
// the unique index of the artists; the MusicBrainz identifier of the group is the one of the release artist, because the artist of the music
// library is the artist the release, and not the individual tracks, belong to. Albums are grouped by the on-disk directory of their tracks,
// because the directory is the source of truth of what an album is: the tracks of one folder that disagree on their MusicBrainz release
// identifier, or that carry none, still belong to the same album.
foreach (IGrouping<string, MusicLibraryScanItemMetadataEntity> artistGroup in stagedMetadata.GroupBy(GetArtistName))
{
cancellationToken.ThrowIfCancellationRequested();
string artistName = artistGroup.Key;
Guid? musicBrainzArtistId = artistGroup.Select(stagedItem => stagedItem.MusicBrainzReleaseArtistId ?? stagedItem.MusicBrainzArtistId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
Result<ArtistEntity?> getArtistResult = await unitOfWork.ArtistRepository.GetByNameAsync(libraryId, artistName, cancellationToken).ConfigureAwait(false);
if (getArtistResult.IsFailure)
return getArtistResult.Errors;
ArtistEntity? existingArtist = getArtistResult.Value;
// A brand new artist is accumulated together with all its new albums, so that the whole aggregate is inserted in a single call.
ArtistEntity? newArtist = null;
foreach (IGrouping<string, MusicLibraryScanItemMetadataEntity> albumGroup in artistGroup.GroupBy(stagedItem => MusicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase))
{
List<MusicLibraryScanItemMetadataEntity> albumStagedItems = [.. albumGroup];
string albumTitle = GetAlbumTitle(albumStagedItems[0]);
string albumDirectory = MusicLibraryPathStructure.GetAlbumDirectory(albumStagedItems[0].Path);
Guid? musicBrainzReleaseId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
Guid? musicBrainzReleaseGroupId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseGroupId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
Guid? musicBrainzReleaseArtistId = albumStagedItems.Select(stagedItem => stagedItem.MusicBrainzReleaseArtistId).FirstOrDefault(musicBrainzId => musicBrainzId is not null);
// Only the tracks that are not stored yet are materialized, the others already have their own track row.
List<MusicLibraryScanItemMetadataEntity> tracksToInsert = [.. albumStagedItems.Where(stagedItem => !existingPaths.Contains(stagedItem.Path))];
if (tracksToInsert.Count == 0)
continue;
if (existingArtist is null)
{
newArtist ??= CreateArtistEntity(libraryId, artistName, musicBrainzArtistId);
AlbumEntity newAlbum = CreateAlbumEntity(libraryId, newArtist.Id, albumTitle, albumStagedItems, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId);
foreach (MusicLibraryScanItemMetadataEntity stagedItem in tracksToInsert)
newAlbum.Tracks.Add(CreateTrackEntity(libraryId, newAlbum.Id, stagedItem));
newAlbum.TotalTracks = newAlbum.Tracks.Count;
newArtist.Albums.Add(newAlbum);
}
else
{
// The directory pins the album of the artist, so releases that share a title but live in different folders are not merged.
Result<AlbumEntity?> getAlbumResult = await unitOfWork.AlbumRepository.GetByTrackDirectoryAsync(existingArtist.Id, albumDirectory, cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
AlbumEntity? existingAlbum = getAlbumResult.Value;
// A library materialized before the directories became the grouping key is matched by title instead.
if (existingAlbum is null)
{
getAlbumResult = await unitOfWork.AlbumRepository.GetByTitleAsync(existingArtist.Id, albumTitle, cancellationToken).ConfigureAwait(false);
if (getAlbumResult.IsFailure)
return getAlbumResult.Errors;
existingAlbum = getAlbumResult.Value;
}
if (existingAlbum is null)
{
AlbumEntity newAlbum = CreateAlbumEntity(libraryId, existingArtist.Id, albumTitle, albumStagedItems, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId);
foreach (MusicLibraryScanItemMetadataEntity stagedItem in tracksToInsert)
newAlbum.Tracks.Add(CreateTrackEntity(libraryId, newAlbum.Id, stagedItem));
newAlbum.TotalTracks = newAlbum.Tracks.Count;
Result<Created> insertAlbumResult = await unitOfWork.AlbumRepository.InsertAsync(newAlbum, cancellationToken).ConfigureAwait(false);
if (insertAlbumResult.IsFailure)
return insertAlbumResult.Errors;
}
else
{
foreach (MusicLibraryScanItemMetadataEntity stagedItem in tracksToInsert)
{
TrackEntity newTrack = CreateTrackEntity(libraryId, existingAlbum.Id, stagedItem);
Result<Created> insertTrackResult = await unitOfWork.TrackRepository.InsertAsync(newTrack, cancellationToken).ConfigureAwait(false);
if (insertTrackResult.IsFailure)
return insertTrackResult.Errors;
}
}
}
}
if (newArtist is not null)
{
Result<Created> insertArtistResult = await unitOfWork.ArtistRepository.InsertAsync(newArtist, cancellationToken).ConfigureAwait(false);
if (insertArtistResult.IsFailure)
return insertArtistResult.Errors;
}
}
// The staged metadata of the scan was consumed, so it is removed, keeping the storage medium bounded across scans.
Result<Deleted> deleteStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false);
if (deleteStagedMetadataResult.IsFailure)
return deleteStagedMetadataResult.Errors;
return Result.Success;
}
/// <summary>
/// Resets the metadata enrichment status of all the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose items are 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>> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken)
{
Result<Updated> resetArtistsResult = await unitOfWork.ArtistRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (resetArtistsResult.IsFailure)
return resetArtistsResult.Errors;
Result<Updated> resetAlbumsResult = await unitOfWork.AlbumRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
if (resetAlbumsResult.IsFailure)
return resetAlbumsResult.Errors;
return await unitOfWork.TrackRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resets the artwork enrichment status of all the artists, albums and tracks of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <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>> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken)
{
return await unitOfWork.MusicArtworkRepository.ResetStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the name of the artist of the provided staged <paramref name="stagedItem"/>, falling back to a placeholder when the metadata does not provide one.
/// </summary>
/// <param name="stagedItem">The staged music metadata item whose artist name is retrieved.</param>
/// <returns>The name of the artist.</returns>
private static string GetArtistName(MusicLibraryScanItemMetadataEntity stagedItem)
{
return string.IsNullOrWhiteSpace(stagedItem.ArtistName) ? UNKNOWN_ARTIST_NAME : stagedItem.ArtistName;
}
/// <summary>
/// Gets the title of the release of the provided staged <paramref name="stagedItem"/>, falling back to a placeholder when the metadata does not provide one.
/// </summary>
/// <param name="stagedItem">The staged music metadata item whose release title is retrieved.</param>
/// <returns>The title of the release.</returns>
private static string GetAlbumTitle(MusicLibraryScanItemMetadataEntity stagedItem)
{
return string.IsNullOrWhiteSpace(stagedItem.ReleaseName) ? UNKNOWN_ALBUM_TITLE : stagedItem.ReleaseName;
}
/// <summary>
/// Creates a new artist entity for the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <param name="musicBrainzArtistId">The MusicBrainz identifier of the artist, read from the tags, if applicable.</param>
/// <returns>The created artist entity.</returns>
private static ArtistEntity CreateArtistEntity(Guid libraryId, string name, Guid? musicBrainzArtistId)
{
return new ArtistEntity
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
Name = name,
MusicBrainzArtistId = musicBrainzArtistId,
MetadataStatus = MetadataStatus.Pending,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
};
}
/// <summary>
/// Creates a new album entity for the artist identified by <paramref name="artistId"/>, using the metadata of the provided staged <paramref name="stagedItems"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <param name="stagedItems">The staged music metadata items of the album.</param>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release, read from the tags, if applicable.</param>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group, read from the tags, if applicable.</param>
/// <param name="musicBrainzReleaseArtistId">The MusicBrainz identifier of the release artist, read from the tags, if applicable.</param>
/// <returns>The created album entity.</returns>
private static AlbumEntity CreateAlbumEntity(Guid libraryId, Guid artistId, string title, IReadOnlyList<MusicLibraryScanItemMetadataEntity> stagedItems, Guid? musicBrainzReleaseId, Guid? musicBrainzReleaseGroupId, Guid? musicBrainzReleaseArtistId)
{
MusicLibraryScanItemMetadataEntity firstStagedItem = stagedItems[0];
return new AlbumEntity
{
Id = Guid.NewGuid(),
ArtistId = artistId,
LibraryId = libraryId,
Title = title,
MusicBrainzReleaseId = musicBrainzReleaseId,
MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId,
MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId,
ReleaseTypes = firstStagedItem.ReleaseType is null ? [] : [new AlbumReleaseTypeEntity(firstStagedItem.ReleaseType.Value)],
OriginalReleaseYear = firstStagedItem.ReleaseYear,
MetadataStatus = MetadataStatus.Pending,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
};
}
/// <summary>
/// Creates a new track entity for the album identified by <paramref name="albumId"/>, using the metadata of the provided staged <paramref name="stagedItem"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="stagedItem">The staged music metadata item of the track.</param>
/// <returns>The created track entity.</returns>
private static TrackEntity CreateTrackEntity(Guid libraryId, Guid albumId, MusicLibraryScanItemMetadataEntity stagedItem)
{
return new TrackEntity
{
Id = Guid.NewGuid(),
AlbumId = albumId,
LibraryId = libraryId,
Path = stagedItem.Path,
Title = string.IsNullOrWhiteSpace(stagedItem.TrackTitle) ? Path.GetFileNameWithoutExtension(stagedItem.Path) : stagedItem.TrackTitle,
TrackNumber = stagedItem.TrackNumber ?? 0,
DiscNumber = stagedItem.DiscNumber,
DurationInSeconds = stagedItem.DurationInSeconds,
SampleRate = stagedItem.SampleRate,
Channels = stagedItem.Channels,
BitDepth = stagedItem.BitDepth,
AudioCodec = stagedItem.AudioCodec,
Bitrate = stagedItem.Bitrate,
AcoustId = stagedItem.AcoustId,
ReplayGainTrackGain = stagedItem.ReplayGainTrackGain,
ReplayGainTrackPeak = stagedItem.ReplayGainTrackPeak,
ReplayGainAlbumGain = stagedItem.ReplayGainAlbumGain,
ReplayGainAlbumPeak = stagedItem.ReplayGainAlbumPeak,
Moods = [.. stagedItem.Moods.Select(mood => new TrackMoodEntity(mood))],
MusicBrainzRecordingId = stagedItem.MusicBrainzRecordingId,
MusicBrainzTrackId = stagedItem.MusicBrainzTrackId,
MusicBrainzWorkId = stagedItem.MusicBrainzWorkId,
WorkTitle = stagedItem.WorkTitle,
MetadataStatus = MetadataStatus.Pending,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
};
}
}
@@ -0,0 +1,601 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists;
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
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.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
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.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Metadata enricher for the media library items of the music media library type, using the metadata providers configured for the media library.
/// The enriched metadata is applied to the artists, their albums and their tracks, and the media contributors discovered while enriching are linked to them.
/// </summary>
internal sealed class MusicMediaLibraryScanMetadataEnricher : IMediaLibraryScanMetadataEnricher
{
private const int ENRICHMENT_PAGE_SIZE = 200; // The number of artists that are enriched in a single batch, keeping the peak memory bounded regardless of the library size.
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<MusicMediaLibraryScanMetadataEnricher> _logger;
/// <summary>
/// The media library type that this metadata enricher supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Music;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanMetadataEnricher"/> 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 enriching the metadata.</param>
public MusicMediaLibraryScanMetadataEnricher(IServiceScopeFactory serviceScopeFactory, ILogger<MusicMediaLibraryScanMetadataEnricher> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
/// Enriches the metadata of the artists, the albums and the tracks of the provided media library, using the metadata providers configured for it.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library whose items are enriched.</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 setting determines whether the providers that require access to the web are used during the enrichment.
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 providers requiring the web will not be used.");
else
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
}
// Get the metadata providers configured for the media library, in their configured order, that support the media library type,
// skipping the providers that require access to the web when the media library does not permit downloading data from the web.
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
List<IMetadataProvider> providers = [];
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
{
List<IMetadataProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
.GetKeyedServices<IMetadataProvider>(configuration.PluginId)
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Music);
providers.AddRange(configuredProviders);
}
// Read whether the metadata of the items of the user is aggregated from multiple providers, when fields are missing.
bool shouldAggregateMetadataWhenMissing = 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 metadata will not be aggregated across providers.");
else
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
// When no metadata provider is available, the items must not be marked as failed to enrich, so the enrichment is skipped entirely.
if (providers.Count > 0)
{
Result<int> getArtistsToEnrichCountResult = await unitOfWork.ArtistRepository.GetArtistsNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
if (getArtistsToEnrichCountResult.IsFailure)
throw new InvalidOperationException(getArtistsToEnrichCountResult.FirstError.Description);
Result<int> getAlbumsToEnrichCountResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
if (getAlbumsToEnrichCountResult.IsFailure)
throw new InvalidOperationException(getAlbumsToEnrichCountResult.FirstError.Description);
Result<int> getTracksToEnrichCountResult = await unitOfWork.TrackRepository.GetTracksNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
if (getTracksToEnrichCountResult.IsFailure)
throw new InvalidOperationException(getTracksToEnrichCountResult.FirstError.Description);
// The progress is measured in items, not artists: an artist is counted together with its albums and its tracks, because enriching a single
// artist can require a large number of metadata provider calls, one for each of its tracks, and would otherwise barely advance the progress.
int totalItemsToEnrich = getArtistsToEnrichCountResult.Value + getAlbumsToEnrichCountResult.Value + getTracksToEnrichCountResult.Value;
// 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 item (an artist, an album or a track) 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;
}
}
// The media contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
// created once even when the same person is discovered for many items of the same page.
Dictionary<string, MediaContributorEntity> contributorsByNormalizedName = [];
// Process the artists that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size.
string? lastName = null;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
Result<IReadOnlyList<ArtistEntity>> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingMetadataAsync(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();
await EnrichArtistAsync(artistEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork, contributorsByNormalizedName, ReportItemProcessedAsync, cancellationToken).ConfigureAwait(false);
// Persist each enriched artist as soon as it is done, then detach it, so that an interrupted scan keeps everything it already
// enriched, and the peak memory stays bounded regardless of the library size.
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
{
// A unique constraint conflict on a shared lookup such as a media contributor can happen when two scans enrich concurrently;
// it must not abort the whole scan, so the artist is left unenriched and retried on the next scan, while the rest proceeds.
if (saveChangesResult.FirstError == Errors.Persistence.UniqueConstraintViolation)
_logger.LogWarning("The enriched metadata of the artist '{ArtistName}' could not be persisted because of a unique constraint conflict; it will be retried on the next scan.", artistEntity.Name);
else
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
}
unitOfWork.ClearTrackedEntities();
contributorsByNormalizedName.Clear();
}
lastName = artistsPage[^1].Name;
}
// The enrichment finished, force the progress to reach its total, so that an item skipped during an early return 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);
}
else
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value);
}
/// <summary>
/// Enriches the metadata of the provided <paramref name="artistEntity"/>, its albums and its tracks, using the provided metadata providers in their configured order.
/// </summary>
/// <param name="artistEntity">The artist whose metadata, and the metadata of its albums and tracks, is enriched.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata is aggregated from multiple providers, when fields are missing, or not.</param>
/// <param name="unitOfWork">The unit of work used to persist the enriched artist.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="onItemProcessed">The callback invoked after each artist, album or track is processed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichArtistAsync(ArtistEntity artistEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IUnitOfWork unitOfWork, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, Func<Task> onItemProcessed, CancellationToken cancellationToken)
{
// Convert the artist aggregate, together with its albums and tracks, to a domain object.
Result<Artist> getArtistResult = artistEntity.ToDomainEntity();
if (getArtistResult.IsFailure)
return;
Artist artist = getArtistResult.Value;
string fallbackPath = artistEntity.Albums.SelectMany(album => album.Tracks).Select(track => track.Path).FirstOrDefault() ?? string.Empty;
if (artistEntity.MetadataStatus != MetadataStatus.Enriched)
{
ArtistMetadataLookupDto artistLookup = new(
LibraryId: artistEntity.LibraryId,
Path: fallbackPath,
MusicBrainzArtistId: artistEntity.MusicBrainzArtistId,
Name: artistEntity.Name);
ResolvedMetadata<ArtistMetadataDto>? resolvedArtist = await ResolveAndApplyMetadataAsync<ArtistMetadataLookupDto, ArtistMetadataDto>(
artistLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableArtistMetadata,
(first, second) => MusicMetadataAggregator.Merge(first, second),
async metadata =>
{
List<MusicMediaContributor> contributors = await ResolveContributorsAsync(metadata.Contributors, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false);
return metadata.ApplyTo(artist, contributors);
}, _logger, cancellationToken).ConfigureAwait(false);
if (resolvedArtist is null)
artistEntity.MetadataStatus = MetadataStatus.Failed;
else
{
artistEntity.MetadataStatus = MetadataStatus.Enriched;
artistEntity.MetadataProvider = resolvedArtist.ProviderName;
artistEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
}
}
// An artist is reported as processed even when its own metadata was already enriched, because it is only visited when one of its descendants still needs it.
await onItemProcessed().ConfigureAwait(false);
foreach (AlbumEntity albumEntity in artistEntity.Albums)
{
Album? album = artist.Albums.FirstOrDefault(candidate => candidate.Id.Value == albumEntity.Id);
if (album is null)
continue;
// The release the tracks of the album are enriched from: it comes from the tags, or from the release the album was matched to, and it is
// only ever a release whose tracklist corresponds to the local files, so the tracks are never resolved from a different edition.
Guid? albumReleaseId = albumEntity.MusicBrainzReleaseId;
if (albumEntity.MetadataStatus != MetadataStatus.Enriched)
{
string albumPath = albumEntity.Tracks.Select(track => track.Path).FirstOrDefault() ?? fallbackPath;
AlbumMetadataLookupDto albumLookup = new(
LibraryId: artistEntity.LibraryId,
Path: albumPath,
MusicBrainzReleaseGroupId: albumEntity.MusicBrainzReleaseGroupId,
MusicBrainzReleaseId: albumEntity.MusicBrainzReleaseId,
Title: albumEntity.Title,
ArtistName: artistEntity.Name,
ReleaseYear: albumEntity.OriginalReleaseYear,
TrackCount: albumEntity.Tracks.Count);
ResolvedMetadata<AlbumMetadataDto>? resolvedAlbum = await ResolveAndApplyMetadataAsync<AlbumMetadataLookupDto, AlbumMetadataDto>(
albumLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableAlbumMetadata,
(first, second) => MusicMetadataAggregator.Merge(first, second),
async metadata =>
{
List<MusicMediaContributor> contributors = await ResolveContributorsAsync(metadata.Contributors, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false);
return metadata.ApplyTo(artist, album, contributors);
}, _logger, cancellationToken).ConfigureAwait(false);
if (resolvedAlbum is null)
albumEntity.MetadataStatus = MetadataStatus.Failed;
else
{
albumReleaseId = resolvedAlbum.Metadata.MusicBrainzReleaseId ?? albumReleaseId;
albumEntity.MetadataStatus = MetadataStatus.Enriched;
albumEntity.MetadataProvider = resolvedAlbum.ProviderName;
albumEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
}
await onItemProcessed().ConfigureAwait(false);
}
foreach (TrackEntity trackEntity in albumEntity.Tracks)
{
if (trackEntity.MetadataStatus == MetadataStatus.Enriched)
continue;
Track? track = album.Tracks.FirstOrDefault(candidate => candidate.Id.Value == trackEntity.Id);
if (track is null)
continue;
TrackMetadataLookupDto trackLookup = new(
LibraryId: artistEntity.LibraryId,
Path: trackEntity.Path,
MusicBrainzRecordingId: trackEntity.MusicBrainzRecordingId,
Isrc: trackEntity.Isrcs.Select(isrc => isrc.Value).FirstOrDefault(),
Title: trackEntity.Title,
ArtistName: artistEntity.Name,
ReleaseName: albumEntity.Title,
TrackNumber: trackEntity.TrackNumber,
DurationInSeconds: trackEntity.DurationInSeconds > 0 ? trackEntity.DurationInSeconds : null,
MusicBrainzReleaseId: albumReleaseId,
DiscNumber: trackEntity.DiscNumber,
MusicBrainzWorkId: trackEntity.MusicBrainzWorkId,
WorkTitle: trackEntity.WorkTitle);
ResolvedMetadata<AudioMetadataDto>? resolvedTrack = await ResolveAndApplyMetadataAsync<TrackMetadataLookupDto, AudioMetadataDto>(
trackLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableAudioMetadata,
(first, second) => MusicMetadataAggregator.Merge(first, second),
async metadata =>
{
List<MusicMediaContributor> contributors = await ResolveContributorsAsync(metadata.Contributors, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false);
return metadata.ApplyTo(artist, album, track, contributors);
}, _logger, cancellationToken).ConfigureAwait(false);
if (resolvedTrack is null)
trackEntity.MetadataStatus = MetadataStatus.Failed;
else
{
trackEntity.MetadataStatus = MetadataStatus.Enriched;
trackEntity.MetadataProvider = resolvedTrack.ProviderName;
trackEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
}
await onItemProcessed().ConfigureAwait(false);
}
}
// Rebuild the repository entity graph from the enriched domain aggregate, carrying over the enrichment tracking columns of the tracked entities.
ArtistEntity enrichedEntity = artist.ToRepositoryEntity();
CopyEnrichmentTracking(enrichedEntity, artistEntity);
Result<Updated> updateResult = await unitOfWork.ArtistRepository.UpdateAsync(enrichedEntity, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
throw new InvalidOperationException(updateResult.FirstError.Description);
}
/// <summary>
/// Resolves the metadata of the provided lookup and applies it to the media item, either from the first provider whose metadata is usable and applies successfully,
/// or, when aggregation is enabled, from the merged metadata of every usable provider.
/// </summary>
/// <typeparam name="TLookup">The type of the lookup the metadata providers must accept.</typeparam>
/// <typeparam name="TMetadata">The type of the metadata returned by the metadata providers.</typeparam>
/// <param name="lookup">The lookup describing the media item.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="shouldAggregate">Whether the metadata of every usable provider is merged, or only the first one is used.</param>
/// <param name="isUsable">The predicate that determines whether a metadata result is usable.</param>
/// <param name="merge">The function that merges two metadata results.</param>
/// <param name="applyAsync">The function that applies a metadata result to the media item.</param>
/// <param name="logger">The logger used to report the metadata providers that fail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied metadata and the name of the provider, or the providers, that supplied it, or <see langword="null"/> when no provider returned applicable metadata.</returns>
private static async Task<ResolvedMetadata<TMetadata>?> ResolveAndApplyMetadataAsync<TLookup, TMetadata>(MetadataLookupDto lookup, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregate, Func<TMetadata, bool> isUsable, Func<TMetadata, TMetadata, TMetadata> merge, Func<TMetadata, Task<Result<Updated>>> applyAsync, ILogger logger, CancellationToken cancellationToken)
where TLookup : MetadataLookupDto
where TMetadata : MetadataDto
{
if (shouldAggregate)
return await ResolveAggregatedAndApplyAsync<TLookup, TMetadata>(lookup, metadataProviders, isUsable, merge, applyAsync, logger, cancellationToken).ConfigureAwait(false);
return await ResolveFirstAndApplyAsync<TLookup, TMetadata>(lookup, metadataProviders, isUsable, applyAsync, logger, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Tries the providers in configured order, applying the metadata of the first one that is usable and applies successfully, without ever querying the providers that come after it.
/// </summary>
/// <typeparam name="TLookup">The type of the lookup the metadata providers must accept.</typeparam>
/// <typeparam name="TMetadata">The type of the metadata returned by the metadata providers.</typeparam>
/// <param name="lookup">The lookup describing the media item.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="isUsable">The predicate that determines whether a metadata result is usable.</param>
/// <param name="applyAsync">The function that applies a metadata result to the media item.</param>
/// <param name="logger">The logger used to report the metadata providers that fail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied metadata and the name of the provider that supplied it, or <see langword="null"/> when no provider returned applicable metadata.</returns>
private static async Task<ResolvedMetadata<TMetadata>?> ResolveFirstAndApplyAsync<TLookup, TMetadata>(MetadataLookupDto lookup, IReadOnlyList<IMetadataProvider> metadataProviders, Func<TMetadata, bool> isUsable, Func<TMetadata, Task<Result<Updated>>> applyAsync, ILogger logger, CancellationToken cancellationToken)
where TLookup : MetadataLookupDto
where TMetadata : MetadataDto
{
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
if (metadataProvider.LookupType != typeof(TLookup))
continue;
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not TMetadata metadata || !isUsable(metadata))
continue;
// The metadata is applied while the provider is being tried, so that a provider whose metadata cannot be applied does not stop the enrichment and the next one is tried instead.
Result<Updated> applyResult = await applyAsync(metadata).ConfigureAwait(false);
if (applyResult.IsFailure)
continue;
return new ResolvedMetadata<TMetadata>(metadata, metadataProvider.Name);
}
catch (Exception exception)
{
// A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
}
}
return null;
}
/// <summary>
/// Queries every provider, merges the metadata of the usable ones, and applies the merged metadata once.
/// </summary>
/// <typeparam name="TLookup">The type of the lookup the metadata providers must accept.</typeparam>
/// <typeparam name="TMetadata">The type of the metadata returned by the metadata providers.</typeparam>
/// <param name="lookup">The lookup describing the media item.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="isUsable">The predicate that determines whether a metadata result is usable.</param>
/// <param name="merge">The function that merges two metadata results.</param>
/// <param name="applyAsync">The function that applies a metadata result to the media item.</param>
/// <param name="logger">The logger used to report the metadata providers that fail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied merged metadata and the names of the providers that supplied it, or <see langword="null"/> when no provider returned applicable metadata.</returns>
private static async Task<ResolvedMetadata<TMetadata>?> ResolveAggregatedAndApplyAsync<TLookup, TMetadata>(MetadataLookupDto lookup, IReadOnlyList<IMetadataProvider> metadataProviders, Func<TMetadata, bool> isUsable, Func<TMetadata, TMetadata, TMetadata> merge, Func<TMetadata, Task<Result<Updated>>> applyAsync, ILogger logger, CancellationToken cancellationToken)
where TLookup : MetadataLookupDto
where TMetadata : MetadataDto
{
TMetadata? mergedMetadata = default;
List<string> providerNames = [];
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
if (metadataProvider.LookupType != typeof(TLookup))
continue;
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not TMetadata metadata || !isUsable(metadata))
continue;
mergedMetadata = mergedMetadata is null ? metadata : merge(mergedMetadata, metadata);
providerNames.Add(metadataProvider.Name);
}
catch (Exception exception)
{
// A failing metadata provider must not prevent the other providers from being tried, but the failure must be surfaced for diagnostics.
logger.LogWarning(exception, "The metadata provider '{ProviderName}' failed while resolving a {LookupType} lookup for '{Lookup}'.", metadataProvider.Name, typeof(TLookup).Name, lookup);
}
}
if (mergedMetadata is null)
return null;
Result<Updated> applyResult = await applyAsync(mergedMetadata).ConfigureAwait(false);
if (applyResult.IsFailure)
return null;
return new ResolvedMetadata<TMetadata>(mergedMetadata, string.Join(", ", providerNames.Distinct(StringComparer.Ordinal)));
}
/// <summary>
/// Finds the media contributor with the name of the provided <paramref name="contributor"/>, or creates it, caching it by its normalized display name
/// so that a contributor is only created once even when the same person is discovered for many items of the same page.
/// </summary>
/// <param name="contributors">The metadata contributors to resolve.</param>
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The resolved domain media contributors, already carrying their persisted identifiers.</returns>
private static async Task<List<MusicMediaContributor>> ResolveContributorsAsync(IReadOnlyCollection<MediaContributorDto>? contributors, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, CancellationToken cancellationToken)
{
List<MusicMediaContributor> resolvedContributors = [];
foreach (MediaContributorDto contributor in contributors ?? [])
{
if (contributor.Name?.DisplayName is null)
continue;
string displayName = contributor.Name.DisplayName;
string normalizedDisplayName = displayName.ToLowerInvariant();
if (!contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? contributorEntity))
{
Result<MediaContributorEntity> getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false);
if (getContributorResult.IsFailure)
throw new InvalidOperationException(getContributorResult.FirstError.Description);
contributorEntity = getContributorResult.Value;
contributorsByNormalizedName[normalizedDisplayName] = contributorEntity;
}
MediaContributorRole role = contributor.Role ?? MediaContributorRole.Performer;
if (resolvedContributors.Any(resolved => resolved.ContributorId.Value == contributorEntity.Id && resolved.Role == role))
continue;
Result<MusicMediaContributor> domainContributorResult = MusicMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role);
if (domainContributorResult.IsFailure)
continue;
resolvedContributors.Add(domainContributorResult.Value);
}
return resolvedContributors;
}
/// <summary>
/// Copies the metadata enrichment tracking columns of the tracked <paramref name="source"/> artist, albums and tracks onto the rebuilt repository entity graph.
/// </summary>
/// <param name="target">The rebuilt repository entity graph that receives the tracking columns.</param>
/// <param name="source">The tracked repository entity graph that carries the tracking columns.</param>
private static void CopyEnrichmentTracking(ArtistEntity target, ArtistEntity source)
{
target.MetadataStatus = source.MetadataStatus;
target.MetadataProvider = source.MetadataProvider;
target.LastMetadataUpdateUtc = source.LastMetadataUpdateUtc;
foreach (AlbumEntity targetAlbum in target.Albums)
{
AlbumEntity? sourceAlbum = source.Albums.FirstOrDefault(album => album.Id == targetAlbum.Id);
if (sourceAlbum is null)
continue;
targetAlbum.MetadataStatus = sourceAlbum.MetadataStatus;
targetAlbum.MetadataProvider = sourceAlbum.MetadataProvider;
targetAlbum.LastMetadataUpdateUtc = sourceAlbum.LastMetadataUpdateUtc;
foreach (TrackEntity targetTrack in targetAlbum.Tracks)
{
TrackEntity? sourceTrack = sourceAlbum.Tracks.FirstOrDefault(track => track.Id == targetTrack.Id);
if (sourceTrack is null)
continue;
targetTrack.MetadataStatus = sourceTrack.MetadataStatus;
targetTrack.MetadataProvider = sourceTrack.MetadataProvider;
targetTrack.LastMetadataUpdateUtc = sourceTrack.LastMetadataUpdateUtc;
}
}
}
/// <summary>
/// Determines whether the provided artist metadata is usable, meaning it has a name.
/// </summary>
/// <param name="metadata">The metadata to validate.</param>
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
private static bool IsUsableArtistMetadata(ArtistMetadataDto metadata)
{
return !string.IsNullOrWhiteSpace(metadata.Name);
}
/// <summary>
/// Determines whether the provided album metadata is usable, meaning it has a title.
/// </summary>
/// <param name="metadata">The metadata to validate.</param>
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
private static bool IsUsableAlbumMetadata(AlbumMetadataDto metadata)
{
return !string.IsNullOrWhiteSpace(metadata.Title);
}
/// <summary>
/// Determines whether the provided audio metadata is usable, meaning it has a title.
/// </summary>
/// <param name="metadata">The metadata to validate.</param>
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
private static bool IsUsableAudioMetadata(AudioMetadataDto metadata)
{
return !string.IsNullOrWhiteSpace(metadata.Title);
}
/// <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, "EnrichingMetadata");
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 metadata resolved for a media library item, along with the provider, or providers, that supplied it.
/// </summary>
/// <typeparam name="TMetadata">The type of the resolved metadata.</typeparam>
/// <param name="Metadata">The resolved metadata of the item.</param>
/// <param name="ProviderName">The name of the provider, or the providers, that supplied the metadata.</param>
private sealed record ResolvedMetadata<TMetadata>(TMetadata Metadata, string ProviderName) where TMetadata : MetadataDto;
}
@@ -0,0 +1,553 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
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.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
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.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
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>
/// Media library scan job for extracting the metadata of the discovered music file system items.
/// </summary>
internal sealed class MusicMetadataExtractionJob : MediaLibraryScanJob, IMusicMetadataExtractionJob
{
private const int EXTRACTION_BATCH_SIZE = 1000; // The number of extracted metadata items that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size.
private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape];
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ILogger<MusicMetadataExtractionJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMetadataExtractionJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">
/// 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 service for logging.</param>
public MusicMetadataExtractionJob(IServiceScopeFactory serviceScopeFactory, ILogger<MusicMetadataExtractionJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
/// Executes the payload of the media library scan job.
/// </summary>
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
/// <param name="id">The id of the media library scan job.</param>
/// <param name="input">The input data to be processed by this payload.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
try
{
// Increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel).
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
// Only execute this job's payload when it has no parents, or when all the parents finished their execution.
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
{
// This needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue.
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// Get the library from the repository, both to verify that it exists and to know its content locations.
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.");
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsFailure)
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
// The library always carries a path template: the one configured by the user, or the ideal structure of the library type as its default.
ILibraryPathTemplateService pathTemplateService = asyncServiceScope.ServiceProvider.GetService<ILibraryPathTemplateService>()!;
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
Result<LibraryPathTemplate> pathTemplateResult = pathTemplateService.ResolveTemplate(domainLibraryResult.Value.LibraryType, domainLibraryResult.Value.PathTemplate.Parts);
if (pathTemplateResult.IsFailure)
throw new InvalidOperationException(pathTemplateResult.FirstError.Description);
LibraryPathTemplate pathTemplate = pathTemplateResult.Value;
// The metadata is extracted only for the files that are new or changed, since the unchanged ones already have their materialized items.
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsFailure)
throw new InvalidOperationException(getPathsResult.FirstError.Description);
IReadOnlyList<string> paths = getPathsResult.Value;
// Set the initial progress of the scan job.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, paths.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
DateTime lastHeartbeat = DateTime.UtcNow;
int processedItems = 0;
List<MusicLibraryScanItemMetadataEntity> metadataBatch = [];
foreach (string path in paths)
{
cancellationToken.ThrowIfCancellationRequested();
metadataBatch.Add(ExtractMetadata(path, domainLibraryResult.Value.ContentLocations, domainLibraryResult.Value.LibraryType, pathTemplate, pathTemplateService, pathService));
if (metadataBatch.Count >= EXTRACTION_BATCH_SIZE)
{
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveBatchResult.IsFailure)
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
metadataBatch.Clear();
unitOfWork.ClearTrackedEntities();
}
processedItems++;
// Increment the number of processed elements progress in a high-frequency counter with low overhead check.
DateTime now = DateTime.UtcNow;
if (now - lastHeartbeat >= heartbeatInterval)
{
publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, processedItems, paths.Count, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
lastHeartbeat = now;
}
}
// Flush any remaining extracted metadata items that did not reach the batch size.
if (metadataBatch.Count > 0)
{
Result<Created> insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
if (insertBatchResult.IsFailure)
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
Result<Success> saveBatchResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveBatchResult.IsFailure)
throw new InvalidOperationException(saveBatchResult.FirstError.Description);
}
// This job finished, increment the number of processed jobs progress.
await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
// Call each linked child with the obtained payload.
foreach (IMediaLibraryScanJob child in Children)
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Canceled;
throw;
}
catch (Exception exception)
{
Status = LibraryScanJobStatus.Failed;
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Extracts the metadata of the music file stored at <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of the music file whose metadata is extracted.</param>
/// <param name="contentLocations">The content locations of the media library the music file belongs to.</param>
/// <param name="libraryType">The type of the media library the music file belongs to.</param>
/// <param name="pathTemplate">The template describing the structure of the media library on disk.</param>
/// <param name="pathTemplateService">The service used to derive the metadata from the path of the music file.</param>
/// <param name="pathService">The service used to determine the path separator and whether the file is inside the content locations of the media library.</param>
/// <returns>The staged music metadata item.</returns>
private MusicLibraryScanItemMetadataEntity ExtractMetadata(string path, IReadOnlyCollection<FileSystemPathId> contentLocations, LibraryType libraryType, LibraryPathTemplate pathTemplate, ILibraryPathTemplateService pathTemplateService, IPathService pathService)
{
string relativePath = GetRelativePath(path, contentLocations, pathService);
Result<Optional<ParsedLibraryPath>> pathMetadataResult = pathTemplateService.Parse(libraryType, pathTemplate, relativePath, pathService.PathSeparator);
string? artistName = null;
MusicReleaseType? releaseType = null;
int? releaseYear = null;
string? releaseName = null;
int? trackNumber = null;
int? discNumber = null;
string? trackTitle = null;
Guid? musicBrainzArtistId = null;
Guid? musicBrainzReleaseArtistId = null;
Guid? musicBrainzReleaseGroupId = null;
Guid? musicBrainzReleaseId = null;
Guid? musicBrainzRecordingId = null;
Guid? musicBrainzTrackId = null;
Guid? musicBrainzWorkId = null;
string? workTitle = null;
if (pathMetadataResult.IsSuccess && pathMetadataResult.Value.HasValue)
{
MusicLibraryPathMetadata pathMetadata = MusicLibraryPathMetadata.FromParsedLibraryPath(pathMetadataResult.Value.Value);
if (pathMetadata.ArtistName.HasValue)
artistName = pathMetadata.ArtistName.Value;
if (pathMetadata.ReleaseType.HasValue)
releaseType = pathMetadata.ReleaseType.Value;
if (pathMetadata.ReleaseYear.HasValue)
releaseYear = pathMetadata.ReleaseYear.Value;
if (pathMetadata.ReleaseName.HasValue)
releaseName = pathMetadata.ReleaseName.Value;
if (pathMetadata.TrackNumber.HasValue)
trackNumber = pathMetadata.TrackNumber.Value;
if (pathMetadata.DiscNumber.HasValue)
discNumber = pathMetadata.DiscNumber.Value;
if (pathMetadata.TrackTitle.HasValue)
trackTitle = pathMetadata.TrackTitle.Value;
}
int durationInSeconds = 0;
int sampleRate = 0;
int channels = 0;
int? bitDepth = null;
string? audioCodec = null;
int? bitrate = null;
string? acoustId = null;
decimal? replayGainTrackGain = null;
decimal? replayGainTrackPeak = null;
decimal? replayGainAlbumGain = null;
decimal? replayGainAlbumPeak = null;
List<string> moods = [];
try
{
using (TagLib.File tagFile = TagLib.File.Create(path))
{
TagLib.Tag tag = tagFile.Tag;
if (!string.IsNullOrWhiteSpace(tag.Title))
trackTitle = tag.Title;
if (!string.IsNullOrWhiteSpace(tag.Album))
releaseName = tag.Album;
// The album artist is preferred over the track artist, because it is the artist the release belongs to.
string? tagArtist = !string.IsNullOrWhiteSpace(tag.FirstAlbumArtist) ? tag.FirstAlbumArtist : tag.FirstPerformer;
if (!string.IsNullOrWhiteSpace(tagArtist))
artistName = tagArtist;
if (tag.Track > 0)
trackNumber = (int)tag.Track;
if (tag.Disc > 0)
discNumber = (int)tag.Disc;
if (tag.Year > 0)
releaseYear = (int)tag.Year;
TagLib.Properties audioProperties = tagFile.Properties;
durationInSeconds = (int)audioProperties.Duration.TotalSeconds;
sampleRate = audioProperties.AudioSampleRate;
channels = audioProperties.AudioChannels;
if (audioProperties.BitsPerSample > 0)
bitDepth = audioProperties.BitsPerSample;
if (audioProperties.AudioBitrate > 0)
bitrate = audioProperties.AudioBitrate;
if (!string.IsNullOrWhiteSpace(audioProperties.Description))
audioCodec = audioProperties.Description;
// The text frames of the ID3v2 tag are read once for the whole file, so that the extended tag lookups below do not walk all the frames
// of the tag again for every key.
IReadOnlyDictionary<string, string[]> id3v2ExtendedFields = GetId3v2ExtendedFields(tagFile);
// The MusicBrainz identifiers written by taggers like Picard are read here, so that the enrichment can look the items up directly,
// instead of guessing them through searches. The work identifier and title are not exposed as properties by the tagging library, so
// they are read from the extended tags of the container, and they only serve as a fallback for recordings that MusicBrainz leaves unlinked to a work.
musicBrainzArtistId = ParseGuid(tag.MusicBrainzArtistId);
musicBrainzReleaseArtistId = ParseGuid(tag.MusicBrainzReleaseArtistId);
musicBrainzReleaseGroupId = ParseGuid(tag.MusicBrainzReleaseGroupId);
musicBrainzReleaseId = ParseGuid(tag.MusicBrainzReleaseId);
musicBrainzRecordingId = ParseGuid(tag.MusicBrainzTrackId);
musicBrainzTrackId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID"));
musicBrainzWorkId = ParseGuid(GetExtendedField(tagFile, id3v2ExtendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID"));
string? extendedWorkTitle = GetExtendedField(tagFile, id3v2ExtendedFields, "WORK", "MUSICBRAINZ_WORK");
if (!string.IsNullOrWhiteSpace(extendedWorkTitle))
workTitle = extendedWorkTitle;
// The AcoustID, the moods and the ReplayGain values written by taggers like Picard are read here as well. The moods can be a single
// slash separated value or several distinct values, depending on the container, so all of them are read and split before being de-duplicated.
acoustId = GetExtendedField(tagFile, id3v2ExtendedFields, "Acoustid Id", "ACOUSTID_ID");
moods = [.. GetExtendedFields(tagFile, id3v2ExtendedFields, "mood", "MOOD", "MOODS")
.SelectMany(mood => mood.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Where(mood => !string.IsNullOrWhiteSpace(mood))
.Distinct(StringComparer.OrdinalIgnoreCase)];
replayGainTrackGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_GAIN", "replaygain_track_gain"));
replayGainTrackPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_TRACK_PEAK", "replaygain_track_peak"));
replayGainAlbumGain = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_GAIN", "replaygain_album_gain"));
replayGainAlbumPeak = ParseDecimal(GetExtendedField(tagFile, id3v2ExtendedFields, "REPLAYGAIN_ALBUM_PEAK", "replaygain_album_peak"));
}
}
catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException)
{
// A music file whose tags cannot be read still contributes the metadata derived from its path, but the failure is logged, so that a
// systematic tagging failure of a whole library does not silently degrade every file to path only metadata.
_logger.LogWarning(exception, "Failed to read the embedded tags of the music file '{Path}'. Its metadata will be derived from the path only.", path);
}
if (string.IsNullOrWhiteSpace(trackTitle))
trackTitle = Path.GetFileNameWithoutExtension(path);
return new MusicLibraryScanItemMetadataEntity
{
Id = Guid.NewGuid(),
LibraryScanId = ScanId.Value,
LibraryId = LibraryId.Value,
Path = path,
ArtistName = artistName,
ReleaseType = releaseType,
ReleaseYear = releaseYear,
ReleaseName = releaseName,
TrackTitle = trackTitle,
TrackNumber = trackNumber,
DiscNumber = discNumber,
DurationInSeconds = durationInSeconds,
SampleRate = sampleRate,
Channels = channels,
BitDepth = bitDepth,
AudioCodec = audioCodec,
Bitrate = bitrate,
AcoustId = acoustId,
ReplayGainTrackGain = replayGainTrackGain,
ReplayGainTrackPeak = replayGainTrackPeak,
ReplayGainAlbumGain = replayGainAlbumGain,
ReplayGainAlbumPeak = replayGainAlbumPeak,
Moods = moods,
MusicBrainzArtistId = musicBrainzArtistId,
MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId,
MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId,
MusicBrainzReleaseId = musicBrainzReleaseId,
MusicBrainzRecordingId = musicBrainzRecordingId,
MusicBrainzTrackId = musicBrainzTrackId,
MusicBrainzWorkId = musicBrainzWorkId,
WorkTitle = workTitle
};
}
/// <summary>
/// Parses the provided tag <paramref name="value"/> as a globally unique identifier.
/// </summary>
/// <param name="value">The tag value to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is missing or malformed.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsedValue) ? parsedValue : null;
}
/// <summary>
/// Reads the text frames of the ID3v2 tag of the provided <paramref name="tagFile"/> once, keyed by their description and compared
/// case-insensitively, so that every extended tag lookup of the file reuses the same enumeration instead of walking all the frames again.
/// </summary>
/// <param name="tagFile">The file whose ID3v2 text frames are read.</param>
/// <returns>The text values of the ID3v2 frames, keyed by their description, or an empty dictionary when the file has no ID3v2 tag.</returns>
private static Dictionary<string, string[]> GetId3v2ExtendedFields(TagLib.File tagFile)
{
Dictionary<string, string[]> fields = new(StringComparer.OrdinalIgnoreCase);
if (tagFile.GetTag(TagLib.TagTypes.Id3v2) is not TagLib.Id3v2.Tag id3v2Tag)
return fields;
// Only the first frame of a given description is kept, so a description that appears more than once always resolves to its first occurrence.
foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames())
if (frame is TagLib.Id3v2.UserTextInformationFrame userTextViewFrame
&& !string.IsNullOrEmpty(userTextViewFrame.Description)
&& !fields.ContainsKey(userTextViewFrame.Description))
fields[userTextViewFrame.Description] = userTextViewFrame.Text;
return fields;
}
/// <summary>
/// Reads an extended tag that the tagging library does not expose as a property, from whichever container tag of the file carries it.
/// </summary>
/// <param name="tagFile">The file whose extended tags are read.</param>
/// <param name="id3v2ExtendedFields">The text frames of the ID3v2 tag of the file, read once for the whole file.</param>
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
/// <returns>The first non-empty value found, or <see langword="null"/> when the file carries none of the provided tags.</returns>
private static string? GetExtendedField(TagLib.File tagFile, IReadOnlyDictionary<string, string[]> id3v2ExtendedFields, params string[] keys)
{
foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes)
{
// The frames of the ID3v2 tag were read once for the whole file, so they are looked up instead of being enumerated again for every key.
if (tagType == TagLib.TagTypes.Id3v2)
{
foreach (string key in keys)
if (id3v2ExtendedFields.TryGetValue(key, out string[]? id3v2Values) && id3v2Values.Length > 0 && !string.IsNullOrWhiteSpace(id3v2Values[0]))
return id3v2Values[0];
continue;
}
TagLib.Tag? tag = tagFile.GetTag(tagType);
if (tag is null)
continue;
foreach (string key in keys)
{
string? value = GetExtendedFieldFromTag(tag, key);
if (!string.IsNullOrWhiteSpace(value))
return value;
}
}
return null;
}
/// <summary>
/// Reads an extended tag with the provided <paramref name="key"/> from the provided <paramref name="tag"/>, according to its container format.
/// </summary>
/// <param name="tag">The container tag whose extended tags are read.</param>
/// <param name="key">The name of the extended tag to read.</param>
/// <returns>The value of the extended tag, or <see langword="null"/> when the tag does not carry it.</returns>
private static string? GetExtendedFieldFromTag(TagLib.Tag tag, string key)
{
switch (tag)
{
case TagLib.Ogg.XiphComment xiphComment:
string[] xiphValues = xiphComment.GetField(key);
return xiphValues.Length > 0 ? xiphValues[0] : null;
case TagLib.Mpeg4.AppleTag appleTag:
return appleTag.GetDashBox("com.apple.iTunes", key);
case TagLib.Ape.Tag apeTag:
if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem)
{
string[] apeValues = apeItem.ToStringArray();
return apeValues.Length > 0 ? apeValues[0] : null;
}
return null;
default:
return null;
}
}
/// <summary>
/// Reads every value of an extended tag that the tagging library does not expose as a property, from whichever container tag of the file carries it.
/// </summary>
/// <param name="tagFile">The file whose extended tags are read.</param>
/// <param name="id3v2ExtendedFields">The text frames of the ID3v2 tag of the file, read once for the whole file.</param>
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
/// <returns>Every non-empty value found, or an empty list when the file carries none of the provided tags.</returns>
private static List<string> GetExtendedFields(TagLib.File tagFile, IReadOnlyDictionary<string, string[]> id3v2ExtendedFields, params string[] keys)
{
List<string> values = [];
foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes)
{
// The frames of the ID3v2 tag were read once for the whole file, so they are looked up instead of being enumerated again for every key.
if (tagType == TagLib.TagTypes.Id3v2)
{
foreach (string key in keys)
if (id3v2ExtendedFields.TryGetValue(key, out string[]? id3v2Values))
values.AddRange(id3v2Values.Where(value => !string.IsNullOrWhiteSpace(value)));
continue;
}
TagLib.Tag? tag = tagFile.GetTag(tagType);
if (tag is null)
continue;
foreach (string key in keys)
values.AddRange(GetExtendedFieldsFromTag(tag, key).Where(value => !string.IsNullOrWhiteSpace(value)));
}
return values;
}
/// <summary>
/// Reads every value of an extended tag with the provided <paramref name="key"/> from the provided <paramref name="tag"/>, according to its container format.
/// </summary>
/// <param name="tag">The container tag whose extended tags are read.</param>
/// <param name="key">The name of the extended tag to read.</param>
/// <returns>Every value of the extended tag, or an empty list when the tag does not carry it.</returns>
private static List<string> GetExtendedFieldsFromTag(TagLib.Tag tag, string key)
{
switch (tag)
{
case TagLib.Ogg.XiphComment xiphComment:
return [.. xiphComment.GetField(key)];
case TagLib.Mpeg4.AppleTag appleTag:
string? value = appleTag.GetDashBox("com.apple.iTunes", key);
return string.IsNullOrWhiteSpace(value) ? [] : [.. value.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)];
case TagLib.Ape.Tag apeTag:
if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem)
return [.. apeItem.ToStringArray()];
return [];
default:
return [];
}
}
/// <summary>
/// Parses a ReplayGain value, optionally suffixed with its unit, into a decimal.
/// </summary>
/// <param name="value">The value to parse.</param>
/// <returns>The parsed decimal, or <see langword="null"/> when the value is missing or malformed.</returns>
private static decimal? ParseDecimal(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
string cleaned = value.Replace("dB", string.Empty, StringComparison.OrdinalIgnoreCase).Trim();
return decimal.TryParse(cleaned, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal parsed) ? parsed : null;
}
/// <summary>
/// Gets the path of the music file stored at <paramref name="path"/>, relative to the content location of the media library it belongs to.
/// </summary>
/// <param name="path">The absolute file system path of the music file.</param>
/// <param name="contentLocations">The content locations of the media library the music file belongs to.</param>
/// <param name="pathService">The service used to determine whether the file is inside a content location of the media library.</param>
/// <returns>The path of the music file, relative to its content location, or the file name when no content location contains it.</returns>
private static string GetRelativePath(string path, IReadOnlyCollection<FileSystemPathId> contentLocations, IPathService pathService)
{
foreach (FileSystemPathId contentLocation in contentLocations)
{
if (pathService.IsPathWithin(path, contentLocation.Path))
{
string relativePath = path[contentLocation.Path.Length..].TrimStart('\\', '/');
if (relativePath.Length > 0)
return relativePath;
}
}
return Path.GetFileName(path);
}
/// <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, "ExtractingMetadata");
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;
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Interface defining the materialization of the media library items of a specific media library type from the results of a media library scan.
/// </summary>
internal interface IMediaLibraryScanItemMaterializer
{
/// <summary>
/// The media library type that this materializer supports.
/// </summary>
LibraryType SupportedLibraryType { get; }
/// <summary>
/// Resets the enrichment state of the media library items stored at the provided <paramref name="paths"/>, so that they are re-enriched, because their content changed since the last scan.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose items are reset.</param>
/// <param name="paths">The file system paths of the media library items whose enrichment state 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>> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken);
/// <summary>
/// Materializes the media library items of the media library from the paths of the media library scan snapshot.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose items are materialized.</param>
/// <param name="scanId">The Id of the media library scan whose results are materialized.</param>
/// <param name="paths">The file system paths of the media library scan snapshot.</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<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList<string> paths, CancellationToken cancellationToken);
/// <summary>
/// Resets the metadata enrichment status of all the media library items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose items are 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>> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Resets the artwork enrichment status of all the media library items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <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>> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken);
}
@@ -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 metadata enrichment of the media library items of a specific media library type.
/// </summary>
internal interface IMediaLibraryScanMetadataEnricher
{
/// <summary>
/// The media library type that this metadata enricher supports.
/// </summary>
LibraryType SupportedLibraryType { get; }
/// <summary>
/// Enriches the metadata of the media library items of the provided media library, using the metadata providers configured for it.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library whose items are enriched.</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,33 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -37,13 +18,11 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo
/// <summary>
/// Media library scan job for enriching the metadata of the media library items, using the metadata providers configured for the media library.
/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them.
/// The enrichment itself is delegated to the metadata enricher of the media library type.
/// </summary>
internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJob, IMediaLibraryScanMetadataEnrichmentJob
{
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<MediaLibraryScanMetadataEnrichmentJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanMetadataEnrichmentJob"/> class.
@@ -52,11 +31,9 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
/// 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 enriching the metadata.</param>
public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger<MediaLibraryScanMetadataEnrichmentJob> logger)
public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
@@ -87,110 +64,22 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// Load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment.
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 providers requiring the web will not be used.");
else
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
}
// Load the media library, whose type determines the metadata 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 metadata providers configured for the media library, in their configured order, that support the media library type,
// skipping the providers that require access to the web when the media library does not permit downloading data from the web.
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
List<IMetadataProvider> providers = [];
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
{
List<IMetadataProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
.GetKeyedServices<IMetadataProvider>(configuration.PluginId)
.Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
providers.AddRange(configuredProviders);
}
IMediaLibraryScanMetadataEnricher? metadataEnricher = asyncServiceScope.ServiceProvider
.GetServices<IMediaLibraryScanMetadataEnricher>()
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
if (metadataEnricher is null)
throw new InvalidOperationException($"No metadata enricher exists for media library type '{libraryType}'.");
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
bool shouldAggregateMetadataWhenMissing = 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 metadata will not be aggregated across providers.");
else
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
await metadataEnricher.EnrichAsync(LibraryId, ScanId, UserId, cancellationToken).ConfigureAwait(false);
// When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely.
if (providers.Count > 0)
{
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(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;
// The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
// created once even when the same person is discovered for many books of the same page.
Dictionary<string, MediaContributorEntity> contributorsByNormalizedName = [];
// Process the books that need their metadata enriched 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.GetBooksNeedingMetadataAsync(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;
foreach (BookEntity bookEntity in booksPage)
{
cancellationToken.ThrowIfCancellationRequested();
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, 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();
contributorsByNormalizedName.Clear();
lastPath = booksPage[^1].Path;
}
}
else
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata 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)
@@ -213,237 +102,4 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Enriches the metadata of the provided <paramref name="bookEntity"/>, using the provided metadata providers in their configured order,
/// linking the media contributors discovered while enriching to the book.
/// </summary>
/// <param name="bookEntity">The book whose metadata is enriched.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not.</param>
/// <param name="bookRepository">The repository used to persist the enriched book.</param>
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, CancellationToken cancellationToken)
{
// Convert the book to a domain object.
Result<Book> getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsFailure)
return;
Book book = getBookResult.Value;
BookMetadataLookupDto bookMetadataLookup = 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, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results.
OpenLibraryId: bookEntity.OpenLibraryId,
Title: bookEntity.Title,
Author: null,
LanguageCode: bookEntity.LanguageCode
);
ResolvedMetadata? resolvedMetadata = shouldAggregateMetadataWhenMissing
? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false)
: await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false);
if (resolvedMetadata is null)
{
// No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata.
bookEntity.MetadataStatus = MetadataStatus.Failed;
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
bookEntity.UpdatedBy = Guid.NewGuid();
return;
}
// Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns.
book.ApplyMetadata(resolvedMetadata.Metadata);
bookEntity.ApplyMetadataToEntity(book);
// Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person.
List<BookContributorEntity> linkedContributors = [];
List<BookMediaContributor> domainContributors = [];
foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? [])
{
if (contributor.Name?.DisplayName is null)
continue;
MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false);
MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author;
if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role))
continue;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = bookEntity.Id,
MediaContributorId = contributorEntity.Id,
Role = role,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
});
domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value);
}
bookEntity.Contributors.Clear();
bookEntity.Contributors.AddRange(linkedContributors);
book.UpdateContributors(domainContributors);
// Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern.
bookEntity.MetadataStatus = MetadataStatus.Enriched;
bookEntity.MetadataProvider = resolvedMetadata.ProviderName;
bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
}
/// <summary>
/// Finds the media contributor with the name of the provided <paramref name="contributor"/>, or creates it, caching it by its normalized display name
/// so that a contributor is only created once even when the same person is discovered for many books of the same page.
/// </summary>
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="contributor">The contributor to find or create.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The found or created media contributor.</returns>
private async Task<MediaContributorEntity> FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken)
{
string displayName = contributor.Name!.DisplayName!;
string normalizedDisplayName = displayName.ToLowerInvariant();
if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor))
return cachedContributor;
Result<MediaContributorEntity> getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, null, cancellationToken).ConfigureAwait(false);
if (getContributorResult.IsFailure)
throw new InvalidOperationException(getContributorResult.FirstError.Description);
contributorsByNormalizedName[normalizedDisplayName] = getContributorResult.Value;
return getContributorResult.Value;
}
/// <summary>
/// Tries the <paramref name="metadataProviders"/> in order, applying the metadata of the first one that returns usable metadata.
/// </summary>
/// <param name="book">The book onto which the metadata is applied.</param>
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied metadata and the provider that supplied it, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<ResolvedMetadata?> TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata);
if (applyMetadataResult.IsFailure)
continue;
return new ResolvedMetadata(bookMetadata, metadataProvider.Name);
}
catch (Exception)
{
// A failing metadata provider must not prevent the other providers from being tried.
}
}
return null;
}
/// <summary>
/// Aggregates the metadata of the <paramref name="book"/> from all the <paramref name="metadataProviders"/>, in their configured order, filling the fields that the earlier providers lack with the values of the later ones.
/// </summary>
/// <param name="book">The book onto which the aggregated metadata is applied.</param>
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied aggregated metadata and the providers that contributed to it, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<ResolvedMetadata?> AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
BookMetadataDto? mergedMetadata = null;
List<string> contributingProviders = [];
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata))
continue;
mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata);
contributingProviders.Add(metadataProvider.Name);
// The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely.
bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata);
}
catch (Exception)
{
// A failing metadata provider must not prevent the other providers from being tried.
}
}
if (mergedMetadata is null)
return null;
Result<Success> applyMetadataResult = book.ApplyMetadata(mergedMetadata);
return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)));
}
/// <summary>
/// Enriches the <paramref name="bookMetadataLookup"/> with the identifiers and the title discovered by the already queried metadata providers.
/// </summary>
/// <param name="bookMetadataLookup">The lookup to enrich.</param>
/// <param name="bookMetadata">The metadata discovered by the already queried metadata providers.</param>
/// <returns>The enriched lookup.</returns>
private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata)
{
string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value;
string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId;
string? title = bookMetadataLookup.Title ?? bookMetadata.Title;
return bookMetadataLookup with
{
Isbn = isbn,
OpenLibraryId = openLibraryId,
Title = title
};
}
/// <summary>
/// Determines whether the provided <paramref name="bookMetadata"/> is usable, meaning it has a title.
/// </summary>
/// <param name="bookMetadata">The metadata to validate.</param>
/// <returns><see langword="true"/> when the metadata is usable, otherwise <see langword="false"/>.</returns>
private static bool IsUsableMetadata(BookMetadataDto bookMetadata)
{
return !string.IsNullOrWhiteSpace(bookMetadata.Title);
}
/// <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, "EnrichingMetadata");
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 metadata resolved for a book, along with the providers that supplied it.
/// </summary>
/// <param name="Metadata">The resolved metadata of the book.</param>
/// <param name="ProviderName">The name of the provider, or the providers, that supplied the metadata.</param>
private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName);
}
@@ -13,6 +13,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -82,6 +83,13 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
LibraryEntity library = getLibraryResult.Value;
// The type of the media library determines the materializer whose enrichment state is invalidated.
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
.GetServices<IMediaLibraryScanItemMaterializer>()
.FirstOrDefault(candidate => candidate.SupportedLibraryType == library.LibraryType);
if (materializer is null)
throw new InvalidOperationException($"No media library item materializer exists for media library type '{library.LibraryType}'.");
// Load the provider configurations of the media library, whose fingerprint is compared against the stored one.
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getMetadataConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getMetadataConfigurationsResult.IsFailure)
@@ -91,33 +99,46 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
if (getArtworkConfigurationsResult.IsFailure)
throw new InvalidOperationException(getArtworkConfigurationsResult.FirstError.Description);
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
// Read whether the metadata and the artwork of the items of the user are aggregated from multiple providers, when missing.
bool shouldAggregateMetadataWhenMissing = false;
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 metadata provider configuration fingerprint will not include the metadata aggregation setting.");
_logger.LogWarning("Failed to read the user settings, the provider configuration fingerprints will not include the aggregation settings.");
else
{
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
shouldAggregateArtworkWhenMissing = getUserSettingsResult.Value?.ShouldAggregateArtworkWhenMissing ?? false;
}
}
// Compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration
// changed, so that the enrichment jobs that follow re-enrich the books. A missing stored fingerprint means the configuration
// was never recorded yet, so the current state of the books is trusted, and only the new fingerprint is stored.
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(getMetadataConfigurationsResult.Value, shouldAggregateMetadataWhenMissing, library.CanDownloadMetadataFromWeb);
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, library.CanDownloadMetadataFromWeb);
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(getArtworkConfigurationsResult.Value, shouldAggregateArtworkWhenMissing, library.CanDownloadMetadataFromWeb);
string pathTemplateFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([.. library.PathTemplateParts]);
if (library.MetadataProvidersConfigurationFingerprint is not null && library.MetadataProvidersConfigurationFingerprint != metadataFingerprint)
{
Result<Updated> resetMetadataResult = await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> resetMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (resetMetadataResult.IsFailure)
throw new InvalidOperationException(resetMetadataResult.FirstError.Description);
}
// A path template change invalidates the metadata derived from the paths, so the metadata state is reset as well.
if (library.PathTemplateFingerprint is not null && library.PathTemplateFingerprint != pathTemplateFingerprint)
{
Result<Updated> resetPathTemplateMetadataResult = await materializer.ResetMetadataStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (resetPathTemplateMetadataResult.IsFailure)
throw new InvalidOperationException(resetPathTemplateMetadataResult.FirstError.Description);
}
if (library.ArtworkProvidersConfigurationFingerprint is not null && library.ArtworkProvidersConfigurationFingerprint != artworkFingerprint)
{
Result<Updated> resetArtworkResult = await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> resetArtworkResult = await materializer.ResetArtworkStatusForLibraryAsync(unitOfWork, LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (resetArtworkResult.IsFailure)
throw new InvalidOperationException(resetArtworkResult.FirstError.Description);
}
@@ -127,6 +148,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
// update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed.
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
library.PathTemplateFingerprint = pathTemplateFingerprint;
library.UpdatedOnUtc = DateTime.UtcNow;
library.UpdatedBy = Guid.NewGuid();
@@ -139,6 +161,8 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// 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)
@@ -1,10 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
@@ -13,9 +11,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -67,9 +63,20 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService<IDomainEventPublisher>()!;
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// Load the media library, whose type determines the materializer used to create the media library items.
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;
IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
.GetServices<IMediaLibraryScanItemMaterializer>()
.FirstOrDefault(candidate => candidate.SupportedLibraryType == libraryType);
if (materializer is null)
throw new InvalidOperationException($"No media library item materializer exists for media library type '{libraryType}'.");
// Set the initial progress of the scan job; it is a single step job, applying the scan results to the storage medium.
Result<Success> publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
if (publishJobProgressResult.IsFailure)
@@ -80,7 +87,7 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
if (getDeletedPathsResult.IsFailure)
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
// Get the paths of the media library scan staging results that changed since the previous scan, so that the books stored at those paths are re-enriched.
// Get the paths of the media library scan staging results that changed since the previous scan, so that the items stored at those paths are re-enriched.
Result<IReadOnlyList<string>> getChangedPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetChangedPathsAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
if (getChangedPathsResult.IsFailure)
throw new InvalidOperationException(getChangedPathsResult.FirstError.Description);
@@ -90,10 +97,10 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
if (applySnapshotSwapResult.IsFailure)
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
// Reset the enrichment state of the books whose content changed, so that they are re-enriched by the enrichment jobs that follow.
// Reset the enrichment state of the media library items whose content changed, so that they are re-enriched by the enrichment jobs that follow.
if (getChangedPathsResult.Value.Count > 0)
{
Result<Updated> resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
Result<Updated> resetEnrichmentStateResult = await materializer.ResetEnrichmentStateForChangedPathsAsync(unitOfWork, LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
if (resetEnrichmentStateResult.IsFailure)
throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description);
}
@@ -105,25 +112,15 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
await domainEventPublisher.PublishAsync(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// Materialize the books of the media library from the scan snapshot, so that they are browsable even without web metadata.
// Materialize the media library items from the scan snapshot, so that they are browsable even without web metadata.
Result<IReadOnlyList<string>> getPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetPathsAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
if (getPathsResult.IsFailure)
throw new InvalidOperationException(getPathsResult.FirstError.Description);
foreach (string path in getPathsResult.Value)
{
cancellationToken.ThrowIfCancellationRequested();
Result<Success> materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false);
if (materializeItemsResult.IsFailure)
throw new InvalidOperationException(materializeItemsResult.FirstError.Description);
Result<BookEntity?> getExistingBookResult = await unitOfWork.BookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false);
if (getExistingBookResult.IsFailure)
throw new InvalidOperationException(getExistingBookResult.FirstError.Description);
if (getExistingBookResult.Value is not null)
continue;
Result<Created> insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
throw new InvalidOperationException(insertBookResult.FirstError.Description);
}
Result<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
throw new InvalidOperationException(saveChangesResult.FirstError.Description);
@@ -133,6 +130,8 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
if (publishJobProgressResult.IsFailure)
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
// 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)
@@ -175,38 +174,4 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed
return Result.Success;
}
/// <summary>
/// Creates a shell book entity for the file stored at <paramref name="path"/> in the media library identified by <paramref name="libraryId"/>,
/// with a title derived from the file name, and no web metadata yet.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <returns>The created shell book entity.</returns>
private static BookEntity CreateShellBookEntity(Guid libraryId, string path)
{
return new BookEntity
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
Path = path,
Title = GetTitleFromPath(path),
MetadataStatus = MetadataStatus.Pending,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
};
}
/// <summary>
/// Derives a book title from the file name of the provided <paramref name="path"/>, by removing the extension and replacing separators with spaces.
/// </summary>
/// <param name="path">The file system path of the book.</param>
/// <returns>The derived title.</returns>
private static string GetTitleFromPath(string path)
{
string fileName = Path.GetFileNameWithoutExtension(path);
string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim();
return title.Length > 0 ? title : fileName;
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using System;
using System.Collections.Generic;
@@ -38,14 +39,30 @@ internal static class ProviderConfigurationFingerprint
/// Computes the fingerprint of the artwork provider configuration of a media library.
/// </summary>
/// <param name="configurations">The artwork provider configurations of the media library.</param>
/// <param name="shouldAggregateArtworkWhenMissing">Whether the artwork of the media library items is aggregated from multiple providers, when it is missing.</param>
/// <param name="canDownloadMetadataFromWeb">Whether the media library permits downloading data from the web.</param>
/// <returns>The fingerprint of the artwork provider configuration.</returns>
public static string ComputeArtworkFingerprint(IReadOnlyList<LibraryArtworkProviderConfigurationEntity> configurations, bool canDownloadMetadataFromWeb)
public static string ComputeArtworkFingerprint(IReadOnlyList<LibraryArtworkProviderConfigurationEntity> configurations, bool shouldAggregateArtworkWhenMissing, bool canDownloadMetadataFromWeb)
{
StringBuilder canonicalRepresentation = new();
foreach (LibraryArtworkProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank))
canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};");
canonicalRepresentation.Append($"web:{canDownloadMetadataFromWeb};");
canonicalRepresentation.Append($"aggregate:{shouldAggregateArtworkWhenMissing};web:{canDownloadMetadataFromWeb};");
return ComputeFingerprint(canonicalRepresentation.ToString());
}
/// <summary>
/// Computes the fingerprint of the path template of a media library, used to detect whether the template changed
/// since the last scan, and thus whether the metadata of the library items needs to be derived from their paths again.
/// </summary>
/// <param name="parts">The ordered parts of the path template of the media library.</param>
/// <returns>The fingerprint of the path template.</returns>
public static string ComputePathTemplateFingerprint(IReadOnlyList<LibraryPathTemplatePartEntity> parts)
{
StringBuilder canonicalRepresentation = new();
foreach (LibraryPathTemplatePartEntity part in parts.OrderBy(part => part.Position))
canonicalRepresentation.Append($"{part.Kind}|{part.Representation}|{part.IsOptional};");
return ComputeFingerprint(canonicalRepresentation.ToString());
}
@@ -0,0 +1,206 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Materializer for the media library items of the books media library type.
/// </summary>
internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanItemMaterializer
{
private readonly ILibraryPathTemplateService _pathTemplateService;
private readonly IPathService _pathService;
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanItemMaterializer"/> class.
/// </summary>
/// <param name="pathTemplateService">Injected service for deriving the metadata of the books from their paths.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
public BooksMediaLibraryScanItemMaterializer(ILibraryPathTemplateService pathTemplateService, IPathService pathService)
{
_pathTemplateService = pathTemplateService;
_pathService = pathService;
}
/// <summary>
/// The media library type that this materializer supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book;
/// <summary>
/// Resets the enrichment state of the books stored at the provided <paramref name="paths"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose books are reset.</param>
/// <param name="paths">The file system paths of the books whose enrichment state 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>> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection<string> paths, CancellationToken cancellationToken)
{
return await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Materializes the books of the media library from the paths of the media library scan snapshot.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose books are materialized.</param>
/// <param name="scanId">The Id of the media library scan whose results are materialized.</param>
/// <param name="paths">The file system paths of the media library scan snapshot.</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<Success>> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList<string> paths, CancellationToken cancellationToken)
{
// The library holds the path template that describes the structure of the library on disk, used to derive the metadata of each book from its path.
Result<LibraryEntity?> getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
Result<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsFailure)
return domainLibraryResult.Errors;
Library library = domainLibraryResult.Value;
Result<LibraryPathTemplate> pathTemplateResult = _pathTemplateService.ResolveTemplate(library.LibraryType, library.PathTemplate.Parts);
if (pathTemplateResult.IsFailure)
return pathTemplateResult.Errors;
LibraryPathTemplate pathTemplate = pathTemplateResult.Value;
// Books that are already stored are never inserted again, so a re-scan of an unchanged file does not duplicate its book. The existing paths are
// loaded in a single query, instead of one existence check per path, so that the number of round trips does not scale with the size of the library.
List<string> stagedPaths = [.. paths];
Result<IReadOnlyCollection<string>> getExistingPathsResult = await unitOfWork.BookRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false);
if (getExistingPathsResult.IsFailure)
return getExistingPathsResult.Errors;
HashSet<string> existingPaths = [.. getExistingPathsResult.Value];
foreach (string path in paths)
{
cancellationToken.ThrowIfCancellationRequested();
if (existingPaths.Contains(path))
continue;
Result<Created> insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(library, path, pathTemplate), cancellationToken).ConfigureAwait(false);
if (insertBookResult.IsFailure)
return insertBookResult.Errors;
}
return Result.Success;
}
/// <summary>
/// Resets the metadata enrichment status of all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose books are 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>> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken)
{
return await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resets the artwork enrichment status of all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="unitOfWork">The unit of work used to interact with the data access layer.</param>
/// <param name="libraryId">The Id of the media library whose books are 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>> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken)
{
return await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates a shell book entity for the file stored at <paramref name="path"/> in the media library identified by <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library the book belongs to.</param>
/// <param name="path">The file system path of the book.</param>
/// <param name="pathTemplate">The template describing the structure of the media library on disk.</param>
/// <returns>The created shell book entity.</returns>
private BookEntity CreateShellBookEntity(Library library, string path, LibraryPathTemplate pathTemplate)
{
string title = GetTitleFromPath(path);
float? volumeNumber = null;
string relativePath = GetRelativePath(path, library.ContentLocations, _pathService);
Result<Optional<ParsedLibraryPath>> parsedPathResult = _pathTemplateService.Parse(library.LibraryType, pathTemplate, relativePath, _pathService.PathSeparator);
if (parsedPathResult.IsSuccess && parsedPathResult.Value.HasValue)
{
ParsedLibraryPath parsedPath = parsedPathResult.Value.Value;
Optional<string> parsedTitle = parsedPath.GetString(LibraryPathPartKind.Title);
if (parsedTitle.HasValue)
title = parsedTitle.Value;
Optional<int> parsedSeriesNumber = parsedPath.GetInt(LibraryPathPartKind.SeriesNumber);
if (parsedSeriesNumber.HasValue)
volumeNumber = parsedSeriesNumber.Value;
}
return new BookEntity
{
Id = Guid.NewGuid(),
LibraryId = library.Id.Value,
Path = path,
Title = title,
VolumeNumber = volumeNumber,
MetadataStatus = MetadataStatus.Pending,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
};
}
/// <summary>
/// Derives a book title from the file name of the provided <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of the book.</param>
/// <returns>The derived title.</returns>
private static string GetTitleFromPath(string path)
{
string fileName = Path.GetFileNameWithoutExtension(path);
string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim();
return title.Length > 0 ? title : fileName;
}
/// <summary>
/// Gets the path of the book stored at <paramref name="path"/>, relative to the content location of the media library it belongs to.
/// </summary>
/// <param name="path">The absolute file system path of the book.</param>
/// <param name="contentLocations">The content locations of the media library the book belongs to.</param>
/// <param name="pathService">The service used to determine whether the file is inside a content location of the media library.</param>
/// <returns>The path of the book, relative to its content location, or the file name when no content location contains it.</returns>
private static string GetRelativePath(string path, IReadOnlyCollection<FileSystemPathId> contentLocations, IPathService pathService)
{
foreach (FileSystemPathId contentLocation in contentLocations)
{
if (pathService.IsPathWithin(path, contentLocation.Path))
{
string relativePath = path[contentLocation.Path.Length..].TrimStart('\\', '/');
if (relativePath.Length > 0)
return relativePath;
}
}
return Path.GetFileName(path);
}
}
@@ -0,0 +1,409 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
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.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Metadata enricher for the media library items of the books media library type, using the metadata providers configured for the media library.
/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them.
/// </summary>
internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanMetadataEnricher
{
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<BooksMediaLibraryScanMetadataEnricher> _logger;
/// <summary>
/// The media library type that this metadata enricher supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book;
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanMetadataEnricher"/> 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 enriching the metadata.</param>
public BooksMediaLibraryScanMetadataEnricher(IServiceScopeFactory serviceScopeFactory, ILogger<BooksMediaLibraryScanMetadataEnricher> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_logger = logger;
}
/// <summary>
/// Enriches the metadata of the books of the provided media library, using the metadata providers configured for it.
/// </summary>
/// <param name="libraryId">The unique identifier of the media library whose books are enriched.</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 setting determines whether the providers that require access to the web are used during the enrichment.
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 providers requiring the web will not be used.");
else
canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb;
}
// Get the metadata providers configured for the media library, in their configured order, that support the media library type,
// skipping the providers that require access to the web when the media library does not permit downloading data from the web.
Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
if (getConfigurationsResult.IsFailure)
throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
List<IMetadataProvider> providers = [];
foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
{
List<IMetadataProvider> configuredProviders = [.. asyncServiceScope.ServiceProvider
.GetKeyedServices<IMetadataProvider>(configuration.PluginId)
.Where(provider => provider.LookupType == typeof(BookMetadataLookupDto)
&& provider.SupportedLibraryTypes.Contains(LibraryType.Book)
&& (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
if (configuredProviders.Count == 0)
_logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book);
providers.AddRange(configuredProviders);
}
// Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing.
bool shouldAggregateMetadataWhenMissing = 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 metadata will not be aggregated across providers.");
else
shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false;
}
// When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely.
if (providers.Count > 0)
{
Result<int> getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(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;
// The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only
// created once even when the same person is discovered for many books of the same page.
Dictionary<string, MediaContributorEntity> contributorsByNormalizedName = [];
// Process the books that need their metadata enriched 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.GetBooksNeedingMetadataAsync(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;
foreach (BookEntity bookEntity in booksPage)
{
cancellationToken.ThrowIfCancellationRequested();
await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, 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();
contributorsByNormalizedName.Clear();
lastPath = booksPage[^1].Path;
}
}
else
_logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", libraryId.Value);
}
/// <summary>
/// Enriches the metadata of the provided <paramref name="bookEntity"/>, using the provided metadata providers in their configured order,
/// linking the media contributors discovered while enriching to the book.
/// </summary>
/// <param name="bookEntity">The book whose metadata is enriched.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="shouldAggregateMetadataWhenMissing">Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not.</param>
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList<IMetadataProvider> metadataProviders, bool shouldAggregateMetadataWhenMissing, IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, CancellationToken cancellationToken)
{
// Convert the book to a domain object.
Result<Book> getBookResult = bookEntity.ToDomainEntity();
if (getBookResult.IsFailure)
return;
Book book = getBookResult.Value;
BookMetadataLookupDto bookMetadataLookup = 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, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results.
OpenLibraryId: bookEntity.OpenLibraryId,
Title: bookEntity.Title,
Author: null,
LanguageCode: bookEntity.LanguageCode
);
ResolvedMetadata? resolvedMetadata = shouldAggregateMetadataWhenMissing
? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false)
: await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false);
if (resolvedMetadata is null)
{
// No metadata provider returned usable metadata, so the book is marked as failed to enrich, keeping its previous metadata.
bookEntity.MetadataStatus = MetadataStatus.Failed;
bookEntity.UpdatedOnUtc = DateTime.UtcNow;
bookEntity.UpdatedBy = Guid.NewGuid();
return;
}
// Apply the enriched metadata to the book, and copy it onto the tracked entity, without touching the enrichment tracking columns.
book.ApplyMetadata(resolvedMetadata.Metadata);
bookEntity.ApplyMetadataToEntity(book);
// Link the media contributors discovered while enriching to the book, finding or creating a single contributor per person.
List<BookContributorEntity> linkedContributors = [];
List<BookMediaContributor> domainContributors = [];
foreach (MediaContributorDto contributor in resolvedMetadata.Metadata.Contributors ?? [])
{
if (contributor.Name?.DisplayName is null)
continue;
MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false);
MediaContributorRole role = contributor.Role ?? MediaContributorRole.Author;
if (linkedContributors.Any(linkedContributor => linkedContributor.MediaContributorId == contributorEntity.Id && linkedContributor.Role == role))
continue;
linkedContributors.Add(new BookContributorEntity
{
Id = Guid.NewGuid(),
BookId = bookEntity.Id,
MediaContributorId = contributorEntity.Id,
Role = role,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.Empty,
UpdatedBy = null
});
domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value);
}
bookEntity.Contributors.Clear();
bookEntity.Contributors.AddRange(linkedContributors);
book.UpdateContributors(domainContributors);
// Mark the book as enriched by the provider, directly on the tracked entity, since the enrichment state is a persistence concern.
bookEntity.MetadataStatus = MetadataStatus.Enriched;
bookEntity.MetadataProvider = resolvedMetadata.ProviderName;
bookEntity.LastMetadataUpdateUtc = DateTime.UtcNow;
}
/// <summary>
/// Finds the media contributor with the name of the provided <paramref name="contributor"/>, or creates it, caching it by its normalized display name
/// so that a contributor is only created once even when the same person is discovered for many books of the same page.
/// </summary>
/// <param name="mediaContributorRepository">The repository used to persist the media contributors discovered while enriching.</param>
/// <param name="contributorsByNormalizedName">The cache of the media contributors discovered in the current page, keyed by their normalized display name.</param>
/// <param name="contributor">The contributor to find or create.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The found or created media contributor.</returns>
private static async Task<MediaContributorEntity> FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary<string, MediaContributorEntity> contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken)
{
string displayName = contributor.Name!.DisplayName!;
string normalizedDisplayName = displayName.ToLowerInvariant();
if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor))
return cachedContributor;
Result<MediaContributorEntity> getContributorResult = await mediaContributorRepository.FindOrCreateByDisplayNameAsync(displayName, null, cancellationToken).ConfigureAwait(false);
if (getContributorResult.IsFailure)
throw new InvalidOperationException(getContributorResult.FirstError.Description);
contributorsByNormalizedName[normalizedDisplayName] = getContributorResult.Value;
return getContributorResult.Value;
}
/// <summary>
/// Tries the <paramref name="metadataProviders"/> in order, applying the metadata of the first one that returns usable metadata.
/// </summary>
/// <param name="book">The book onto which the metadata is applied.</param>
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied metadata and the provider that supplied it, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<ResolvedMetadata?> TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || string.IsNullOrWhiteSpace(bookMetadata.Title))
continue;
Result<Success> applyMetadataResult = book.ApplyMetadata(bookMetadata);
if (applyMetadataResult.IsFailure)
continue;
return new ResolvedMetadata(bookMetadata, metadataProvider.Name);
}
catch (Exception)
{
// A failing metadata provider must not prevent the other providers from being tried.
}
}
return null;
}
/// <summary>
/// Aggregates the metadata of the <paramref name="book"/> from all the <paramref name="metadataProviders"/>, in their configured order, filling the fields that the earlier providers lack with the values of the later ones.
/// </summary>
/// <param name="book">The book onto which the aggregated metadata is applied.</param>
/// <param name="bookMetadataLookup">The lookup describing the book.</param>
/// <param name="metadataProviders">The metadata providers, in their configured order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The applied aggregated metadata and the providers that contributed to it, or <see langword="null"/> when no provider returned usable metadata.</returns>
private static async Task<ResolvedMetadata?> AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList<IMetadataProvider> metadataProviders, CancellationToken cancellationToken)
{
BookMetadataDto? mergedMetadata = null;
List<string> contributingProviders = [];
foreach (IMetadataProvider metadataProvider in metadataProviders)
{
try
{
MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
if (metadataResult is not BookMetadataDto bookMetadata || string.IsNullOrWhiteSpace(bookMetadata.Title))
continue;
mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata);
contributingProviders.Add(metadataProvider.Name);
// The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely.
bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata);
}
catch (Exception)
{
// A failing metadata provider must not prevent the other providers from being tried.
}
}
if (mergedMetadata is null)
return null;
Result<Success> applyMetadataResult = book.ApplyMetadata(mergedMetadata);
return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)));
}
/// <summary>
/// Enriches the <paramref name="bookMetadataLookup"/> with the identifiers and the title discovered by the already queried metadata providers.
/// </summary>
/// <param name="bookMetadataLookup">The lookup to enrich.</param>
/// <param name="bookMetadata">The metadata discovered by the already queried metadata providers.</param>
/// <returns>The enriched lookup.</returns>
private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata)
{
string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value;
string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId;
string? title = bookMetadataLookup.Title ?? bookMetadata.Title;
return bookMetadataLookup with
{
Isbn = isbn,
OpenLibraryId = openLibraryId,
Title = title
};
}
/// <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, "EnrichingMetadata");
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 metadata resolved for a book, along with the providers that supplied it.
/// </summary>
/// <param name="Metadata">The resolved metadata of the book.</param>
/// <param name="ProviderName">The name of the provider, or the providers, that supplied the metadata.</param>
private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName);
}