mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +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}'.")
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user