Adds media libraries cancel scan option

This commit is contained in:
BinaryAlley committed 2025-02-01 16:30:48 +02:00
1 parent d6edb0b22b
commit e862f5de30
77 files changed
+1585 -194

No files matched your search

@@ -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;
}
}
}