mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +00:00
Moves media library scanning to domain layer
This commit is contained in:
1 parent
8b51abe0b2
commit
c4246d2e69
209 files changed
+3793
-641
No files matched your search
+12
-13
@@ -15,6 +15,7 @@ using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Threading;
|
||||
@@ -90,7 +91,7 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
|
||||
// create a domain library object
|
||||
ErrorOr<Library> createLibraryResult = Library.Create(
|
||||
_currentUserService.UserId!.Value,
|
||||
UserId.Create(_currentUserService.UserId!.Value),
|
||||
request.Title!,
|
||||
Enum.Parse<LibraryType>(request.LibraryType!),
|
||||
request.ContentLocations!,
|
||||
@@ -98,7 +99,8 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMedatadaFromWeb,
|
||||
request.SaveMetadataInMediaDirectories
|
||||
request.SaveMetadataInMediaDirectories,
|
||||
[]
|
||||
);
|
||||
|
||||
if (createLibraryResult.IsError)
|
||||
@@ -115,22 +117,19 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// retrieve the newly saved media library from the persistence medium and return it
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// retrieve the updated media library from the persistence medium and return it
|
||||
ErrorOr<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getCreatedLibraryResult.IsError)
|
||||
return getCreatedLibraryResult.Errors;
|
||||
if (getCreatedLibraryResult.Value is null)
|
||||
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
|
||||
|
||||
// mark the media library as saved
|
||||
createLibraryResult.Value.Save();
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return getCreatedLibraryResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,6 +6,6 @@ using Mediator;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan;
|
||||
|
||||
/// <summary>
|
||||
/// Command for cancelling the previously started scan of all media libraries.
|
||||
/// Command for canceling the previously started scan of all media libraries.
|
||||
/// </summary>
|
||||
public record CancelLibrariesScanCommand : IRequest<ErrorOr<Success>>;
|
||||
+73
-8
@@ -1,8 +1,18 @@
|
||||
#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.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -10,33 +20,88 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command for cancelling the scan of all media libraries.
|
||||
/// Handler for the command for canceling the scan of all media libraries.
|
||||
/// </summary>
|
||||
public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IMediaLibrariesScanTracker _librariesScanTracker;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <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)
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public CancelLibrariesScanCommandHandler(
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_currentUserService = currentUserService;
|
||||
_librariesScanTracker = librariesScanTracker;
|
||||
_authorizationService = authorizationService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command for cancelling the scan of all media libraries.
|
||||
/// Handles the command for canceling 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);
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the running library scans of the current user from the repository
|
||||
ErrorOr<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getRunningLibraryScansResult.IsError)
|
||||
return getRunningLibraryScansResult.Errors;
|
||||
|
||||
// filter the library scans to process
|
||||
List<LibraryScanEntity> authorizedLibraryScans = [];
|
||||
// admins can see all library scans
|
||||
if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value);
|
||||
else // for regular users, only take the library scans that belong to them
|
||||
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == _currentUserService.UserId));
|
||||
|
||||
// convert persistence library scans to domain entities
|
||||
IEnumerable<ErrorOr<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
||||
|
||||
List<IDomainEvent> domainEvents = [];
|
||||
|
||||
// for each library scan, perform the cancellation
|
||||
foreach (ErrorOr<LibraryScan> libraryScanDomainResult in libraryScansDomainResult)
|
||||
{
|
||||
if (libraryScanDomainResult.IsError)
|
||||
return libraryScanDomainResult.Errors;
|
||||
|
||||
// cancel the media library scan
|
||||
ErrorOr<Success> cancelScanResult = libraryScanDomainResult.Value.CancelScan();
|
||||
if (cancelScanResult.IsError)
|
||||
return cancelScanResult.Errors;
|
||||
|
||||
// update the status of the library scan in the repository
|
||||
ErrorOr<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsError)
|
||||
return updateLibraryScanResult.Errors;
|
||||
|
||||
// collect all the domain events created during this library scan start
|
||||
domainEvents.AddRange(libraryScanDomainResult.Value.GetDomainEvents());
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in domainEvents)
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return await ValueTask.FromResult(Result.Success);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -8,10 +8,12 @@ using System.Diagnostics;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan;
|
||||
|
||||
/// <summary>
|
||||
/// Command for cancelling the scan of a media library by its Id.
|
||||
/// Command for canceling the scan of a media library.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the media library whose scan is cancelled.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
/// <param name="LibraryId">The unique identifier of the media library whose scan is cancelled.</param>
|
||||
/// <param name="ScanId">The unique identifier of the scan to cancel.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}; ScanId: {ScanId}")]
|
||||
public record CancelLibraryScanCommand(
|
||||
Guid Id
|
||||
Guid LibraryId,
|
||||
Guid ScanId
|
||||
) : IRequest<ErrorOr<Success>>;
|
||||
+59
-14
@@ -3,48 +3,93 @@ 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.DomainEvents;
|
||||
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 Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
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.CancelLibraryScan;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command for cancelling the scan of a media library.
|
||||
/// Handler for the command for canceling the scan of a media library.
|
||||
/// </summary>
|
||||
public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScanCommand, ErrorOr<Success>>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
|
||||
/// <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)
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public CancelLibraryScanCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command for cancelling the scan of a media library.
|
||||
/// Handles the command for canceling 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);
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the library scan from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(request.ScanId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScansResult.IsError)
|
||||
return getLibraryScansResult.Errors;
|
||||
if (getLibraryScansResult.Value is null)
|
||||
return DomainErrors.LibraryScanning.LibraryScanNotFound;
|
||||
|
||||
// if the user that wants to scan the library is not an Admin or is not the owner of the library, they do not have the right to scan it
|
||||
if (getLibraryScansResult.Value.UserId != _currentUserService.UserId ||
|
||||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// convert the repository scan to a domain object
|
||||
ErrorOr<LibraryScan> libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsError)
|
||||
return libraryScanDomainResult.Errors;
|
||||
|
||||
// cancel the media library scan
|
||||
ErrorOr<Success> cancelScanResult = libraryScanDomainResult.Value.CancelScan();
|
||||
if (cancelScanResult.IsError)
|
||||
return cancelScanResult.Errors;
|
||||
|
||||
// update the status of the library scan in the repository
|
||||
ErrorOr<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsError)
|
||||
return updateLibraryScanResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in libraryScanDomainResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return await ValueTask.FromResult(Result.Success);
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -16,8 +16,11 @@ public class CancelLibraryScanCommandValidator : AbstractValidator<CancelLibrary
|
||||
/// </summary>
|
||||
public CancelLibraryScanCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Id)
|
||||
RuleFor(x => x.LibraryId)
|
||||
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
RuleFor(x => x.ScanId)
|
||||
.NotEmpty().WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary
|
||||
/// <summary>
|
||||
/// Command for deleting a media library by its Id.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the media library to delete.</param>
|
||||
/// <param name="Id">The unique identifier of the media library to delete.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record DeleteLibraryCommand(
|
||||
Guid Id
|
||||
|
||||
+2
-5
@@ -7,7 +7,6 @@ using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Mediator;
|
||||
@@ -53,9 +52,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
|
||||
/// </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}"/> containing either a successfuly created <see cref="LibraryResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// get the library with the specified id from the repository
|
||||
@@ -82,7 +79,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
|
||||
return deleteDomainLibraryResult.Errors;
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents())
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// perform the deletion
|
||||
|
||||
+58
-9
@@ -3,14 +3,17 @@ 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.DomainEvents;
|
||||
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.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -26,25 +29,25 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IMediaLibraryScanningService _libraryScanningService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanLibrariesCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="libraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public ScanLibrariesCommandHandler(
|
||||
IAuthorizationService authorizationService,
|
||||
ICurrentUserService currentUserService,
|
||||
IMediaLibraryScanningService libraryScanningService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_libraryScanningService = libraryScanningService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
@@ -56,8 +59,10 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<IEnumerable<ScanLibraryResponse>>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// get all media libraries that are enabled and unlocked from the persistence medium
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get all media libraries that are enabled and unlocked from the persistence medium
|
||||
ErrorOr<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getLibrariesResult.IsError)
|
||||
return getLibrariesResult.Errors;
|
||||
@@ -70,14 +75,58 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
|
||||
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value);
|
||||
|
||||
List<ScanLibraryResponse> responses = [];
|
||||
List<IDomainEvent> domainEvents = [];
|
||||
|
||||
// for each library, start the scan
|
||||
foreach (ErrorOr<Library> domainLibraryResult in domainEntitiesResult)
|
||||
{
|
||||
if (domainLibraryResult.IsError)
|
||||
return domainLibraryResult.Errors;
|
||||
Guid scanId = await _libraryScanningService.StartScanAsync(domainLibraryResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
responses.Add(new ScanLibraryResponse(scanId, domainLibraryResult.Value.Id.Value));
|
||||
|
||||
// get the past month's scans for this library
|
||||
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult =
|
||||
await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (pastLibraryScansResult.IsError)
|
||||
return pastLibraryScansResult.Errors;
|
||||
|
||||
// convert the repository scans history to domain objects
|
||||
IEnumerable<ErrorOr<LibraryScan>> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities();
|
||||
foreach (ErrorOr<LibraryScan> pastLibraryScanDomainResult in pastLibraryScansDomainResult)
|
||||
if (pastLibraryScanDomainResult.IsError)
|
||||
return pastLibraryScanDomainResult.Errors;
|
||||
|
||||
// start the media library scan
|
||||
ErrorOr<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||
LibraryId.Create(domainLibraryResult.Value.Id.Value),
|
||||
UserId.Create(_currentUserService.UserId!.Value),
|
||||
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
||||
);
|
||||
if (libraryScanResult.IsError)
|
||||
return libraryScanResult.Errors;
|
||||
|
||||
ErrorOr<Success> startScanResult = libraryScanResult.Value.QueueScan();
|
||||
// when the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned.
|
||||
// instead, just don't start the scan on such a library, and start it on the others that can be started
|
||||
if (startScanResult.IsError)
|
||||
continue;
|
||||
|
||||
// add the library scan to the persistence medium
|
||||
ErrorOr<Created> insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertLibraryScanResult.IsError)
|
||||
return insertLibraryScanResult.Errors;
|
||||
|
||||
// collect all the domain events created during this library scan start
|
||||
domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents());
|
||||
|
||||
responses.Add(new ScanLibraryResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value));
|
||||
}
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in domainEvents)
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return responses;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@ 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>
|
||||
/// <param name="Id">The unique identifier of the library to scan.</param>
|
||||
public record ScanLibraryCommand(
|
||||
Guid Id
|
||||
) : IRequest<ErrorOr<ScanLibraryResponse>>;
|
||||
+53
-13
@@ -3,14 +3,20 @@ 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.DomainEvents;
|
||||
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.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
@@ -26,25 +32,25 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
|
||||
/// <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="domainEventsQueue">Injected service for the queue of domain events.</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,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
@@ -56,8 +62,10 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
/// <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>();
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the media library from the persistence medium
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
@@ -65,7 +73,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
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 the user that wants to scan 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;
|
||||
@@ -77,14 +85,46 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
|
||||
if (getLibraryResult.Value.IsLocked)
|
||||
return DomainErrors.Library.CannotScanLockedLibrary;
|
||||
|
||||
// convert persistence libraries to domain entities
|
||||
// convert the persistence library to a domain entity
|
||||
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);
|
||||
// get the past month's scans for this library
|
||||
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (pastLibraryScansResult.IsError)
|
||||
return pastLibraryScansResult.Errors;
|
||||
|
||||
// convert the repository scans history to domain objects
|
||||
IEnumerable<ErrorOr<LibraryScan>> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities();
|
||||
foreach (ErrorOr<LibraryScan> pastLibraryScanDomainResult in pastLibraryScansDomainResult)
|
||||
if (pastLibraryScanDomainResult.IsError)
|
||||
return pastLibraryScanDomainResult.Errors;
|
||||
|
||||
// queue the media library scan
|
||||
ErrorOr<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||
LibraryId.Create(request.Id),
|
||||
UserId.Create(_currentUserService.UserId!.Value),
|
||||
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
||||
);
|
||||
if (libraryScanResult.IsError)
|
||||
return libraryScanResult.Errors;
|
||||
|
||||
ErrorOr<Success> queueScanResult = libraryScanResult.Value.QueueScan();
|
||||
if (queueScanResult.IsError)
|
||||
return queueScanResult.Errors;
|
||||
|
||||
// add the library scan to the persistence medium
|
||||
ErrorOr<Created> insertLibraryScanResult = await libraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertLibraryScanResult.IsError)
|
||||
return insertLibraryScanResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in libraryScanResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return new ScanLibraryResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -11,8 +11,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary
|
||||
/// <summary>
|
||||
/// Command for updating a media library.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the media library.</param>
|
||||
/// <param name="OwnerId">The Id of the user owning the media library.</param>
|
||||
/// <param name="Id">The unique identifier of the media library.</param>
|
||||
/// <param name="OwnerId">The unique identifier 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>
|
||||
/// <param name="ContentLocations">The file system paths of the directories where the media library elements are located.</param>
|
||||
|
||||
+16
-7
@@ -16,8 +16,11 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
@@ -83,13 +86,14 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
return DomainErrors.Library.CoverFileMustBeAnImage;
|
||||
}
|
||||
|
||||
// get a library repository
|
||||
// get a library repository and retrieve the library to update
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
else if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
|
||||
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it
|
||||
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
|
||||
(!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
|
||||
@@ -99,7 +103,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
// create a domain library object
|
||||
ErrorOr<Library> createLibraryResult = Library.Create(
|
||||
LibraryId.Create(request.Id),
|
||||
request.OwnerId,
|
||||
UserId.Create(request.OwnerId),
|
||||
request.Title!,
|
||||
Enum.Parse<LibraryType>(request.LibraryType!),
|
||||
request.ContentLocations!,
|
||||
@@ -107,7 +111,8 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMedatadaFromWeb,
|
||||
request.SaveMetadataInMediaDirectories
|
||||
request.SaveMetadataInMediaDirectories,
|
||||
getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
|
||||
);
|
||||
if (createLibraryResult.IsError)
|
||||
return createLibraryResult.Errors;
|
||||
@@ -120,16 +125,20 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
return updateLibraryResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// retrieve the updated media library from the persistence medium and return it
|
||||
ErrorOr<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getCreatedLibraryResult.IsError)
|
||||
return getCreatedLibraryResult.Errors;
|
||||
if (getCreatedLibraryResult.Value is null)
|
||||
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
|
||||
|
||||
// mark the media library as saved
|
||||
createLibraryResult.Value.Save();
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return getCreatedLibraryResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+4
-8
@@ -111,7 +111,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
|
||||
/// <summary>
|
||||
/// Saves the cover image of a media library to the internal media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library for which to save the cover image.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to save the cover image.</param>
|
||||
/// <param name="imagePath">The file path of the image file that will be copied to the media directory.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
@@ -200,14 +200,10 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the cover image of a media library to the internal media directory.
|
||||
/// Deletes the cover image from the media directory.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library for which to save the cover image.</param>
|
||||
/// <param name="imagePath">The file path of the image file that will be copied to the media directory.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either the location of the new cover image, or an error message.
|
||||
/// </returns>
|
||||
/// <param name="libraryPath">The path where the library content is located.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private ErrorOr<Deleted> DeleteCoverImageFromMediaDirectory(string libraryPath)
|
||||
{
|
||||
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#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.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan is cancelled.
|
||||
/// </summary>
|
||||
public class LibraryScanCancelledDomainEventHandler : INotificationHandler<LibraryScanCancelledDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly ILibraryScanRepository _libraryScanRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanCancelledDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <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 LibraryScanCancelledDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_libraryScanRepository = unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the event raised when a media library scan is cancelled.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
// get the library scan from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await _libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScansResult.IsError)
|
||||
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
||||
if (getLibraryScansResult.Value is null)
|
||||
throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound);
|
||||
|
||||
// convert the repository scan to a domain object
|
||||
ErrorOr<LibraryScan> libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsError)
|
||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
||||
|
||||
// cancel the media library scan
|
||||
ErrorOr<Success> cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value);
|
||||
if (cancelScanResult.IsError)
|
||||
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#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.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan has failed.
|
||||
/// </summary>
|
||||
public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryScanFailedDomainEvent>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanCancelledDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanFailedDomainEventHandler(IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the event raised when a media library scan has failed.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the library scan from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScansResult.IsError)
|
||||
throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors);
|
||||
if (getLibraryScansResult.Value is null)
|
||||
throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound);
|
||||
|
||||
// convert the repository scan to a domain object
|
||||
ErrorOr<LibraryScan> libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsError)
|
||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
||||
|
||||
// mark the media library scan as failed
|
||||
ErrorOr<Success> failScanResult = libraryScanDomainResult.Value.FailScan();
|
||||
// we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs might trigger this domain event,
|
||||
// trying to set as failed a scan that has already been marked as failed by a concurrent job
|
||||
if (!failScanResult.IsError)
|
||||
{
|
||||
// update the status of the library scan in the repository
|
||||
ErrorOr<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsError)
|
||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library's scan progress changes.
|
||||
/// </summary>
|
||||
public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler<LibraryScanProgressChangedDomainEvent>
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the event raised when a media library's scan progress changes.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#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.DomainEvents;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan is queued.
|
||||
/// </summary>
|
||||
public class LibraryScanQueuedDomainEventHandler : INotificationHandler<LibraryScanQueuedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanQueuedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="domainEventsQueue">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanQueuedDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IDomainEventsQueue domainEventsQueue, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the event raised when a media library scan is queued.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// get the library scan that was queued, from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScanResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryScanResult.IsError || getLibraryScanResult.Value is null)
|
||||
throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors);
|
||||
|
||||
// convert the repository entity to a domain entity
|
||||
ErrorOr<LibraryScan> libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity();
|
||||
if (libraryScanDomainResult.IsError)
|
||||
throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors);
|
||||
|
||||
// start the media library scan
|
||||
ErrorOr<Success> startScanResult = await _mediaLibraryScanningService.StartScanAsync(
|
||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMedatadaFromWeb, cancellationToken).ConfigureAwait(false);
|
||||
if (startScanResult.IsError)
|
||||
throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors);
|
||||
|
||||
// queue any domain events
|
||||
foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(queuedDomainEvent);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the event raised when a media library scan is started.
|
||||
/// </summary>
|
||||
public class LibraryScanStartedDomainEventHandler : INotificationHandler<LibraryScanStartedDomainEvent>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanStartedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanStartedDomainEventHandler(IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the event raised when a media library scan is started.
|
||||
/// </summary>
|
||||
/// <param name="domainEvent">The domain event to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async ValueTask Handle(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
|
||||
// update the status of the library scan in the repository
|
||||
ErrorOr<Updated> updateLibraryScanResult = await libraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateLibraryScanResult.IsError)
|
||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -11,7 +11,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||
/// <summary>
|
||||
/// Query for getting a media library by its Id.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the media library to get.</param>
|
||||
/// <param name="Id">The unique identifier of the media library to get.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record GetLibraryQuery(
|
||||
Guid Id
|
||||
|
||||
+11
-10
@@ -1,16 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.Scanning;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Tracking;
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Cancellation;
|
||||
|
||||
/// <summary>
|
||||
/// Tracker used for in-progress media library scans.
|
||||
/// Tracker used for canceling in-memory media library scans.
|
||||
/// </summary>
|
||||
internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposable
|
||||
internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable
|
||||
{
|
||||
private readonly ConcurrentDictionary<MediaScanTrackerModel, CancellationTokenSource> _runningScans = new();
|
||||
private bool _disposed;
|
||||
@@ -18,8 +19,8 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab
|
||||
/// <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>
|
||||
/// <param name="scanId">The unique identifier of the scan operation to track.</param>
|
||||
/// <param name="userId">The unique identifier 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());
|
||||
@@ -28,8 +29,8 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab
|
||||
/// <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>
|
||||
/// <param name="scanId">The unique identifier of the scan to get the cancellation token for<./param>
|
||||
/// <param name="userId">The unique identifier 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)
|
||||
{
|
||||
@@ -41,8 +42,8 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab
|
||||
/// <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>
|
||||
/// <param name="scanId">The unique identifier of the scan operation to cancel.</param>
|
||||
/// <param name="userId">The unique identifier of the user requesting the cancellation.</param>
|
||||
public void CancelScan(Guid scanId, Guid userId)
|
||||
{
|
||||
foreach (MediaScanTrackerModel key in _runningScans.Keys)
|
||||
@@ -63,7 +64,7 @@ internal class MediaLibrariesScanTracker : IMediaLibrariesScanTracker, IDisposab
|
||||
/// <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>
|
||||
/// <param name="userId">The unique identifier of the user whose scans should be canceled.</param>
|
||||
public void CancelUserScans(Guid userId)
|
||||
{
|
||||
foreach (MediaScanTrackerModel key in _runningScans.Keys)
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service used to scan a media library.
|
||||
/// </summary>
|
||||
public interface 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>
|
||||
/// <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);
|
||||
}
|
||||
+70
-6
@@ -1,5 +1,10 @@
|
||||
#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.DomainEvents;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Payloads;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
@@ -7,6 +12,12 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -18,20 +29,26 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering file system items.
|
||||
/// </summary>
|
||||
internal class FileSystemDiscoveryJob : MediaLibraryScanJob
|
||||
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
|
||||
{
|
||||
private readonly IDirectoryService _directoryService;
|
||||
private readonly IFileService _fileService;
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="directoryService">Injected service for handling directories.</param>
|
||||
/// <param name="fileService">Injected service for handling files.</param>
|
||||
public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService)
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public FileSystemDiscoveryJob(IDirectoryService directoryService, IFileService fileService, IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_directoryService = directoryService;
|
||||
_fileService = fileService;
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -44,9 +61,45 @@ internal class FileSystemDiscoveryJob : MediaLibraryScanJob
|
||||
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
|
||||
Console.WriteLine("started file discovering");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
|
||||
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<ScanJobProgress> scanJobProgressResult = ScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
_jobProgress = scanJobProgressResult.Value;
|
||||
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Console.WriteLine($"Reporting job progress in file discovery. Total: {_jobProgress.TotalItems}; Completed: {_jobProgress.CompletedItems}; Current: {_jobProgress.CurrentOperation}");
|
||||
// recursively get the file system tree for each of the media library content locations
|
||||
List<FileSystemTreeNode> contentLocationTrees = [];
|
||||
foreach (FileSystemPathId contentLocation in Library.ContentLocations)
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
ErrorOr<FileSystemTreeNode> treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken);
|
||||
@@ -57,16 +110,27 @@ internal class FileSystemDiscoveryJob : MediaLibraryScanJob
|
||||
}
|
||||
else
|
||||
contentLocationTrees.Add(treeResult.Value);
|
||||
|
||||
// increment the number of processed elements progress
|
||||
scanJobProgressResult = ScanJobProgress.Create(
|
||||
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
Console.WriteLine("ended file discovering");
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
// call each linked child with the obtained payload
|
||||
foreach (MediaLibraryScanJob children in Children)
|
||||
foreach (IMediaLibraryScanJob children in Children)
|
||||
await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Cancelled;
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -77,7 +141,7 @@ internal class FileSystemDiscoveryJob : MediaLibraryScanJob
|
||||
/// <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, CancellationToken cancellationToken = default)
|
||||
private 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());
|
||||
|
||||
+12
-3
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -11,7 +12,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs
|
||||
/// <summary>
|
||||
/// Media library scan job for comparing hashes.
|
||||
/// </summary>
|
||||
internal class HashComparerJob : MediaLibraryScanJob
|
||||
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
@@ -23,16 +24,24 @@ internal class HashComparerJob : MediaLibraryScanJob
|
||||
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Console.WriteLine("started file hashing");
|
||||
List<int> ints = [1, 2, 3];
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(1111, cancellationToken).ConfigureAwait(false);
|
||||
Console.WriteLine("ticking");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
}
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
Console.WriteLine("ended file hashing");
|
||||
// call each linked child with the obtained payload
|
||||
foreach (MediaLibraryScanJob children in Children)
|
||||
foreach (IMediaLibraryScanJob children in Children)
|
||||
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Cancelled;
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan jobs factory.
|
||||
/// </summary>
|
||||
internal interface IMediaLibraryScanJobFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
|
||||
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
|
||||
TJob CreateJob<TJob>(Library library) where TJob : MediaLibraryScanJob;
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Abstract class defining a media library scan job.
|
||||
/// </summary>
|
||||
internal abstract class 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<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<MediaLibraryScanJob> Parents { get; protected set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media library upon which the scan is performed.
|
||||
/// </summary>
|
||||
public required Library Library { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the status of the current media library scan job.
|
||||
/// </summary>
|
||||
public LibraryScanJobStatus Status { get; protected set; } = LibraryScanJobStatus.Pending;
|
||||
|
||||
/// <summary>
|
||||
/// Adds a media library scan job to the list of child media library scan jobs that will be triggered when this job's payload completes execution.
|
||||
/// </summary>
|
||||
/// <param name="job">The child media library scan job to be added.</param>
|
||||
public void AddChild(MediaLibraryScanJob job)
|
||||
{
|
||||
if (!Children.Contains(job) && !Parents.Contains(job))
|
||||
Children.Add(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a media library scan job to the list of parent media library scan jobs that will trigger this job when their payload will complete execution.
|
||||
/// </summary>
|
||||
/// <param name="job">The child media library scan job to be added.</param>
|
||||
public void AddParent(MediaLibraryScanJob job)
|
||||
{
|
||||
if (!Parents.Contains(job) && !Children.Contains(job))
|
||||
Parents.Add(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The id of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public abstract Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken);
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Concrete implementation for the media library scan jobs factory.
|
||||
/// </summary>
|
||||
internal class MediaLibraryScanJobFactory : IMediaLibraryScanJobFactory
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanJobFactory"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider.</param>
|
||||
public MediaLibraryScanJobFactory(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new media library scan job of type <typeparamref name="TJob"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TJob">The type of media library scan job to create.</typeparam>
|
||||
/// <returns>A media library scan job of type <typeparamref name="TJob"/>.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
|
||||
public TJob CreateJob<TJob>(Library library) where TJob : MediaLibraryScanJob
|
||||
{
|
||||
// resolve the job from DI
|
||||
TJob job = _serviceProvider.GetRequiredService<TJob>() ?? throw new ArgumentException();
|
||||
job.Library = library;
|
||||
return job;
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -11,7 +12,7 @@ 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 : MediaLibraryScanJob
|
||||
internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
@@ -23,16 +24,18 @@ internal class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob
|
||||
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Console.WriteLine("started repo discovering");
|
||||
List<int> ints = [1, 2, 3];
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
Console.WriteLine("ended repo discovering");
|
||||
// call each linked child with the obtained payload
|
||||
foreach (MediaLibraryScanJob children in Children)
|
||||
foreach (IMediaLibraryScanJob children in Children)
|
||||
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Cancelled;
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
+7
-4
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -12,7 +13,7 @@ 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 : MediaLibraryScanJob
|
||||
internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
@@ -24,16 +25,18 @@ internal class GoodReadsMetadataScrapJob : MediaLibraryScanJob
|
||||
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Console.WriteLine("started goodreads metadata");
|
||||
List<int> ints = [1, 2, 3];
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
Console.WriteLine("ended goodreads metadata");
|
||||
// call each linked child with the obtained payload
|
||||
foreach (MediaLibraryScanJob children in Children)
|
||||
foreach (IMediaLibraryScanJob children in Children)
|
||||
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Cancelled;
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
using System.Threading.Channels;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the message queue for handling <see cref="MediaLibraryScanJob"/> instances.
|
||||
/// </summary>
|
||||
internal interface IMediaLibrariesScanQueue
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaLibraryScanJob"/> instances.
|
||||
/// </summary>
|
||||
public ChannelWriter<MediaLibraryScanJob> Writer { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaLibraryScanJob"/> instances.
|
||||
/// </summary>
|
||||
public ChannelReader<MediaLibraryScanJob> Reader { get; }
|
||||
}
|
||||
+13
-13
@@ -1,30 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using System.Threading.Channels;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue;
|
||||
|
||||
/// <summary>
|
||||
/// Provides an in-memory message queue for handling <see cref="MediaLibraryScanJob"/> instances.
|
||||
/// Provides an in-memory message queue for handling <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// </summary>
|
||||
internal class MediaLibrariesScanQueue : IMediaLibrariesScanQueue
|
||||
{
|
||||
private readonly Channel<MediaLibraryScanJob> _channel = Channel.CreateUnbounded<MediaLibraryScanJob>();
|
||||
private readonly Channel<IMediaLibraryScanJob> _channel = Channel.CreateUnbounded<IMediaLibraryScanJob>(new UnboundedChannelOptions
|
||||
{
|
||||
SingleWriter = false,
|
||||
SingleReader = false,
|
||||
AllowSynchronousContinuations = true
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="MediaLibraryScanJob"/> instances.
|
||||
/// Gets the writer for the queue, allowing producers to enqueue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// </summary>
|
||||
public ChannelWriter<MediaLibraryScanJob> Writer
|
||||
{
|
||||
get { return _channel.Writer; }
|
||||
}
|
||||
public ChannelWriter<IMediaLibraryScanJob> Writer => _channel.Writer;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="MediaLibraryScanJob"/> instances.
|
||||
/// Gets the reader for the queue, allowing consumers to dequeue <see cref="IMediaLibraryScanJob"/> instances.
|
||||
/// </summary>
|
||||
public ChannelReader<MediaLibraryScanJob> Reader
|
||||
{
|
||||
get { return _channel.Reader; }
|
||||
}
|
||||
public ChannelReader<IMediaLibraryScanJob> Reader => _channel.Reader;
|
||||
}
|
||||
+9
-7
@@ -1,7 +1,8 @@
|
||||
#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 Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System;
|
||||
using System.Threading;
|
||||
@@ -16,16 +17,17 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queu
|
||||
internal sealed class MediaLibraryScanJobProcessorJob : BackgroundService
|
||||
{
|
||||
private readonly IMediaLibrariesScanQueue _mediaScanQueue;
|
||||
private readonly IMediaLibrariesScanTracker _librariesScanTracker;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
|
||||
/// <summary>
|
||||
/// 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 MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanTracker librariesScanTracker)
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected service for scanning media libraries.</param>
|
||||
public MediaLibraryScanJobProcessorJob(IMediaLibrariesScanQueue mediaScanQueue, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker)
|
||||
{
|
||||
_mediaScanQueue = mediaScanQueue;
|
||||
_librariesScanTracker = librariesScanTracker;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -38,10 +40,10 @@ internal sealed class MediaLibraryScanJobProcessorJob : 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 (MediaLibraryScanJob mediaScanJob in _mediaScanQueue.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
await foreach (IMediaLibraryScanJob 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);
|
||||
CancellationToken scanToken = _mediaLibrariesScanCancellationTracker.GetTokenForScan(mediaScanJob.ScanId.Value, mediaScanJob.UserId.Value);
|
||||
// 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());
|
||||
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining a factory for creating media library scanners.
|
||||
/// </summary>
|
||||
internal interface IMediaLibraryScannerFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a media library scanner based on the provided library type.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The type of the library that determines the type of the created media library scanner.</param>
|
||||
/// <returns>A media library scanner for the specified media library type.</returns>
|
||||
IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType);
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining a media library scanner for a specific media library type.
|
||||
/// </summary>
|
||||
internal interface IMediaTypeScanner
|
||||
{
|
||||
/// <summary>
|
||||
/// The media library type that this media library scanner supports.
|
||||
/// </summary>
|
||||
LibraryType SupportedType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="library">The media library for which to create the media library scan jobs.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
IEnumerable<MediaLibraryScanJob> CreateScanJobsForLibrary(Library library);
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a factory for creating media library scanners.
|
||||
/// </summary>
|
||||
internal class MediaLibraryScannerFactory : IMediaLibraryScannerFactory
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScannerFactory"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider.</param>
|
||||
public MediaLibraryScannerFactory(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a media library scanner for the specified library type.
|
||||
/// </summary>
|
||||
/// <param name="libraryType">The type of the media library.</param>
|
||||
/// <returns>A media library scanner for the specified library type.</returns>
|
||||
public IMediaTypeScanner CreateLibraryScanner(LibraryType libraryType)
|
||||
{
|
||||
return libraryType switch
|
||||
{
|
||||
// implemented scanners
|
||||
LibraryType.Book => _serviceProvider.GetRequiredService<IBookLibraryTypeScanner>(),
|
||||
LibraryType.EBook => throw new NotImplementedException("EBook scanner is not implemented."),
|
||||
LibraryType.ComicBook => throw new NotImplementedException("ComicBook scanner is not implemented."),
|
||||
LibraryType.Magazine => throw new NotImplementedException("Magazine scanner is not implemented."),
|
||||
LibraryType.Newspaper => throw new NotImplementedException("Newspaper scanner is not implemented."),
|
||||
LibraryType.Manga => throw new NotImplementedException("Manga scanner is not implemented."),
|
||||
LibraryType.GraphicNovel => throw new NotImplementedException("GraphicNovel scanner is not implemented."),
|
||||
LibraryType.AcademicPaper => throw new NotImplementedException("AcademicPaper scanner is not implemented."),
|
||||
LibraryType.SheetMusic => throw new NotImplementedException("SheetMusic scanner is not implemented."),
|
||||
LibraryType.Movie => throw new NotImplementedException("Movie scanner is not implemented."),
|
||||
LibraryType.TvShow => throw new NotImplementedException("TvShow scanner is not implemented."),
|
||||
LibraryType.Documentary => throw new NotImplementedException("Documentary scanner is not implemented."),
|
||||
LibraryType.Anime => throw new NotImplementedException("Anime scanner is not implemented."),
|
||||
LibraryType.ConcertVideo => throw new NotImplementedException("ConcertVideo scanner is not implemented."),
|
||||
LibraryType.TutorialVideo => throw new NotImplementedException("TutorialVideo scanner is not implemented."),
|
||||
LibraryType.HomeVideo => throw new NotImplementedException("HomeVideo scanner is not implemented."),
|
||||
LibraryType.YouTubeVideo => throw new NotImplementedException("YouTubeVideo scanner is not implemented."),
|
||||
LibraryType.MusicVideo => throw new NotImplementedException("MusicVideo scanner is not implemented."),
|
||||
LibraryType.LiveRecordingVideo => throw new NotImplementedException("LiveRecordingVideo scanner is not implemented."),
|
||||
LibraryType.InterviewVideo => throw new NotImplementedException("InterviewVideo scanner is not implemented."),
|
||||
LibraryType.CoverSongVideo => throw new NotImplementedException("CoverSongVideo scanner is not implemented."),
|
||||
LibraryType.PodcastVideo => throw new NotImplementedException("PodcastVideo scanner is not implemented."),
|
||||
LibraryType.Music => throw new NotImplementedException("Music scanner is not implemented."),
|
||||
LibraryType.Audiobook => throw new NotImplementedException("Audiobook scanner is not implemented."),
|
||||
LibraryType.LiveRecordingAudio => throw new NotImplementedException("LiveRecordingAudio scanner is not implemented."),
|
||||
LibraryType.InterviewAudio => throw new NotImplementedException("InterviewAudio scanner is not implemented."),
|
||||
LibraryType.CoverSongAudio => throw new NotImplementedException("CoverSongAudio scanner is not implemented."),
|
||||
LibraryType.Remix => throw new NotImplementedException("Remix scanner is not implemented."),
|
||||
LibraryType.SoundEffect => throw new NotImplementedException("SoundEffect scanner is not implemented."),
|
||||
LibraryType.PodcastAudio => throw new NotImplementedException("PodcastAudio scanner is not implemented."),
|
||||
LibraryType.Photo => throw new NotImplementedException("Photo scanner is not implemented."),
|
||||
LibraryType.Playlist => throw new NotImplementedException("Playlist scanner is not implemented."),
|
||||
LibraryType.Collection => throw new NotImplementedException("Collection scanner is not implemented."),
|
||||
LibraryType.Subtitles => throw new NotImplementedException("Subtitles scanner is not implemented."),
|
||||
LibraryType.Lyrics => throw new NotImplementedException("Lyrics scanner is not implemented."),
|
||||
// catch-all for unknown or unsupported types
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(libraryType), $"No scanner exists for library type '{libraryType}'.")
|
||||
};
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.Common;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Jobs.WrittenContent.Books;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scanner for a books media library type.
|
||||
/// </summary>
|
||||
internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
{
|
||||
private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public LibraryType SupportedType { get; } = LibraryType.Book;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScannerFactory"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
|
||||
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
|
||||
{
|
||||
_mediaScanJobFactory = mediaScanJobFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IEnumerable<MediaLibraryScanJob> CreateScanJobsForLibrary(Library library)
|
||||
{
|
||||
// declare the list of jobs that this scanner requires
|
||||
FileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<FileSystemDiscoveryJob>(library);
|
||||
RepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob<RepositoryMetadataDiscoveryJob>(library);
|
||||
HashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob<HashComparerJob>(library);
|
||||
GoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob<GoodReadsMetadataScrapJob>(library);
|
||||
|
||||
// establish the hierarchical relationships between jobs
|
||||
fileSystemDiscoveryJob.AddChild(hashComparerJob);
|
||||
repositoryMetadataDiscoveryJob.AddChild(hashComparerJob);
|
||||
|
||||
hashComparerJob.AddParent(fileSystemDiscoveryJob);
|
||||
hashComparerJob.AddParent(repositoryMetadataDiscoveryJob);
|
||||
|
||||
if (library.DownloadMedatadaFromWeb)
|
||||
{
|
||||
hashComparerJob.AddChild(goodReadsMetadataScrapJob);
|
||||
goodReadsMetadataScrapJob.AddParent(hashComparerJob);
|
||||
}
|
||||
|
||||
// return the top level jobs that will be triggered when the scan will be started
|
||||
yield return fileSystemDiscoveryJob;
|
||||
yield return repositoryMetadataDiscoveryJob;
|
||||
}
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Scanners.WrittenContent;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining a media library scanner for a books media library type.
|
||||
/// </summary>
|
||||
internal interface IBookLibraryTypeScanner : IMediaTypeScanner
|
||||
{
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
Reference in new issue
Block a user