From 69919f7ca19b6664a2d3b73bc1c7ad8ba19c58c8 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 24 Jan 2025 12:08:03 +0200 Subject: [PATCH] Implements media library scan system infrastructure --- .../ApplicationLayerServices.cs | 17 +++ .../Management/LibraryEntityMapping.cs | 11 ++ .../Common/Utilities/TaskUtilities.cs | 29 ++++ .../ScanLibraries/ScanLibrariesCommand.cs | 11 ++ .../ScanLibrariesCommandHandler.cs | 77 +++++++++++ .../Scanning/ILibraryScanningService.cs | 20 +++ .../Services/Scanning/IMediaScanQueue.cs | 22 +++ .../Jobs/Common/FileSystemDiscoveryJob.cs | 129 ++++++++++++++++++ .../Scanning/Jobs/Common/HashComparerJob.cs | 31 +++++ .../Jobs/Common/IMediaScanJobFactory.cs | 20 +++ .../Scanning/Jobs/Common/MediaScanJob.cs | 67 +++++++++ .../Jobs/Common/MediaScanJobFactory.cs | 38 ++++++ .../Common/RepositoryMetadataDiscoveryJob.cs | 31 +++++ .../Jobs/Payloads/FileSystemTreeNode.cs | 34 +++++ .../Books/GoodReadsMetadataScrapJob.cs | 32 +++++ .../Scanning/LibraryScanningService.cs | 51 +++++++ .../Scanning/MediaScanJobProcessorJob.cs | 41 ++++++ .../Services/Scanning/MediaScanQueue.cs | 30 ++++ .../Scanners/Common/ILibraryScannerFactory.cs | 18 +++ .../Scanners/Common/IMediaTypeScanner.cs | 26 ++++ .../Scanners/Common/LibraryScannerFactory.cs | 75 ++++++++++ .../WrittenContent/BookLibraryTypeScanner.cs | 53 +++++++ .../WrittenContent/IBookLibraryTypeScanner.cs | 12 ++ .../Lumina.Application.csproj | 1 + .../MediaLibrary/LibraryScanJobStatus.cs | 27 ++++ .../Library/Management/ApiRoutes.Libraries.cs | 1 + .../GetLibrariesEndpointSummary.cs | 1 - .../ScanLibraries/ScanLibrariesEndpoint.cs | 51 +++++++ .../ScanLibrariesEndpointSummary.cs | 66 +++++++++ 29 files changed, 1021 insertions(+), 1 deletion(-) create mode 100644 src/Lumina.Application/Common/Utilities/TaskUtilities.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaScanJobFactory.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJob.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJobFactory.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/ILibraryScannerFactory.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/LibraryScannerFactory.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs create mode 100644 src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 5422de9d..6b50b318 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -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(); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + return services; } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 430ec2fb..7766d988 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -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 ); } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted responses. + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(library => library.ToDomainEntity()); + } } diff --git a/src/Lumina.Application/Common/Utilities/TaskUtilities.cs b/src/Lumina.Application/Common/Utilities/TaskUtilities.cs new file mode 100644 index 00000000..228091b9 --- /dev/null +++ b/src/Lumina.Application/Common/Utilities/TaskUtilities.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Utilities; + +/// +/// Task extension method to handle exceptions (avoid littering whole project with try...catch'es). +/// +public static class TaskUtilities +{ + /// + /// Extends Task by providing exception handling when a task is invoked on a void method (not awaited). + /// + /// The task to be awaited. + public static async void FireAndForgetSafeAsync(this Task task) + { + try + { + await task; + } + catch (Exception ex) + { + Debug.WriteLine(ex); + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs new file mode 100644 index 00000000..f8051849 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs @@ -0,0 +1,11 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; + +/// +/// Command for initiating the scan of all media libraries. +/// +public record ScanLibrariesCommand() : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs new file mode 100644 index 00000000..7d519d65 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -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; + +/// +/// Handler for the command for initiating the scan of all media libraries. +/// +public class ScanLibrariesCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly ILibraryScanningService _libraryScanningService; + private readonly IAuthorizationService _authorizationService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for scanning media libraries. + /// Injected unit of work for interacting with the data access layer repositories. + public ScanLibrariesCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + ILibraryScanningService libraryScanningService, + IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _libraryScanningService = libraryScanningService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the command for initiating the scan of all media libraries. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async ValueTask> 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(); + ErrorOr> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getLibrariesResult.IsError) + return getLibrariesResult.Errors; + + // convert persistence libraries to domain entities, and start scanning them + IEnumerable> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); + foreach (ErrorOr domainLibraryResult in domainEntitiesResult) + { + if (domainLibraryResult.IsError) + return domainLibraryResult.Errors; + await _libraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false); + } + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs new file mode 100644 index 00000000..faec0da1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs @@ -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; + +/// +/// Interface for the service used to scan a media library. +/// +public interface ILibraryScanningService +{ + /// + /// Starts the scan of . + /// + /// The media library to scan. + /// Cancellation token that can be used to stop the execution. + Task StartScanAsync(Library library, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs new file mode 100644 index 00000000..394ee60a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs @@ -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; + +/// +/// Interface for the message queue for handling instances. +/// +internal interface IMediaScanQueue +{ + /// + /// Gets the writer for the queue, allowing producers to enqueue instances. + /// + public ChannelWriter Writer { get; } + + /// + /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// + public ChannelReader Reader { get; } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs new file mode 100644 index 00000000..70959750 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs @@ -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; + +/// +/// Media library scan job for discovering file system items. +/// +internal class FileSystemDiscoveryJob : MediaScanJob +{ + private readonly IDirectoryService _directoryService; + private readonly IFileService _fileService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling directories. + /// Injected service for handling files. + public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService) + { + _directoryService = directoryService; + _fileService = fileService; + } + + /// + public override async Task ExecuteAsync(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 contentLocationTrees = []; + foreach (FileSystemPathId contentLocation in Library.ContentLocations) + { + ErrorOr 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); + } + } + + /// + /// Builds a hierarchical tree structure representing the file system starting from the specified path. + /// + /// The identifier of the root path from which to build the tree. + /// Specifies whether hidden files and directories should be included in the tree. + /// An containing either a , or an error. + public ErrorOr BuildTree(FileSystemPathId path, bool includeHiddenElements = false) + { + // validate the path and get the root directory node + ErrorOr rootDirectoryResult = Directory.Create(path, path.Path, Optional.None(), Optional.None()); + if (rootDirectoryResult.IsError) + return rootDirectoryResult.Errors; + + // build the tree starting from the root directory + return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements); + } + + /// + /// Recursively builds a tree node for a given directory, including its subdirectories and files. + /// + /// The directory for which to build a tree node. + /// Specifies whether hidden files and directories should be included in the node's children. + /// An containing either a , or an error. + private ErrorOr BuildNodeRecursive(Directory directory, bool includeHiddenElements) + { + FileSystemTreeNode node = new() + { + Path = directory.Id.Path, + Name = directory.Name, + ItemType = FileSystemItemType.Directory, + Children = [] + }; + + // fetch and add subdirectories + ErrorOr> subdirectoriesResult = _directoryService.GetSubdirectories(directory, includeHiddenElements); + if (subdirectoriesResult.IsError) + return subdirectoriesResult.Errors; + + foreach (Directory subdirectory in subdirectoriesResult.Value) + { + ErrorOr subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements); + if (subNodeResult.IsError) + return subNodeResult.Errors; + + node.Children.Add(subNodeResult.Value); + } + + // fetch and add files + ErrorOr> 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; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs new file mode 100644 index 00000000..c65b0998 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/HashComparerJob.cs @@ -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; + +/// +/// Media library scan job for comparing hashes. +/// +internal class HashComparerJob : MediaScanJob +{ + /// + public override async Task ExecuteAsync(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 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); + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaScanJobFactory.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaScanJobFactory.cs new file mode 100644 index 00000000..f79ee714 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaScanJobFactory.cs @@ -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; + +/// +/// Interface for the media library scan jobs factory. +/// +internal interface IMediaScanJobFactory +{ + /// + /// Creates a new media library scan job of type . + /// + /// The type of media library scan job to create. + /// A media library scan job of type . + /// Thrown when the type of the requested media library scan job has not been registered. + TJob CreateJob(Library library) where TJob : MediaScanJob; +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJob.cs new file mode 100644 index 00000000..d67b5fde --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJob.cs @@ -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; + +/// +/// Abstract class defining a media library scan job. +/// +internal abstract class MediaScanJob +{ + internal int parentsPayloadsExecuted; + + /// + /// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution. + /// + public List Children { get; protected set; } = []; + + /// + /// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution. + /// + public List Parents { get; protected set; } = []; + + /// + /// Gets or sets the media library upon which the scan is performed. + /// + public required Library Library { get; set; } + + /// + /// Gets or sets the status of the current media library scan job. + /// + public LibraryScanJobStatus Status { get; protected set; } = LibraryScanJobStatus.Pending; + + /// + /// 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. + /// + /// The child media library scan job to be added. + public void AddChild(MediaScanJob job) + { + if (!Children.Contains(job) && !Parents.Contains(job)) + Children.Add(job); + } + + /// + /// 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. + /// + /// The child media library scan job to be added. + public void AddParent(MediaScanJob job) + { + if (!Parents.Contains(job) && !Children.Contains(job)) + Parents.Add(job); + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The id of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public abstract Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJobFactory.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJobFactory.cs new file mode 100644 index 00000000..b7b1ddf5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJobFactory.cs @@ -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; + +/// +/// Concrete implementation for the media library scan jobs factory. +/// +internal class MediaScanJobFactory : IMediaScanJobFactory +{ + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider. + public MediaScanJobFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + /// + /// Creates a new media library scan job of type . + /// + /// The type of media library scan job to create. + /// A media library scan job of type . + /// Thrown when the type of the requested media library scan job has not been registered. + public TJob CreateJob(Library library) where TJob : MediaScanJob + { + // resolve the job from DI + TJob job = _serviceProvider.GetRequiredService() ?? throw new ArgumentException(); + job.Library = library; + return job; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs new file mode 100644 index 00000000..d4a9c233 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs @@ -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; + +/// +/// Media library scan job for retrieving persistence data from any eventual previous scans. +/// +internal class RepositoryMetadataDiscoveryJob : MediaScanJob +{ + /// + public override async Task ExecuteAsync(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 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); + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs new file mode 100644 index 00000000..28b30b52 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Payloads/FileSystemTreeNode.cs @@ -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; + +/// +/// Generic file system node. +/// +[DebuggerDisplay("Path: {Path}")] +public class FileSystemTreeNode +{ + /// + /// Gets or sets the full path of the file or directory. + /// + public string Path { get; set; } = null!; + + /// + /// Gets or sets the name of the file or directory. + /// + public string Name { get; set; } = null!; + + /// + /// Gets or sets the type of the item, indicating whether it is a file, directory, or drive. + /// + public FileSystemItemType ItemType { get; set; } + + /// + /// Gets or sets the list of child nodes. + /// + public List Children { get; set; } = []; +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs new file mode 100644 index 00000000..c39b29ed --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -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; + +/// +/// Media library scan job for retrieving written content metadata from GoodReads. +/// +internal class GoodReadsMetadataScrapJob : MediaScanJob +{ + /// + public override async Task ExecuteAsync(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 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); + } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs new file mode 100644 index 00000000..990a70a3 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs @@ -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; + +/// +/// Service used to scan a media library. +/// +internal class LibraryScanningService : ILibraryScanningService +{ + private readonly IMediaScanQueue _mediaScanQueue; + private readonly ILibraryScannerFactory _libraryScannerFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected queue used for processing media libraries scan jobs. + /// Injected factory for creating media library scanners. + public LibraryScanningService(IMediaScanQueue mediaScanQueue, ILibraryScannerFactory libraryScannerFactory) + { + _mediaScanQueue = mediaScanQueue; + _libraryScannerFactory = libraryScannerFactory; + } + + /// + /// Starts the scan of . + /// + /// The media library to scan. + /// Cancellation token that can be used to stop the execution. + 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 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) { } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs new file mode 100644 index 00000000..bf534fd1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs @@ -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; + +/// +/// Background service for processing media library scan jobs from an in-memory message queue. +/// +internal sealed class MediaScanJobProcessorJob : BackgroundService +{ + private readonly IMediaScanQueue _mediaScanQueue; + + /// + /// Initializes a new instance of the class. + /// + /// Injected queue used for processing media libraries scan jobs. + public MediaScanJobProcessorJob(IMediaScanQueue mediaScanQueue) + { + _mediaScanQueue = mediaScanQueue; + } + + /// + /// Method called when the background service starts. + /// + /// Cancellation token that can be used to stop the execution. + 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(); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs new file mode 100644 index 00000000..79ff3652 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs @@ -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; + +/// +/// Provides an in-memory message queue for handling instances. +/// +internal class MediaScanQueue : IMediaScanQueue +{ + private readonly Channel _channel = Channel.CreateUnbounded(); + + /// + /// Gets the writer for the queue, allowing producers to enqueue instances. + /// + public ChannelWriter Writer + { + get { return _channel.Writer; } + } + + /// + /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// + public ChannelReader Reader + { + get { return _channel.Reader; } + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/ILibraryScannerFactory.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/ILibraryScannerFactory.cs new file mode 100644 index 00000000..fa815ba5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/ILibraryScannerFactory.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Enums.MediaLibrary; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; + +/// +/// Interface defining a factory for creating media library scanners. +/// +internal interface ILibraryScannerFactory +{ + /// + /// Creates a media library scanner based on the provided library type. + /// + /// The type of the library that determines the type of the created media library scanner. + /// A media library scanner for the specified media library type. + IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs new file mode 100644 index 00000000..c9da4c4b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaTypeScanner.cs @@ -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; + +/// +/// Interface defining a media library scanner for a specific media library type. +/// +internal interface IMediaTypeScanner +{ + /// + /// The media library type that this media library scanner supports. + /// + LibraryType SupportedType { get; } + + /// + /// Creates the media library scan jobs for the provided media library. + /// + /// The media library for which to create the media library scan jobs. + /// A collection of media library scan jobs. + IEnumerable CreateScanJobsForLibrary(Library library); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/LibraryScannerFactory.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/LibraryScannerFactory.cs new file mode 100644 index 00000000..a161ee5e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/LibraryScannerFactory.cs @@ -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; + +/// +/// Defines a factory for creating media library scanners. +/// +internal class LibraryScannerFactory : ILibraryScannerFactory +{ + private readonly IServiceProvider _serviceProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider. + public LibraryScannerFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + + /// + /// Creates a media library scanner for the specified library type. + /// + /// The type of the media library. + /// A media library scanner for the specified library type. + public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType) + { + return libraryType switch + { + // implemented scanners + LibraryType.Book => _serviceProvider.GetRequiredService(), + LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."), + LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."), + 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}'.") + }; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs new file mode 100644 index 00000000..3b0d2b73 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/BookLibraryTypeScanner.cs @@ -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; + +/// +/// Media library scanner for a books media library type. +/// +internal class BookLibraryTypeScanner : IBookLibraryTypeScanner +{ + private readonly IMediaScanJobFactory _mediaScanJobFactory; + + /// + public LibraryType SupportedType { get; } = LibraryType.Book; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating media library scan jobs. + public BookLibraryTypeScanner(IMediaScanJobFactory mediaScanJobFactory) + { + _mediaScanJobFactory = mediaScanJobFactory; + } + + /// + public IEnumerable CreateScanJobsForLibrary(Library library) + { + // declare the list of jobs that this scanner requires + FileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(library); + RepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(library); + HashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(library); + GoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(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; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs new file mode 100644 index 00000000..18038c96 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/WrittenContent/IBookLibraryTypeScanner.cs @@ -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; + +/// +/// Interface defining a media library scanner for a books media library type. +/// +internal interface IBookLibraryTypeScanner : IMediaTypeScanner +{ +} diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index 56ecccde..e9b99955 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -28,6 +28,7 @@ + diff --git a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs new file mode 100644 index 00000000..350eb590 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs @@ -0,0 +1,27 @@ +namespace Lumina.Domain.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the statuses of the jobs ran on media libraries scan. +/// +public enum LibraryScanJobStatus +{ + /// + /// Job is still pending. + /// + Pending, + + /// + /// Job is running. + /// + Running, + + /// + /// Job has finished successfully. + /// + Completed, + + /// + /// Job has failed. + /// + Failed +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index d7726077..da9222f5 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -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"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs index 8ca542f9..10dc2144 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointSummary.cs @@ -46,7 +46,6 @@ public class GetLibrariesEndpointSummary : Summary +/// API endpoint for the /libraries/scan route. +/// +public class ScanLibrariesEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public ScanLibrariesEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Libraries.SCAN_LIBRARIES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Initiates a scan of all media libraries. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs new file mode 100644 index 00000000..2ae0a443 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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" + } + ); + } +}