From 35ac1dbdcbef3b9d5392d06197818ab03b06bc65 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 9 Oct 2026 20:53:00 +0300 Subject: [PATCH] Adds the music library scanning pipeline, its scanner, scan jobs, and path structure --- .../Jobs/IMusicFileSystemDiscoveryJob.cs | 13 + .../Jobs/IMusicMetadataExtractionJob.cs | 14 + .../Scanners/IMusicLibraryTypeScanner.cs | 13 + .../Scanners/MusicLibraryTypeScanner.cs | 81 +++ .../FileSystemStructureSeedService.cs | 8 +- .../Services/FileTypeService.cs | 29 +- .../ILibraryPathTemplateService.cs | 4 +- .../LibraryPathTemplateService.cs | 14 +- .../Scanners/MediaLibraryScannerFactory.cs | 7 +- .../Metadata/MusicMetadataAggregator.cs | 205 ++++++ .../Music/MusicFileSystemDiscoveryJob.cs | 332 +++++++++ .../Audio/Music/MusicLibraryPathStructure.cs | 59 ++ .../MusicMediaLibraryScanItemMaterializer.cs | 312 ++++++++ .../MusicMediaLibraryScanMetadataEnricher.cs | 601 ++++++++++++++++ .../Audio/Music/MusicMetadataExtractionJob.cs | 553 ++++++++++++++ .../IMediaLibraryScanItemMaterializer.cs | 61 ++ .../IMediaLibraryScanMetadataEnricher.cs | 31 + .../MediaLibraryScanMetadataEnrichmentJob.cs | 374 +--------- ...canProviderConfigurationInvalidationJob.cs | 34 +- .../Common/MediaLibraryScanResultsSaveJob.cs | 79 +- .../ProviderConfigurationFingerprint.cs | 21 +- .../BooksMediaLibraryScanItemMaterializer.cs | 206 ++++++ .../BooksMediaLibraryScanMetadataEnricher.cs | 409 +++++++++++ .../Scanners/MusicLibraryTypeScannerTests.cs | 149 ++++ .../FileSystemStructureSeedServiceTests.cs | 11 +- .../LibraryPathTemplateServiceTests.cs | 50 +- .../MediaLibraryScannerFactoryTests.cs | 19 +- .../Metadata/MusicMetadataAggregatorTests.cs | 128 ++++ .../Music/MusicFileSystemDiscoveryJobTests.cs | 379 ++++++++++ .../Music/MusicLibraryPathStructureTests.cs | 133 ++++ ...icMediaLibraryScanItemMaterializerTests.cs | 184 +++++ .../Music/MusicMetadataExtractionJobTests.cs | 277 +++++++ ...iaLibraryScanMetadataEnrichmentJobTests.cs | 673 +----------------- ...oviderConfigurationInvalidationJobTests.cs | 48 +- .../MediaLibraryScanResultsSaveJobTests.cs | 70 +- .../ProviderConfigurationFingerprintTests.cs | 198 ++++++ ...ksMediaLibraryScanItemMaterializerTests.cs | 107 +++ ...ksMediaLibraryScanMetadataEnricherTests.cs | 383 ++++++++++ 38 files changed, 5119 insertions(+), 1150 deletions(-) create mode 100644 src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicFileSystemDiscoveryJob.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Jobs/IMusicMetadataExtractionJob.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/IMusicLibraryTypeScanner.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScanner.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregator.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructure.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializer.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanMetadataEnricher.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJob.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanItemMaterializer.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/IMediaLibraryScanMetadataEnricher.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs create mode 100644 tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs 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 materializeItemsResult = await materializer.MaterializeItemsAsync(unitOfWork, LibraryId.Value, ScanId.Value, getPathsResult.Value, cancellationToken).ConfigureAwait(false); + if (materializeItemsResult.IsFailure) + throw new InvalidOperationException(materializeItemsResult.FirstError.Description); - Result getExistingBookResult = await unitOfWork.BookRepository.GetByPathAsync(LibraryId.Value, path, cancellationToken).ConfigureAwait(false); - if (getExistingBookResult.IsFailure) - throw new InvalidOperationException(getExistingBookResult.FirstError.Description); - if (getExistingBookResult.Value is not null) - continue; - - Result insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(LibraryId.Value, path), cancellationToken).ConfigureAwait(false); - if (insertBookResult.IsFailure) - throw new InvalidOperationException(insertBookResult.FirstError.Description); - } Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) throw new InvalidOperationException(saveChangesResult.FirstError.Description); @@ -133,6 +130,8 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + // Increment the number of completed jobs progress. + await domainEventPublisher.PublishAsync(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); Status = LibraryScanJobStatus.Completed; // When this job has no linked children, it is the last job in the directed acyclic job graph, and the scan is completed. if (Children.Count == 0) @@ -175,38 +174,4 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed return Result.Success; } - - /// - /// Creates a shell book entity for the file stored at in the media library identified by , - /// with a title derived from the file name, and no web metadata yet. - /// - /// The Id of the media library the book belongs to. - /// The file system path of the book. - /// The created shell book entity. - private static BookEntity CreateShellBookEntity(Guid libraryId, string path) - { - return new BookEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - Path = path, - Title = GetTitleFromPath(path), - MetadataStatus = MetadataStatus.Pending, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - }; - } - - /// - /// Derives a book title from the file name of the provided , by removing the extension and replacing separators with spaces. - /// - /// The file system path of the book. - /// The derived title. - private static string GetTitleFromPath(string path) - { - string fileName = Path.GetFileNameWithoutExtension(path); - string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim(); - return title.Length > 0 ? title : fileName; - } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs index 3c3c9208..03387db0 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprint.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; using System; using System.Collections.Generic; @@ -38,14 +39,30 @@ internal static class ProviderConfigurationFingerprint /// Computes the fingerprint of the artwork provider configuration of a media library. /// /// The artwork provider configurations of the media library. + /// Whether the artwork of the media library items is aggregated from multiple providers, when it is missing. /// Whether the media library permits downloading data from the web. /// The fingerprint of the artwork provider configuration. - public static string ComputeArtworkFingerprint(IReadOnlyList configurations, bool canDownloadMetadataFromWeb) + public static string ComputeArtworkFingerprint(IReadOnlyList configurations, bool shouldAggregateArtworkWhenMissing, bool canDownloadMetadataFromWeb) { StringBuilder canonicalRepresentation = new(); foreach (LibraryArtworkProviderConfigurationEntity configuration in configurations.OrderBy(configuration => configuration.Rank)) canonicalRepresentation.Append($"{configuration.PluginId:D}|{configuration.IsEnabled}|{configuration.Rank};"); - canonicalRepresentation.Append($"web:{canDownloadMetadataFromWeb};"); + canonicalRepresentation.Append($"aggregate:{shouldAggregateArtworkWhenMissing};web:{canDownloadMetadataFromWeb};"); + + return ComputeFingerprint(canonicalRepresentation.ToString()); + } + + /// + /// Computes the fingerprint of the path template of a media library, used to detect whether the template changed + /// since the last scan, and thus whether the metadata of the library items needs to be derived from their paths again. + /// + /// The ordered parts of the path template of the media library. + /// The fingerprint of the path template. + public static string ComputePathTemplateFingerprint(IReadOnlyList parts) + { + StringBuilder canonicalRepresentation = new(); + foreach (LibraryPathTemplatePartEntity part in parts.OrderBy(part => part.Position)) + canonicalRepresentation.Append($"{part.Kind}|{part.Representation}|{part.IsOptional};"); return ComputeFingerprint(canonicalRepresentation.ToString()); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs new file mode 100644 index 00000000..735ae418 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializer.cs @@ -0,0 +1,206 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Materializer for the media library items of the books media library type. +/// +internal sealed class BooksMediaLibraryScanItemMaterializer : IMediaLibraryScanItemMaterializer +{ + private readonly ILibraryPathTemplateService _pathTemplateService; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for deriving the metadata of the books from their paths. + /// Injected service for handling file system paths. + public BooksMediaLibraryScanItemMaterializer(ILibraryPathTemplateService pathTemplateService, IPathService pathService) + { + _pathTemplateService = pathTemplateService; + _pathService = pathService; + } + + /// + /// The media library type that this materializer supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Resets the enrichment state of the books stored at the provided . + /// + /// The unit of work used to interact with the data access layer. + /// The Id of the media library whose books are reset. + /// The file system paths of the books 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.BookRepository.ResetEnrichmentStateForPathsAsync(libraryId, paths, cancellationToken).ConfigureAwait(false); + } + + /// + /// Materializes the books 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 books 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 library holds the path template that describes the structure of the library on disk, used to derive the metadata of each book from its path. + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + if (domainLibraryResult.IsFailure) + return domainLibraryResult.Errors; + Library library = domainLibraryResult.Value; + Result pathTemplateResult = _pathTemplateService.ResolveTemplate(library.LibraryType, library.PathTemplate.Parts); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; + LibraryPathTemplate pathTemplate = pathTemplateResult.Value; + + // Books that are already stored are never inserted again, so a re-scan of an unchanged file does not duplicate its book. The existing paths are + // loaded in a single query, instead of one existence check per path, so that the number of round trips does not scale with the size of the library. + List stagedPaths = [.. paths]; + Result> getExistingPathsResult = await unitOfWork.BookRepository.GetExistingPathsAsync(libraryId, stagedPaths, cancellationToken).ConfigureAwait(false); + if (getExistingPathsResult.IsFailure) + return getExistingPathsResult.Errors; + HashSet existingPaths = [.. getExistingPathsResult.Value]; + + foreach (string path in paths) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (existingPaths.Contains(path)) + continue; + + Result insertBookResult = await unitOfWork.BookRepository.InsertAsync(CreateShellBookEntity(library, path, pathTemplate), cancellationToken).ConfigureAwait(false); + if (insertBookResult.IsFailure) + return insertBookResult.Errors; + } + return Result.Success; + } + + /// + /// Resets the metadata enrichment status of all the books 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 books 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) + { + return await unitOfWork.BookRepository.ResetMetadataStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resets the artwork enrichment status of all the books 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 books are 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.BookRepository.ResetArtworkStatusForLibraryAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates a shell book entity for the file stored at in the media library identified by . + /// + /// The media library the book belongs to. + /// The file system path of the book. + /// The template describing the structure of the media library on disk. + /// The created shell book entity. + private BookEntity CreateShellBookEntity(Library library, string path, LibraryPathTemplate pathTemplate) + { + string title = GetTitleFromPath(path); + float? volumeNumber = null; + + string relativePath = GetRelativePath(path, library.ContentLocations, _pathService); + Result> parsedPathResult = _pathTemplateService.Parse(library.LibraryType, pathTemplate, relativePath, _pathService.PathSeparator); + if (parsedPathResult.IsSuccess && parsedPathResult.Value.HasValue) + { + ParsedLibraryPath parsedPath = parsedPathResult.Value.Value; + Optional parsedTitle = parsedPath.GetString(LibraryPathPartKind.Title); + if (parsedTitle.HasValue) + title = parsedTitle.Value; + Optional parsedSeriesNumber = parsedPath.GetInt(LibraryPathPartKind.SeriesNumber); + if (parsedSeriesNumber.HasValue) + volumeNumber = parsedSeriesNumber.Value; + } + + return new BookEntity + { + Id = Guid.NewGuid(), + LibraryId = library.Id.Value, + Path = path, + Title = title, + VolumeNumber = volumeNumber, + MetadataStatus = MetadataStatus.Pending, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = Guid.Empty, + UpdatedBy = null + }; + } + + /// + /// Derives a book title from the file name of the provided . + /// + /// The file system path of the book. + /// The derived title. + private static string GetTitleFromPath(string path) + { + string fileName = Path.GetFileNameWithoutExtension(path); + string title = Regex.Replace(fileName, @"[_\-\.]+", " ").Trim(); + return title.Length > 0 ? title : fileName; + } + + /// + /// Gets the path of the book stored at , relative to the content location of the media library it belongs to. + /// + /// The absolute file system path of the book. + /// The content locations of the media library the book belongs to. + /// The service used to determine whether the file is inside a content location of the media library. + /// The path of the book, 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); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs new file mode 100644 index 00000000..4f204d21 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricher.cs @@ -0,0 +1,409 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Metadata enricher for the media library items of the books media library type, using the metadata providers configured for the media library. +/// The enriched metadata is applied to the books, and the media contributors discovered while enriching the metadata are linked to them. +/// +internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanMetadataEnricher +{ + private const int ENRICHMENT_PAGE_SIZE = 1000; // The number of books that are enriched in a single batch, keeping the peak memory bounded regardless of the library size. + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + + /// + /// The media library type that this metadata enricher supports. + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected logger used to report the issues encountered while enriching the metadata. + public BooksMediaLibraryScanMetadataEnricher(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + + /// + /// Enriches the metadata of the books of the provided media library, using the metadata providers configured for it. + /// + /// The unique identifier of the media library whose books 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.LookupType == typeof(BookMetadataLookupDto) + && provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + providers.AddRange(configuredProviders); + } + + // Read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing. + bool shouldAggregateMetadataWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers."); + else + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + } + + // When no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely. + if (providers.Count > 0) + { + Result 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, libraryId, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // The contributors discovered while enriching a page are cached by normalized display name, so that a contributor is only + // created once even when the same person is discovered for many books of the same page. + Dictionary 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.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); + + // Check if enough time has passed since the last update. + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // Increment the number of processed elements progress. + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, libraryId, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // Persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size. + Result 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); + } + + /// + /// 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 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, 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 static 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 || string.IsNullOrWhiteSpace(bookMetadata.Title)) + 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 || string.IsNullOrWhiteSpace(bookMetadata.Title)) + continue; + + mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata); + contributingProviders.Add(metadataProvider.Name); + // The identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely. + bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata); + } + catch (Exception) + { + // A failing metadata provider must not prevent the other providers from being tried. + } + } + + if (mergedMetadata is null) + return null; + + Result 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 + }; + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The unique identifier of the media library being scanned. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private static async Task> PublishJobProgressAsync(IDomainEventPublisher domainEventPublisher, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + Result scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "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/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs new file mode 100644 index 00000000..2ad9ebb3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/Scanners/MusicLibraryTypeScannerTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryTypeScannerTests +{ + private readonly IMediaLibraryScanJobFactory _mockJobFactory = Substitute.For(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void SupportedLibraryType_ShouldBeMusic() + { + // Arrange + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act & Assert + Assert.Equal(LibraryType.Music, sut.SupportedLibraryType); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithEnrichmentJobs() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + TestScanJob diffJob = CreateJob(); + TestScanJob hashJob = CreateJob(); + TestScanJob metadataExtractionJob = CreateJob(); + TestScanJob saveJob = CreateJob(); + TestScanJob invalidationJob = CreateJob(); + TestScanJob enrichmentJob = CreateJob(); + TestScanJob artworkEnrichmentJob = CreateJob(); + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)]; + + // Assert + IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); + Assert.Same(discoveryJob, rootJob); + Assert.Contains(diffJob, discoveryJob.Children); + Assert.Contains(discoveryJob, diffJob.Parents); + Assert.Contains(hashJob, diffJob.Children); + Assert.Contains(diffJob, hashJob.Parents); + Assert.Contains(metadataExtractionJob, hashJob.Children); + Assert.Contains(hashJob, metadataExtractionJob.Parents); + Assert.Contains(saveJob, metadataExtractionJob.Children); + Assert.Contains(metadataExtractionJob, saveJob.Parents); + Assert.Contains(invalidationJob, saveJob.Children); + Assert.Contains(saveJob, invalidationJob.Parents); + Assert.Contains(enrichmentJob, invalidationJob.Children); + Assert.Contains(invalidationJob, enrichmentJob.Parents); + Assert.Contains(artworkEnrichmentJob, enrichmentJob.Children); + Assert.Contains(enrichmentJob, artworkEnrichmentJob.Parents); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + MusicLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + _ = sut.CreateScanJobsForLibrary(libraryId).ToList(); + + // Assert + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); + } + + private TestScanJob CreateJob() where TJob : class, IMediaLibraryScanJob + { + TestScanJob job = new() + { + ScanId = _scanIdFixture.Create(), + UserId = _userIdFixture.Create(), + LibraryId = _libraryIdFixture.Create() + }; + _mockJobFactory.CreateJob(Arg.Any()).Returns((TJob)(object)job); + return job; + } + + /// + /// Concrete test implementation of the abstract class that satisfies all job interfaces. + /// + private sealed class TestScanJob : MediaLibraryScanJob, + IMusicFileSystemDiscoveryJob, + IMediaLibraryScanDiffJob, + IMediaLibraryScanHashJob, + IMusicMetadataExtractionJob, + IMediaLibraryScanResultsSaveJob, + IMediaLibraryScanProviderConfigurationInvalidationJob, + IMediaLibraryScanMetadataEnrichmentJob, + IMediaLibraryScanArtworkEnrichmentJob + { + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter. + /// The unique identifier of the media library scan job. + /// The input data to be processed. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public override Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs index 8bf0cae6..b5e976bd 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedServiceTests.cs @@ -44,6 +44,7 @@ public class FileSystemStructureSeedServiceTests // Arrange _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music")); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(false); _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) .Returns(callInfo => Result.Success(FileSystemPathId.Create(Path.Combine(_rootPath, callInfo.ArgAt(1))).Value)); @@ -53,8 +54,11 @@ public class FileSystemStructureSeedServiceTests // Assert Assert.True(result.IsSuccess); - _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); - _mockDirectoryProviderService.Received(2).CreateDirectory(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.Received(3).CreateDirectory(Arg.Any(), Arg.Any()); + _mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any(), "libraries"); + _mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any(), "books"); + _mockDirectoryProviderService.Received(1).CreateDirectory(Arg.Any(), "music"); } [Fact] @@ -63,6 +67,7 @@ public class FileSystemStructureSeedServiceTests // Arrange _mockPathService.CombinePath(_rootPath, "libraries").Returns(Path.Combine(_rootPath, "libraries")); _mockPathService.CombinePath(_rootPath, "books").Returns(Path.Combine(_rootPath, "books")); + _mockPathService.CombinePath(_rootPath, "music").Returns(Path.Combine(_rootPath, "music")); _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(true); // Act @@ -70,7 +75,7 @@ public class FileSystemStructureSeedServiceTests // Assert Assert.True(result.IsSuccess); - _mockDirectoryProviderService.Received(2).DirectoryExists(Arg.Any()); + _mockDirectoryProviderService.Received(3).DirectoryExists(Arg.Any()); _mockDirectoryProviderService.DidNotReceive().CreateDirectory(Arg.Any(), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs index 9ebc9bb7..4e125f6a 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs @@ -224,29 +224,29 @@ public class LibraryPathTemplateServiceTests public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath) { // Act - Result result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/'); + Result> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/'); // Assert Assert.False(result.IsFailure); - Assert.Null(result.Value); + Assert.False(result.Value.HasValue); } [Fact] public void Parse_WhenTemplateIsEmpty_ShouldReturnNull() { // Act - Result result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/'); + Result> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/'); // Assert Assert.False(result.IsFailure); - Assert.Null(result.Value); + Assert.False(result.Value.HasValue); } [Fact] public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError() { // Act - Result result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/'); + Result> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/'); // Assert Assert.True(result.IsFailure); @@ -261,11 +261,11 @@ public class LibraryPathTemplateServiceTests LibraryPathTemplate template = CreateMusicTemplate(); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/'); // Assert Assert.False(result.IsFailure); - ParsedLibraryPath parsedPath = result.Value!; + ParsedLibraryPath parsedPath = result.Value.Value; Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value); Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value); Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value); @@ -280,11 +280,11 @@ public class LibraryPathTemplateServiceTests LibraryPathTemplate template = CreateMusicTemplate(); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/'); // Assert Assert.False(result.IsFailure); - Assert.Null(result.Value); + Assert.False(result.Value.HasValue); } [Fact] @@ -305,11 +305,11 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/'); // Assert Assert.False(result.IsFailure); - Assert.Equal(7, result.Value!.GetInt(LibraryPathPartKind.TrackNumber).Value); + Assert.Equal(7, result.Value.Value.GetInt(LibraryPathPartKind.TrackNumber).Value); } [Fact] @@ -330,11 +330,11 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/'); // Assert Assert.False(result.IsFailure); - Assert.Null(result.Value); + Assert.False(result.Value.HasValue); } [Fact] @@ -351,11 +351,11 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "1973", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "1973", '/'); // Assert Assert.False(result.IsFailure); - Assert.Equal(1973, result.Value!.GetInt(LibraryPathPartKind.ReleaseYear).Value); + Assert.Equal(1973, result.Value.Value.GetInt(LibraryPathPartKind.ReleaseYear).Value); } [Fact] @@ -372,11 +372,11 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "73", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "73", '/'); // Assert Assert.False(result.IsFailure); - Assert.Null(result.Value); + Assert.False(result.Value.HasValue); } [Fact] @@ -397,12 +397,12 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/'); // Assert Assert.False(result.IsFailure); - Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value); - Assert.False(result.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue); + Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value); + Assert.False(result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue); } [Fact] @@ -423,12 +423,12 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/'); // Assert Assert.False(result.IsFailure); - Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value); - Assert.Equal(2, result.Value.GetInt(LibraryPathPartKind.DiscNumber).Value); + Assert.Equal("Pink Floyd", result.Value.Value.GetString(LibraryPathPartKind.Artist).Value); + Assert.Equal(2, result.Value.Value.GetInt(LibraryPathPartKind.DiscNumber).Value); } [Fact] @@ -452,11 +452,11 @@ public class LibraryPathTemplateServiceTests ]); // Act - Result result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/'); + Result> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/'); // Assert Assert.False(result.IsFailure); - Assert.Equal("Tolkien", result.Value!.GetString(LibraryPathPartKind.Author).Value); + Assert.Equal("Tolkien", result.Value.Value.GetString(LibraryPathPartKind.Author).Value); } /// diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs index 9a3f743b..e495f603 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -33,6 +34,23 @@ public class MediaLibraryScannerFactoryTests Assert.Same(expectedScanner, scanner); } + [Fact] + public void CreateLibraryScanner_WhenLibraryTypeIsMusic_ShouldReturnMusicLibraryTypeScanner() + { + // Arrange + IMusicLibraryTypeScanner expectedScanner = Substitute.For(); + ServiceCollection services = new(); + services.AddSingleton(expectedScanner); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScannerFactory sut = new(serviceProvider); + + // Act + IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Music); + + // Assert + Assert.Same(expectedScanner, scanner); + } + [Theory] [InlineData(LibraryType.EBook)] // eBook scanner is not implemented [InlineData(LibraryType.ComicBook)] // comic book scanner is not implemented @@ -55,7 +73,6 @@ public class MediaLibraryScannerFactoryTests [InlineData(LibraryType.InterviewVideo)] // interview video scanner is not implemented [InlineData(LibraryType.CoverSongVideo)] // cover song video scanner is not implemented [InlineData(LibraryType.PodcastVideo)] // podcast video scanner is not implemented - [InlineData(LibraryType.Music)] // music scanner is not implemented [InlineData(LibraryType.Audiobook)] // audiobook scanner is not implemented [InlineData(LibraryType.LiveRecordingAudio)] // live recording audio scanner is not implemented [InlineData(LibraryType.InterviewAudio)] // interview audio scanner is not implemented diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs new file mode 100644 index 00000000..ecd0616c --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Metadata/MusicMetadataAggregatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMetadataAggregatorTests +{ + private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + + [Fact] + public void Merge_WhenMergingArtistMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond() + { + // Arrange + MediaContributorDto firstContributor = _mediaContributorDtoFixture.Create(); + MediaContributorDto secondContributor = _mediaContributorDtoFixture.Create(); + ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", includeCountry: false, contributors: [firstContributor], genres: []); + ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", contributors: [secondContributor], genres: []); + + // Act + ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Name); + Assert.Equal("CA", merged.Country); + Assert.Equal(2, merged.Contributors!.Count); + Assert.Contains(merged.Contributors, contributor => contributor == firstContributor); + Assert.Contains(merged.Contributors, contributor => contributor == secondContributor); + } + + [Fact] + public void Merge_WhenFirstArtistHasTheValue_ShouldNotTakeTheSecondValue() + { + // Arrange + ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", country: "US", genres: [], contributors: []); + ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", genres: [], contributors: []); + + // Act + ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Name); + Assert.Equal("US", merged.Country); + } + + [Fact] + public void Merge_WhenMergingAlbumMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond() + { + // Arrange + AlbumMetadataDto first = _albumMetadataDtoFixture.Create(title: "First", includeBarcode: false, includeReleaseInfo: false); + AlbumMetadataDto second = _albumMetadataDtoFixture.Create(title: "Second", barcode: "1234567890123"); + + // Act + AlbumMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Title); + Assert.Equal("1234567890123", merged.Barcode); + Assert.NotNull(merged.ReleaseInfo); + } + + [Fact] + public void Merge_WhenMergingAudioMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond() + { + // Arrange + AudioMetadataDto first = _audioMetadataDtoFixture.Create(title: "First", includeDurationInSeconds: false); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(title: "Second", durationInSeconds: 360); + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First", merged.Title); + Assert.Equal(360, merged.DurationInSeconds); + } + + [Fact] + public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate() + { + // Arrange + // The tags of a compilation provide a release year without a full date, while MusicBrainz provides the original release date of the recording. + ReleaseInfoDto firstReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseYear: 1981); + ReleaseInfoDto secondReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(1975, 10, 31), originalReleaseYear: 1975); + AudioMetadataDto first = _audioMetadataDtoFixture.Create(releaseInfo: firstReleaseInfo); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(releaseInfo: secondReleaseInfo); + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second); + + // Assert + // The merged date and year must describe the same point in time, otherwise the release information would be rejected when applied. + Assert.NotNull(merged.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 10, 31), merged.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, merged.ReleaseInfo.OriginalReleaseYear); + } + + [Fact] + public void Merge_WhenBothAudioMetadataHaveIsrcs_ShouldUnionThemWithoutDuplicates() + { + // Arrange + AudioMetadataDto first = _audioMetadataDtoFixture.Create(); + AudioMetadataDto second = _audioMetadataDtoFixture.Create(); + AudioMetadataDto mergedInput = first with { Isrcs = [.. first.Isrcs!.Concat(second.Isrcs!)] }; + + // Act + AudioMetadataDto merged = MusicMetadataAggregator.Merge(mergedInput, second); + + // Assert + Assert.Equal(mergedInput.Isrcs!.Select(isrc => isrc.Value).Distinct(StringComparer.OrdinalIgnoreCase).Count(), merged.Isrcs!.Count); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs new file mode 100644 index 00000000..8cb45421 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicFileSystemDiscoveryJobTests.cs @@ -0,0 +1,379 @@ +#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.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +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.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicFileSystemDiscoveryJobTests +{ + private const string ROOT_PATH = @"C:\Music"; + private const string AUDIO_FILE_PATH = @"C:\Music\song.mp3"; + private const string IMAGE_FILE_PATH = @"C:\Music\cover.jpg"; + + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly IDirectoryScanFingerprintRepository _mockFingerprintRepository; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MusicFileSystemDiscoveryJob _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly DirectoryScanFingerprintEntityFixture _fingerprintFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + /// + /// Initializes a new instance of the class. + /// + public MusicFileSystemDiscoveryJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockFingerprintRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockFingerprintRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockServiceProvider.GetService(typeof(IFileProviderService)).Returns(_mockFileProviderService); + _mockServiceProvider.GetService(typeof(IDirectoryProviderService)).Returns(_mockDirectoryProviderService); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + // Default stubs that keep the happy path working, overridden per test where needed. + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Updated); + _mockFileProviderService.GetSize(Arg.Any()).Returns(Result.From(0)); + _mockFileProviderService.GetLastWriteTime(Arg.Any()).Returns(Result.From(Optional.None())); + _mockDirectoryProviderService.GetLastWriteTime(Arg.Any()).Returns(Result.From(Optional.None())); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryHasAudioFiles_ShouldStageOnlyTheAudioFilesAndComplete() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []); + _mockFileProviderService.GetSize(Arg.Is(path => path.Path == AUDIO_FILE_PATH)).Returns(Result.From(1234L)); + _mockFileProviderService.GetLastWriteTime(Arg.Is(path => path.Path == AUDIO_FILE_PATH)) + .Returns(Result.From(Optional.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)))); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 + && entities.First().Path == AUDIO_FILE_PATH + && entities.First().Size == 1234 + && entities.First().LibraryScanId == _scanId.Value + && entities.First().NeedsRehash), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt() + { + // Arrange + const string SUBDIRECTORY_PATH = @"C:\Music\Album"; + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [], subdirectories: [SUBDIRECTORY_PATH]); + SetupDirectory(SUBDIRECTORY_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Path == AUDIO_FILE_PATH), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryIsUnchanged_ShouldSkipIt() + { + // Arrange + DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true); + _mockDirectoryProviderService.GetLastWriteTime(Arg.Is(path => path.Path == ROOT_PATH)) + .Returns(Result.From(Optional.Some(lastWriteTime))); + _mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Dictionary + { + [ROOT_PATH] = _fingerprintFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime) + })); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + _mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any(), true); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryChanged_ShouldStoreAFingerprint() + { + // Arrange + DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true); + _mockDirectoryProviderService.GetLastWriteTime(Arg.Is(path => path.Path == ROOT_PATH)) + .Returns(Result.From(Optional.Some(lastWriteTime))); + _mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Dictionary + { + [ROOT_PATH] = _fingerprintFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime.AddDays(-1)) + })); + SetupDirectory(ROOT_PATH, files: [], subdirectories: []); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockFingerprintRepository.Received(1).UpsertRangeAsync( + Arg.Is>(fingerprints => fingerprints.Count == 1 && fingerprints.First().Path == ROOT_PATH), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFileSizeAndLastWriteTimeCannotBeRead_ShouldStageTheFileWithDefaults() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + _mockFileProviderService.GetSize(Arg.Any()).Returns(Error.Failure("FileSystem.Error", "Failed to read the size")); + _mockFileProviderService.GetLastWriteTime(Arg.Any()).Returns(Error.Failure("FileSystem.Error", "Failed to read the last write time")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockStagingResultsRepository.Received(1).InsertRangeAsync( + Arg.Is>(entities => entities.Count == 1 && entities.First().Size == 0 && entities.First().Ticks == 0), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenReadingTheDirectoryFails_ShouldSkipItAndComplete() + { + // Arrange + SetupLibrary(); + _mockFileProviderService.GetFilePaths(Arg.Any(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the files")); + _mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Any(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the subdirectories")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to stage the discovered files")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFingerprintUpsertFails_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true); + SetupDirectory(ROOT_PATH, files: [], subdirectories: []); + _mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Dictionary())); + _mockFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to store the fingerprints")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren() + { + // Arrange + SetupLibrary(); + SetupDirectory(ROOT_PATH, files: [], subdirectories: []); + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + /// + /// Stubs the media library reader with a library whose single content location is the test root path. + /// + /// Whether the library skips the directories that have not changed since the last scan. + private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false) + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [ROOT_PATH], + shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the file and directory providers for the provided directory. + /// + /// The file system path of the directory. + /// The file system paths of the files of the directory. + /// The file system paths of the subdirectories of the directory. + private void SetupDirectory(string directory, string[] files, string[] subdirectories) + { + _mockFileProviderService.GetFilePaths(Arg.Is(path => path.Path == directory), true) + .Returns(Result.From>([.. files.Select(file => PathId(file))])); + _mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is(path => path.Path == directory), true) + .Returns(Result.From>([.. subdirectories.Select(subdirectoryPath => PathId(subdirectoryPath))])); + } + + /// + /// Creates a file system path id for the provided path. + /// + /// The path to create the id for. + /// The created file system path id. + private static FileSystemPathId PathId(string path) + { + return FileSystemPathId.Create(path).Value; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs new file mode 100644 index 00000000..bc50eb7f --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicLibraryPathStructureTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryPathStructureTests +{ + private const string ALBUM_DIRECTORY = @"C:\Music\Queen\A Night at the Opera"; + private const string TRACK_PATH = @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac"; + + [Fact] + public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory() + { + // Act + string result = MusicLibraryPathStructure.GetAlbumDirectory(TRACK_PATH); + + // Assert + Assert.Equal(ALBUM_DIRECTORY, result); + } + + [Theory] + [InlineData("Disc 1")] // canonical disc directory name + [InlineData("disc 2")] // lowercase disc directory name + [InlineData("CD3")] // compact disc directory name + [InlineData("disk4")] // disk directory name + public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(string discDirectoryName) + { + // Arrange + string trackPath = $@"{ALBUM_DIRECTORY}\{discDirectoryName}\Bohemian Rhapsody.flac"; + + // Act + string result = MusicLibraryPathStructure.GetAlbumDirectory(trackPath); + + // Assert + Assert.Equal(ALBUM_DIRECTORY, result); + } + + [Fact] + public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory() + { + // Arrange + const string NON_DISC_TRACK_PATH = @"C:\Music\Queen\Live\Bohemian Rhapsody.flac"; + + // Act + string result = MusicLibraryPathStructure.GetAlbumDirectory(NON_DISC_TRACK_PATH); + + // Assert + Assert.Equal(@"C:\Music\Queen\Live", result); + } + + [Fact] + public void GetAlbumDirectory_WhenThePathIsNullOrEmpty_ShouldReturnTheProvidedPath() + { + // Act + string nullResult = MusicLibraryPathStructure.GetAlbumDirectory(null!); + string emptyResult = MusicLibraryPathStructure.GetAlbumDirectory(string.Empty); + + // Assert + Assert.Null(nullResult); + Assert.Equal(string.Empty, emptyResult); + } + + [Fact] + public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath() + { + // Arrange + const string FILE_NAME_ONLY = "Bohemian Rhapsody.flac"; + + // Act + string result = MusicLibraryPathStructure.GetAlbumDirectory(FILE_NAME_ONLY); + + // Assert + Assert.Equal(FILE_NAME_ONLY, result); + } + + [Fact] + public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt() + { + // Arrange + const string RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\Album\A Night at the Opera\Bohemian Rhapsody.flac"; + + // Act + string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(RELEASE_TYPE_TRACK_PATH); + + // Assert + Assert.Equal("Album", result); + } + + [Fact] + public void GetReleaseTypeDirectoryName_WhenTheReleaseTypeDirectoryIsLowercase_ShouldReturnIt() + { + // Arrange + const string LOWERCASE_RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\album\A Night at the Opera\Bohemian Rhapsody.flac"; + + // Act + string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(LOWERCASE_RELEASE_TYPE_TRACK_PATH); + + // Assert + Assert.Equal("album", result); + } + + [Fact] + public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory() + { + // Arrange + const string MULTI_DISC_TRACK_PATH = @"C:\Music\Queen\Album\A Night at the Opera\Disc 1\Bohemian Rhapsody.flac"; + + // Act + string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(MULTI_DISC_TRACK_PATH); + + // Assert + Assert.Equal("Album", result); + } + + [Fact] + public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull() + { + // Arrange + const string NON_RELEASE_TYPE_TRACK_PATH = @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac"; + + // Act + string? result = MusicLibraryPathStructure.GetReleaseTypeDirectoryName(NON_RELEASE_TYPE_TRACK_PATH); + + // Assert + Assert.Null(result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs new file mode 100644 index 00000000..6e447304 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanItemMaterializerTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaLibraryScanItemMaterializerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IMusicLibraryScanItemMetadataRepository _mockStagedMetadataRepository; + private readonly MusicMediaLibraryScanItemMaterializer _sut; + private readonly MusicLibraryScanItemMetadataEntityFixture _stagedMetadataEntityFixture = new(); + private readonly List _insertedArtists = []; + private readonly Guid _libraryId = Guid.NewGuid(); + private readonly Guid _scanId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public MusicMediaLibraryScanItemMaterializerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockStagedMetadataRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockStagedMetadataRepository); + + _mockArtistRepository.GetByNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockAlbumRepository.GetByTitleAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockArtistRepository.InsertAsync(Arg.Do(artist => _insertedArtists.Add(artist)), Arg.Any()) + .Returns(Result.From(new Created())); + _mockAlbumRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Created())); + _mockTrackRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Created())); + _mockTrackRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + _mockStagedMetadataRepository.DeleteByScanIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new Deleted())); + + _sut = new MusicMediaLibraryScanItemMaterializer(); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenTheTracksLiveInDifferentDirectories_ShouldMaterializeOneAlbumPerDirectory() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + Guid firstReleaseId = Guid.NewGuid(); + Guid secondReleaseId = Guid.NewGuid(); + Guid firstRecordingId = Guid.NewGuid(); + Guid secondRecordingId = Guid.NewGuid(); + MusicLibraryScanItemMetadataEntity firstStagedItem = _stagedMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/release-one/first.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: releaseArtistId, + musicBrainzReleaseId: firstReleaseId, + musicBrainzRecordingId: firstRecordingId); + MusicLibraryScanItemMetadataEntity secondStagedItem = _stagedMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/release-two/second.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: releaseArtistId, + musicBrainzReleaseId: secondReleaseId, + musicBrainzRecordingId: secondRecordingId); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([firstStagedItem, secondStagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + // The same artist name groups the items under a single artist, whose identifier is the one of the release artist. + ArtistEntity artist = Assert.Single(_insertedArtists); + Assert.Equal(releaseArtistId, artist.MusicBrainzArtistId); + // The distinct release identifiers keep the identically titled releases apart. + Assert.Equal(2, artist.Albums.Count); + AlbumEntity firstAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == firstReleaseId); + AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId); + Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId); + Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenCompilationTracksHaveDifferentTrackArtists_ShouldMaterializeASingleAlbumArtist() + { + // Arrange + Guid variousArtistsId = Guid.NewGuid(); + Guid compilationReleaseId = Guid.NewGuid(); + MusicLibraryScanItemMetadataEntity firstStagedItem = _stagedMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Various Artists", + releaseName: "Now That Is Music", + path: "/music/various-artists/now-that-is-music/first.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: variousArtistsId, + musicBrainzReleaseId: compilationReleaseId); + MusicLibraryScanItemMetadataEntity secondStagedItem = _stagedMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Various Artists", + releaseName: "Now That Is Music", + path: "/music/various-artists/now-that-is-music/second.mp3", + musicBrainzArtistId: Guid.NewGuid(), + musicBrainzReleaseArtistId: variousArtistsId, + musicBrainzReleaseId: compilationReleaseId); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([firstStagedItem, secondStagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + // The different track artists of the compilation do not split the release artist into several identically named artists. + ArtistEntity artist = Assert.Single(_insertedArtists); + Assert.Equal("Various Artists", artist.Name); + Assert.Equal(variousArtistsId, artist.MusicBrainzArtistId); + AlbumEntity album = Assert.Single(artist.Albums); + Assert.Equal(2, album.Tracks.Count); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenTheTagsDoNotCarryMusicBrainzIds_ShouldGroupByTheNameAndTitle() + { + // Arrange + MusicLibraryScanItemMetadataEntity firstStagedItem = _stagedMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/shared-release/first.mp3", + includeMusicBrainzTags: false); + MusicLibraryScanItemMetadataEntity secondStagedItem = _stagedMetadataEntityFixture.Create( + libraryId: _libraryId, + artistName: "Shared Artist Name", + releaseName: "Shared Release Title", + path: "/music/shared-artist/shared-release/second.mp3", + includeMusicBrainzTags: false); + _mockStagedMetadataRepository.GetByScanIdAsync(_scanId, Arg.Any()) + .Returns(Result.From>([firstStagedItem, secondStagedItem])); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, [firstStagedItem.Path, secondStagedItem.Path], CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + // Without identifiers, the items fall back to the name and the title, so they collapse into a single artist with a single album. + ArtistEntity artist = Assert.Single(_insertedArtists); + AlbumEntity album = Assert.Single(artist.Albums); + Assert.Null(artist.MusicBrainzArtistId); + Assert.Null(album.MusicBrainzReleaseId); + Assert.Equal(2, album.Tracks.Count); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs new file mode 100644 index 00000000..ab24cd4b --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMetadataExtractionJobTests.cs @@ -0,0 +1,277 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMetadataExtractionJobTests +{ + private const string ROOT_PATH = @"C:\Music"; + private const string AUDIO_FILE_PATH = @"C:\Music\Queen\Bohemian Rhapsody.mp3"; + + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly ILibraryPathTemplateService _mockPathTemplateService; + private readonly IPathService _mockPathService; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MusicMetadataExtractionJob _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryId _libraryId; + private readonly ScanId _scanId; + private readonly UserId _userId; + + /// + /// Initializes a new instance of the class. + /// + public MusicMetadataExtractionJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository = Substitute.For(); + _mockMusicMetadataRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockPathTemplateService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + _mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService); + _mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + // Default stubs that keep the happy path working, overridden per test where needed. + _mockMusicMetadataRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()).Returns(Result.Created); + _mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(_libraryPathTemplateFixture.Create())); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.From>(Optional.None())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); + + _libraryId = _libraryIdFixture.Create(); + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For>()) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockMusicMetadataRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenThereArePathsToProcess_ShouldStageTheirMetadataAndComplete() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().Path == AUDIO_FILE_PATH + && items.First().LibraryScanId == _scanId.Value + && items.First().LibraryId == _libraryId.Value + && items.First().TrackTitle == "Bohemian Rhapsody"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThePathMatchesTheTemplate_ShouldApplyThePathDerivedMetadata() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Queen", + [LibraryPathPartKind.ReleaseType] = "Album", + [LibraryPathPartKind.ReleaseYear] = "1975", + [LibraryPathPartKind.ReleaseName] = "A Night at the Opera", + [LibraryPathPartKind.TrackNumber] = "11", + [LibraryPathPartKind.DiscNumber] = "1", + [LibraryPathPartKind.TrackName] = "Bohemian Rhapsody" + }); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>(Optional.Some(parsedPath))); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockMusicMetadataRepository.Received(1).InsertRangeAsync( + Arg.Is>(items => items.Count == 1 + && items.First().ArtistName == "Queen" + && items.First().ReleaseType == MusicReleaseType.Album + && items.First().ReleaseYear == 1975 + && items.First().ReleaseName == "A Night at the Opera" + && items.First().TrackNumber == 11 + && items.First().DiscNumber == 1 + && items.First().TrackTitle == "Bohemian Rhapsody"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + _mockMusicMetadataRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to stage the extracted metadata")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren() + { + // Arrange + SetupLibrary(); + SetupPaths(AUDIO_FILE_PATH); + IMediaLibraryScanJob mockChild = Substitute.For(); + mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + _sut.AddChild(mockChild); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + await mockChild.Received(1).ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + /// + /// Stubs the media library reader with a library whose single content location is the test root path. + /// + private void SetupLibrary() + { + LibraryEntity library = _libraryEntityFixture.Create( + id: _libraryId.Value, + libraryType: LibraryType.Music, + contentLocations: [ROOT_PATH]); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Stubs the staging results repository with the paths that need their metadata extracted. + /// + /// The file system paths that need their metadata extracted. + private void SetupPaths(params string[] paths) + { + _mockStagingResultsRepository.GetPathsNeedingRehashAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(paths)); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index d315fb11..b4fefe93 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -1,26 +1,8 @@ #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.Repositories.MediaLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.Fixtures.Core.DTO.Common; -using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -31,18 +13,13 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; -using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -59,21 +36,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; - private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; - private readonly IBookRepository _mockBookRepository; - private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaLibraryScanMetadataEnricher _mockMetadataEnricher; private readonly IDomainEventPublisher _mockDomainEventPublisher; - private readonly ILogger _mockLogger; private readonly MediaLibraryScanMetadataEnrichmentJob _sut; private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); - private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); - private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); - private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); - private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; @@ -91,25 +60,27 @@ public class MediaLibraryScanMetadataEnrichmentJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); - _mockConfigurationRepository = Substitute.For(); - _mockBookRepository = Substitute.For(); - _mockMediaContributorRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); - _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // The job resolves the metadata enricher of the loaded library type from the service scope, so the music enricher must be available. + _mockMetadataEnricher = Substitute.For(); + _mockMetadataEnricher.SupportedLibraryType.Returns(LibraryType.Music); + _mockMetadataEnricher.EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanMetadataEnricher[] { _mockMetadataEnricher }); + _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); - _mockLogger = Substitute.For>(); - _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); - _sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory, _mockLogger) + _sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory) { ScanId = _scanId, UserId = _userId, @@ -118,633 +89,39 @@ public class MediaLibraryScanMetadataEnrichmentJobTests } [Fact] - public async Task ExecuteAsync_WhenNoBooksNeedEnrichment_ShouldCompleteAndPublishFinishedEvent() + public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent() { // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(0)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed() - { - // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - _mockUnitOfWork.Received(1).ClearTrackedEntities(); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() - { - // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations")); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + await _mockMetadataEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() - { - // Arrange - using CancellationTokenSource cancellationTokenSource = new(); - cancellationTokenSource.Cancel(); - - // Act - Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); - - // Assert - await Assert.ThrowsAnyAsync(() => operation); - Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - IMetadataProvider secondProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description")); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - // the book has no known identifiers of its own, so the findings of the first provider are fed to the second one - book.OpenLibraryId = null; - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the second provider receives the lookup enriched with the open library Id discovered by the first provider - await secondProvider.Received(1).GetMetadataAsync( - Arg.Is(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"), - Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } [Fact] - public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata() + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - IMetadataProvider secondProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata - await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the enrichment state is tracked directly on the entity, so the failed status is visible on the same instance - Assert.Equal(MetadataStatus.Failed, book.MetadataStatus); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenMetadataIsEnriched_ShouldSetTheEnrichmentTrackingColumnsOnTheEntity() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the enrichment tracking columns are managed directly on the entity by the enrichment job - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("First Provider", book.MetadataProvider); - Assert.NotNull(book.LastMetadataUpdateUtc); - Assert.Equal("First Title", book.Title); - Assert.Equal("First Publisher", book.Publisher); - } - - [Fact] - public async Task ExecuteAsync_WhenMetadataHasContributors_ShouldFindOrCreateThemAndLinkThemToTheBook() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); - MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", role: MediaContributorRole.Translator); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author, translator])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); - MediaContributorEntity translatorEntity = _mediaContributorEntityFixture.Create(displayName: "Jane Translator"); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Result.From(authorEntity)); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()) - .Returns(Result.From(translatorEntity)); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Jane Translator", Arg.Any(), Arg.Any()); - - // the participation rows are replaced on the entity, carrying the canonical role of each contributor - Assert.Equal(2, book.Contributors.Count); - BookContributorEntity linkedAuthor = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == authorEntity.Id); - Assert.Equal(MediaContributorRole.Author, linkedAuthor.Role); - Assert.Equal(book.Id, linkedAuthor.BookId); - BookContributorEntity linkedTranslator = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == translatorEntity.Id); - Assert.Equal(MediaContributorRole.Translator, linkedTranslator.Role); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - } - - [Fact] - public async Task ExecuteAsync_WhenTheSameContributorAppearsInMultipleBooksOfAPage_ShouldFindOrCreateItOnlyOnce() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - - BookEntity firstBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/a.epub"); - BookEntity secondBook = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/b.epub"); - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(2)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([firstBook, secondBook]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Result.From(authorEntity)); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the contributor cache of the page guarantees a single contributor per person, so the repository is queried only once - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()); - Assert.Single(firstBook.Contributors); - Assert.Single(secondBook.Contributors); - Assert.Equal(authorEntity.Id, firstBook.Contributors[0].MediaContributorId); - Assert.Equal(authorEntity.Id, secondBook.Contributors[0].MediaContributorId); - } - - [Fact] - public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess() - { - // Arrange - Guid localPluginId = Guid.NewGuid(); - Guid webPluginId = Guid.NewGuid(); - IMetadataProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.RequiresWebAccess.Returns(false); - localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); - IMetadataProvider webProvider = Substitute.For(); - webProvider.Name.Returns("Web Provider"); - webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - webProvider.RequiresWebAccess.Returns(true); - webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); - - SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, localPluginId, webPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched - await localProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); - await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess() - { - // Arrange - Guid localPluginId = Guid.NewGuid(); - Guid webPluginId = Guid.NewGuid(); - IMetadataProvider localProvider = Substitute.For(); - localProvider.Name.Returns("Local Provider"); - localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - localProvider.RequiresWebAccess.Returns(false); - localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); - IMetadataProvider webProvider = Substitute.For(); - webProvider.Name.Returns("Web Provider"); - webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - webProvider.RequiresWebAccess.Returns(true); - webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); - - SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); - ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) - .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true))); - _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); - - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, localPluginId, webPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // the provider requiring access to the web is used when the library permits downloading data from the web - await webProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenCountingTheBooksNeedingMetadataFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to count the books to enrich")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenGettingTheBooksPageNeedingMetadataFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)])); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the books to enrich")); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileTryingTheProvidersInOrder_ShouldTryTheNextProvider() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); - IMetadataProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a failing metadata provider must not prevent the metadata of the next provider from being used - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("Second Provider", book.MetadataProvider); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAMetadataProviderThrowsWhileAggregatingMetadata_ShouldUseTheFindingsOfTheOtherProviders() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - Guid secondPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(Task.FromException(new InvalidOperationException("The metadata provider failed"))); - IMetadataProvider secondProvider = Substitute.For(); - secondProvider.Name.Returns("Second Provider"); - secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId, secondPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal("Second Provider", book.MetadataProvider); - Assert.Equal("Second Title", book.Title); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAContributorHasNoDisplayName_ShouldSkipLinkingIt() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(role: MediaContributorRole.Author) with { Name = null }; - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a contributor without a display name cannot be linked to the book, so no contributor is queried or created - await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); - Assert.Empty(book.Contributors); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenAContributorHasNoRole_ShouldLinkItWithTheDefaultRole() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto contributorWithoutRole = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert") with { Role = null }; - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [contributorWithoutRole])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub", includeMetadata: false); - SetupSingleBookPage(book, firstPluginId); - - MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Result.From(authorEntity)); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - // a contributor without a role is linked with the default canonical role - BookContributorEntity linkedContributor = Assert.Single(book.Contributors); - Assert.Equal(MediaContributorRole.Author, linkedContributor.Role); - Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenFindingOrCreatingAContributorFails_ShouldMarkJobAsFailed() - { - // Arrange - Guid firstPluginId = Guid.NewGuid(); - IMetadataProvider firstProvider = Substitute.For(); - firstProvider.Name.Returns("First Provider"); - firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); - firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) - .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); - - SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); - BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - SetupSingleBookPage(book, firstPluginId); - - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to find or create the contributor")); - - // Act - await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); - - // Assert - Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); - } - - [Fact] - public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload() - { - // Arrange - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); - - IMediaLibraryScanJob mockChildJob = Substitute.For(); - mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - _sut.AddChild(mockChildJob); - Guid id = Guid.NewGuid(); - object input = new(); - - // Act - await _sut.ExecuteAsync(id, input, CancellationToken.None); - - // Assert - await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any()); - Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); - } - - /// - /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. - /// - /// The Id of the plugin providing the first metadata provider. - /// The first metadata provider to resolve. - /// The Id of the plugin providing the second metadata provider, if any. - /// The second metadata provider to resolve, if any. - /// Whether the user settings enable aggregating metadata from multiple providers when fields are missing. - private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false) - { - ServiceCollection services = new(); - services.AddKeyedSingleton(firstPluginId, firstProvider); - if (secondPluginId is not null && secondProvider is not null) - services.AddKeyedSingleton(secondPluginId.Value, secondProvider); - services.AddSingleton(_mockUnitOfWork); - services.AddSingleton(_mockDomainEventPublisher); - // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test - ServiceProvider realServiceProvider = services.BuildServiceProvider(); - AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); - _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); - - IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); - mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing))); - _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); - } - - /// - /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers. - /// - /// The book the job must enrich. - /// The Ids of the plugins configured as metadata providers for the library. - private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds) - { - _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From>( - configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList())); - _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) - .Returns(Result.From(1)); - _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From>([book]), Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + await _mockMetadataEnricher.DidNotReceive().EnrichAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs index 84ef1735..d3e9deb9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanProviderConfigurationInvalidationJobTests.cs @@ -12,9 +12,11 @@ using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -22,6 +24,7 @@ using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContex using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; @@ -83,6 +86,9 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available. + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(Substitute.For(), Substitute.For()) }); _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) @@ -113,7 +119,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // a missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted + // A missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted. await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -121,6 +127,24 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } + [Fact] + public async Task ExecuteAsync_WhenFingerprintsArePersisted_ShouldPublishProgressChangedEvent() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library"); + SetupLibraryAndConfigurations(library); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus() { @@ -134,7 +158,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job + // The metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job. await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -155,7 +179,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job + // The artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job. await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -172,9 +196,9 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests List artworkConfigurations = _artworkConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1); SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations); - // the stored fingerprints match the ones computed from the current provider configuration + // The stored fingerprints match the ones computed from the current provider configuration. string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb); - string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, library.CanDownloadMetadataFromWeb); + string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, false, library.CanDownloadMetadataFromWeb); library.MetadataProvidersConfigurationFingerprint = metadataFingerprint; library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint; @@ -182,7 +206,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted + // The configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted. await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any(), Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -194,7 +218,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly() { // Arrange - // both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity + // Both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity. LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK"); SetupLibraryAndConfigurations(library); _mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()) @@ -206,8 +230,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and - // flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run + // Regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and + // flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run. await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any()); await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); @@ -359,7 +383,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted + // Reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted. Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -377,7 +401,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the user settings repository is optional, its absence must not prevent the fingerprints from being persisted + // The user settings repository is optional, its absence must not prevent the fingerprints from being persisted. Assert.NotNull(library.MetadataProvidersConfigurationFingerprint); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -413,6 +437,8 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests /// The artwork provider configurations of the media library. private void SetupLibraryAndConfigurations(LibraryEntity library, List? metadataConfigurations = null, List? artworkConfigurations = null) { + // The job resolves the materializer by the library type, so the fixture-provided library must be of the type the books materializer supports. + library.LibraryType = LibraryType.Book; _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); SetupConfigurations(metadataConfigurations, artworkConfigurations); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs index ccc0f5ee..53222d92 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs @@ -1,22 +1,27 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System; @@ -39,6 +44,7 @@ public class MediaLibraryScanResultsSaveJobTests private readonly IServiceScope _mockServiceScope; private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository; private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; private readonly IBookRepository _mockBookRepository; @@ -47,6 +53,7 @@ public class MediaLibraryScanResultsSaveJobTests private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; @@ -64,13 +71,23 @@ public class MediaLibraryScanResultsSaveJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); _mockSnapshotRepository = Substitute.For(); _mockStagingResultsRepository = Substitute.For(); _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + // By default no book exists yet, so every scanned path is materialized; the tests that need existing books override this. + _mockBookRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + // The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available. + ILibraryPathTemplateService mockPathTemplateService = Substitute.For(); + mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(LibraryPathTemplate.Empty())); + _mockServiceProvider.GetService(typeof(IEnumerable)) + .Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, Substitute.For()) }); _mockDomainEventPublisher = Substitute.For(); _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) @@ -80,6 +97,8 @@ public class MediaLibraryScanResultsSaveJobTests _scanId = _scanIdFixture.Create(); _userId = _userIdFixture.Create(); _libraryId = _libraryIdFixture.Create(); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Book))); _sut = new MediaLibraryScanResultsSaveJob(_mockServiceScopeFactory) { ScanId = _scanId, @@ -102,8 +121,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["book1.pdf", "book2.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) - .Returns(Result.From(null)); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -121,6 +140,31 @@ public class MediaLibraryScanResultsSaveJobTests await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldPublishProgressChangedEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState() { @@ -139,7 +183,7 @@ public class MediaLibraryScanResultsSaveJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // no book content changed since the last scan, so the enrichment state of the books must not be reset + // No book content changed since the last scan, so the enrichment state of the books must not be reset. await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } @@ -156,8 +200,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["existing.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any()) - .Returns(Result.From(_bookEntityFixture.Create(path: "existing.pdf"))); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>(["existing.pdf"])); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act @@ -292,7 +336,7 @@ public class MediaLibraryScanResultsSaveJobTests } [Fact] - public async Task ExecuteAsync_WhenGettingExistingBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + public async Task ExecuteAsync_WhenGettingExistingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) @@ -303,8 +347,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["book1.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to get the existing book")); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the existing paths")); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -329,8 +373,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["book1.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) - .Returns(Result.From(null)); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to insert the shell book")); @@ -385,8 +429,8 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>(["_.pdf"])); - _mockBookRepository.GetByPathAsync(_libraryId.Value, "_.pdf", Arg.Any()) - .Returns(Result.From(null)); + _mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); @@ -395,7 +439,7 @@ public class MediaLibraryScanResultsSaveJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - // the file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback + // The file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback. await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any()); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs new file mode 100644 index 00000000..8e2fc93b --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ProviderConfigurationFingerprintTests.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ProviderConfigurationFingerprintTests +{ + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new(); + + [Fact] + public void ComputeMetadataFingerprint_WhenCalledWithTheSameConfiguration_ShouldReturnTheSameFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = + [ + _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0), + _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1) + ]; + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity first = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + LibraryMetadataProviderConfigurationEntity second = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([first, second], false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([second, first], false, true); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity enabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: true); + LibraryMetadataProviderConfigurationEntity disabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: false); + + // Act + string enabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([enabled], false, true); + string disabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([disabled], false, true); + + // Assert + Assert.NotEqual(enabledFingerprint, disabledFingerprint); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)]; + + // Act + string withoutAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + string withAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, true, true); + + // Assert + Assert.NotEqual(withoutAggregation, withAggregation); + } + + [Fact] + public void ComputeMetadataFingerprint_WhenTheWebAccessSettingChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)]; + + // Act + string withoutWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, false); + string withWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true); + + // Assert + Assert.NotEqual(withoutWebAccess, withWebAccess); + } + + [Fact] + public void ComputeArtworkFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first, second], false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second, first], false, true); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeArtworkFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first], false, true); + string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second], false, true); + + // Assert + Assert.NotEqual(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputeArtworkFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List configurations = [_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)]; + + // Act + string withoutAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, false, true); + string withAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, true, true); + + // Assert + Assert.NotEqual(withoutAggregation, withAggregation); + } + + [Fact] + public void ComputePathTemplateFingerprint_WhenOnlyTheOrderOfPartsDiffers_ShouldReturnTheSameFingerprint() + { + // Arrange + LibraryPathTemplatePartEntity first = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}"); + LibraryPathTemplatePartEntity second = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.ReleaseName, representation: "{0}"); + + // Act + string firstFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([first, second]); + string secondFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([second, first]); + + // Assert + Assert.Equal(firstFingerprint, secondFingerprint); + } + + [Fact] + public void ComputePathTemplateFingerprint_WhenAPartChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + LibraryPathTemplatePartEntity artist = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}"); + LibraryPathTemplatePartEntity releaseName = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.ReleaseName, representation: "{0}"); + + // Act + string artistFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([artist]); + string releaseNameFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([releaseName]); + + // Assert + Assert.NotEqual(artistFingerprint, releaseNameFingerprint); + } + + [Fact] + public void ComputePathTemplateFingerprint_WhenTheOptionalityChanges_ShouldReturnADifferentFingerprint() + { + // Arrange + LibraryPathTemplatePartEntity required = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false); + LibraryPathTemplatePartEntity optional = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true); + + // Act + string requiredFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([required]); + string optionalFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([optional]); + + // Assert + Assert.NotEqual(requiredFingerprint, optionalFingerprint); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs new file mode 100644 index 00000000..08b6719e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanItemMaterializerTests.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryScanItemMaterializerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryPathTemplateService _mockPathTemplateService; + private readonly IPathService _mockPathService; + private readonly BooksMediaLibraryScanItemMaterializer _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _libraryId; + private readonly Guid _scanId; + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryScanItemMaterializerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockPathTemplateService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _libraryId = Guid.NewGuid(); + _scanId = Guid.NewGuid(); + + // Default stubs: the library has no path template of its own, no book is stored yet, and the separator is the Windows one. + _mockPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()) + .Returns(Result.From(LibraryPathTemplate.Empty())); + _mockPathService.PathSeparator.Returns('\\'); + _mockBookRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Created)); + _mockPathTemplateService.Parse(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(Optional.None())); + + _sut = new BooksMediaLibraryScanItemMaterializer(_mockPathTemplateService, _mockPathService); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenPathSharesTheContentLocationPrefixButIsOutside_ShouldFallBackToTheFileNameRelativePath() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]); + _mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockPathService.IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music").Returns(false); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\MusicBackup\\track.epub"], CancellationToken.None); + + // Assert + // A sibling directory whose name only starts with the content location name is not inside the library, so the item is not parsed against + // the path template, and the file name is used as the relative path instead. + Assert.False(result.IsFailure); + _mockPathService.Received(1).IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music"); + _mockPathTemplateService.Received(1).Parse(Arg.Any(), Arg.Any(), "track.epub", '\\'); + } + + [Fact] + public async Task MaterializeItemsAsync_WhenPathIsInsideTheContentLocation_ShouldParseThePathRelativeToTheContentLocation() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]); + _mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockPathService.IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music").Returns(true); + + // Act + Result result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, ["C:\\Music\\Artist\\track.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music"); + _mockPathTemplateService.Received(1).Parse(Arg.Any(), Arg.Any(), "Artist\\track.epub", '\\'); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs new file mode 100644 index 00000000..c5a7e404 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksMediaLibraryScanMetadataEnricherTests.cs @@ -0,0 +1,383 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +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.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksMediaLibraryScanMetadataEnricherTests +{ + private const string PROVIDER_A_NAME = "ProviderA"; + private const string PROVIDER_B_NAME = "ProviderB"; + + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IBookRepository _mockBookRepository; + private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IMetadataProvider _mockProviderA; + private readonly IMetadataProvider _mockProviderB; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ServiceProvider _serviceProvider; + private readonly BooksMediaLibraryScanMetadataEnricher _sut; + private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public BooksMediaLibraryScanMetadataEnricherTests() + { + _mockUnitOfWork = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockMetadataConfigurationRepository = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository); + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + + _mockProviderA = Substitute.For(); + ConfigureProvider(_mockProviderA, PROVIDER_A_NAME); + _mockProviderB = Substitute.For(); + ConfigureProvider(_mockProviderB, PROVIDER_B_NAME); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + + // The configured providers are registered under the plugin Ids they are configured with, the way the host registers plugin provided services. + Guid pluginAId = Guid.NewGuid(); + Guid pluginBId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result>.Success( + [ + _metadataConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1), + _metadataConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2) + ])); + + ServiceCollection services = new(); + services.AddScoped(_ => _mockUnitOfWork); + services.AddScoped(_ => _mockDomainEventPublisher); + services.AddKeyedTransient(pluginAId, (serviceProvider, serviceKey) => _mockProviderA); + services.AddKeyedTransient(pluginBId, (serviceProvider, serviceKey) => _mockProviderB); + _serviceProvider = services.BuildServiceProvider(); + + _sut = new BooksMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService(), NullLogger.Instance); + + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result>.Success([])); + _mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any()) + .Returns(Result.Success(null)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.From(Result.Success)); + } + + [Fact] + public async Task EnrichAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipTheEnrichment() + { + // Arrange + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result>.Success([])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheMetadataConfigurationsCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Provider.Error", "Failed to read the configurations")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(PROVIDER_A_NAME, book.MetadataProvider); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal(PROVIDER_B_NAME, book.MetadataProvider); + } + + [Fact] + public async Task EnrichAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookFailed() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)null); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + Assert.Equal(MetadataStatus.Failed, book.MetadataStatus); + } + + [Fact] + public async Task EnrichAsync_WhenAggregationIsEnabled_ShouldQueryEveryProviderAndMergeTheirMetadata() + { + // Arrange + _mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any()) + .Returns(Result.Success(_userSettingsEntityFixture.Create(userId: _userId.Value, shouldAggregateMetadataWhenMissing: true))); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + _mockProviderB.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune Messiah")); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); + Assert.Equal($"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}", book.MetadataProvider); + } + + [Fact] + public async Task EnrichAsync_WhenTheMetadataHasContributors_ShouldLinkThemToTheBook() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); + _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(contributor)); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata( + "Dune", + contributors: [_mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author, legalName: null)])); + + // Act + await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + + // Assert + await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", null, Arg.Any()); + BookContributorEntity linkedContributor = Assert.Single(book.Contributors); + Assert.Equal(contributor.Id, linkedContributor.MediaContributorId); + Assert.Equal(MediaContributorRole.Author, linkedContributor.Role); + } + + [Fact] + public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to count the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException() + { + // Arrange + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to read the books")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value); + SetupBooks(book); + _mockProviderA.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns((MetadataDto?)CreateApplicableBookMetadata("Dune")); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Error.Failure("Repository.Error", "Failed to save the changes")); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + /// + /// Stubs the book reader with a single page holding the provided books. + /// + /// The books of the page. + private void SetupBooks(params BookEntity[] books) + { + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.Success(books.Length)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result>.Success(books), + Result>.Success([])); + } + + /// + /// Configures the provided substitute metadata provider so that it declares the book lookup type for the books media library type. + /// + /// The metadata provider substitute to configure. + /// The display name the provider reports. + private static void ConfigureProvider(IMetadataProvider metadataProvider, string name) + { + metadataProvider.Name.Returns(name); + metadataProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + metadataProvider.RequiresWebAccess.Returns(false); + metadataProvider.LookupType.Returns(typeof(BookMetadataLookupDto)); + } + + /// + /// Creates a book metadata that is usable and carries only a title, and optionally a set of contributors. + /// + /// The title of the book. + /// The optional contributors of the book. + /// The created book metadata. + private BookMetadataDto CreateApplicableBookMetadata(string title, List? contributors = null) + { + return _bookMetadataDtoFixture.Create( + title: title, + contributors: contributors); + } +}