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