From e862f5de30379116d5b602fa5a8cb6c75d4dde8e Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 1 Feb 2025 16:30:48 +0200 Subject: [PATCH] Adds media libraries cancel scan option --- README.md | 2 + .../ApplicationLayerServices.cs | 13 +- .../Models/Scanning/MediaScanTrackerModel.cs | 12 ++ .../CancelLibraryScanRequestMapping.cs | 24 ++++ .../Management/ScanLibraryRequestMapping.cs | 24 ++++ .../Common/Utilities/TaskUtilities.cs | 7 +- .../CancelLibrariesScanCommand.cs | 11 ++ .../CancelLibrariesScanCommandHandler.cs | 42 ++++++ .../CancelLibraryScanCommand.cs | 17 +++ .../CancelLibraryScanCommandHandler.cs | 50 +++++++ .../CancelLibraryScanCommandValidator.cs | 23 ++++ .../ScanLibraries/ScanLibrariesCommand.cs | 4 +- .../ScanLibrariesCommandHandler.cs | 30 +++-- .../ScanLibrary/ScanLibraryCommand.cs | 16 +++ .../ScanLibrary/ScanLibraryCommandHandler.cs | 90 +++++++++++++ .../ScanLibraryCommandValidator.cs | 23 ++++ ...ice.cs => IMediaLibraryScanningService.cs} | 12 +- .../Jobs/Common/FileSystemDiscoveryJob.cs | 55 +++++--- .../Scanning/Jobs/Common/HashComparerJob.cs | 28 ++-- ...tory.cs => IMediaLibraryScanJobFactory.cs} | 4 +- ...MediaScanJob.cs => MediaLibraryScanJob.cs} | 20 ++- ...ctory.cs => MediaLibraryScanJobFactory.cs} | 8 +- .../Common/RepositoryMetadataDiscoveryJob.cs | 28 ++-- .../Books/GoodReadsMetadataScrapJob.cs | 28 ++-- .../Scanning/LibraryScanningService.cs | 51 ------- .../Scanning/MediaLibraryScanningService.cs | 84 ++++++++++++ .../IMediaLibrariesScanQueue.cs} | 14 +- .../MediaLibrariesScanQueue.cs} | 16 +-- .../MediaLibraryScanJobProcessorJob.cs} | 23 +++- ...tory.cs => IMediaLibraryScannerFactory.cs} | 2 +- .../Scanners/Common/IMediaTypeScanner.cs | 2 +- ...ctory.cs => MediaLibraryScannerFactory.cs} | 6 +- .../WrittenContent/BookLibraryTypeScanner.cs | 6 +- .../Tracking/IMediaLibrariesScanTracker.cs | 40 ++++++ .../Tracking/MediaLibrariesScanTracker.cs | 100 ++++++++++++++ .../Management/CancelLibraryScanRequest.cs | 15 +++ .../Management/DeleteLibraryRequest.cs | 2 +- .../Management/ScanLibraryRequest.cs | 15 +++ .../Management/LibraryResponse.cs | 2 +- .../Management/ScanLibraryResponse.cs | 17 +++ .../MediaLibrary/LibraryScanJobStatus.cs | 5 + .../Common/Errors/Errors.Library.cs | 4 +- .../Library/Management/ApiRoutes.Libraries.cs | 3 + .../CancelLibrariesScanEndpoint.cs | 51 +++++++ .../CancelLibrariesScanEndpointSummary.cs | 56 ++++++++ .../CancelLibraryScanEndpoint.cs | 52 +++++++ .../CancelLibraryScanEndpointSummary.cs | 76 +++++++++++ .../DeleteLibraryEndpointSummary.cs | 110 +++++++++++++++ .../ScanLibraries/ScanLibrariesEndpoint.cs | 6 +- .../ScanLibrariesEndpointSummary.cs | 28 ++-- .../ScanLibrary/ScanLibraryEndpoint.cs | 53 ++++++++ .../ScanLibrary/ScanLibraryEndpointSummary.cs | 127 ++++++++++++++++++ .../Models/Libraries/ScanLibraryModel.cs | 23 ++++ .../Management/LibraryManagementController.cs | 39 +++++- .../ExceptionHandlingMiddleware.de-DE.resx | 6 + .../ExceptionHandlingMiddleware.en-US.resx | 6 + .../ExceptionHandlingMiddleware.es-ES.resx | 6 + .../ExceptionHandlingMiddleware.fr-FR.resx | 6 + .../ExceptionHandlingMiddleware.it-IT.resx | 6 + .../ExceptionHandlingMiddleware.ja-JP.resx | 6 + .../ExceptionHandlingMiddleware.resx | 6 + .../ExceptionHandlingMiddleware.ro-RO.resx | 6 + .../ExceptionHandlingMiddleware.ru-RU.resx | 6 + .../ExceptionHandlingMiddleware.zh-CN.resx | 6 + .../Views/Library/Management/Index.de-DE.resx | 3 + .../Views/Library/Management/Index.en-US.resx | 3 + .../Views/Library/Management/Index.es-ES.resx | 3 + .../Views/Library/Management/Index.fr-FR.resx | 3 + .../Views/Library/Management/Index.it-IT.resx | 3 + .../Views/Library/Management/Index.ja-JP.resx | 3 + .../Views/Library/Management/Index.resx | 3 + .../Views/Library/Management/Index.ro-RO.resx | 3 + .../Views/Library/Management/Index.ru-RU.resx | 3 + .../Views/Library/Management/Index.zh-CN.resx | 3 + .../Views/Library/Management/Index.cshtml | 81 +++++++++-- .../wwwroot/images/ui/stop.svg | 5 + .../wwwroot/images/ui/trigger.svg | 4 + 77 files changed, 1585 insertions(+), 194 deletions(-) create mode 100644 src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMapping.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/{ILibraryScanningService.cs => IMediaLibraryScanningService.cs} (65%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/{IMediaScanJobFactory.cs => IMediaLibraryScanJobFactory.cs} (88%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/{MediaScanJob.cs => MediaLibraryScanJob.cs} (80%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/{MediaScanJobFactory.cs => MediaLibraryScanJobFactory.cs} (85%) delete mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/{IMediaScanQueue.cs => Queue/IMediaLibrariesScanQueue.cs} (67%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/{MediaScanQueue.cs => Queue/MediaLibrariesScanQueue.cs} (64%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/{MediaScanJobProcessorJob.cs => Queue/MediaLibraryScanJobProcessorJob.cs} (55%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/{ILibraryScannerFactory.cs => IMediaLibraryScannerFactory.cs} (94%) rename src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/{LibraryScannerFactory.cs => MediaLibraryScannerFactory.cs} (95%) create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs create mode 100644 src/Lumina.Presentation.Web/wwwroot/images/ui/stop.svg create mode 100644 src/Lumina.Presentation.Web/wwwroot/images/ui/trigger.svg diff --git a/README.md b/README.md index b59a2f4b..8211b28b 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ Several icons used in this project were adapted from icons sourced from [svgrepo - [`question.svg`](https://www.svgrepo.com/svg/486470/question-filled) (MIT License) - [`warning.svg`](https://www.svgrepo.com/svg/454067/warning) (MIT License) - [`error.svg`](https://www.svgrepo.com/svg/486408/error-filled) (MIT License) +- [`trigger.svg`](https://www.svgrepo.com/svg/489497/lightning-1) (Public Domain License) +- [`stop.svg`](https://www.svgrepo.com/svg/521862/stop) (CC Attribution License) ## License diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index 6b50b318..4c702442 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -5,8 +5,10 @@ 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.Queue; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; using Mediator; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics.CodeAnalysis; @@ -41,12 +43,13 @@ public static class ApplicationLayerServices services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); - services.AddScoped(); - services.AddSingleton(); - services.AddScoped(); - services.AddScoped(); - services.AddHostedService(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); services.AddTransient(); services.AddTransient(); diff --git a/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs b/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs new file mode 100644 index 00000000..27e0df92 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Models/Scanning/MediaScanTrackerModel.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Models.Scanning; + +/// +/// Model for tracking media library scans. +/// +/// The Id of the media library scan to be tracked. +/// The Id of the username who initiated the media library scan. +public record MediaScanTrackerModel(Guid ScanId, Guid UserId); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs new file mode 100644 index 00000000..5810f204 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/CancelLibraryScanRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; +using Lumina.Contracts.Requests.MediaLibrary.Management; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class CancelLibraryScanRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static CancelLibraryScanCommand ToCommand(this CancelLibraryScanRequest request) + { + return new CancelLibraryScanCommand( + request.Id + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMapping.cs new file mode 100644 index 00000000..caa0179d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/ScanLibraryRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; +using Lumina.Contracts.Requests.MediaLibrary.Management; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; + +/// +/// Extension methods for converting . +/// +public static class ScanLibraryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static ScanLibraryCommand ToCommand(this ScanLibraryRequest request) + { + return new ScanLibraryCommand( + request.Id + ); + } +} diff --git a/src/Lumina.Application/Common/Utilities/TaskUtilities.cs b/src/Lumina.Application/Common/Utilities/TaskUtilities.cs index 228091b9..9b73ed6c 100644 --- a/src/Lumina.Application/Common/Utilities/TaskUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/TaskUtilities.cs @@ -15,7 +15,8 @@ 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) + /// Optional continuation when finishes. + public static async void FireAndForgetSafeAsync(this Task task, Action? onComplete = null) { try { @@ -25,5 +26,9 @@ public static class TaskUtilities { Debug.WriteLine(ex); } + finally + { + onComplete?.Invoke(); + } } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs new file mode 100644 index 00000000..9a5da911 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommand.cs @@ -0,0 +1,11 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; + +/// +/// Command for cancelling the previously started scan of all media libraries. +/// +public record CancelLibrariesScanCommand : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs new file mode 100644 index 00000000..d5452457 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +using Mediator; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; + +/// +/// Handler for the command for cancelling the scan of all media libraries. +/// +public class CancelLibrariesScanCommandHandler : IRequestHandler> +{ + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibrariesScanTracker _librariesScanTracker; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service to retrieve the current user information. + /// Injected service for scanning media libraries. + public CancelLibrariesScanCommandHandler(ICurrentUserService currentUserService, IMediaLibrariesScanTracker librariesScanTracker) + { + _currentUserService = currentUserService; + _librariesScanTracker = librariesScanTracker; + } + + /// + /// Handles the command for cancelling 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(CancelLibrariesScanCommand request, CancellationToken cancellationToken) + { + _librariesScanTracker.CancelUserScans(_currentUserService.UserId!.Value); + return await ValueTask.FromResult(Result.Success); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs new file mode 100644 index 00000000..7510cc8b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Mediator; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; + +/// +/// Command for cancelling the scan of a media library by its Id. +/// +/// The Id of the media library whose scan is cancelled. +[DebuggerDisplay("Id: {Id}")] +public record CancelLibraryScanCommand( + Guid Id +) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs new file mode 100644 index 00000000..eeea9cdd --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -0,0 +1,50 @@ +#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.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Mediator; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; + +/// +/// Handler for the command for cancelling the scan of a media library. +/// +public class CancelLibraryScanCommandHandler : IRequestHandler> +{ + private readonly IMediaLibraryScanningService _mediaLibraryScanningService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for scanning media libraries. + public CancelLibraryScanCommandHandler(IMediaLibraryScanningService mediaLibraryScanningService) + { + _mediaLibraryScanningService = mediaLibraryScanningService; + } + + /// + /// Handles the command for cancelling the scan of a media library. + /// + /// 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(CancelLibraryScanCommand request, CancellationToken cancellationToken) + { + _mediaLibraryScanningService.CancelScan(request.Id); + return await ValueTask.FromResult(Result.Success); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs new file mode 100644 index 00000000..72990614 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; + +/// +/// Validates the needed validation rules for . +/// +public class CancelLibraryScanCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public CancelLibraryScanCommandValidator() + { + RuleFor(x => x.Id) + .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs index f8051849..f06b1af9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommand.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Contracts.Responses.MediaLibrary.Management; using Mediator; +using System.Collections.Generic; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; @@ -8,4 +10,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Command for initiating the scan of all media libraries. /// -public record ScanLibrariesCommand() : IRequest>; +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 index 621b6300..2aa5cf60 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -7,12 +7,14 @@ 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.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Mediator; +using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; -using Lumina.Application.Common.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; @@ -20,11 +22,11 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries /// /// Handler for the command for initiating the scan of all media libraries. /// -public class ScanLibrariesCommandHandler : IRequestHandler> +public class ScanLibrariesCommandHandler : IRequestHandler>> { private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; - private readonly ILibraryScanningService _libraryScanningService; + private readonly IMediaLibraryScanningService _libraryScanningService; private readonly IAuthorizationService _authorizationService; /// @@ -37,7 +39,7 @@ public class ScanLibrariesCommandHandler : IRequestHandlerThe 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) + 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 that are enabled and unlocked from the persistence medium ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); ErrorOr> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsError) return getLibrariesResult.Errors; - // convert persistence libraries to domain entities, and start scanning them + // convert persistence libraries to domain entities IEnumerable> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); + + // if the current user is not an admin, they can only scan the libraries that belong to them + if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) + domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value); + + List responses = []; + // for each library, start the scan foreach (ErrorOr domainLibraryResult in domainEntitiesResult) { if (domainLibraryResult.IsError) return domainLibraryResult.Errors; - await _libraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false); + Guid scanId = await _libraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false); + responses.Add(new ScanLibraryResponse(scanId, domainLibraryResult.Value.Id.Value)); } - return Result.Success; + return responses; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs new file mode 100644 index 00000000..c31948a9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Mediator; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; + +/// +/// Command for initiating the scan of a media library. +/// +/// The Id of the library to scan. +public record ScanLibraryCommand( + Guid Id +) : IRequest>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs new file mode 100644 index 00000000..30fb6df9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -0,0 +1,90 @@ +#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.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Mediator; +using System; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; + +/// +/// Handler for the command for initiating the scan of a media library. +/// +public class ScanLibraryCommandHandler : IRequestHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibraryScanningService _mediaLibraryScanningService; + 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 ScanLibraryCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IMediaLibraryScanningService mediaLibraryScanningService, + IUnitOfWork unitOfWork) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _mediaLibraryScanningService = mediaLibraryScanningService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the command for initiating the scan of a media library. + /// + /// 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(ScanLibraryCommand request, CancellationToken cancellationToken) + { + // get the media library from the persistence medium + ILibraryRepository libraryRepository = _unitOfWork.GetRepository(); + ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsError) + return getLibraryResult.Errors; + + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // if the user that wants to delete the library is not an Admin or is not the owner of the library, they do not have the right to scan it + if (getLibraryResult.Value.UserId != _currentUserService.UserId || + !await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + // check if the library is enabled and unlocked, before scanning it + if (!getLibraryResult.Value.IsEnabled) + return DomainErrors.Library.CannotScanDisabledLibrary; + + if (getLibraryResult.Value.IsLocked) + return DomainErrors.Library.CannotScanLockedLibrary; + + // convert persistence libraries to domain entities + ErrorOr domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); + + if (domainLibraryResult.IsError) + return domainLibraryResult.Errors; + + // start the media library scan + Guid scanId = await _mediaLibraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false); + return new ScanLibraryResponse(scanId, domainLibraryResult.Value.Id.Value); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs new file mode 100644 index 00000000..6527d2b0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandValidator.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; + +/// +/// Validates the needed validation rules for . +/// +public class ScanLibraryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ScanLibraryCommandValidator() + { + RuleFor(x => x.Id) + .NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description) + .Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs similarity index 65% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs index faec0da1..f0ff4ba1 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/ILibraryScanningService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaLibraryScanningService.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -9,12 +10,19 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; /// /// Interface for the service used to scan a media library. /// -public interface ILibraryScanningService +public interface IMediaLibraryScanningService { /// /// 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); + /// The Id of the media library scan. + Task StartScanAsync(Library library, CancellationToken cancellationToken); + + /// + /// Cancels the scan identified by . + /// + /// The Id of the scan to cancel. + void CancelScan(Guid scanId); } 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 index 70959750..57853c67 100644 --- 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 @@ -18,7 +18,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for discovering file system items. /// -internal class FileSystemDiscoveryJob : MediaScanJob +internal class FileSystemDiscoveryJob : MediaLibraryScanJob { private readonly IDirectoryService _directoryService; private readonly IFileService _fileService; @@ -37,28 +37,37 @@ internal class FileSystemDiscoveryJob : 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) + try { - 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) + 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) { - ErrorOr treeResult = BuildTree(contentLocation, includeHiddenElements: true); - if (treeResult.IsError) + 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) { - // handle errors, maybe: - // Status = LibraryScanJobStatus.Failed; + cancellationToken.ThrowIfCancellationRequested(); + ErrorOr treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken); + if (treeResult.IsError) + { + // handle errors, maybe: + // Status = LibraryScanJobStatus.Failed; + } + else + contentLocationTrees.Add(treeResult.Value); } - else - contentLocationTrees.Add(treeResult.Value); + Status = LibraryScanJobStatus.Completed; + // call each linked child with the obtained payload + foreach (MediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false); } - Status = LibraryScanJobStatus.Completed; - // call each linked child with the obtained payload - foreach (MediaScanJob children in Children) - await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Cancelled; + throw; } } @@ -68,7 +77,7 @@ internal class FileSystemDiscoveryJob : MediaScanJob /// 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) + public ErrorOr BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default) { // validate the path and get the root directory node ErrorOr rootDirectoryResult = Directory.Create(path, path.Path, Optional.None(), Optional.None()); @@ -76,7 +85,7 @@ internal class FileSystemDiscoveryJob : MediaScanJob return rootDirectoryResult.Errors; // build the tree starting from the root directory - return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements); + return BuildNodeRecursive(rootDirectoryResult.Value, includeHiddenElements, cancellationToken); } /// @@ -85,7 +94,7 @@ internal class FileSystemDiscoveryJob : MediaScanJob /// 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) + private ErrorOr BuildNodeRecursive(Directory directory, bool includeHiddenElements, CancellationToken cancellationToken) { FileSystemTreeNode node = new() { @@ -102,7 +111,8 @@ internal class FileSystemDiscoveryJob : MediaScanJob foreach (Directory subdirectory in subdirectoriesResult.Value) { - ErrorOr subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements); + cancellationToken.ThrowIfCancellationRequested(); + ErrorOr subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements, cancellationToken); if (subNodeResult.IsError) return subNodeResult.Errors; @@ -116,6 +126,7 @@ internal class FileSystemDiscoveryJob : MediaScanJob foreach (File file in filesResult.Value) { + cancellationToken.ThrowIfCancellationRequested(); node.Children.Add(new FileSystemTreeNode { Path = file.Id.Path, 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 index c65b0998..eaad25ec 100644 --- 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 @@ -11,21 +11,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for comparing hashes. /// -internal class HashComparerJob : MediaScanJob +internal class HashComparerJob : MediaLibraryScanJob { /// 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) + try { - 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); + 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 (MediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Cancelled; + throw; } } } 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/IMediaLibraryScanJobFactory.cs similarity index 88% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaScanJobFactory.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaLibraryScanJobFactory.cs index f79ee714..8a88cfdd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaScanJobFactory.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/IMediaLibraryScanJobFactory.cs @@ -8,7 +8,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Interface for the media library scan jobs factory. /// -internal interface IMediaScanJobFactory +internal interface IMediaLibraryScanJobFactory { /// /// Creates a new media library scan job of type . @@ -16,5 +16,5 @@ internal interface IMediaScanJobFactory /// 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; + TJob CreateJob(Library library) where TJob : MediaLibraryScanJob; } 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/MediaLibraryScanJob.cs similarity index 80% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJob.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJob.cs index d67b5fde..c57baed0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJob.cs @@ -12,19 +12,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Abstract class defining a media library scan job. /// -internal abstract class MediaScanJob +internal abstract class MediaLibraryScanJob { internal int parentsPayloadsExecuted; + + /// + /// Gets or sets the Id of the media library scan that this job is part of. + /// + public Guid ScanId { get; set; } + + /// + /// Gets or sets the Id of the user that initiated the media library scan that this job is part of. + /// + public Guid UserId { get; set; } /// /// 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; } = []; + 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; } = []; + public List Parents { get; protected set; } = []; /// /// Gets or sets the media library upon which the scan is performed. @@ -40,7 +50,7 @@ internal abstract class MediaScanJob /// 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) + public void AddChild(MediaLibraryScanJob job) { if (!Children.Contains(job) && !Parents.Contains(job)) Children.Add(job); @@ -50,7 +60,7 @@ internal abstract class MediaScanJob /// 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) + public void AddParent(MediaLibraryScanJob job) { if (!Parents.Contains(job) && !Children.Contains(job)) Parents.Add(job); 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/MediaLibraryScanJobFactory.cs similarity index 85% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJobFactory.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJobFactory.cs index b7b1ddf5..860c0dfd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaScanJobFactory.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Jobs/Common/MediaLibraryScanJobFactory.cs @@ -9,15 +9,15 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Concrete implementation for the media library scan jobs factory. /// -internal class MediaScanJobFactory : IMediaScanJobFactory +internal class MediaLibraryScanJobFactory : IMediaLibraryScanJobFactory { private readonly IServiceProvider _serviceProvider; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The service provider. - public MediaScanJobFactory(IServiceProvider serviceProvider) + public MediaLibraryScanJobFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } @@ -28,7 +28,7 @@ internal class MediaScanJobFactory : IMediaScanJobFactory /// 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 + public TJob CreateJob(Library library) where TJob : MediaLibraryScanJob { // resolve the job from DI TJob job = _serviceProvider.GetRequiredService() ?? throw new ArgumentException(); 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 index d4a9c233..944fb537 100644 --- 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 @@ -11,21 +11,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for retrieving persistence data from any eventual previous scans. /// -internal class RepositoryMetadataDiscoveryJob : MediaScanJob +internal class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob { /// 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) + try { - 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); + 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 (MediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Cancelled; + throw; } } } 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 index c39b29ed..3b67ac13 100644 --- 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 @@ -12,21 +12,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs /// /// Media library scan job for retrieving written content metadata from GoodReads. /// -internal class GoodReadsMetadataScrapJob : MediaScanJob +internal class GoodReadsMetadataScrapJob : MediaLibraryScanJob { /// 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) + try { - 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); + 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 (MediaLibraryScanJob children in Children) + await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + Status = LibraryScanJobStatus.Cancelled; + throw; } } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs deleted file mode 100644 index 990a70a3..00000000 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/LibraryScanningService.cs +++ /dev/null @@ -1,51 +0,0 @@ -#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/MediaLibraryScanningService.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs new file mode 100644 index 00000000..fe43dc86 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaLibraryScanningService.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; +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 MediaLibraryScanningService : IMediaLibraryScanningService +{ + private readonly IMediaLibrariesScanQueue _mediaScanQueue; + private readonly IMediaLibraryScannerFactory _libraryScannerFactory; + private readonly ICurrentUserService _currentUserService; + private readonly IMediaLibrariesScanTracker _librariesScanTracker; + + /// + /// Initializes a new instance of the class. + /// + /// Injected queue used for processing media libraries scan jobs. + /// Injected factory for creating media library scanners. + public MediaLibraryScanningService( + IMediaLibrariesScanQueue mediaScanQueue, + IMediaLibraryScannerFactory libraryScannerFactory, + IMediaLibrariesScanTracker librariesScanTracker, + ICurrentUserService currentUserService) + { + _mediaScanQueue = mediaScanQueue; + _libraryScannerFactory = libraryScannerFactory; + _currentUserService = currentUserService; + _librariesScanTracker = librariesScanTracker; + } + + /// + /// Starts the scan of . + /// + /// The media library to scan. + /// Cancellation token that can be used to stop the execution. + /// The Id of the media library scan. + public async Task StartScanAsync(Library library, CancellationToken cancellationToken) + { + Guid scanId = Guid.NewGuid(); + _librariesScanTracker.RegisterScan(scanId, _currentUserService.UserId!.Value); + + try + { + // link the user's cancellation token with the scan's token + CancellationTokenSource linkedSource = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken, _librariesScanTracker.GetTokenForScan(scanId, _currentUserService.UserId!.Value)); + + // get a media library scanner 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 (MediaLibraryScanJob job in jobs) + { + job.ScanId = scanId; + job.UserId = _currentUserService.UserId!.Value; + await _mediaScanQueue.Writer.WriteAsync(job, linkedSource.Token).ConfigureAwait(false); + } + } + catch (NotImplementedException) { } + return scanId; + } + + /// + /// Cancels the scan identified by . + /// + /// The Id of the scan to cancel. + public void CancelScan(Guid scanId) + { + _librariesScanTracker.CancelScan(scanId, _currentUserService.UserId!.Value); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs similarity index 67% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs index 394ee60a..c9ceb29c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/IMediaScanQueue.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/IMediaLibrariesScanQueue.cs @@ -3,20 +3,20 @@ using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Com using System.Threading.Channels; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; /// -/// Interface for the message queue for handling instances. +/// Interface for the message queue for handling instances. /// -internal interface IMediaScanQueue +internal interface IMediaLibrariesScanQueue { /// - /// Gets the writer for the queue, allowing producers to enqueue instances. + /// Gets the writer for the queue, allowing producers to enqueue instances. /// - public ChannelWriter Writer { get; } + public ChannelWriter Writer { get; } /// - /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// Gets the reader for the queue, allowing consumers to dequeue instances. /// - public ChannelReader Reader { get; } + public ChannelReader Reader { get; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs similarity index 64% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs index 79ff3652..180bdd52 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanQueue.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibrariesScanQueue.cs @@ -3,27 +3,27 @@ using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Com using System.Threading.Channels; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; /// -/// Provides an in-memory message queue for handling instances. +/// Provides an in-memory message queue for handling instances. /// -internal class MediaScanQueue : IMediaScanQueue +internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue { - private readonly Channel _channel = Channel.CreateUnbounded(); + private readonly Channel _channel = Channel.CreateUnbounded(); /// - /// Gets the writer for the queue, allowing producers to enqueue instances. + /// Gets the writer for the queue, allowing producers to enqueue instances. /// - public ChannelWriter Writer + public ChannelWriter Writer { get { return _channel.Writer; } } /// - /// Gets the reader for the queue, allowing consumers to dequeue instances. + /// Gets the reader for the queue, allowing consumers to dequeue instances. /// - public ChannelReader Reader + public ChannelReader Reader { get { return _channel.Reader; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs similarity index 55% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs index bf534fd1..acd83cb5 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/MediaScanJobProcessorJob.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Queue/MediaLibraryScanJobProcessorJob.cs @@ -1,28 +1,31 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Utilities; using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common; +using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning; +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue; /// /// Background service for processing media library scan jobs from an in-memory message queue. /// -internal sealed class MediaScanJobProcessorJob : BackgroundService +internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService { - private readonly IMediaScanQueue _mediaScanQueue; + private readonly IMediaLibrariesScanQueue _mediaScanQueue; + private readonly IMediaLibrariesScanTracker _librariesScanTracker; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected queue used for processing media libraries scan jobs. - public MediaScanJobProcessorJob(IMediaScanQueue mediaScanQueue) + public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanTracker librariesScanTracker) { _mediaScanQueue = mediaScanQueue; + _librariesScanTracker = librariesScanTracker; } /// @@ -35,7 +38,13 @@ internal sealed class MediaScanJobProcessorJob : BackgroundService // 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(); + await foreach (MediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + // get the cancellation token that was associated with this library scan + CancellationToken scanToken = _librariesScanTracker.GetTokenForScan(mediaScanJob.ScanId, mediaScanJob.UserId); + // create linked token to handle both scan cancellation and service shutdown + CancellationTokenSource linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, scanToken); + mediaScanJob.ExecuteAsync(Guid.NewGuid(), new { }, linkedSource.Token).FireAndForgetSafeAsync(() => linkedSource.Dispose()); + } } } 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/IMediaLibraryScannerFactory.cs similarity index 94% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/ILibraryScannerFactory.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaLibraryScannerFactory.cs index fa815ba5..3c4a3c85 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/ILibraryScannerFactory.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/IMediaLibraryScannerFactory.cs @@ -7,7 +7,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scan /// /// Interface defining a factory for creating media library scanners. /// -internal interface ILibraryScannerFactory +internal interface IMediaLibraryScannerFactory { /// /// Creates a media library scanner based on the provided library type. 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 index c9da4c4b..f28140ee 100644 --- 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 @@ -22,5 +22,5 @@ internal interface IMediaTypeScanner /// /// The media library for which to create the media library scan jobs. /// A collection of media library scan jobs. - IEnumerable CreateScanJobsForLibrary(Library library); + 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/MediaLibraryScannerFactory.cs similarity index 95% rename from src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/LibraryScannerFactory.cs rename to src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/MediaLibraryScannerFactory.cs index a161ee5e..c5ff3b39 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/LibraryScannerFactory.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Scanners/Common/MediaLibraryScannerFactory.cs @@ -10,15 +10,15 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scan /// /// Defines a factory for creating media library scanners. /// -internal class LibraryScannerFactory : ILibraryScannerFactory +internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory { private readonly IServiceProvider _serviceProvider; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The service provider. - public LibraryScannerFactory(IServiceProvider serviceProvider) + public MediaLibraryScannerFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } 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 index bf7c3a20..b1470ff3 100644 --- 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 @@ -13,7 +13,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scan /// internal class BookLibraryTypeScanner : IBookLibraryTypeScanner { - private readonly IMediaScanJobFactory _mediaScanJobFactory; + private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory; /// public LibraryType SupportedType { get; } = LibraryType.Book; @@ -22,13 +22,13 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner /// Initializes a new instance of the class. /// /// Injected factory for creating media library scan jobs. - public BookLibraryTypeScanner(IMediaScanJobFactory mediaScanJobFactory) + public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory) { _mediaScanJobFactory = mediaScanJobFactory; } /// - public IEnumerable CreateScanJobsForLibrary(Library library) + public IEnumerable CreateScanJobsForLibrary(Library library) { // declare the list of jobs that this scanner requires FileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(library); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs new file mode 100644 index 00000000..d580b9c7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/IMediaLibrariesScanTracker.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; + +/// +/// Interface for the tracker used for in-progress media library scans. +/// +public interface IMediaLibrariesScanTracker +{ + /// + /// Gets the cancellation token for a scan identified by and . + /// + /// The Id of the scan to get the cancellation token for<./param> + /// The Id of the user who initiated the scan for which to get the cancellation token. + /// A cancellation token for the specified scan. + CancellationToken GetTokenForScan(Guid scanId, Guid userId); + + /// + /// Registers a new scan operation for tracking. + /// + /// The Id of the scan operation to track. + /// The Id of the user who initiated the scan to track. + void RegisterScan(Guid scanId, Guid userId); + + /// + /// Cancels a scan identified by and . + /// + /// The Id of the scan operation to cancel. + /// The Id of the user requesting the cancellation. + void CancelScan(Guid scanId, Guid userId); + + /// + /// Cancels all active scan operations for a user identified by . + /// + /// The Id of the user whose scans should be cancelled. + void CancelUserScans(Guid userId); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs new file mode 100644 index 00000000..cac7e9b4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Services/Scanning/Tracking/MediaLibrariesScanTracker.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.Scanning; +using System; +using System.Collections.Concurrent; +using System.Threading; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking; + +/// +/// Tracker used for in-progress media library scans. +/// +internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposable +{ + private readonly ConcurrentDictionary _runningScans = new(); + private bool _disposed; + + /// + /// Registers a new scan operation for tracking. + /// + /// The Id of the scan operation to track. + /// The Id of the user who initiated the scan to track. + public void RegisterScan(Guid scanId, Guid userId) + { + _runningScans.TryAdd(new MediaScanTrackerModel(scanId, userId), new CancellationTokenSource()); + } + + /// + /// Gets the cancellation token for a scan identified by and . + /// + /// The Id of the scan to get the cancellation token for<./param> + /// The Id of the user who initiated the scan for which to get the cancellation token. + /// A cancellation token for the specified scan. + public CancellationToken GetTokenForScan(Guid scanId, Guid userId) + { + return _runningScans.TryGetValue(new MediaScanTrackerModel(scanId, userId), out CancellationTokenSource? scan) + ? scan.Token + : CancellationToken.None; + } + + /// + /// Cancels a scan identified by and . + /// + /// The Id of the scan operation to cancel. + /// The Id of the user requesting the cancellation. + public void CancelScan(Guid scanId, Guid userId) + { + foreach (MediaScanTrackerModel key in _runningScans.Keys) + { + if (key.ScanId == scanId && key.UserId == userId) + { + if (_runningScans.TryGetValue(key, out CancellationTokenSource? scan)) + { + scan.Cancel(); + // remove and dispose after cancellation + if (_runningScans.TryRemove(key, out CancellationTokenSource? removedScan)) + removedScan?.Dispose(); + } + } + } + } + + /// + /// Cancels all active scan operations for a user identified by . + /// + /// The Id of the user whose scans should be cancelled. + public void CancelUserScans(Guid userId) + { + foreach (MediaScanTrackerModel key in _runningScans.Keys) + { + if (key.UserId == userId) + { + if (_runningScans.TryGetValue(key, out CancellationTokenSource? scan)) + { + scan.Cancel(); + // remove and dispose after cancellation + if (_runningScans.TryRemove(key, out CancellationTokenSource? removedScan)) + removedScan?.Dispose(); + } + } + } + } + + /// + /// Disposes the tracker and cancels all media library scans. + /// + public void Dispose() + { + if (!_disposed) + { + foreach (CancellationTokenSource scan in _runningScans.Values) + { + scan.Cancel(); + scan.Dispose(); + } + _runningScans.Clear(); + _disposed = true; + } + } +} diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs new file mode 100644 index 00000000..354463ea --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/CancelLibraryScanRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents a request to cancel the scan of a media library by its Id. +/// +/// The Id of the media library whose scan is cancelled. Required. +[DebuggerDisplay("Id: {Id}")] +public record CancelLibraryScanRequest( + Guid Id +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs index d5ea42af..a2ef737f 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/DeleteLibraryRequest.cs @@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// /// Represents a request to delete a media library by its Id. /// -/// The Id of the media library. Required. +/// The Id of the media library to be deleted. Required. [DebuggerDisplay("Id: {Id}")] public record DeleteLibraryRequest( Guid Id diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs new file mode 100644 index 00000000..8a487bf0 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/ScanLibraryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.Management; + +/// +/// Represents a request to scan a media library. +/// +/// The Id of the media library to be scanned. Required. +[DebuggerDisplay("Id: {Id}")] +public record ScanLibraryRequest( + Guid Id +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index ef6a42c4..8ce380d8 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -10,7 +10,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// /// Represents a media library response. /// -/// The id of the media library. +/// The Id of the media library. /// The Id of the user owning the media library. /// The title of the media library. /// The type of the media library. diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs new file mode 100644 index 00000000..8a3dffc0 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/ScanLibraryResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.Management; + +/// +/// Represents a media library scan response. +/// +/// The Id of the media library scan. +/// The Id of the scanned media library. +[DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")] +public record ScanLibraryResponse( + Guid ScanId, + Guid LibraryId +); diff --git a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs index 350eb590..0a162970 100644 --- a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs +++ b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanJobStatus.cs @@ -20,6 +20,11 @@ public enum LibraryScanJobStatus /// Completed, + /// + /// Job has been cancelled. + /// + Cancelled, + /// /// Job has failed. /// diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index 43802d9d..fae60e76 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -11,7 +11,9 @@ public static partial class Errors { public static class Library { - public static Error LibraryIdCannotBeEmpty => Error.Forbidden(description: nameof(LibraryIdCannotBeEmpty)); + public static Error CannotScanLockedLibrary => Error.Forbidden(description: nameof(CannotScanLockedLibrary)); + public static Error CannotScanDisabledLibrary => Error.Forbidden(description: nameof(CannotScanDisabledLibrary)); + public static Error LibraryIdCannotBeEmpty => Error.Validation(description: nameof(LibraryIdCannotBeEmpty)); public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists)); public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); 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 256a8c0e..5f8c6fe2 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 @@ -17,5 +17,8 @@ public static partial class ApiRoutes public const string UPDATE_LIBRARY = "/libraries/{id}"; public const string DELETE_LIBRARY = "/libraries/{id}"; public const string SCAN_LIBRARIES = "/libraries/scan"; + public const string SCAN_LIBRARY = "/libraries/{id}/scan"; + public const string CANCEL_LIBRARIES_SCAN = "/libraries/cancel-scan"; + public const string CANCEL_LIBRARY_SCAN = "/libraries/{id}/cancel-scan"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs new file mode 100644 index 00000000..df9c5a71 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpoint.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; +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.CancelLibrariesScan; + +/// +/// API endpoint for the /libraries/cancel-scan route. +/// +public class CancelLibrariesScanEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CancelLibrariesScanEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN); + Version(1); + DontCatchExceptions(); + } + + /// + /// Cancels a previously started 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 CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs new file mode 100644 index 00000000..c99c5d18 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointSummary.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CancelLibrariesScanEndpointSummary() + { + Summary = "Cancells the previously started scan of all media libraries."; + Description = "Cancells the scanning process of all media libraries of a user, or all libraries, if the user making the request is an Admin."; + + Response(204, "The media libraries scan was successfully cancelled."); + + 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/cancel-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/cancel-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/cancel-scan" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs new file mode 100644 index 00000000..16c81909 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpoint.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; +using Lumina.Contracts.Requests.MediaLibrary.Management; +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.CancelLibraryScan; + +/// +/// API endpoint for the /libraries/{id}/cancel-scan route. +/// +public class CancelLibraryScanEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public CancelLibraryScanEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN); + Version(1); + DontCatchExceptions(); + } + + /// + /// Cancels a previously started scan of all media libraries. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs new file mode 100644 index 00000000..bead73d8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CancelLibraryScanEndpointSummary() + { + Summary = "Cancells the previously started scan of a media library."; + Description = "Cancells the scanning process of a media library of a user, if the user making the request is an Admin or the library belongs to them."; + + Response(204, "The media library scan was successfully cancelled."); + + 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/{id}/cancel-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/{id}/cancel-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/{id}/cancel-scan" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{id}/cancel-scan", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs new file mode 100644 index 00000000..acccbc28 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteLibraryEndpointSummary() + { + Summary = "Deletes an existing media library."; + Description = "Deletes a media library, if the user making the request is an Admin, or the owner of the library."; + + ExampleRequest = new DeleteLibraryRequest( + Id: Guid.NewGuid() + ); + + RequestParam(r => r.Id, "The Id of the media library to be deleted. Required."); + + Response(200, "The media library was successfuly deleted."); + + 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/{id}" + }, + 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/{id}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{id}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "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/{id}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{id}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{id}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs index 877ec9e2..6fa7329d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpoint.cs @@ -2,10 +2,12 @@ using ErrorOr; using FastEndpoints; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; +using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Presentation.Api.Common.Routes.Library.Management; using Lumina.Presentation.Api.Core.Endpoints.Common; using Mediator; using Microsoft.AspNetCore.Http; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -45,7 +47,7 @@ public class ScanLibrariesEndpoint : BaseEndpoint /// 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); + ErrorOr> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), 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 index 2ae0a443..36641e04 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointSummary.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -17,9 +19,19 @@ public class ScanLibrariesEndpointSummary : Summary +/// API endpoint for the /libraries/{id}/scan route. +/// +public class ScanLibraryEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public ScanLibraryEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.POST); + Routes(ApiRoutes.Libraries.SCAN_LIBRARY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Initiates a scan of a media library. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken) + { + ErrorOr result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs new file mode 100644 index 00000000..c7e7c538 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ScanLibraryEndpointSummary() + { + Summary = "Triggers the scan of a media library."; + Description = "Starts the scanning process of a media library of a user."; + + Response(200, "The media library scan was successfully started.", + example: new ScanLibraryResponse( + ScanId: Guid.NewGuid(), + LibraryId: Guid.NewGuid() + )); + + 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/{id}/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/{id}/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/{id}/scan" + } + } + ); + + Response(403, "The request failed because the library is disabled or locked, or the user initiating the scan is not an Admin or the library owner.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "CannotScanDisabledLibrary", + instance = "/api/v1/libraries/{id}/scan", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "CannotScanLockedLibrary", + instance = "/api/v1/libraries/{id}/scan", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{id}/scan", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the provided library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{id}/scan", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{id}/scan", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs b/src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs new file mode 100644 index 00000000..eadddf2d --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Libraries/ScanLibraryModel.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Libraries; + +/// +/// Represents a media library scan response. +/// +[DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")] +public class ScanLibraryModel +{ + /// + /// Gets or sets the Id of the media library scan. + /// + public Guid? ScanId { get; set; } + + /// + /// Gets or sets the Id of the scanned media library. + /// + public Guid? LibraryId { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index 5f635c73..83c38f45 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -121,7 +121,42 @@ public class LibraryManagementController : Controller [HttpPost("api-scan-libraries")] public async Task ScanAllLibraries(CancellationToken cancellationToken = default) { - await _apiHttpClient.PostAsync($"libraries/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); - return Json(new { success = true, data = true }); + ScanLibraryModel[] response = await _apiHttpClient.PostAsync($"libraries/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Initiates the scan of a media library. + /// + /// The id of the media library whose scan is started. + /// Cancellation token that can be used to stop the execution. + [HttpPost("api-scan-library/{id}")] + public async Task ScanLibrary(Guid id, CancellationToken cancellationToken = default) + { + ScanLibraryModel response = await _apiHttpClient.PostAsync($"libraries/{id}/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + + /// + /// Cancells the previously started scan of all media libraries. + /// + /// Cancellation token that can be used to stop the execution. + [HttpPost("api-cancel-libraries-scan")] + public async Task CancelLibrariesScan(CancellationToken cancellationToken = default) + { + await _apiHttpClient.PostAsync($"libraries/cancel-scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + return Json(new { success = true }); + } + + /// + /// Cancells the previously started scan of a media library. + /// + /// The id of the media library whose scan is cancelled. + /// Cancellation token that can be used to stop the execution. + [HttpPost("api-cancel-library-scan/{id}")] + public async Task CancelLibraryScan(Guid id, CancellationToken cancellationToken = default) + { + await _apiHttpClient.PostAsync($"libraries/{id}/cancel-scan", new EmptyModel(), cancellationToken).ConfigureAwait(false); + return Json(new { success = true }); } } diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 01ad9aef..816ce2a2 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -543,4 +543,10 @@ Die Coverdatei muss ein Bild sein! + + Eine deaktivierte Bibliothek kann nicht gescannt werden! + + + Eine gesperrte Bibliothek kann nicht gescannt werden! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index d9489262..83ca976f 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -543,4 +543,10 @@ Cover file must be an image! + + Cannot scan a disabled library! + + + Cannot scan a locked library! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index 93ffbcf6..bdf989a1 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -543,4 +543,10 @@ ¡El archivo de portada debe ser una imagen! + + ¡No se puede escanear una biblioteca desactivada! + + + ¡No se puede escanear una biblioteca bloqueada! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 0f7aa647..1fabf8e4 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -543,4 +543,10 @@ Le fichier de couverture doit être une image! + + Impossible de scanner une bibliothèque désactivée! + + + Impossible de scanner une bibliothèque verrouillée! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 311bba59..c773a4be 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -543,4 +543,10 @@ Il file di copertina deve essere un'immagine! + + Impossibile scansionare una libreria disabilitata! + + + Impossibile scansionare una libreria bloccata! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index e593ace3..d3649ed1 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -543,4 +543,10 @@ カバーファイルは画像である必要があります! + + 無効化されたライブラリはスキャンできません! + + + ロックされたライブラリはスキャンできません! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index fcd32e32..27081c14 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -543,4 +543,10 @@ Cover file must be an image! + + Cannot scan a disabled library! + + + Cannot scan a locked library! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index 0edd4874..abf3a931 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -543,4 +543,10 @@ Fișierul copertă trebuie să fie o imagine! + + Nu se poate scana o bibliotecă dezactivată! + + + Nu se poate scana o bibliotecă blocată! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index ca4c8f8f..27e42a27 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -543,4 +543,10 @@ Файл обложки должен быть изображением! + + Невозможно сканировать отключенную библиотеку! + + + Невозможно сканировать заблокированную библиотеку! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 448253f9..2d31b834 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -543,4 +543,10 @@ 封面文件必须是图片! + + 无法扫描已禁用的库! + + + 无法扫描已锁定的库! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index 15334cda..f34074bd 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -231,6 +231,9 @@ Entfernen + + Scannen + Alle Bibliotheken Scannen diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index 6055637b..65ae5693 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -231,6 +231,9 @@ Remove + + Scan + Scan All Libraries diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index 8fda5a80..0a254a0a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -231,6 +231,9 @@ Eliminar + + Escanear + Escanear Todas Las Bibliotecas diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 3970a7b1..8c73c26c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -231,6 +231,9 @@ Supprimer + + Scanner + Scanner Toutes Les Bibliothèques diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index dc9edd08..5563d276 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -231,6 +231,9 @@ Rimuovere + + Scansiona + Scansiona Tutte Le Librerie diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index 162efdf0..a8a226f3 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -231,6 +231,9 @@ 削除 + + スキャン + すべてのライブラリをスキャン diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index 6055637b..65ae5693 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -231,6 +231,9 @@ Remove + + Scan + Scan All Libraries diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index f9d9382e..553497a1 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -231,6 +231,9 @@ Șterge + + Scanează + Scanează Toate Bibliotecile diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index d174f846..2c1c4a76 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -231,6 +231,9 @@ Удалить + + Сканировать + Сканировать Все Библиотеки diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index e269dfe8..4e1c565c 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -231,6 +231,9 @@ 删除 + + 扫描 + 扫描所有库 diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml index b0dfaad2..f8dbdcc3 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -102,12 +102,14 @@ const editUrl = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement", new { id = default(Guid) })' .replace('/@(default(Guid))', `/${library.id}`); return ` - + ${library.title} ${jsLocalizedLibraryTypes[library.libraryType]} ${library.isEnabled === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} ${library.isLocked === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} + + @_localizer[ @_localizer[ @@ -126,17 +128,15 @@ // on delete library icon click const handleDeleteLibraryClick = async function(e) { if (e.target.matches('img[src*="delete.svg"]')) { - const row = e.target.closest('.form-table-row'); - const libraryTitle = row.querySelector('span').textContent; - - if (await dialogService.show('@_localizer["DeleteLibraryConfirm"]'.replace('{0}', libraryTitle), - jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { - const libraryId = row.querySelector('a').href.split('/').pop(); + const row = e.target.closest('tr'); + + if (await dialogService.show('@_localizer["DeleteLibraryConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { + const libraryId = row.getAttribute('data-library-id'); const url = '@_urlService.GetAbsoluteUrl("DeleteLibrary", "LibraryManagement", new { id = default(Guid) })'; const success = await callApiDeleteAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); if (success) { - await loadLibrariesAsync(); // Reload the entire library list + await loadLibrariesAsync(); // reload the entire library list notificationService.show('@_localizer["LibraryDeleted"]', NotificationType.SUCCESS); } } @@ -149,19 +149,82 @@ if (data) { btnScanAllLibraries.style.display = 'none'; btnCancelLibrariesScan.style.display = 'block'; + + // toggle icons only for libraries that had their scan started + const tbody = document.querySelector('tbody'); + data.forEach(scan => { + const row = tbody.querySelector(`tr[data-library-id="${scan.libraryId}"]`); + if (row) { + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + + scanIcon.classList.add('hidden'); + cancelScanIcon.classList.remove('hidden'); + } + }); + } + }; + + // on scan library icon click + const handleScanLibraryClick = async function(e) { + if (e.target.matches('img[src*="trigger.svg"]')) { + const row = e.target.closest('tr'); + + const libraryId = row.getAttribute('data-library-id'); + const url = '@_urlService.GetAbsoluteUrl("ScanLibrary", "LibraryManagement", new { id = default(Guid) })'; + const success = await callApiPostAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); + + if (success) { + const scanIcon = e.target; + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + + scanIcon.classList.add('hidden'); + cancelScanIcon.classList.remove('hidden'); + } } }; // on cancel all libraries scan button click const handleCancelLibrariesScanClick = async function(e) { + await callApiPostAsync('@_urlService.GetAbsoluteUrl("CancelLibrariesScan", "LibraryManagement")', {}); btnCancelLibrariesScan.style.display = 'none'; btnScanAllLibraries.style.display = 'block'; + + // toggle icons for all rows + const tbody = document.querySelector('tbody'); + const allRows = tbody.querySelectorAll('tr'); + + allRows.forEach(row => { + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + + scanIcon.classList.remove('hidden'); + cancelScanIcon.classList.add('hidden'); + }); + }; + + // on cancel library scan icon click + const handleCancelLibraryScanClick = async function(e) { + if (e.target.matches('img[src*="stop.svg"]')) { + const row = e.target.closest('tr'); + + const libraryId = row.getAttribute('data-library-id'); + const url = '@_urlService.GetAbsoluteUrl("CancelLibraryScan", "LibraryManagement", new { id = default(Guid) })'; + await callApiPostAsync(url.replace('/@(default(Guid))', `/${libraryId}`)); + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + + scanIcon.classList.remove('hidden'); + cancelScanIcon.classList.add('hidden'); + } }; // add listeners btnScanAllLibraries.addEventListener('click', handleScanAllLibrariesClick); btnCancelLibrariesScan.addEventListener('click', handleCancelLibrariesScanClick); document.addEventListener('click', handleDeleteLibraryClick); + document.addEventListener('click', handleScanLibraryClick); + document.addEventListener('click', handleCancelLibraryScanClick); document.addEventListener('DOMContentLoaded', InitializeAsync); // register cleanup for these listeners @@ -169,6 +232,8 @@ btnScanAllLibraries.removeEventListener('click', handleScanAllLibrariesClick); btnCancelLibrariesScan.removeEventListener('click', handleCancelLibrariesScanClick); document.removeEventListener('click', handleDeleteLibraryClick); + document.removeEventListener('click', handleScanLibraryClick); + document.removeEventListener('click', handleCancelLibraryScanClick); document.removeEventListener('DOMContentLoaded', InitializeAsync); }); diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/stop.svg b/src/Lumina.Presentation.Web/wwwroot/images/ui/stop.svg new file mode 100644 index 00000000..65d4ddbf --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/images/ui/stop.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/trigger.svg b/src/Lumina.Presentation.Web/wwwroot/images/ui/trigger.svg new file mode 100644 index 00000000..ed62bdf0 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/images/ui/trigger.svg @@ -0,0 +1,4 @@ + + + +