diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs
new file mode 100644
index 00000000..58bdb569
--- /dev/null
+++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs
@@ -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;
+
+///
+/// Interface for the media library scan job for discovering music file system items.
+///
+public interface IMusicFileSystemDiscoveryJob : IMediaLibraryScanJob
+{
+}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs
new file mode 100644
index 00000000..3c454483
--- /dev/null
+++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs
@@ -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;
+
+///
+/// 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.
+///
+public interface IMusicMetadataExtractionJob : IMediaLibraryScanJob
+{
+}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs
new file mode 100644
index 00000000..7dd2cf48
--- /dev/null
+++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs
@@ -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;
+
+///
+/// Interface defining a media library scanner for a music media library type.
+///
+public interface IMusicLibraryTypeScanner : IMediaTypeScanner
+{
+}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs
new file mode 100644
index 00000000..0965e084
--- /dev/null
+++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs
@@ -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;
+
+///
+/// Media library scanner for a music media library type.
+///
+internal class MusicLibraryTypeScanner : IMusicLibraryTypeScanner
+{
+ private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
+
+ ///
+ /// The media library type that this media library scanner supports.
+ ///
+ public LibraryType SupportedLibraryType { get; } = LibraryType.Music;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating media library scan jobs.
+ public MusicLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
+ {
+ _mediaScanJobFactory = mediaScanJobFactory;
+ }
+
+ ///
+ /// Creates the media library scan jobs for the provided media library.
+ ///
+ /// The unique identifier of the media library for which to create the media library scan jobs.
+ /// A collection of media library scan jobs.
+ public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId)
+ {
+ // Declare the list of jobs that this scanner requires.
+ IMusicFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId);
+ IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob(libraryId);
+ IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob(libraryId);
+ IMusicMetadataExtractionJob musicMetadataExtractionJob = _mediaScanJobFactory.CreateJob(libraryId);
+ IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob(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(libraryId);
+ IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId);
+ IMediaLibraryScanArtworkEnrichmentJob mediaLibraryScanArtworkEnrichmentJob = _mediaScanJobFactory.CreateJob(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;
+ }
+}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs
index c4eeea2d..cf805d40 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs
@@ -32,7 +32,7 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService
/// An representing either a successful operation, or an error.
public Result SetDefaultDirectories(string rootPath)
{
- // make sure the root path exists
+ // Make sure the root path exists.
Result 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 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 createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName);
diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs
index 03c35de9..b6f3fd9f 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileTypeService.cs
@@ -54,22 +54,22 @@ public class FileTypeService : IFileTypeService
/// An containing the type of image or an error.
public async Task> 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 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
/// if the file is a SVG image, otherwise.
private bool IsSvg(string initialContent, string path)
{
- // check if it starts with The path of the media library item, relative to the root of its content location.
/// The character used to separate path segments on the current platform.
///
- /// An containing either the derived metadata, or an error. A successful result whose value is
+ /// An containing either the derived metadata, or an error. A successful result whose value has no value
/// means the path does not match the template.
///
- Result Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator);
+ Result> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator);
}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs
index ecd9fef5..2f412cb4 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs
@@ -96,13 +96,13 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
/// The path of the media library item, relative to the root of its content location.
/// The character used to separate path segments on the current platform.
///
- /// An containing either the derived metadata, or an error. A successful result whose value is
+ /// An containing either the derived metadata, or an error. A successful result whose value has no value
/// means the path does not match the template.
///
- public Result Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator)
+ public Result> Parse(LibraryType libraryType, LibraryPathTemplate template, string relativePath, char pathSeparator)
{
if (string.IsNullOrWhiteSpace(relativePath) || template.IsEmpty)
- return Result.Success(null);
+ return Result>.Success(Optional.None());
Result 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.Success(null);
+ return Result>.Success(Optional.None());
Dictionary 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.Success(ParsedLibraryPath.Create(values));
+ return Result>.Success(Optional.Some(ParsedLibraryPath.Create(values)));
}
///
@@ -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);
}
diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs
index bb976ead..f75e5d94 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactory.cs
@@ -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(),
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(),
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}'.")
};
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs
new file mode 100644
index 00000000..000eb03c
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs
@@ -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;
+
+///
+/// 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.
+///
+internal static class MusicMetadataAggregator
+{
+ ///
+ /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields.
+ ///
+ /// The first artist metadata to merge, whose values have priority.
+ /// The second artist metadata, filling the fields that the first metadata lacks.
+ /// The merged artist metadata.
+ 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}"));
+ }
+
+ ///
+ /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields.
+ ///
+ /// The first album metadata to merge, whose values have priority.
+ /// The second album metadata, filling the fields that the first metadata lacks.
+ /// The merged album metadata.
+ 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));
+ }
+
+ ///
+ /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields.
+ ///
+ /// The first audio metadata to merge, whose values have priority.
+ /// The second audio metadata, filling the fields that the first metadata lacks.
+ /// The merged audio metadata.
+ 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()));
+ }
+
+ ///
+ /// Merges the release information of the two metadata, keeping the first non-null value of each field.
+ ///
+ /// The first release information, whose values have priority.
+ /// The second release information, filling the fields that the first one lacks.
+ /// The merged release information, or when both are .
+ 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));
+ }
+
+ ///
+ /// Gets the first non-null value of the two values.
+ ///
+ /// The type of the values.
+ /// The value with priority.
+ /// The fallback value.
+ /// The first non-null value, or when both are .
+ private static T? First(T? first, T? second)
+ {
+ return first is not null && !IsEmpty(first) ? first : second;
+ }
+
+ ///
+ /// Determines whether the provided value is an empty string.
+ ///
+ /// The type of the value.
+ /// The value to check.
+ /// when the value is an empty string, otherwise .
+ private static bool IsEmpty(T? value)
+ {
+ return value is string text && string.IsNullOrWhiteSpace(text);
+ }
+
+ ///
+ /// Returns the union of the two collections, de-duplicated by the key, keeping the items of the first collection on key conflicts.
+ ///
+ /// The type of the collection items.
+ /// The first collection, whose items have priority.
+ /// The second collection.
+ /// The function used to extract the de-duplication key of an item.
+ /// The union of the two collections, or when both are .
+ private static List? Union(List? first, List? second, Func keySelector)
+ where T : class
+ {
+ if (first is null && second is null)
+ return null;
+
+ Dictionary seen = new(StringComparer.OrdinalIgnoreCase);
+ List result = [];
+
+ void AddRange(List? items)
+ {
+ foreach (T item in items ?? [])
+ if (seen.TryAdd(keySelector(item) ?? string.Empty, item))
+ result.Add(item);
+ }
+
+ AddRange(first);
+ AddRange(second);
+ return result;
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs
new file mode 100644
index 00000000..9e6c6f1e
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs
@@ -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;
+
+///
+/// Media library scan job for discovering music file system items.
+///
+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 s_audioExtensions = new(
+ [
+ ".mp3", ".flac", ".m4a", ".aac", ".ogg", ".opus",
+ ".wav", ".wma", ".aiff", ".aif", ".ape", ".wv",
+ ".dsf", ".dff", ".mka"
+ ],
+ StringComparer.OrdinalIgnoreCase
+ );
+ private readonly IServiceScopeFactory _serviceScopeFactory;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ ///
+ /// 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.
+ ///
+ public MusicFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ }
+
+ ///
+ /// Executes the payload of the media library scan job.
+ ///
+ /// The type of the input parameter representing the data to be processed by this payload.
+ /// The id of the media library scan job.
+ /// The input data to be processed by this payload.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(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()!;
+ IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
+ IFileProviderService fileProviderService = asyncServiceScope.ServiceProvider.GetService()!;
+ IDirectoryProviderService directoryProviderService = asyncServiceScope.ServiceProvider.GetService()!;
+
+ MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
+
+ // Get the library from the repository.
+ Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
+ throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
+
+ // Convert it to a domain object.
+ Result 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? fingerprintsByPath = null;
+ if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
+ {
+ Result> 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 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 stagingBatch = [];
+ List 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 insertResult = await unitOfWork.LibraryScanStagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
+ if (insertResult.IsFailure)
+ throw new InvalidOperationException(insertResult.FirstError.Description);
+ }
+ if (fingerprintBatch.Count > 0)
+ {
+ Result 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);
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The path of the root directory from which to start collecting files.
+ /// The service used to enumerate the files of a directory.
+ /// The service used to enumerate the subdirectories of a directory.
+ /// Whether to skip the directories whose last write time has not changed since the last scan, or not.
+ /// The directory scan fingerprints of the library, mapped by the directory path. Can be when the fast skip is disabled.
+ /// The batch of discovered files that is written to the staging results when it reaches the batch size.
+ /// The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.
+ /// The repository used to write the discovered files to the staging results.
+ /// The repository used to write the directory scan fingerprints to the storage medium.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveOptimization)]
+ private async Task DiscoverContentLocationAsync(
+ string rootDirectoryPath,
+ IFileProviderService fileProviderService,
+ IDirectoryProviderService directoryProviderService,
+ bool shouldSkipUnchangedDirectories,
+ Dictionary? fingerprintsByPath,
+ List stagingBatch,
+ List fingerprintBatch,
+ ILibraryScanStagingResultsRepository stagingResultsRepository,
+ IDirectoryScanFingerprintRepository directoryScanFingerprintRepository,
+ CancellationToken cancellationToken)
+ {
+ Result rootPathResult = FileSystemPathId.Create(rootDirectoryPath);
+ if (rootPathResult.IsFailure)
+ return;
+
+ Queue 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> 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 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> 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 getSizeResult = fileProviderService.GetSize(filePath);
+ if (getSizeResult.IsSuccess && getSizeResult.Value.HasValue)
+ size = getSizeResult.Value.Value;
+
+ long ticks = 0;
+ Result> 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 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> getSubdirectoriesResult = directoryProviderService.GetSubdirectoryPaths(currentDirectory, true);
+ if (getSubdirectoriesResult.IsSuccess)
+ {
+ foreach (FileSystemPathId subdirectory in getSubdirectoriesResult.Value)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ directoryQueue.Enqueue(subdirectory);
+ }
+ }
+ }
+ }
+
+ ///
+ /// Publishes a job progress update.
+ ///
+ /// The service used to publish the progress update.
+ /// The composite unique identifier of a media library scan.
+ /// The current job progress.
+ /// The total job progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
+ {
+ Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "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;
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs
new file mode 100644
index 00000000..cc5143b6
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs
@@ -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;
+
+///
+/// Derives the structure of a music library on disk from the file system path of a music file.
+///
+internal static class MusicLibraryPathStructure
+{
+ ///
+ /// Matches the name of a directory that holds one disc of a multi-disc album, like "Disc 1" or "CD2".
+ ///
+ private static readonly Regex s_discDirectoryPattern = new(@"^(?:disk|disc|cd)\s*\d+$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
+
+ ///
+ /// Gets the on-disk directory of the album the track stored at 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.
+ ///
+ /// The file system path of the track whose album directory is retrieved.
+ /// The file system path of the album directory, or the directory of the track when it cannot be resolved.
+ 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;
+ }
+
+ ///
+ /// Gets the name of the on-disk release type directory of the track stored at , 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.
+ ///
+ /// The file system path of the track whose release type directory is retrieved.
+ /// The name of the on-disk release type directory, or when the library does not use one.
+ 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;
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs
new file mode 100644
index 00000000..9c40388c
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs
@@ -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;
+
+///
+/// Materializer for the media library items of the music media library type.
+///
+internal sealed class MusicMediaLibraryScanItemMaterializer : IMediaLibraryScanItemMaterializer
+{
+ private const string UNKNOWN_ARTIST_NAME = "Unknown Artist";
+ private const string UNKNOWN_ALBUM_TITLE = "Unknown Album";
+
+ ///
+ /// The media library type that this materializer supports.
+ ///
+ public LibraryType SupportedLibraryType => LibraryType.Music;
+
+ ///
+ /// Resets the enrichment state of the tracks stored at the provided , together with their albums and artists.
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose tracks are reset.
+ /// The file system paths of the tracks whose enrichment state is reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken)
+ {
+ return await unitOfWork.TrackRepository.ResetEnrichmentStateForPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Materializes the artists, albums and tracks of the media library from the metadata staged for the media library scan.
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose items are materialized.
+ /// The Id of the media library scan whose results are materialized.
+ /// The file system paths of the media library scan snapshot.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList 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> getStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.GetByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false);
+ if (getStagedMetadataResult.IsFailure)
+ return getStagedMetadataResult.Errors;
+ IReadOnlyList 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 stagedPaths = [.. stagedMetadata.Select(stagedItem => stagedItem.Path)];
+ Result> getExistingPathsResult = await unitOfWork.TrackRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false);
+ if (getExistingPathsResult.IsFailure)
+ return getExistingPathsResult.Errors;
+ HashSet 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 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 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 albumGroup in artistGroup.GroupBy(stagedItem => MusicLibraryPathStructure.GetAlbumDirectory(stagedItem.Path), StringComparer.OrdinalIgnoreCase))
+ {
+ List 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 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 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 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 insertTrackResult = await unitOfWork.TrackRepository.InsertAsync(newTrack, cancellationToken).ConfigureAwait(false);
+ if (insertTrackResult.IsFailure)
+ return insertTrackResult.Errors;
+ }
+ }
+ }
+ }
+
+ if (newArtist is not null)
+ {
+ Result 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 deleteStagedMetadataResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.DeleteByScanIdAsync(scanId, cancellationToken).ConfigureAwait(false);
+ if (deleteStagedMetadataResult.IsFailure)
+ return deleteStagedMetadataResult.Errors;
+
+ return Result.Success;
+ }
+
+ ///
+ /// Resets the metadata enrichment status of all the artists, albums and tracks of the media library identified by .
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose items are reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken)
+ {
+ Result resetArtistsResult = await unitOfWork.ArtistRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
+ if (resetArtistsResult.IsFailure)
+ return resetArtistsResult.Errors;
+ Result resetAlbumsResult = await unitOfWork.AlbumRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
+ if (resetAlbumsResult.IsFailure)
+ return resetAlbumsResult.Errors;
+ return await unitOfWork.TrackRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resets the artwork enrichment status of all the artists, albums and tracks of the media library identified by .
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose artwork is reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken)
+ {
+ return await unitOfWork.MusicArtworkRepository.ResetStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Gets the name of the artist of the provided staged , falling back to a placeholder when the metadata does not provide one.
+ ///
+ /// The staged music metadata item whose artist name is retrieved.
+ /// The name of the artist.
+ private static string GetArtistName(MusicLibraryScanItemMetadataEntity stagedItem)
+ {
+ return string.IsNullOrWhiteSpace(stagedItem.ArtistName) ? UNKNOWN_ARTIST_NAME : stagedItem.ArtistName;
+ }
+
+ ///
+ /// Gets the title of the release of the provided staged , falling back to a placeholder when the metadata does not provide one.
+ ///
+ /// The staged music metadata item whose release title is retrieved.
+ /// The title of the release.
+ private static string GetAlbumTitle(MusicLibraryScanItemMetadataEntity stagedItem)
+ {
+ return string.IsNullOrWhiteSpace(stagedItem.ReleaseName) ? UNKNOWN_ALBUM_TITLE : stagedItem.ReleaseName;
+ }
+
+ ///
+ /// Creates a new artist entity for the media library identified by .
+ ///
+ /// The Id of the media library the artist belongs to.
+ /// The name of the artist.
+ /// The MusicBrainz identifier of the artist, read from the tags, if applicable.
+ /// The created artist entity.
+ 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
+ };
+ }
+
+ ///
+ /// Creates a new album entity for the artist identified by , using the metadata of the provided staged .
+ ///
+ /// The Id of the media library the album belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The title of the album.
+ /// The staged music metadata items of the album.
+ /// The MusicBrainz identifier of the release, read from the tags, if applicable.
+ /// The MusicBrainz identifier of the release group, read from the tags, if applicable.
+ /// The MusicBrainz identifier of the release artist, read from the tags, if applicable.
+ /// The created album entity.
+ private static AlbumEntity CreateAlbumEntity(Guid libraryId, Guid artistId, string title, IReadOnlyList 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
+ };
+ }
+
+ ///
+ /// Creates a new track entity for the album identified by , using the metadata of the provided staged .
+ ///
+ /// The Id of the media library the track belongs to.
+ /// The Id of the album the track belongs to.
+ /// The staged music metadata item of the track.
+ /// The created track entity.
+ 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
+ };
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs
new file mode 100644
index 00000000..2c631cb0
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs
@@ -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;
+
+///
+/// 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.
+///
+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 _logger;
+
+ ///
+ /// The media library type that this metadata enricher supports.
+ ///
+ public LibraryType SupportedLibraryType => LibraryType.Music;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected factory for creating scopes in which services are requested.
+ /// Injected logger used to report the issues encountered while enriching the metadata.
+ public MusicMediaLibraryScanMetadataEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Enriches the metadata of the artists, the albums and the tracks of the provided media library, using the metadata providers configured for it.
+ ///
+ /// The unique identifier of the media library whose items are enriched.
+ /// The unique identifier of the media library scan.
+ /// The unique identifier of the user that initiated the media library scan.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ public async Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken)
+ {
+ await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
+ IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService()!;
+ IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
+
+ MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(scanId, userId);
+
+ // Load the media library, whose 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 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> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getConfigurationsResult.IsFailure)
+ throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
+ List providers = [];
+ foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
+ {
+ List configuredProviders = [.. asyncServiceScope.ServiceProvider
+ .GetKeyedServices(configuration.PluginId)
+ .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Music)
+ && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
+ if (configuredProviders.Count == 0)
+ _logger.LogWarning("No 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 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 getArtistsToEnrichCountResult = await unitOfWork.ArtistRepository.GetArtistsNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getArtistsToEnrichCountResult.IsFailure)
+ throw new InvalidOperationException(getArtistsToEnrichCountResult.FirstError.Description);
+
+ Result getAlbumsToEnrichCountResult = await unitOfWork.AlbumRepository.GetAlbumsNeedingMetadataCountAsync(libraryId.Value, cancellationToken).ConfigureAwait(false);
+ if (getAlbumsToEnrichCountResult.IsFailure)
+ throw new InvalidOperationException(getAlbumsToEnrichCountResult.FirstError.Description);
+
+ Result 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 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 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 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> getArtistsPageResult = await unitOfWork.ArtistRepository.GetArtistsNeedingMetadataAsync(libraryId.Value, lastName, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
+ if (getArtistsPageResult.IsFailure)
+ throw new InvalidOperationException(getArtistsPageResult.FirstError.Description);
+ IReadOnlyList artistsPage = getArtistsPageResult.Value;
+ if (artistsPage.Count == 0)
+ break;
+
+ foreach (ArtistEntity artistEntity in artistsPage)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ 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 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 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);
+ }
+
+ ///
+ /// Enriches the metadata of the provided , its albums and its tracks, using the provided metadata providers in their configured order.
+ ///
+ /// The artist whose metadata, and the metadata of its albums and tracks, is enriched.
+ /// The metadata providers, in their configured order.
+ /// Whether the metadata is aggregated from multiple providers, when fields are missing, or not.
+ /// The unit of work used to persist the enriched artist.
+ /// The cache of the media contributors discovered in the current page, keyed by their normalized display name.
+ /// The callback invoked after each artist, album or track is processed.
+ /// Cancellation token that can be used to stop the execution.
+ private async Task EnrichArtistAsync(ArtistEntity artistEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IUnitOfWork unitOfWork, Dictionary contributorsByNormalizedName, Func onItemProcessed, CancellationToken cancellationToken)
+ {
+ // Convert the artist aggregate, together with its albums and tracks, to a domain object.
+ Result 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? resolvedArtist = await ResolveAndApplyMetadataAsync(
+ artistLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableArtistMetadata,
+ (first, second) => MusicMetadataAggregator.Merge(first, second),
+ async metadata =>
+ {
+ List 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? resolvedAlbum = await ResolveAndApplyMetadataAsync(
+ albumLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableAlbumMetadata,
+ (first, second) => MusicMetadataAggregator.Merge(first, second),
+ async metadata =>
+ {
+ List 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? resolvedTrack = await ResolveAndApplyMetadataAsync(
+ trackLookup, metadataProviders, shouldAggregateMetadataWhenMissing, IsUsableAudioMetadata,
+ (first, second) => MusicMetadataAggregator.Merge(first, second),
+ async metadata =>
+ {
+ List 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 updateResult = await unitOfWork.ArtistRepository.UpdateAsync(enrichedEntity, cancellationToken).ConfigureAwait(false);
+ if (updateResult.IsFailure)
+ throw new InvalidOperationException(updateResult.FirstError.Description);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The type of the lookup the metadata providers must accept.
+ /// The type of the metadata returned by the metadata providers.
+ /// The lookup describing the media item.
+ /// The metadata providers, in their configured order.
+ /// Whether the metadata of every usable provider is merged, or only the first one is used.
+ /// The predicate that determines whether a metadata result is usable.
+ /// The function that merges two metadata results.
+ /// The function that applies a metadata result to the media item.
+ /// The logger used to report the metadata providers that fail.
+ /// Cancellation token that can be used to stop the execution.
+ /// The applied metadata and the name of the provider, or the providers, that supplied it, or when no provider returned applicable metadata.
+ private static async Task?> ResolveAndApplyMetadataAsync(MetadataLookupDto lookup, IReadOnlyList metadataProviders, bool shouldAggregate, Func isUsable, Func merge, Func>> applyAsync, ILogger logger, CancellationToken cancellationToken)
+ where TLookup : MetadataLookupDto
+ where TMetadata : MetadataDto
+ {
+ if (shouldAggregate)
+ return await ResolveAggregatedAndApplyAsync(lookup, metadataProviders, isUsable, merge, applyAsync, logger, cancellationToken).ConfigureAwait(false);
+ return await ResolveFirstAndApplyAsync(lookup, metadataProviders, isUsable, applyAsync, logger, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The type of the lookup the metadata providers must accept.
+ /// The type of the metadata returned by the metadata providers.
+ /// The lookup describing the media item.
+ /// The metadata providers, in their configured order.
+ /// The predicate that determines whether a metadata result is usable.
+ /// The function that applies a metadata result to the media item.
+ /// The logger used to report the metadata providers that fail.
+ /// Cancellation token that can be used to stop the execution.
+ /// The applied metadata and the name of the provider that supplied it, or when no provider returned applicable metadata.
+ private static async Task?> ResolveFirstAndApplyAsync(MetadataLookupDto lookup, IReadOnlyList metadataProviders, Func isUsable, Func>> 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 applyResult = await applyAsync(metadata).ConfigureAwait(false);
+ if (applyResult.IsFailure)
+ continue;
+ return new ResolvedMetadata(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;
+ }
+
+ ///
+ /// Queries every provider, merges the metadata of the usable ones, and applies the merged metadata once.
+ ///
+ /// The type of the lookup the metadata providers must accept.
+ /// The type of the metadata returned by the metadata providers.
+ /// The lookup describing the media item.
+ /// The metadata providers, in their configured order.
+ /// The predicate that determines whether a metadata result is usable.
+ /// The function that merges two metadata results.
+ /// The function that applies a metadata result to the media item.
+ /// The logger used to report the metadata providers that fail.
+ /// Cancellation token that can be used to stop the execution.
+ /// The applied merged metadata and the names of the providers that supplied it, or when no provider returned applicable metadata.
+ private static async Task?> ResolveAggregatedAndApplyAsync(MetadataLookupDto lookup, IReadOnlyList metadataProviders, Func isUsable, Func merge, Func>> applyAsync, ILogger logger, CancellationToken cancellationToken)
+ where TLookup : MetadataLookupDto
+ where TMetadata : MetadataDto
+ {
+ TMetadata? mergedMetadata = default;
+ List 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 applyResult = await applyAsync(mergedMetadata).ConfigureAwait(false);
+ if (applyResult.IsFailure)
+ return null;
+ return new ResolvedMetadata(mergedMetadata, string.Join(", ", providerNames.Distinct(StringComparer.Ordinal)));
+ }
+
+ ///
+ /// Finds the media contributor with the name of the provided , 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.
+ ///
+ /// The metadata contributors to resolve.
+ /// The repository used to persist the media contributors discovered while enriching.
+ /// The cache of the media contributors discovered in the current page, keyed by their normalized display name.
+ /// Cancellation token that can be used to stop the execution.
+ /// The resolved domain media contributors, already carrying their persisted identifiers.
+ private static async Task> ResolveContributorsAsync(IReadOnlyCollection? contributors, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken)
+ {
+ List 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 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 domainContributorResult = MusicMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role);
+ if (domainContributorResult.IsFailure)
+ continue;
+ resolvedContributors.Add(domainContributorResult.Value);
+ }
+ return resolvedContributors;
+ }
+
+ ///
+ /// Copies the metadata enrichment tracking columns of the tracked artist, albums and tracks onto the rebuilt repository entity graph.
+ ///
+ /// The rebuilt repository entity graph that receives the tracking columns.
+ /// The tracked repository entity graph that carries the tracking columns.
+ 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;
+ }
+ }
+ }
+
+ ///
+ /// Determines whether the provided artist metadata is usable, meaning it has a name.
+ ///
+ /// The metadata to validate.
+ /// when the metadata is usable, otherwise .
+ private static bool IsUsableArtistMetadata(ArtistMetadataDto metadata)
+ {
+ return !string.IsNullOrWhiteSpace(metadata.Name);
+ }
+
+ ///
+ /// Determines whether the provided album metadata is usable, meaning it has a title.
+ ///
+ /// The metadata to validate.
+ /// when the metadata is usable, otherwise .
+ private static bool IsUsableAlbumMetadata(AlbumMetadataDto metadata)
+ {
+ return !string.IsNullOrWhiteSpace(metadata.Title);
+ }
+
+ ///
+ /// Determines whether the provided audio metadata is usable, meaning it has a title.
+ ///
+ /// The metadata to validate.
+ /// when the metadata is usable, otherwise .
+ private static bool IsUsableAudioMetadata(AudioMetadataDto metadata)
+ {
+ return !string.IsNullOrWhiteSpace(metadata.Title);
+ }
+
+ ///
+ /// Publishes a job progress update.
+ ///
+ /// The service used to publish the progress update.
+ /// The unique identifier of the media library being scanned.
+ /// The composite unique identifier of a media library scan.
+ /// The current job progress.
+ /// The total job progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
+ {
+ Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "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;
+ }
+
+ ///
+ /// The metadata resolved for a media library item, along with the provider, or providers, that supplied it.
+ ///
+ /// The type of the resolved metadata.
+ /// The resolved metadata of the item.
+ /// The name of the provider, or the providers, that supplied the metadata.
+ private sealed record ResolvedMetadata(TMetadata Metadata, string ProviderName) where TMetadata : MetadataDto;
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs
new file mode 100644
index 00000000..b89f3a1b
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs
@@ -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;
+
+///
+/// Media library scan job for extracting the metadata of the discovered music file system items.
+///
+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 _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ ///
+ /// Injected factory for creating scopes in which services are requested.
+ /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
+ ///
+ /// Injected service for logging.
+ public MusicMetadataExtractionJob(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ {
+ _serviceScopeFactory = serviceScopeFactory;
+ _logger = logger;
+ }
+
+ ///
+ /// Executes the payload of the media library scan job.
+ ///
+ /// The type of the input parameter representing the data to be processed by this payload.
+ /// The id of the media library scan job.
+ /// The input data to be processed by this payload.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(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()!;
+ IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
+
+ 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 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 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()!;
+ IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!;
+ Result 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> getPathsResult = await unitOfWork.LibraryScanStagingResultsRepository.GetPathsNeedingRehashAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
+ if (getPathsResult.IsFailure)
+ throw new InvalidOperationException(getPathsResult.FirstError.Description);
+ IReadOnlyList paths = getPathsResult.Value;
+
+ // Set the initial progress of the scan job.
+ Result 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 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 insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
+ if (insertBatchResult.IsFailure)
+ throw new InvalidOperationException(insertBatchResult.FirstError.Description);
+ Result 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 insertBatchResult = await unitOfWork.MusicLibraryScanItemMetadataRepository.InsertRangeAsync(metadataBatch, cancellationToken).ConfigureAwait(false);
+ if (insertBatchResult.IsFailure)
+ throw new InvalidOperationException(insertBatchResult.FirstError.Description);
+ Result 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);
+ }
+ }
+
+ ///
+ /// Extracts the metadata of the music file stored at .
+ ///
+ /// The file system path of the music file whose metadata is extracted.
+ /// The content locations of the media library the music file belongs to.
+ /// The type of the media library the music file belongs to.
+ /// The template describing the structure of the media library on disk.
+ /// The service used to derive the metadata from the path of the music file.
+ /// The service used to determine the path separator and whether the file is inside the content locations of the media library.
+ /// The staged music metadata item.
+ private MusicLibraryScanItemMetadataEntity ExtractMetadata(string path, IReadOnlyCollection contentLocations, LibraryType libraryType, LibraryPathTemplate pathTemplate, ILibraryPathTemplateService pathTemplateService, IPathService pathService)
+ {
+ string relativePath = GetRelativePath(path, contentLocations, pathService);
+ Result> 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 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 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
+ };
+ }
+
+ ///
+ /// Parses the provided tag as a globally unique identifier.
+ ///
+ /// The tag value to parse.
+ /// The parsed identifier, or when the value is missing or malformed.
+ private static Guid? ParseGuid(string? value)
+ {
+ return Guid.TryParse(value, out Guid parsedValue) ? parsedValue : null;
+ }
+
+ ///
+ /// Reads the text frames of the ID3v2 tag of the provided 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.
+ ///
+ /// The file whose ID3v2 text frames are read.
+ /// The text values of the ID3v2 frames, keyed by their description, or an empty dictionary when the file has no ID3v2 tag.
+ private static Dictionary GetId3v2ExtendedFields(TagLib.File tagFile)
+ {
+ Dictionary 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;
+ }
+
+ ///
+ /// Reads an extended tag that the tagging library does not expose as a property, from whichever container tag of the file carries it.
+ ///
+ /// The file whose extended tags are read.
+ /// The text frames of the ID3v2 tag of the file, read once for the whole file.
+ /// The candidate names of the extended tag to read, in the order they are tried.
+ /// The first non-empty value found, or when the file carries none of the provided tags.
+ private static string? GetExtendedField(TagLib.File tagFile, IReadOnlyDictionary 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;
+ }
+
+ ///
+ /// Reads an extended tag with the provided from the provided , according to its container format.
+ ///
+ /// The container tag whose extended tags are read.
+ /// The name of the extended tag to read.
+ /// The value of the extended tag, or when the tag does not carry it.
+ 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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The file whose extended tags are read.
+ /// The text frames of the ID3v2 tag of the file, read once for the whole file.
+ /// The candidate names of the extended tag to read, in the order they are tried.
+ /// Every non-empty value found, or an empty list when the file carries none of the provided tags.
+ private static List GetExtendedFields(TagLib.File tagFile, IReadOnlyDictionary id3v2ExtendedFields, params string[] keys)
+ {
+ List 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;
+ }
+
+ ///
+ /// Reads every value of an extended tag with the provided from the provided , according to its container format.
+ ///
+ /// The container tag whose extended tags are read.
+ /// The name of the extended tag to read.
+ /// Every value of the extended tag, or an empty list when the tag does not carry it.
+ private static List 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 [];
+ }
+ }
+
+ ///
+ /// Parses a ReplayGain value, optionally suffixed with its unit, into a decimal.
+ ///
+ /// The value to parse.
+ /// The parsed decimal, or when the value is missing or malformed.
+ 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;
+ }
+
+ ///
+ /// Gets the path of the music file stored at , relative to the content location of the media library it belongs to.
+ ///
+ /// The absolute file system path of the music file.
+ /// The content locations of the media library the music file belongs to.
+ /// The service used to determine whether the file is inside a content location of the media library.
+ /// The path of the music file, relative to its content location, or the file name when no content location contains it.
+ private static string GetRelativePath(string path, IReadOnlyCollection 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);
+ }
+
+ ///
+ /// Publishes a job progress update.
+ ///
+ /// The service used to publish the progress update.
+ /// The composite unique identifier of a media library scan.
+ /// The current job progress.
+ /// The total job progress.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
+ {
+ Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "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;
+ }
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs
new file mode 100644
index 00000000..2938eec8
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs
@@ -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;
+
+///
+/// Interface defining the materialization of the media library items of a specific media library type from the results of a media library scan.
+///
+internal interface IMediaLibraryScanItemMaterializer
+{
+ ///
+ /// The media library type that this materializer supports.
+ ///
+ LibraryType SupportedLibraryType { get; }
+
+ ///
+ /// Resets the enrichment state of the media library items stored at the provided , so that they are re-enriched, because their content changed since the last scan.
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose items are reset.
+ /// The file system paths of the media library items whose enrichment state is reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> ResetEnrichmentStateForChangedPathsAsync(IUnitOfWork unitOfWork, Guid libraryId, IReadOnlyCollection paths, CancellationToken cancellationToken);
+
+ ///
+ /// Materializes the media library items of the media library from the paths of the media library scan snapshot.
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose items are materialized.
+ /// The Id of the media library scan whose results are materialized.
+ /// The file system paths of the media library scan snapshot.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> MaterializeItemsAsync(IUnitOfWork unitOfWork, Guid libraryId, Guid scanId, IReadOnlyList paths, CancellationToken cancellationToken);
+
+ ///
+ /// Resets the metadata enrichment status of all the media library items of the media library identified by .
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose items are reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> ResetMetadataStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken);
+
+ ///
+ /// Resets the artwork enrichment status of all the media library items of the media library identified by .
+ ///
+ /// The unit of work used to interact with the data access layer.
+ /// The Id of the media library whose artwork is reset.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ Task> ResetArtworkStatusForLibraryAsync(IUnitOfWork unitOfWork, Guid libraryId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs
new file mode 100644
index 00000000..886f2160
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
+
+///
+/// Interface defining the metadata enrichment of the media library items of a specific media library type.
+///
+internal interface IMediaLibraryScanMetadataEnricher
+{
+ ///
+ /// The media library type that this metadata enricher supports.
+ ///
+ LibraryType SupportedLibraryType { get; }
+
+ ///
+ /// Enriches the metadata of the media library items of the provided media library, using the metadata providers configured for it.
+ ///
+ /// The unique identifier of the media library whose items are enriched.
+ /// The unique identifier of the media library scan.
+ /// The unique identifier of the user that initiated the media library scan.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that represents the asynchronous operation.
+ Task EnrichAsync(LibraryId libraryId, ScanId scanId, UserId userId, CancellationToken cancellationToken);
+}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
index 7db6d886..86b77f91 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs
@@ -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
///
/// 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.
///
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 _logger;
///
/// Initializes a new instance of the 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.
///
- /// Injected logger used to report the issues encountered while enriching the metadata.
- public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory, ILogger logger)
+ public MediaLibraryScanMetadataEnrichmentJob(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
- _logger = logger;
}
///
@@ -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 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 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> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
- if (getConfigurationsResult.IsFailure)
- throw new InvalidOperationException(getConfigurationsResult.FirstError.Description);
- List providers = [];
- foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank))
- {
- List configuredProviders = [.. asyncServiceScope.ServiceProvider
- .GetKeyedServices(configuration.PluginId)
- .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book)
- && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))];
- if (configuredProviders.Count == 0)
- _logger.LogWarning("No 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()
+ .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 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 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 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 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> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
- if (getBooksPageResult.IsFailure)
- throw new InvalidOperationException(getBooksPageResult.FirstError.Description);
- IReadOnlyList booksPage = getBooksPageResult.Value;
- if (booksPage.Count == 0)
- break;
-
- 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 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);
}
}
-
- ///
- /// Enriches the metadata of the provided , using the provided metadata providers in their configured order,
- /// linking the media contributors discovered while enriching to the book.
- ///
- /// The book whose metadata is enriched.
- /// The metadata providers, in their configured order.
- /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not.
- /// The repository used to persist the enriched book.
- /// The repository used to persist the media contributors discovered while enriching.
- /// The cache of the media contributors discovered in the current page, keyed by their normalized display name.
- /// Cancellation token that can be used to stop the execution.
- private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IBookRepository bookRepository, IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, CancellationToken cancellationToken)
- {
- // Convert the book to a domain object.
- Result 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 linkedContributors = [];
- List 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;
- }
-
- ///
- /// Finds the media contributor with the name of the provided , 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.
- ///
- /// The repository used to persist the media contributors discovered while enriching.
- /// The cache of the media contributors discovered in the current page, keyed by their normalized display name.
- /// The contributor to find or create.
- /// Cancellation token that can be used to stop the execution.
- /// The found or created media contributor.
- private async Task FindOrCreateContributorAsync(IMediaContributorRepository mediaContributorRepository, Dictionary contributorsByNormalizedName, MediaContributorDto contributor, CancellationToken cancellationToken)
- {
- string displayName = contributor.Name!.DisplayName!;
- string normalizedDisplayName = displayName.ToLowerInvariant();
-
- if (contributorsByNormalizedName.TryGetValue(normalizedDisplayName, out MediaContributorEntity? cachedContributor))
- return cachedContributor;
-
- Result 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;
- }
-
- ///
- /// Tries the in order, applying the metadata of the first one that returns usable metadata.
- ///
- /// The book onto which the metadata is applied.
- /// The lookup describing the book.
- /// The metadata providers, in their configured order.
- /// Cancellation token that can be used to stop the execution.
- /// The applied metadata and the provider that supplied it, or when no provider returned usable metadata.
- private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList 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 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;
- }
-
- ///
- /// Aggregates the metadata of the from all the , in their configured order, filling the fields that the earlier providers lack with the values of the later ones.
- ///
- /// The book onto which the aggregated metadata is applied.
- /// The lookup describing the book.
- /// The metadata providers, in their configured order.
- /// Cancellation token that can be used to stop the execution.
- /// The applied aggregated metadata and the providers that contributed to it, or when no provider returned usable metadata.
- private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken)
- {
- BookMetadataDto? mergedMetadata = null;
- List 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 applyMetadataResult = book.ApplyMetadata(mergedMetadata);
- return applyMetadataResult.IsFailure ? null : new ResolvedMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)));
- }
-
- ///
- /// Enriches the with the identifiers and the title discovered by the already queried metadata providers.
- ///
- /// The lookup to enrich.
- /// The metadata discovered by the already queried metadata providers.
- /// The enriched lookup.
- 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
- };
- }
-
- ///
- /// Determines whether the provided is usable, meaning it has a title.
- ///
- /// The metadata to validate.
- /// when the metadata is usable, otherwise .
- private static bool IsUsableMetadata(BookMetadataDto bookMetadata)
- {
- return !string.IsNullOrWhiteSpace(bookMetadata.Title);
- }
-
- ///
- /// Publishes a job progress update.
- ///
- /// The service used to publish the progress update.
- /// The composite unique identifier of a media library scan.
- /// The current job progress.
- /// The total job progress.
- /// Cancellation token that can be used to stop the execution.
- /// An representing either a successful operation, or an error.
- private async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
- {
- Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "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;
- }
-
- ///
- /// The metadata resolved for a book, along with the providers that supplied it.
- ///
- /// The resolved metadata of the book.
- /// The name of the provider, or the providers, that supplied the metadata.
- private sealed record ResolvedMetadata(BookMetadataDto Metadata, string ProviderName);
}
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs
index 40b350c9..73d9af1c 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJob.cs
@@ -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()
+ .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> 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 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 resetMetadataResult = await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ Result 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 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 resetArtworkResult = await unitOfWork.BookRepository.ResetArtworkStatusForLibraryAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
+ Result 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)
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs
index b78a12d1..86556917 100644
--- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs
@@ -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()!;
IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!;
-
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
+ // Load the media library, whose type determines the materializer used to create the media library items.
+ Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
+ throw new InvalidOperationException(getLibraryResult.IsFailure ? getLibraryResult.FirstError.Description : "The media library was not found.");
+ LibraryType libraryType = getLibraryResult.Value.LibraryType;
+
+ IMediaLibraryScanItemMaterializer? materializer = asyncServiceScope.ServiceProvider
+ .GetServices()
+ .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 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> 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 resetEnrichmentStateResult = await unitOfWork.BookRepository.ResetEnrichmentStateForPathsAsync(LibraryId.Value, getChangedPathsResult.Value, cancellationToken).ConfigureAwait(false);
+ Result 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> 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