Merge pull request #112 from BinaryAlley/feature/add-libraries-cancel-scan-option

Adds media libraries cancel scan option
This commit is contained in:
BinaryAlley authored and GitHub committed 2025-02-01 14:41:50 +00:00
commit c1100e5398
77 files changed
+1585 -194

No files matched your search

+2
View File
@@ -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
@@ -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<IDomainEventsQueue, DomainEventsQueue>();
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
services.AddSingleton<IMediaLibrariesScanTracker, MediaLibrariesScanTracker>();
services.AddScoped<IBookLibraryTypeScanner, BookLibraryTypeScanner>();
services.AddScoped<ILibraryScanningService, LibraryScanningService>();
services.AddSingleton<IMediaScanQueue, MediaScanQueue>();
services.AddScoped<ILibraryScannerFactory, LibraryScannerFactory>();
services.AddScoped<IMediaScanJobFactory, MediaScanJobFactory>();
services.AddHostedService<MediaScanJobProcessorJob>();
services.AddScoped<IMediaLibraryScanningService, MediaLibraryScanningService>();
services.AddScoped<IMediaLibraryScannerFactory, MediaLibraryScannerFactory>();
services.AddScoped<IMediaLibraryScanJobFactory, MediaLibraryScanJobFactory>();
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
services.AddTransient<FileSystemDiscoveryJob>();
services.AddTransient<RepositoryMetadataDiscoveryJob>();
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.Scanning;
/// <summary>
/// Model for tracking media library scans.
/// </summary>
/// <param name="ScanId">The Id of the media library scan to be tracked.</param>
/// <param name="UserId">The Id of the username who initiated the media library scan.</param>
public record MediaScanTrackerModel(Guid ScanId, Guid UserId);
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="CancelLibraryScanRequest"/>.
/// </summary>
public static class CancelLibraryScanRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="CancelLibraryScanCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static CancelLibraryScanCommand ToCommand(this CancelLibraryScanRequest request)
{
return new CancelLibraryScanCommand(
request.Id
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="ScanLibraryRequest"/>.
/// </summary>
public static class ScanLibraryRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="ScanLibraryCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static ScanLibraryCommand ToCommand(this ScanLibraryRequest request)
{
return new ScanLibraryCommand(
request.Id
);
}
}
@@ -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).
/// </summary>
/// <param name="task">The task to be awaited.</param>
public static async void FireAndForgetSafeAsync(this Task task)
/// <param name="onComplete">Optional continuation when <paramref name="task"/> finishes.</param>
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();
}
}
}
@@ -0,0 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan;
/// <summary>
/// Command for cancelling the previously started scan of all media libraries.
/// </summary>
public record CancelLibrariesScanCommand : IRequest<ErrorOr<Success>>;
@@ -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;
/// <summary>
/// Handler for the command for cancelling the scan of all media libraries.
/// </summary>
public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibrariesScanTracker _librariesScanTracker;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibrariesScanCommandHandler"/> class.
/// </summary>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
public CancelLibrariesScanCommandHandler(ICurrentUserService currentUserService, IMediaLibrariesScanTracker librariesScanTracker)
{
_currentUserService = currentUserService;
_librariesScanTracker = librariesScanTracker;
}
/// <summary>
/// Handles the command for cancelling the scan of all media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(CancelLibrariesScanCommand request, CancellationToken cancellationToken)
{
_librariesScanTracker.CancelUserScans(_currentUserService.UserId!.Value);
return await ValueTask.FromResult(Result.Success);
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan;
/// <summary>
/// Command for cancelling the scan of a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library whose scan is cancelled.</param>
[DebuggerDisplay("Id: {Id}")]
public record CancelLibraryScanCommand(
Guid Id
) : IRequest<ErrorOr<Success>>;
@@ -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;
/// <summary>
/// Handler for the command for cancelling the scan of a media library.
/// </summary>
public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScanCommand, ErrorOr<Success>>
{
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanCommandHandler"/> class.
/// </summary>
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
public CancelLibraryScanCommandHandler(IMediaLibraryScanningService mediaLibraryScanningService)
{
_mediaLibraryScanningService = mediaLibraryScanningService;
}
/// <summary>
/// Handles the command for cancelling the scan of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(CancelLibraryScanCommand request, CancellationToken cancellationToken)
{
_mediaLibraryScanningService.CancelScan(request.Id);
return await ValueTask.FromResult(Result.Success);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan;
/// <summary>
/// Validates the needed validation rules for <see cref="CancelLibraryScanCommand"/>.
/// </summary>
public class CancelLibraryScanCommandValidator : AbstractValidator<CancelLibraryScanCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanCommandValidator"/> class.
/// </summary>
public CancelLibraryScanCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
}
}
@@ -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
/// <summary>
/// Command for initiating the scan of all media libraries.
/// </summary>
public record ScanLibrariesCommand() : IRequest<ErrorOr<Success>>;
public record ScanLibrariesCommand() : IRequest<ErrorOr<IEnumerable<ScanLibraryResponse>>>;
@@ -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
/// <summary>
/// Handler for the command for initiating the scan of all media libraries.
/// </summary>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<Success>>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<ScanLibraryResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly ILibraryScanningService _libraryScanningService;
private readonly IMediaLibraryScanningService _libraryScanningService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
@@ -37,7 +39,7 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
public ScanLibrariesCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
ILibraryScanningService libraryScanningService,
IMediaLibraryScanningService libraryScanningService,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
@@ -52,26 +54,30 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
public async ValueTask<ErrorOr<IEnumerable<ScanLibraryResponse>>> 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<ILibraryRepository>();
ErrorOr<IEnumerable<LibraryEntity>> 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<ErrorOr<Library>> 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<ScanLibraryResponse> responses = [];
// for each library, start the scan
foreach (ErrorOr<Library> 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;
}
}
@@ -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;
/// <summary>
/// Command for initiating the scan of a media library.
/// </summary>
/// <param name="Id">The Id of the library to scan.</param>
public record ScanLibraryCommand(
Guid Id
) : IRequest<ErrorOr<ScanLibraryResponse>>;
@@ -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;
/// <summary>
/// Handler for the command for initiating the scan of a media library.
/// </summary>
public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, ErrorOr<ScanLibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public ScanLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IMediaLibraryScanningService mediaLibraryScanningService,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_mediaLibraryScanningService = mediaLibraryScanningService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the command for initiating the scan of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<ScanLibraryResponse>> Handle(ScanLibraryCommand request, CancellationToken cancellationToken)
{
// get the media library from the persistence medium
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> 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<Library> 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);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <summary>
/// Validates the needed validation rules for <see cref="ScanLibraryCommand"/>.
/// </summary>
public class ScanLibraryCommandValidator : AbstractValidator<ScanLibraryCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryCommandValidator"/> class.
/// </summary>
public ScanLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
}
}
@@ -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;
/// <summary>
/// Interface for the service used to scan a media library.
/// </summary>
public interface ILibraryScanningService
public interface IMediaLibraryScanningService
{
/// <summary>
/// Starts the scan of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library to scan.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
Task StartScanAsync(Library library, CancellationToken cancellationToken);
/// <returns>The Id of the media library scan.</returns>
Task<Guid> StartScanAsync(Library library, CancellationToken cancellationToken);
/// <summary>
/// Cancels the scan identified by <paramref name="scanId"/>.
/// </summary>
/// <param name="scanId">The Id of the scan to cancel.</param>
void CancelScan(Guid scanId);
}
@@ -18,7 +18,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Media library scan job for discovering file system items.
/// </summary>
internal class FileSystemDiscoveryJob : MediaScanJob
internal class FileSystemDiscoveryJob : MediaLibraryScanJob
{
private readonly IDirectoryService _directoryService;
private readonly IFileService _fileService;
@@ -37,28 +37,37 @@ internal class FileSystemDiscoveryJob : MediaScanJob
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
try
{
Status = LibraryScanJobStatus.Running;
// recursively get the file system tree for each of the media library content locations
List<FileSystemTreeNode> contentLocationTrees = [];
foreach (FileSystemPathId contentLocation in Library.ContentLocations)
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<FileSystemTreeNode> 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<FileSystemTreeNode> contentLocationTrees = [];
foreach (FileSystemPathId contentLocation in Library.ContentLocations)
{
// handle errors, maybe:
// Status = LibraryScanJobStatus.Failed;
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> 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
/// <param name="path">The identifier of the root path from which to build the tree.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the tree.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
public ErrorOr<FileSystemTreeNode> BuildTree(FileSystemPathId path, bool includeHiddenElements = false)
public ErrorOr<FileSystemTreeNode> BuildTree(FileSystemPathId path, bool includeHiddenElements = false, CancellationToken cancellationToken = default)
{
// validate the path and get the root directory node
ErrorOr<Directory> rootDirectoryResult = Directory.Create(path, path.Path, Optional<DateTime>.None(), Optional<DateTime>.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);
}
/// <summary>
@@ -85,7 +94,7 @@ internal class FileSystemDiscoveryJob : MediaScanJob
/// <param name="directory">The directory for which to build a tree node.</param>
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included in the node's children.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="FileSystemTreeNode"/>, or an error.</returns>
private ErrorOr<FileSystemTreeNode> BuildNodeRecursive(Directory directory, bool includeHiddenElements)
private ErrorOr<FileSystemTreeNode> 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<FileSystemTreeNode> subNodeResult = BuildNodeRecursive(subdirectory, includeHiddenElements);
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> 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,
@@ -11,21 +11,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Media library scan job for comparing hashes.
/// </summary>
internal class HashComparerJob : MediaScanJob
internal class HashComparerJob : MediaLibraryScanJob
{
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
try
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Cancelled;
throw;
}
}
}
@@ -8,7 +8,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Interface for the media library scan jobs factory.
/// </summary>
internal interface IMediaScanJobFactory
internal interface IMediaLibraryScanJobFactory
{
/// <summary>
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
@@ -16,5 +16,5 @@ internal interface IMediaScanJobFactory
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
TJob CreateJob<TJob>(Library library) where TJob : MediaScanJob;
TJob CreateJob<TJob>(Library library) where TJob : MediaLibraryScanJob;
}
@@ -12,19 +12,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Abstract class defining a media library scan job.
/// </summary>
internal abstract class MediaScanJob
internal abstract class MediaLibraryScanJob
{
internal int parentsPayloadsExecuted;
/// <summary>
/// Gets or sets the Id of the media library scan that this job is part of.
/// </summary>
public Guid ScanId { get; set; }
/// <summary>
/// Gets or sets the Id of the user that initiated the media library scan that this job is part of.
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Gets or sets the list of child media scan jobs that will be triggered when this job's payload completes execution.
/// </summary>
public List<MediaScanJob> Children { get; protected set; } = [];
public List<MediaLibraryScanJob> Children { get; protected set; } = [];
/// <summary>
/// Gets or sets the list of parent media scan jobs that will trigger this job when their payload will complete execution.
/// </summary>
public List<MediaScanJob> Parents { get; protected set; } = [];
public List<MediaLibraryScanJob> Parents { get; protected set; } = [];
/// <summary>
/// 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.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
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.
/// </summary>
/// <param name="job">The child media library scan job to be added.</param>
public void AddParent(MediaScanJob job)
public void AddParent(MediaLibraryScanJob job)
{
if (!Parents.Contains(job) && !Children.Contains(job))
Parents.Add(job);
@@ -9,15 +9,15 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Concrete implementation for the media library scan jobs factory.
/// </summary>
internal class MediaScanJobFactory : IMediaScanJobFactory
internal class MediaLibraryScanJobFactory : IMediaLibraryScanJobFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="MediaScanJobFactory"/> class.
/// Initializes a new instance of the <see cref="MediaLibraryScanJobFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public MediaScanJobFactory(IServiceProvider serviceProvider)
public MediaLibraryScanJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
@@ -28,7 +28,7 @@ internal class MediaScanJobFactory : IMediaScanJobFactory
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
public TJob CreateJob<TJob>(Library library) where TJob : MediaScanJob
public TJob CreateJob<TJob>(Library library) where TJob : MediaLibraryScanJob
{
// resolve the job from DI
TJob job = _serviceProvider.GetRequiredService<TJob>() ?? throw new ArgumentException();
@@ -11,21 +11,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Media library scan job for retrieving persistence data from any eventual previous scans.
/// </summary>
internal class RepositoryMetadataDiscoveryJob : MediaScanJob
internal class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob
{
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
try
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Cancelled;
throw;
}
}
}
@@ -12,21 +12,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
/// <summary>
/// Media library scan job for retrieving written content metadata from GoodReads.
/// </summary>
internal class GoodReadsMetadataScrapJob : MediaScanJob
internal class GoodReadsMetadataScrapJob : MediaLibraryScanJob
{
/// <inheritdoc/>
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
{
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
try
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
Status = LibraryScanJobStatus.Running;
List<int> ints = [1, 2, 3];
Status = LibraryScanJobStatus.Completed;
// call each linked child with the obtained payload
foreach (MediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Status = LibraryScanJobStatus.Cancelled;
throw;
}
}
}
@@ -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;
/// <summary>
/// Service used to scan a media library.
/// </summary>
internal class LibraryScanningService : ILibraryScanningService
{
private readonly IMediaScanQueue _mediaScanQueue;
private readonly ILibraryScannerFactory _libraryScannerFactory;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScanningService"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
/// <param name="libraryScannerFactory">Injected factory for creating media library scanners.</param>
public LibraryScanningService(IMediaScanQueue mediaScanQueue, ILibraryScannerFactory libraryScannerFactory)
{
_mediaScanQueue = mediaScanQueue;
_libraryScannerFactory = libraryScannerFactory;
}
/// <summary>
/// Starts the scan of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library to scan.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task StartScanAsync(Library library, CancellationToken cancellationToken)
{
try
{
// get a media library scanne for the provided media library type
IMediaTypeScanner scanner = _libraryScannerFactory.CreateLibraryScanner(library.LibraryType);
// get the list of scan jobs for the retrieved scanner
IEnumerable<MediaScanJob> jobs = scanner.CreateScanJobsForLibrary(library);
// enqueue the jobs on the channel from where they will be processed
foreach (MediaScanJob job in jobs)
await _mediaScanQueue.Writer.WriteAsync(job, cancellationToken).ConfigureAwait(false);
}
catch (NotImplementedException) { }
}
}
@@ -0,0 +1,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;
/// <summary>
/// Service used to scan a media library.
/// </summary>
internal class MediaLibraryScanningService : IMediaLibraryScanningService
{
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
private readonly IMediaLibraryScannerFactory _libraryScannerFactory;
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibrariesScanTracker _librariesScanTracker;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanningService"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
/// <param name="libraryScannerFactory">Injected factory for creating media library scanners.</param>
public MediaLibraryScanningService(
IMediaLibrariesScanQueue mediaScanQueue,
IMediaLibraryScannerFactory libraryScannerFactory,
IMediaLibrariesScanTracker librariesScanTracker,
ICurrentUserService currentUserService)
{
_mediaScanQueue = mediaScanQueue;
_libraryScannerFactory = libraryScannerFactory;
_currentUserService = currentUserService;
_librariesScanTracker = librariesScanTracker;
}
/// <summary>
/// Starts the scan of <paramref name="library"/>.
/// </summary>
/// <param name="library">The media library to scan.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The Id of the media library scan.</returns>
public async Task<Guid> 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<MediaLibraryScanJob> 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;
}
/// <summary>
/// Cancels the scan identified by <paramref name="scanId"/>.
/// </summary>
/// <param name="scanId">The Id of the scan to cancel.</param>
public void CancelScan(Guid scanId)
{
_librariesScanTracker.CancelScan(scanId, _currentUserService.UserId!.Value);
}
}
@@ -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;
/// <summary>
/// Interface for the message queue for handling <see cref="MediaScanJob"/> instances.
/// Interface for the message queue for handling <see cref="MediaLibraryScanJob"/> instances.
/// </summary>
internal interface IMediaScanQueue
internal interface IMediaLibrariesScanQueue
{
/// <summary>
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaScanJob"/> instances.
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaLibraryScanJob"/> instances.
/// </summary>
public ChannelWriter<MediaScanJob> Writer { get; }
public ChannelWriter<MediaLibraryScanJob> Writer { get; }
/// <summary>
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaScanJob"/> instances.
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaLibraryScanJob"/> instances.
/// </summary>
public ChannelReader<MediaScanJob> Reader { get; }
public ChannelReader<MediaLibraryScanJob> Reader { get; }
}
@@ -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;
/// <summary>
/// Provides an in-memory message queue for handling <see cref="MediaScanJob"/> instances.
/// Provides an in-memory message queue for handling <see cref="MediaLibraryScanJob"/> instances.
/// </summary>
internal class MediaScanQueue : IMediaScanQueue
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
{
private readonly Channel<MediaScanJob> _channel = Channel.CreateUnbounded<MediaScanJob>();
private readonly Channel<MediaLibraryScanJob> _channel = Channel.CreateUnbounded<MediaLibraryScanJob>();
/// <summary>
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaScanJob"/> instances.
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaLibraryScanJob"/> instances.
/// </summary>
public ChannelWriter<MediaScanJob> Writer
public ChannelWriter<MediaLibraryScanJob> Writer
{
get { return _channel.Writer; }
}
/// <summary>
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaScanJob"/> instances.
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaLibraryScanJob"/> instances.
/// </summary>
public ChannelReader<MediaScanJob> Reader
public ChannelReader<MediaLibraryScanJob> Reader
{
get { return _channel.Reader; }
}
@@ -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;
/// <summary>
/// Background service for processing media library scan jobs from an in-memory message queue.
/// </summary>
internal sealed class MediaScanJobProcessorJob : BackgroundService
internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService
{
private readonly IMediaScanQueue _mediaScanQueue;
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
private readonly IMediaLibrariesScanTracker _librariesScanTracker;
/// <summary>
/// Initializes a new instance of the <see cref="MediaScanJobProcessorJob"/> class.
/// Initializes a new instance of the <see cref="MediaLibraryScanJobProcessorJob"/> class.
/// </summary>
/// <param name="mediaScanQueue">Injected queue used for processing media libraries scan jobs.</param>
public MediaScanJobProcessorJob(IMediaScanQueue mediaScanQueue)
public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanTracker librariesScanTracker)
{
_mediaScanQueue = mediaScanQueue;
_librariesScanTracker = librariesScanTracker;
}
/// <summary>
@@ -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());
}
}
}
@@ -7,7 +7,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scan
/// <summary>
/// Interface defining a factory for creating media library scanners.
/// </summary>
internal interface ILibraryScannerFactory
internal interface IMediaLibraryScannerFactory
{
/// <summary>
/// Creates a media library scanner based on the provided library type.
@@ -22,5 +22,5 @@ internal interface IMediaTypeScanner
/// </summary>
/// <param name="library">The media library for which to create the media library scan jobs.</param>
/// <returns>A collection of media library scan jobs.</returns>
IEnumerable<MediaScanJob> CreateScanJobsForLibrary(Library library);
IEnumerable<MediaLibraryScanJob> CreateScanJobsForLibrary(Library library);
}
@@ -10,15 +10,15 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scan
/// <summary>
/// Defines a factory for creating media library scanners.
/// </summary>
internal class LibraryScannerFactory : ILibraryScannerFactory
internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
{
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryScannerFactory"/> class.
/// Initializes a new instance of the <see cref="MediaLibraryScannerFactory"/> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
public LibraryScannerFactory(IServiceProvider serviceProvider)
public MediaLibraryScannerFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
@@ -13,7 +13,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scan
/// </summary>
internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
{
private readonly IMediaScanJobFactory _mediaScanJobFactory;
private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
/// <inheritdoc/>
public LibraryType SupportedType { get; } = LibraryType.Book;
@@ -22,13 +22,13 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
/// Initializes a new instance of the <see cref="LibraryScannerFactory"/> class.
/// </summary>
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
public BookLibraryTypeScanner(IMediaScanJobFactory mediaScanJobFactory)
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
{
_mediaScanJobFactory = mediaScanJobFactory;
}
/// <inheritdoc/>
public IEnumerable<MediaScanJob> CreateScanJobsForLibrary(Library library)
public IEnumerable<MediaLibraryScanJob> CreateScanJobsForLibrary(Library library)
{
// declare the list of jobs that this scanner requires
FileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<FileSystemDiscoveryJob>(library);
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking;
/// <summary>
/// Interface for the tracker used for in-progress media library scans.
/// </summary>
public interface IMediaLibrariesScanTracker
{
/// <summary>
/// Gets the cancellation token for a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The Id of the scan to get the cancellation token for<./param>
/// <param name="userId">The Id of the user who initiated the scan for which to get the cancellation token.</param>
/// <returns>A cancellation token for the specified scan.</returns>
CancellationToken GetTokenForScan(Guid scanId, Guid userId);
/// <summary>
/// Registers a new scan operation for tracking.
/// </summary>
/// <param name="scanId">The Id of the scan operation to track.</param>
/// <param name="userId">The Id of the user who initiated the scan to track.</param>
void RegisterScan(Guid scanId, Guid userId);
/// <summary>
/// Cancels a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The Id of the scan operation to cancel.</param>
/// <param name="userId">The Id of the user requesting the cancellation.</param>
void CancelScan(Guid scanId, Guid userId);
/// <summary>
/// Cancels all active scan operations for a user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose scans should be cancelled.</param>
void CancelUserScans(Guid userId);
}
@@ -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;
/// <summary>
/// Tracker used for in-progress media library scans.
/// </summary>
internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposable
{
private readonly ConcurrentDictionary<MediaScanTrackerModel, CancellationTokenSource> _runningScans = new();
private bool _disposed;
/// <summary>
/// Registers a new scan operation for tracking.
/// </summary>
/// <param name="scanId">The Id of the scan operation to track.</param>
/// <param name="userId">The Id of the user who initiated the scan to track.</param>
public void RegisterScan(Guid scanId, Guid userId)
{
_runningScans.TryAdd(new MediaScanTrackerModel(scanId, userId), new CancellationTokenSource());
}
/// <summary>
/// Gets the cancellation token for a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The Id of the scan to get the cancellation token for<./param>
/// <param name="userId">The Id of the user who initiated the scan for which to get the cancellation token.</param>
/// <returns>A cancellation token for the specified scan.</returns>
public CancellationToken GetTokenForScan(Guid scanId, Guid userId)
{
return _runningScans.TryGetValue(new MediaScanTrackerModel(scanId, userId), out CancellationTokenSource? scan)
? scan.Token
: CancellationToken.None;
}
/// <summary>
/// Cancels a scan identified by <paramref name="scanId"/> and <paramref name="userId"/>.
/// </summary>
/// <param name="scanId">The Id of the scan operation to cancel.</param>
/// <param name="userId">The Id of the user requesting the cancellation.</param>
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();
}
}
}
}
/// <summary>
/// Cancels all active scan operations for a user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose scans should be cancelled.</param>
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();
}
}
}
}
/// <summary>
/// Disposes the tracker and cancels all media library scans.
/// </summary>
public void Dispose()
{
if (!_disposed)
{
foreach (CancellationTokenSource scan in _runningScans.Values)
{
scan.Cancel();
scan.Dispose();
}
_runningScans.Clear();
_disposed = true;
}
}
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// <summary>
/// Represents a request to cancel the scan of a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library whose scan is cancelled. Required.</param>
[DebuggerDisplay("Id: {Id}")]
public record CancelLibraryScanRequest(
Guid Id
);
@@ -8,7 +8,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// <summary>
/// Represents a request to delete a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library. Required.</param>
/// <param name="Id">The Id of the media library to be deleted. Required.</param>
[DebuggerDisplay("Id: {Id}")]
public record DeleteLibraryRequest(
Guid Id
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.Management;
/// <summary>
/// Represents a request to scan a media library.
/// </summary>
/// <param name="Id">The Id of the media library to be scanned. Required.</param>
[DebuggerDisplay("Id: {Id}")]
public record ScanLibraryRequest(
Guid Id
);
@@ -10,7 +10,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management;
/// <summary>
/// Represents a media library response.
/// </summary>
/// <param name="Id">The id of the media library.</param>
/// <param name="Id">The Id of the media library.</param>
/// <param name="UserId">The Id of the user owning the media library.</param>
/// <param name="Title">The title of the media library.</param>
/// <param name="LibraryType">The type of the media library.</param>
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.Management;
/// <summary>
/// Represents a media library scan response.
/// </summary>
/// <param name="ScanId">The Id of the media library scan.</param>
/// <param name="LibraryId">The Id of the scanned media library.</param>
[DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")]
public record ScanLibraryResponse(
Guid ScanId,
Guid LibraryId
);
@@ -20,6 +20,11 @@ public enum LibraryScanJobStatus
/// </summary>
Completed,
/// <summary>
/// Job has been cancelled.
/// </summary>
Cancelled,
/// <summary>
/// Job has failed.
/// </summary>
@@ -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));
@@ -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";
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/libraries/cancel-scan</c> route.
/// </summary>
public class CancelLibrariesScanEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CancelLibrariesScanEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Libraries.CANCEL_LIBRARIES_SCAN);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Cancels a previously started scan of all media libraries.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<Success> result = await _sender.Send(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="CancelLibrariesScanEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CancelLibrariesScanEndpointSummary : Summary<CancelLibrariesScanEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibrariesScanEndpointSummary"/> class.
/// </summary>
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"
}
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/libraries/{id}/cancel-scan</c> route.
/// </summary>
public class CancelLibraryScanEndpoint : BaseEndpoint<CancelLibraryScanRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CancelLibraryScanEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Libraries.CANCEL_LIBRARY_SCAN);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Cancels a previously started scan of all media libraries.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CancelLibraryScanRequest request, CancellationToken cancellationToken)
{
ErrorOr<Success> result = await _sender.Send(new CancelLibrariesScanCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="CancelLibraryScanEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CancelLibraryScanEndpointSummary : Summary<CancelLibraryScanEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanEndpointSummary"/> class.
/// </summary>
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<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeleteLibraryEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteLibraryEndpointSummary : Summary<DeleteLibraryEndpoint, DeleteLibraryRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryEndpointSummary"/> class.
/// </summary>
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<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -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<EmptyRequest, IResult>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<Success> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
ErrorOr<IEnumerable<ScanLibraryResponse>> result = await _sender.Send(new ScanLibrariesCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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<ScanLibrariesEndpoint, Empty
public ScanLibrariesEndpointSummary()
{
Summary = "Triggers the scan of all media libraries.";
Description = "Starts the scanning process of all media libraries, if the user making the request is an Admin.";
Description = "Starts the scanning process of all media libraries of a user, or all libraries, if the user is an Admin.";
Response(204, "The media libraries scan was successfully started.");
Response(200, "The media libraries scan was successfully started.",
example: new ScanLibraryResponse[] {
new (
ScanId: Guid.NewGuid(),
LibraryId: Guid.NewGuid()
),
new (
ScanId: Guid.NewGuid(),
LibraryId: Guid.NewGuid()
)
});
Response(401, "Authentication required.", "application/problem+json",
example: new[]
@@ -50,17 +62,5 @@ public class ScanLibrariesEndpointSummary : Summary<ScanLibrariesEndpoint, Empty
}
}
);
Response(403, "The request failed because the user making the request is not an Admin.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1//libraries/scan",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary;
/// <summary>
/// API endpoint for the <c>/libraries/{id}/scan</c> route.
/// </summary>
public class ScanLibraryEndpoint : BaseEndpoint<ScanLibraryRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibrariesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ScanLibraryEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Libraries.SCAN_LIBRARY);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Initiates a scan of a media library.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ScanLibraryRequest request, CancellationToken cancellationToken)
{
ErrorOr<ScanLibraryResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="ScanLibraryEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryEndpointSummary"/> class.
/// </summary>
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<string, string[]>
{
{
"General.Validation", new[]
{
"LibraryIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Libraries;
/// <summary>
/// Represents a media library scan response.
/// </summary>
[DebuggerDisplay("ScanId: {ScanId} LibraryId: {LibraryId}")]
public class ScanLibraryModel
{
/// <summary>
/// Gets or sets the Id of the media library scan.
/// </summary>
public Guid? ScanId { get; set; }
/// <summary>
/// Gets or sets the Id of the scanned media library.
/// </summary>
public Guid? LibraryId { get; set; }
}
@@ -121,7 +121,42 @@ public class LibraryManagementController : Controller
[HttpPost("api-scan-libraries")]
public async Task<IActionResult> ScanAllLibraries(CancellationToken cancellationToken = default)
{
await _apiHttpClient.PostAsync<EmptyModel, EmptyModel>($"libraries/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = true });
ScanLibraryModel[] response = await _apiHttpClient.PostAsync<ScanLibraryModel[], EmptyModel>($"libraries/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
}
/// <summary>
/// Initiates the scan of a media library.
/// </summary>
/// <param name="id">The id of the media library whose scan is started.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpPost("api-scan-library/{id}")]
public async Task<IActionResult> ScanLibrary(Guid id, CancellationToken cancellationToken = default)
{
ScanLibraryModel response = await _apiHttpClient.PostAsync<ScanLibraryModel, EmptyModel>($"libraries/{id}/scan", new EmptyModel(), cancellationToken).ConfigureAwait(false);
return Json(new { success = true, data = response });
}
/// <summary>
/// Cancells the previously started scan of all media libraries.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpPost("api-cancel-libraries-scan")]
public async Task<IActionResult> CancelLibrariesScan(CancellationToken cancellationToken = default)
{
await _apiHttpClient.PostAsync<EmptyModel, EmptyModel>($"libraries/cancel-scan", new EmptyModel(), cancellationToken).ConfigureAwait(false);
return Json(new { success = true });
}
/// <summary>
/// Cancells the previously started scan of a media library.
/// </summary>
/// <param name="id">The id of the media library whose scan is cancelled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpPost("api-cancel-library-scan/{id}")]
public async Task<IActionResult> CancelLibraryScan(Guid id, CancellationToken cancellationToken = default)
{
await _apiHttpClient.PostAsync<EmptyModel, EmptyModel>($"libraries/{id}/cancel-scan", new EmptyModel(), cancellationToken).ConfigureAwait(false);
return Json(new { success = true });
}
}
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Die Coverdatei muss ein Bild sein!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Eine deaktivierte Bibliothek kann nicht gescannt werden!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Eine gesperrte Bibliothek kann nicht gescannt werden!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Cover file must be an image!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Cannot scan a disabled library!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Cannot scan a locked library!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>¡El archivo de portada debe ser una imagen!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>¡No se puede escanear una biblioteca desactivada!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>¡No se puede escanear una biblioteca bloqueada!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Le fichier de couverture doit être une image!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Impossible de scanner une bibliothèque désactivée!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Impossible de scanner une bibliothèque verrouillée!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Il file di copertina deve essere un'immagine!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Impossibile scansionare una libreria disabilitata!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Impossibile scansionare una libreria bloccata!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>カバーファイルは画像である必要があります!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>無効化されたライブラリはスキャンできません!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>ロックされたライブラリはスキャンできません!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Cover file must be an image!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Cannot scan a disabled library!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Cannot scan a locked library!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Fișierul copertă trebuie să fie o imagine!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Nu se poate scana o bibliotecă dezactivată!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Nu se poate scana o bibliotecă blocată!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Файл обложки должен быть изображением!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>Невозможно сканировать отключенную библиотеку!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>Невозможно сканировать заблокированную библиотеку!</value>
</data>
</root>
@@ -543,4 +543,10 @@
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>封面文件必须是图片!</value>
</data>
<data name="CannotScanDisabledLibrary" xml:space="preserve">
<value>无法扫描已禁用的库!</value>
</data>
<data name="CannotScanLockedLibrary" xml:space="preserve">
<value>无法扫描已锁定的库!</value>
</data>
</root>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Entfernen</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Scannen</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Alle Bibliotheken Scannen</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Remove</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Scan</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Scan All Libraries</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Eliminar</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Escanear</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Escanear Todas Las Bibliotecas</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Supprimer</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Scanner</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Scanner Toutes Les Bibliothèques</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Rimuovere</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Scansiona</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Scansiona Tutte Le Librerie</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>削除</value>
</data>
<data name="Scan" xml:space="preserve">
<value>スキャン</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>すべてのライブラリをスキャン</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Remove</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Scan</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Scan All Libraries</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Șterge</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Scanează</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Scanează Toate Bibliotecile</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>Удалить</value>
</data>
<data name="Scan" xml:space="preserve">
<value>Сканировать</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>Сканировать Все Библиотеки</value>
</data>
@@ -231,6 +231,9 @@
<data name="Remove" xml:space="preserve">
<value>删除</value>
</data>
<data name="Scan" xml:space="preserve">
<value>扫描</value>
</data>
<data name="ScanAllLibraries" xml:space="preserve">
<value>扫描所有库</value>
</data>
@@ -102,12 +102,14 @@
const editUrl = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement", new { id = default(Guid) })'
.replace('/@(default(Guid))', `/${library.id}`);
return `
<tr>
<tr data-library-id="${library.id}">
<td title="${library.title}">${library.title}</td>
<td>${jsLocalizedLibraryTypes[library.libraryType]}</td>
<td class="text-center">${library.isEnabled === true ? `@_localizer["Yes"]` : `@_localizer["No"]`}</td>
<td class="text-center">${library.isLocked === true ? `@_localizer["Yes"]` : `@_localizer["No"]`}</td>
<td class="text-end">
<img src="/images/ui/stop.svg" alt="@_localizer["CancelScan"]" title="@_localizer["Scan"]" class="hidden remove-form-table-row-icon" />
<img src="/images/ui/trigger.svg" alt="@_localizer["Scan"]" title="@_localizer["Scan"]" class="remove-form-table-row-icon" />
<a href="${editUrl}">
<img src="/images/ui/edit.svg" alt="@_localizer["Edit"]" title="@_localizer["Edit"]" class="remove-form-table-row-icon" />
</a>
@@ -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);
});
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6 12C6 12.5523 6.44772 13 7 13L17 13C17.5523 13 18 12.5523 18 12C18 11.4477 17.5523 11 17 11H7C6.44772 11 6 11.4477 6 12Z" style="fill:#009BFC;fill-opacity:1;stroke:none"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M12 23C18.0751 23 23 18.0751 23 12C23 5.92487 18.0751 1 12 1C5.92487 1 1 5.92487 1 12C1 18.0751 5.92487 23 12 23ZM12 20.9932C7.03321 20.9932 3.00683 16.9668 3.00683 12C3.00683 7.03321 7.03321 3.00683 12 3.00683C16.9668 3.00683 20.9932 7.03321 20.9932 12C20.9932 16.9668 16.9668 20.9932 12 20.9932Z" style="fill:#009BFC;fill-opacity:1;stroke:none"/>
</svg>

After

Width:  |  Height:  |  Size: 809 B

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
␍<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M6 14L13 2V10H18L11 22V14H6Z" style="fill:#009BFC;fill-opacity:1;stroke:none"/>
</svg>

After

Width:  |  Height:  |  Size: 240 B