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

@@ -3,6 +3,7 @@ using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Presentation.Api.Common.Authentication;
using MessagePack;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
@@ -201,13 +202,18 @@ public static class PresentationApiLayerServices
services.AddCors(corsOptions =>
{
corsOptions.AddPolicy("AllowAll",
corsPolicyBuilder => corsPolicyBuilder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
corsOptions.AddPolicy("SecurePolicy",
corsPolicyBuilder => corsPolicyBuilder
.WithOrigins(configuration.GetValue<string[]>("CorsSettings:AllowedOrigins") ?? [])
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddSignalR()
.AddMessagePackProtocol(messagePackHubProtocolOptions =>
messagePackHubProtocolOptions.SerializerOptions = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData));
services.AddScoped<ICurrentUserService, HttpContextCurrentUserService>();
return services;
@@ -19,6 +19,7 @@ public static partial class ApiRoutes
public const string SCAN_LIBRARIES = "/libraries/scans";
public const string SCAN_LIBRARY = "/libraries/{id}/scans";
public const string LIBRARY_SCAN_PROGRESS = "/libraries/{libraryId}/scans/{scanId}/progress";
public const string GET_RUNNING_LIBRARIES_SCAN = "/libraries/scans/running";
public const string CANCEL_LIBRARIES_SCAN = "/libraries/scans/cancel";
public const string CANCEL_LIBRARY_SCAN = "/libraries/{libraryId}/scans/{scanId}/cancel";
}
@@ -32,6 +32,9 @@ public class GetLibraryScanProgressEndpointSummary : Summary<GetLibraryScanProgr
RequestParam(r => r.LibraryId, "The Id of the media library whose scan progress is requested. Required.");
RequestParam(r => r.ScanId, "The Id of the media library scan whose progress is requested. Required.");
ResponseParam<MediaLibraryScanProgressResponse>(r => r.ScanId, "The object representing the unique identifier of the media library scan.");
ResponseParam<MediaLibraryScanProgressResponse>(r => r.UserId, "The object representing the unique identifier of the user initiating this media library scan.");
ResponseParam<MediaLibraryScanProgressResponse>(r => r.LibraryId, "The object representing the unique identifier of the media library that is scanned.");
ResponseParam<MediaLibraryScanProgressResponse>(r => r.TotalJobs, "The total number of jobs to be processed by the scan.");
ResponseParam<MediaLibraryScanProgressResponse>(r => r.CompletedJobs, "The number of jobs that have been processed.");
ResponseParam<MediaLibraryScanProgressResponse>(r => r.CurrentJobProgress, "The progress of the currently processing job.");
@@ -39,6 +42,9 @@ public class GetLibraryScanProgressEndpointSummary : Summary<GetLibraryScanProgr
ResponseParam<MediaLibraryScanProgressResponse>(r => r.OverallProgressPercentage, "The ratio between the number of processed jobs and the total number of jobs to process, as percentage.");
Response(200, "The progress of the media library scan is returned.", example: new MediaLibraryScanProgressResponse(
ScanId: Guid.NewGuid(),
UserId: Guid.NewGuid(),
LibraryId: Guid.NewGuid(),
TotalJobs: 10,
CompletedJobs: 4,
CurrentJobProgress: new MediaLibraryScanJobProgressResponse(
@@ -47,7 +53,7 @@ public class GetLibraryScanProgressEndpointSummary : Summary<GetLibraryScanProgr
CurrentOperation: "Comparing file hashes",
ProgressPercentage: 50
),
Status: LibraryScanJobStatus.Running,
Status: LibraryScanJobStatus.Running.ToString(),
OverallProgressPercentage: 40
));
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Presentation.Api.Common.Routes.Library.Management;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetRunningLibraryScans;
/// <summary>
/// API endpoint for the <c>/libraries/scans/running</c> route.
/// </summary>
public class GetRunningLibraryScansEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetRunningLibraryScansEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetRunningLibraryScansEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Libraries.GET_RUNNING_LIBRARIES_SCAN);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the list of ongoing media libraries scans.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>> result = await _sender.Send(new GetRunningLibraryScansQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
+8 -3
View File
@@ -7,6 +7,7 @@ using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.DependencyInjection;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.Middlewares;
using Microsoft.AspNetCore.Builder;
@@ -93,12 +94,14 @@ public class Program
}
}
app.UseCors("AllowAll");
app.UseRouting();
app.UseCors("SecurePolicy");
//app.UseExceptionHandler("/error"); // uses a middleware which re-executes the request to the error path
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
@@ -123,8 +126,8 @@ public class Program
.WithDotNetFlag(true);
});
// add the middleware that fires domain events and ensures eventual transactional consistency
app.UseMiddleware<EventualConsistencyMiddleware>();
// add the middleware that fires domain events and ensures eventual transactional consistency, but NOT for long-polling/WebSockets stuff like SignalR, which would keep the db locked
app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/scanProgressHub"), app => app.UseMiddleware<EventualConsistencyMiddleware>());
// create a directory relative to the application's startup directory, and use it to store static files that are served at the /media route on the API
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
@@ -149,6 +152,8 @@ public class Program
RequestPath = "/media"
});
app.MapHub<MediaLibraryScanProgressHub>("/scanProgressHub");
await app.RunAsync().ConfigureAwait(false);
}
}
+13 -1
View File
@@ -51,5 +51,17 @@
"Application": "LuminaApi"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"CorsSettings": {
"AllowedOrigins": [
"http://localhost:5012"
]
},
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5214"
}
}
}
}