Merge pull request #109 from BinaryAlley/feature/implement-media-library-scan-system-infrastructure

Implements media library scan system infrastructure
This commit is contained in:
BinaryAlley authored and GitHub committed 2025-01-24 10:13:32 +00:00
commit 1c28355197
29 files changed
+1021 -1

No files matched your search

@@ -2,6 +2,11 @@
using FluentValidation;
using Lumina.Application.Common.Behaviors;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
@@ -36,6 +41,18 @@ public static class ApplicationLayerServices
services.AddScoped<IDomainEventsQueue, DomainEventsQueue>();
services.AddScoped<IBookLibraryTypeScanner, BookLibraryTypeScanner>();
services.AddScoped<ILibraryScanningService, LibraryScanningService>();
services.AddSingleton<IMediaScanQueue, MediaScanQueue>();
services.AddScoped<ILibraryScannerFactory, LibraryScannerFactory>();
services.AddScoped<IMediaScanJobFactory, MediaScanJobFactory>();
services.AddHostedService<MediaScanJobProcessorJob>();
services.AddTransient<FileSystemDiscoveryJob>();
services.AddTransient<RepositoryMetadataDiscoveryJob>();
services.AddTransient<HashComparerJob>();
services.AddTransient<GoodReadsMetadataScrapJob>();
return services;
}
}
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Linq;
#endregion
@@ -49,4 +50,14 @@ public static class LibraryEntityMapping
repositoryEntity.CoverImage
);
}
/// <summary>
/// Converts <paramref name="repositoryEntities"/> to a collection of <see cref="Library"/>.
/// </summary>
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>The converted responses.</returns>
public static IEnumerable<ErrorOr<Library>> ToDomainEntities(this IEnumerable<LibraryEntity> repositoryEntities)
{
return repositoryEntities.Select(library => library.ToDomainEntity());
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Utilities;
/// <summary>
/// Task extension method to handle exceptions (avoid littering whole project with try...catch'es).
/// </summary>
public static class TaskUtilities
{
/// <summary>
/// Extends Task by providing exception handling when a task is invoked on a void method (not awaited).
/// </summary>
/// <param name="task">The task to be awaited.</param>
public static async void FireAndForgetSafeAsync(this Task task)
{
try
{
await task;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
@@ -0,0 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries;
/// <summary>
/// Command for initiating the scan of all media libraries.
/// </summary>
public record ScanLibrariesCommand() : IRequest<ErrorOr<Success>>;
@@ -0,0 +1,77 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
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.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Application.Common.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries;
/// <summary>
/// Handler for the command for initiating the scan of all media libraries.
/// </summary>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly ILibraryScanningService _libraryScanningService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibrariesCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="libraryScanningService">Injected service for scanning media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScanLibrariesCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
ILibraryScanningService libraryScanningService,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_libraryScanningService = libraryScanningService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the command for initiating the scan of all media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
{
// if the user that made the request is not an Admin, they do not have the right to perform scans
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return Errors.Authorization.NotAuthorized;
// get all media libraries from the persistence medium
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsError)
return getLibrariesResult.Errors;
// convert persistence libraries to domain entities, and start scanning them
IEnumerable<ErrorOr<Library>> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities();
foreach (ErrorOr<Library> domainLibraryResult in domainEntitiesResult)
{
if (domainLibraryResult.IsError)
return domainLibraryResult.Errors;
await _libraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false);
}
return Result.Success;
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
/// <summary>
/// Interface for the service used to scan a media library.
/// </summary>
public interface ILibraryScanningService
{
/// <summary>
/// Starts the scan of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library to scan.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task StartScanAsync(Library library, CancellationToken cancellationToken);
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using System.Threading.Channels;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
/// <summary>
/// Interface for the message queue for handling <see cref="MediaScanJob"/> instances.
/// </summary>
internal interface IMediaScanQueue
{
/// <summary>
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaScanJob"/> instances.
/// </summary>
public ChannelWriter<MediaScanJob> Writer { get; }
/// <summary>
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaScanJob"/> instances.
/// </summary>
public ChannelReader<MediaScanJob> Reader { get; }
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for discovering file system items.
/// </summary>
internal class FileSystemDiscoveryJob : MediaScanJob
{
private readonly IDirectoryService _directoryService;
private readonly IFileService _fileService;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
/// </summary>
/// <param name="directoryService">Injected service for handling directories.</param>
/// <param name="fileService">Injected service for handling files.</param>
public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService)
{
_directoryService = directoryService;
_fileService = fileService;
}
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
// recursively get the file system tree for each of the media library content locations
List<FileSystemTreeNode> contentLocationTrees = [];
foreach (FileSystemPathId contentLocation in Library.ContentLocations)
{
ErrorOr<FileSystemTreeNode> treeResult = BuildTree(contentLocation, includeHiddenElements: true);
if (treeResult.IsError)
{
// handle errors, maybe:
// Status = LibraryScanJobStatus.Failed;
}
else
contentLocationTrees.Add(treeResult.Value);
}
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Builds a hierarchical tree structure representing the file system starting from the specified path.
/// </summary>
/// <param name="path">The identifier of the root path from which to build the tree.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the tree.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
public ErrorOr<FileSystemTreeNode> BuildTree(FileSystemPathId path, bool includeHiddenElements = false)
{
// validate the path and get the root directory node
ErrorOr<Directory> rootDirectoryResult = Directory.Create(path, path.Path, Optional<DateTime>.None(), Optional<DateTime>.None());
if (rootDirectoryResult.IsError)
return rootDirectoryResult.Errors;
// build the tree starting from the root directory
return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements);
}
/// <summary>
/// Recursively builds a tree node for a given directory, including its subdirectories and files.
/// </summary>
/// <param name="directory">The directory for which to build a tree node.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the node's children.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildNodeRecursive(Directory directory, bool includeHiddenElements)
{
FileSystemTreeNode node = new()
{
Path = directory.Id.Path,
Name = directory.Name,
ItemType = FileSystemItemType.Directory,
Children = []
};
// fetch and add subdirectories
ErrorOr<IEnumerable<Directory>> subdirectoriesResult = _directoryService.GetSubdirectories(directory, includeHiddenElements);
if (subdirectoriesResult.IsError)
return subdirectoriesResult.Errors;
foreach (Directory subdirectory in subdirectoriesResult.Value)
{
ErrorOr<FileSystemTreeNode> subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements);
if (subNodeResult.IsError)
return subNodeResult.Errors;
node.Children.Add(subNodeResult.Value);
}
// fetch and add files
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(directory.Id, includeHiddenElements);
if (filesResult.IsError)
return filesResult.Errors;
foreach (File file in filesResult.Value)
{
node.Children.Add(new FileSystemTreeNode
{
Path = file.Id.Path,
Name = file.Name,
ItemType = FileSystemItemType.File,
Children = [] // files have no children
});
}
return node;
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for comparing hashes.
/// </summary>
internal class HashComparerJob : MediaScanJob
{
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Interface for the media library scan jobs factory.
/// </summary>
internal interface IMediaScanJobFactory
{
/// <summary>
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
/// </summary>
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
TJob CreateJob<TJob>(Library library) where TJob : MediaScanJob;
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Abstract class defining a media library scan job.
/// </summary>
internal abstract class MediaScanJob
{
internal int parentsPayloadsExecuted;
/// <summary>
/// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
public List<MediaScanJob> Children { get; protected set; } = [];
/// <summary>
/// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
public List<MediaScanJob> Parents { get; protected set; } = [];
/// <summary>
/// Gets or sets the media library upon which the scan is performed.
/// </summary>
public required Library Library { get; set; }
/// <summary>
/// Gets or sets the status of the current media library scan job.
/// </summary>
public LibraryScanJobStatus Status { get; protected set; } = LibraryScanJobStatus.Pending;
/// <summary>
/// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
public void AddChild(MediaScanJob job)
{
if (!Children.Contains(job) && !Parents.Contains(job))
Children.Add(job);
}
/// <summary>
/// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
public void AddParent(MediaScanJob job)
{
if (!Parents.Contains(job) && !Children.Contains(job))
Parents.Add(job);
}
/// <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 abstract Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken);
}
@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Concrete implementation for the media library scan jobs factory.
/// </summary>
internal class MediaScanJobFactory : IMediaScanJobFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="MediaScanJobFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public MediaScanJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
/// </summary>
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
public TJob CreateJob<TJob>(Library library) where TJob : MediaScanJob
{
// resolve the job from DI
TJob job = _serviceProvider.GetRequiredService<TJob>() ?? throw new ArgumentException();
job.Library = library;
return job;
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
/// <summary>
/// Media library scan job for retrieving persistence data from any eventual previous scans.
/// </summary>
internal class RepositoryMetadataDiscoveryJob : MediaScanJob
{
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads;
/// <summary>
/// Generic file system node.
/// </summary>
[DebuggerDisplay("Path: {Path}")]
public class FileSystemTreeNode
{
/// <summary>
/// Gets or sets the full path of the file or directory.
/// </summary>
public string Path { get; set; } = null!;
/// <summary>
/// Gets or sets the name of the file or directory.
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Gets or sets the type of the item, indicating whether it is a file, directory, or drive.
/// </summary>
public FileSystemItemType ItemType { get; set; }
/// <summary>
/// Gets or sets the list of child nodes.
/// </summary>
public List<FileSystemTreeNode> Children { get; set; } = [];
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using Lumina.Domain.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Media library scan job for retrieving written content metadata from GoodReads.
/// </summary>
internal class GoodReadsMetadataScrapJob : MediaScanJob
{
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
/// <summary>
/// Service used to scan a media library.
/// </summary>
internal class LibraryScanningService : ILibraryScanningService
{
private readonly IMediaScanQueue _mediaScanQueue;
private readonly ILibraryScannerFactory _libraryScannerFactory;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanningService"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
/// <param name="libraryScannerFactory">Injected factory for creating media library scanners.</param>
public LibraryScanningService(IMediaScanQueue mediaScanQueue, ILibraryScannerFactory libraryScannerFactory)
{
_mediaScanQueue = mediaScanQueue;
_libraryScannerFactory = libraryScannerFactory;
}
/// <summary>
/// Starts the scan of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library to scan.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task StartScanAsync(Library library, CancellationToken cancellationToken)
{
try
{
// get a media library scanne for the provided media library type
IMediaTypeScanner scanner = _libraryScannerFactory.CreateLibraryScanner(library.LibraryType);
// get the list of scan jobs for the retrieved scanner
IEnumerable<MediaScanJob> jobs = scanner.CreateScanJobsForLibrary(library);
// enqueue the jobs on the channel from where they will be processed
foreach (MediaScanJob job in jobs)
await _mediaScanQueue.Writer.WriteAsync(job, cancellationToken).ConfigureAwait(false);
}
catch (NotImplementedException) { }
}
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
/// <summary>
/// Background service for processing media library scan jobs from an in-memory message queue.
/// </summary>
internal sealed class MediaScanJobProcessorJob : BackgroundService
{
private readonly IMediaScanQueue _mediaScanQueue;
/// <summary>
/// Initializes a new instance of the <see cref="MediaScanJobProcessorJob"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
public MediaScanJobProcessorJob(IMediaScanQueue mediaScanQueue)
{
_mediaScanQueue = mediaScanQueue;
}
/// <summary>
/// Method called when the background service starts.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
// continuously processes and executes media library scan jobs from the queue until the application shuts down
// remark: since only top level scan jobs are placed on the bus, but they themselves trigger the execution of their children jobs, and so on,
// their completion should not be awaited here due to some of them being long running tasks; therefor they are just fired synchronously
// without being awaited, while still properly handling any exceptions they might throw in their asynchronous execution
await foreach (MediaScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
mediaScanJob.ExecuteAsync(Guid.NewGuid(), new {}, cancellationToken).FireAndForgetSafeAsync();
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using System.Threading.Channels;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
/// <summary>
/// Provides an in-memory message queue for handling <see cref="MediaScanJob"/> instances.
/// </summary>
internal class MediaScanQueue : IMediaScanQueue
{
private readonly Channel<MediaScanJob> _channel = Channel.CreateUnbounded<MediaScanJob>();
/// <summary>
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaScanJob"/> instances.
/// </summary>
public ChannelWriter<MediaScanJob> Writer
{
get { return _channel.Writer; }
}
/// <summary>
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaScanJob"/> instances.
/// </summary>
public ChannelReader<MediaScanJob> Reader
{
get { return _channel.Reader; }
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.MediaLibrary;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
/// <summary>
/// Interface defining a factory for creating media library scanners.
/// </summary>
internal interface ILibraryScannerFactory
{
/// <summary>
/// Creates a media library scanner based on the provided library type.
/// </summary>
/// <param name="libraryType">The type of the library that determines the type of the created media library scanner.</param>
/// <returns>A media library scanner for the specified media library type.</returns>
IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType);
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
/// <summary>
/// Interface defining a media library scanner for a specific media library type.
/// </summary>
internal interface IMediaTypeScanner
{
/// <summary>
/// The media library type that this media library scanner supports.
/// </summary>
LibraryType SupportedType { get; }
/// <summary>
/// Creates the media library scan jobs for the provided media library.
/// </summary>
/// <param name="library">The media library for which to create the media library scan jobs.</param>
/// <returns>A collection of media library scan jobs.</returns>
IEnumerable<MediaScanJob> CreateScanJobsForLibrary(Library library);
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Microsoft.Extensions.DependencyInjection;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
/// <summary>
/// Defines a factory for creating media library scanners.
/// </summary>
internal class LibraryScannerFactory : ILibraryScannerFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScannerFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public LibraryScannerFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// Creates a media library scanner for the specified library type.
/// </summary>
/// <param name="libraryType">The type of the media library.</param>
/// <returns>A media library scanner for the specified library type.</returns>
public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType)
{
return libraryType switch
{
// 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."),
LibraryType.Magazine => throw new NotImplementedException("Magazine scanner is not implemented."),
LibraryType.Newspaper => throw new NotImplementedException("Newspaper scanner is not implemented."),
LibraryType.Manga => throw new NotImplementedException("Manga scanner is not implemented."),
LibraryType.GraphicNovel => throw new NotImplementedException("GraphicNovel scanner is not implemented."),
LibraryType.AcademicPaper => throw new NotImplementedException("AcademicPaper scanner is not implemented."),
LibraryType.SheetMusic => throw new NotImplementedException("SheetMusic scanner is not implemented."),
LibraryType.Movie => throw new NotImplementedException("Movie scanner is not implemented."),
LibraryType.TvShow => throw new NotImplementedException("TvShow scanner is not implemented."),
LibraryType.Documentary => throw new NotImplementedException("Documentary scanner is not implemented."),
LibraryType.Anime => throw new NotImplementedException("Anime scanner is not implemented."),
LibraryType.ConcertVideo => throw new NotImplementedException("ConcertVideo scanner is not implemented."),
LibraryType.TutorialVideo => throw new NotImplementedException("TutorialVideo scanner is not implemented."),
LibraryType.HomeVideo => throw new NotImplementedException("HomeVideo scanner is not implemented."),
LibraryType.YouTubeVideo => throw new NotImplementedException("YouTubeVideo scanner is not implemented."),
LibraryType.MusicVideo => throw new NotImplementedException("MusicVideo scanner is not implemented."),
LibraryType.LiveRecordingVideo => throw new NotImplementedException("LiveRecordingVideo scanner is not implemented."),
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.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."),
LibraryType.CoverSongAudio => throw new NotImplementedException("CoverSongAudio scanner is not implemented."),
LibraryType.Remix => throw new NotImplementedException("Remix scanner is not implemented."),
LibraryType.SoundEffect => throw new NotImplementedException("SoundEffect scanner is not implemented."),
LibraryType.PodcastAudio => throw new NotImplementedException("PodcastAudio scanner is not implemented."),
LibraryType.Photo => throw new NotImplementedException("Photo scanner is not implemented."),
LibraryType.Playlist => throw new NotImplementedException("Playlist scanner is not implemented."),
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
_ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.")
};
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
/// <summary>
/// Media library scanner for a books media library type.
/// </summary>
internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
{
private readonly IMediaScanJobFactory _mediaScanJobFactory;
/// <inheritdoc/>
public LibraryType SupportedType { get; } = LibraryType.Book;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScannerFactory"/> class.
/// </summary>
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
public BookLibraryTypeScanner(IMediaScanJobFactory mediaScanJobFactory)
{
_mediaScanJobFactory = mediaScanJobFactory;
}
/// <inheritdoc/>
public IEnumerable<MediaScanJob> CreateScanJobsForLibrary(Library library)
{
// declare the list of jobs that this scanner requires
FileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<FileSystemDiscoveryJob>(library);
RepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob<RepositoryMetadataDiscoveryJob>(library);
HashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob<HashComparerJob>(library);
GoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob<GoodReadsMetadataScrapJob>(library);
// establish the hierarchical relationships between jobs
fileSystemDiscoveryJob.AddChild(hashComparerJob);
repositoryMetadataDiscoveryJob.AddChild(hashComparerJob);
hashComparerJob.AddParent(fileSystemDiscoveryJob);
hashComparerJob.AddParent(repositoryMetadataDiscoveryJob);
hashComparerJob.AddChild(goodReadsMetadataScrapJob);
goodReadsMetadataScrapJob.AddParent(hashComparerJob);
// return the top level jobs that will be triggered when the scan will be started
yield return fileSystemDiscoveryJob;
yield return repositoryMetadataDiscoveryJob;
}
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
/// <summary>
/// Interface defining a media library scanner for a books media library type.
/// </summary>
internal interface IBookLibraryTypeScanner : IMediaTypeScanner
{
}
@@ -28,6 +28,7 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,27 @@
namespace Lumina.Domain.Common.Enums.MediaLibrary;
/// <summary>
/// Enumeration for the statuses of the jobs ran on media libraries scan.
/// </summary>
public enum LibraryScanJobStatus
{
/// <summary>
/// Job is still pending.
/// </summary>
Pending,
/// <summary>
/// Job is running.
/// </summary>
Running,
/// <summary>
/// Job has finished successfully.
/// </summary>
Completed,
/// <summary>
/// Job has failed.
/// </summary>
Failed
}
@@ -15,5 +15,6 @@ public static partial class ApiRoutes
public const string ADD_LIBRARY = "/libraries";
public const string UPDATE_LIBRARY = "/libraries/{id}";
public const string DELETE_LIBRARY = "/libraries/{id}";
public const string SCAN_LIBRARIES = "/libraries/scan";
}
}
@@ -46,7 +46,6 @@ public class GetLibrariesEndpointSummary : Summary<GetLibrariesEndpoint, EmptyRe
)
});
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries;
/// <summary>
/// API endpoint for the <c>/libraries/scan</c> route.
/// </summary>
public class ScanLibrariesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibrariesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ScanLibrariesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Libraries.SCAN_LIBRARIES);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Initiates a scan of all media libraries.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<Success> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries;
/// <summary>
/// Class used for providing a textual description for the <see cref="ScanLibrariesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibrariesEndpointSummary : Summary<ScanLibrariesEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibrariesEndpointSummary"/> class.
/// </summary>
public ScanLibrariesEndpointSummary()
{
Summary = "Triggers the scan of all media libraries.";
Description = "Starts the scanning process of all media libraries, if the user making the request is an Admin.";
Response(204, "The media libraries scan was successfully started.");
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/libraries/scan"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/libraries/scan"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/libraries/scan"
}
}
);
Response(403, "The request failed because the user making the request is not an Admin.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1//libraries/scan",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
}
}