Adds real time media libraries scan progress update via SignalR

This commit is contained in:
BinaryAlley committed 2025-02-22 17:45:09 +02:00
1 parent d70b2dcaa0
commit e0d61802df
71 files changed
+1292 -131

No files matched your search

@@ -5,6 +5,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Application.Core.MediaLibrary.Management.Services.Scanning.Queue;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
@@ -17,6 +18,7 @@ using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
using Microsoft.Extensions.DependencyInjection;
@@ -65,6 +67,8 @@ public static class InfrastructureLayerServices
services.AddTransient<IHashComparerJob, HashComparerJob>();
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
services.AddTransient<IRepositoryMetadataSaveJob, RepositoryMetadataSaveJob>();
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
return services;
}
}
@@ -34,13 +34,12 @@ public static class SharedConfiguration
configuration.AddJsonFile("appsettings.shared.Development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the common settings section
// bind the appsettings sections
services.AddOptions<CommonSettingsModel>()
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
// bind the database connection string section
services.AddOptions<DatabaseSettingsModel>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME))
.ValidateFluently()
@@ -56,6 +55,11 @@ public static class SharedConfiguration
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<CorsSettingsModel>()
.Bind(configuration.GetRequiredSection(CorsSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<EncryptionSettingsModel>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
.ValidateFluently()
@@ -22,5 +22,7 @@ public static partial class Errors
public static Error JwtExpiryMinutesMustBePositive => Error.Validation(description: nameof(JwtExpiryMinutesMustBePositive));
public static Error JwtIssuerCannotBeEmpty => Error.Validation(description: nameof(JwtIssuerCannotBeEmpty));
public static Error JwtAudienceCannotBeEmpty => Error.Validation(description: nameof(JwtAudienceCannotBeEmpty));
public static Error CorsOriginsCannotBeEmpty => Error.Validation(description: nameof(CorsOriginsCannotBeEmpty));
public static Error CorsOriginIsInvalid => Error.Validation(description: nameof(CorsOriginIsInvalid));
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class CorsSettingsModel
{
public const string SECTION_NAME = "CorsSettings";
/// <summary>
/// The allowed hosts in regards to cross-origin resource sharing rules.
/// </summary>
public required string[] AllowedOrigins { get; init; }
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
using System;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the JwtSettings application configuration settings section.
/// </summary>
public class CorsSettingsModelValidator : AbstractValidator<CorsSettingsModel>
{
/// <summary>
/// Initializes validation rules for CORS configuration
/// </summary>
public CorsSettingsModelValidator()
{
RuleFor(x => x.AllowedOrigins)
.NotEmpty()
.WithMessage(Errors.Errors.Configuration.CorsOriginsCannotBeEmpty.Description)
.ForEach(originRule =>
{
originRule.NotEmpty()
.WithMessage(Errors.Errors.Configuration.CorsOriginsCannotBeEmpty.Description)
.Must(BeValidOrigin)
.WithMessage(Errors.Errors.Configuration.CorsOriginIsInvalid.Description);
});
}
/// <summary>
/// Validates individual origin format
/// </summary>
private bool BeValidOrigin(string origin)
{
if (origin == "*")
return true; // wildcard allowed without credentials
return Uri.TryCreate(origin, UriKind.Absolute, out Uri? uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && !origin.EndsWith('/');
}
}
@@ -58,24 +58,25 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
{
Status = LibraryScanJobStatus.Running;
await Task.Delay(25000);
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>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -83,7 +84,7 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -91,18 +92,18 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "DiscoveringFiles");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
// recursively get the file system tree for each of the media library content locations
List<FileSystemTreeNode> contentLocationTrees = [];
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
{
await Task.Delay(5000);
await Task.Delay(1000);
cancellationToken.ThrowIfCancellationRequested();
ErrorOr<FileSystemTreeNode> treeResult = BuildTree(contentLocation, includeHiddenElements: true, cancellationToken);
if (treeResult.IsError)
@@ -118,14 +119,16 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
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);
await publisher!.Publish(new LibraryScanFailedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine("ended file discovering");
Status = LibraryScanJobStatus.Completed;
@@ -133,6 +136,7 @@ internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemD
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, contentLocationTrees, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
@@ -13,6 +13,7 @@ using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -54,12 +55,13 @@ internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -67,38 +69,41 @@ internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 50, "ComparingFileHashes");
//ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
List<int> ints = Enumerable.Range(0, 50).ToList();
foreach (int nr in ints)
{
await Task.Delay(5400);
await Task.Delay(100);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
nr, 50, "ComparingFileHashes");
//scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended file hashing");
// call each linked child with the obtained payload
@@ -46,6 +46,7 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
@@ -57,12 +58,13 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -70,7 +72,7 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -78,36 +80,39 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(5400);
await Task.Delay(1000);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "RetrievingPastScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(
new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended repo discovering");
// call each linked child with the obtained payload
foreach (IMediaLibraryScanJob children in Children)
await children.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
@@ -46,6 +46,7 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
parentsPayloadsExecuted++; // increment the number of parents that finished their execution and called this job
// only execute this job's payload when it has no parents, or when all the parents finished their execution
if (Parents.Count == 0 || parentsPayloadsExecuted == Parents.Count)
{
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
await Task.Run(async () =>
@@ -57,12 +58,13 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -70,7 +72,7 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -78,34 +80,35 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
foreach (int nr in ints)
{
await Task.Delay(5400);
await Task.Delay(500);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "SavingScanData");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, and it's the last in the chain, the scan is completed
Status = LibraryScanJobStatus.Completed;
await publisher!.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Console.WriteLine("ended repo saving");
// this should always be the last job in the directed acyclic job graph, so no linked child to call further
}, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
@@ -14,6 +14,7 @@ using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -55,12 +56,13 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
// 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);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
@@ -68,38 +70,41 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (domainLibraryResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
// set the initial progress of the scan job
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsDownload");
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload");
//ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
List<int> ints = [1, 2, 3];
List<int> ints = Enumerable.Range(0, 20).ToList();
foreach (int nr in ints)
{
await Task.Delay(5400);
await Task.Delay(100);
// increment the number of processed elements progress
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
nr, 20, "GoodReadsMetadataDownload");
//scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
if (scanJobProgressResult.IsError)
{
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), ScanId, LibraryId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
return;
}
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
Guid.NewGuid(), ScanId, UserId, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
}
// this job finished, increment the number of processed jobs progress
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), ScanId, UserId, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
Status = LibraryScanJobStatus.Completed;
Console.WriteLine("ended goodreads metadata");
// call each linked child with the obtained payload
@@ -0,0 +1,92 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Microsoft.AspNetCore.SignalR;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
/// <summary>
/// Class used to notify SignalR clients about changes in the progress of a media library scan.
/// </summary>
public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibraryScanProgressNotifier
{
private readonly IHubContext<MediaLibraryScanProgressHub> _hubContext;
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
/// <summary>
/// Initializes a new instance of the <see cref="DebouncedMediaLibraryScanProgressNotifier"/> class.
/// </summary>
/// <param name="hubContext">SignalR hub context abstraction.</param>
/// <param name="mediaLibrariesScanProgressTracker">Injected service for tracking the progress of media library scans.</param>
public DebouncedMediaLibraryScanProgressNotifier(IHubContext<MediaLibraryScanProgressHub> hubContext, IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker)
{
_hubContext = hubContext;
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
}
/// <summary>
/// Notifies the SignalR clients about a change in the progress of a media library scan.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan whose progress changed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendLibraryProgressUpdateEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
{
ErrorOr<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(mediaLibraryScanCompositeId);
if (!progressResult.IsError)
{
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync("libraryScanProgressUpdateEvent", progress, cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>
/// Notifies the SignalR clients about the completion of a media library scan.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that completed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendLibraryScanFinishedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
{
ErrorOr<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
if (!progressResult.IsError)
{
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync("libraryScanFinishedEvent", progress, cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>
/// Notifies the SignalR clients about the failure of a media library scan.
/// </summary>
/// <param name="mediaLibraryScanCompositeId">The object representing the unique identifier for the media library scan that failed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
{
ErrorOr<MediaLibraryScanProgress> progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId);
if (!progressResult.IsError)
{
MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse();
await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync(
"libraryScanFailedEvent", progress with { Status = LibraryScanJobStatus.Failed.ToString() }, cancellationToken).ConfigureAwait(false);
}
}
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
/// <summary>
/// SignalR hub for managing real-time media library scan progress updates.
/// </summary>
public class MediaLibraryScanProgressHub : Hub
{
/// <summary>
/// Subscribes the current connection to scan progress notifications for a specific scan operation.
/// </summary>
/// <param name="scanId">Unique identifier of the scan operation.</param>
/// <param name="userId">Unique identifier of the requesting user.</param>
public async Task SubscribeToScan(Guid scanId, Guid userId)
{
await Groups.AddToGroupAsync(Context.ConnectionId, $"{scanId}-{userId}");
}
}
@@ -16,6 +16,8 @@
<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.10.0" />
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Core" Version="1.2.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.0" />