diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 48d64613..78e869ac 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -1,3 +1,24 @@ +## General Setup +In the `appsettings.json` file from the **API server** app, make sure there is an entry looking like this: +```json +"CorsSettings": { + "AllowedOrigins": [ + "http://localhost:5012" + ] +} +``` +where the `AllowedOrigins` section includes the address set in the `Kestrel` section of the `appsettings.json` filefrom the **Web Client** app: +```json +"Kestrel": { + "Endpoints": { + "Http": { + "Url": "http://localhost:5012" + } + } +} +``` +The above values are the defaults of Lumina, but you can change them to whatever host and port you desire, as long as they are both the same, in both files. Failing to do so will result in SignalR not being able to make a connection between the client app and the server API. + ## Reverse Proxy Setup ### Rate Limiting Headers The application uses IP-based rate limiting on some endpoints. When deploying behind a reverse proxy, you must forward the diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs index f90f94d5..ce67ac21 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/MediaLibraryScanProgressMapping.cs @@ -18,10 +18,13 @@ public static class MediaLibraryScanProgressMapping public static MediaLibraryScanProgressResponse ToResponse(this MediaLibraryScanProgress domainValueObject) { return new MediaLibraryScanProgressResponse( + domainValueObject.ScanId.Value, + domainValueObject.UserId.Value, + domainValueObject.LibraryId.Value, domainValueObject.TotalJobs, domainValueObject.CompletedJobs, domainValueObject.CurrentJobProgress.Value?.ToResponse(), - domainValueObject.Status, + domainValueObject.Status.ToString(), domainValueObject.OverallProgressPercentage ); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index 532be7ba..11784bc4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -4,6 +4,7 @@ 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.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; @@ -20,14 +21,17 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events; /// public class LibraryScanFailedDomainEventHandler : INotificationHandler { + private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; private readonly IUnitOfWork _unitOfWork; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. - public LibraryScanFailedDomainEventHandler(IUnitOfWork unitOfWork) + /// Injected service for notifying media libraries scan progress changes to third parties. + public LibraryScanFailedDomainEventHandler(IMediaLibraryScanProgressNotifier debouncedLibraryScanProgressNotifier, IUnitOfWork unitOfWork) { + _debouncedLibraryScanProgressNotifier = debouncedLibraryScanProgressNotifier; _unitOfWork = unitOfWork; } @@ -41,7 +45,8 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler(); // get the library scan from the repository - ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync( + domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsError) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) @@ -64,6 +69,8 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler @@ -32,14 +33,17 @@ public class LibraryScanFinishedDomainEventHandler : INotificationHandler /// Injected service for tracking the progress of media library scans. /// Injected tracker used for canceling media library scans. + /// Injected service for notifying media libraries scan progress changes to third parties. /// Injected unit of work for interacting with the data access layer repositories. public LibraryScanFinishedDomainEventHandler( IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker, + IMediaLibraryScanProgressNotifier debouncedLibraryScanProgressNotifier, IUnitOfWork unitOfWork) { _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; _mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker; + _debouncedLibraryScanProgressNotifier = debouncedLibraryScanProgressNotifier; _unitOfWork = unitOfWork; } @@ -53,7 +57,8 @@ public class LibraryScanFinishedDomainEventHandler : INotificationHandler(); // get the library scan from the repository - ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync( + domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsError) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) @@ -76,8 +81,11 @@ public class LibraryScanFinishedDomainEventHandler : INotificationHandler { private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; /// /// Initializes a new instance of the class. /// /// Injected tracker used for media library scans progress. - public LibraryScanJobProgressChangedDomainEventHandler(IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker) + /// Injected service for notifying media libraries scan progress changes to third parties. + public LibraryScanJobProgressChangedDomainEventHandler( + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IMediaLibraryScanProgressNotifier debouncedLibraryScanProgressNotifier) { _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _debouncedLibraryScanProgressNotifier = debouncedLibraryScanProgressNotifier; } /// @@ -32,7 +37,8 @@ public class LibraryScanJobProgressChangedDomainEventHandler : INotificationHand /// Cancellation token that can be used to stop the execution. public async ValueTask Handle(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) { - _mediaLibrariesScanProgressTracker.UpdateScanJobProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId), domainEvent.Progress); - await Task.CompletedTask; + _mediaLibrariesScanProgressTracker.UpdateScanJobProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId, domainEvent.Progress); + // notify SignalR clients that the library scan progress changed + await _debouncedLibraryScanProgressNotifier.SendLibraryProgressUpdateEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs index af3c74d4..42059d36 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandler.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Progress; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Mediator; using System.Threading; using System.Threading.Tasks; @@ -15,14 +15,19 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events; public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler { private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; /// /// Initializes a new instance of the class. /// /// Injected tracker used for media library scans progress. - public LibraryScanProgressChangedDomainEventHandler(IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker) + /// Injected service for notifying media libraries scan progress changes to third parties. + public LibraryScanProgressChangedDomainEventHandler( + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IMediaLibraryScanProgressNotifier debouncedLibraryScanProgressNotifier) { _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _debouncedLibraryScanProgressNotifier = debouncedLibraryScanProgressNotifier; } /// @@ -32,7 +37,8 @@ public class LibraryScanProgressChangedDomainEventHandler : INotificationHandler /// Cancellation token that can be used to stop the execution. public async ValueTask Handle(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken) { - _mediaLibrariesScanProgressTracker.UpdateScanProgress(MediaLibraryScanCompositeId.Create(domainEvent.ScanId, domainEvent.UserId)); - await Task.CompletedTask; + _mediaLibrariesScanProgressTracker.UpdateScanProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId); + // notify SignalR clients that the library scan progress changed + await _debouncedLibraryScanProgressNotifier.SendLibraryProgressUpdateEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs new file mode 100644 index 00000000..38692fe5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Progress/IMediaLibraryScanProgressNotifier.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Progress; + +/// +/// Interface for the class used to notify SignalR clients about changes in the progress of a media library scan. +/// +public interface IMediaLibraryScanProgressNotifier +{ + /// + /// Notifies the SignalR clients about a change in the progress of a media library scan. + /// + /// The object representing the unique identifier for the media library scan whose progress changed. + /// Cancellation token that can be used to stop the execution. + Task SendLibraryProgressUpdateEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken); + + /// + /// Notifies the SignalR clients about the completion of a media library scan. + /// + /// The object representing the unique identifier for the media library scan that completed. + /// Cancellation token that can be used to stop the execution. + Task SendLibraryScanFinishedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken); + + /// + /// Notifies the SignalR clients about the failure of a media library scan. + /// + /// The object representing the unique identifier for the media library scan that failed. + /// Cancellation token that can be used to stop the execution. + Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs new file mode 100644 index 00000000..7cb2d613 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQuery.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Mediator; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; + +/// +/// Query for getting the list of ongoing media library scans. +/// +public record GetRunningLibraryScansQuery : IRequest>>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs new file mode 100644 index 00000000..f084de5f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandler.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Mediator; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; + +/// +/// Handler for the query to get the ongoing media library scans. +/// +public class GetRunningLibraryScansQueryHandler : IRequestHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for tracking the progress of media library scans. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + public GetRunningLibraryScansQueryHandler( + IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker, + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IUnitOfWork unitOfWork) + { + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the ongoing media library scans. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfuly created , or an error message. + /// + public async ValueTask>> Handle(GetRunningLibraryScansQuery request, CancellationToken cancellationToken) + { + // get the ongoing library scans from the repository + ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository(); + ErrorOr> getRunningScansResult = await libraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); + if (getRunningScansResult.IsError) + return getRunningScansResult.Errors; + + // filter the library scans by what the user is allowed to see + LibraryScanEntity[] userRunningRepositoryLibraryScans = []; + // admins can see all libraries + if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false)) + userRunningRepositoryLibraryScans = getRunningScansResult.Value.ToArray(); + else // for regular users, only take the libraries that belong to them + userRunningRepositoryLibraryScans = getRunningScansResult.Value + .Where(libraryScan => libraryScan.UserId == _currentUserService.UserId).ToArray(); + + // for each of the filtered library scans, get their progress + List libraryScanProgresses = []; + IEnumerable> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities(); + foreach (ErrorOr userRunningDomainLibraryScan in userRunningDomainLibraryScans) + { + if (userRunningDomainLibraryScan.IsError) + return userRunningDomainLibraryScan.Errors; + else + { + ErrorOr getLibraryScanProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress( + MediaLibraryScanCompositeId.Create(userRunningDomainLibraryScan.Value.Id, userRunningDomainLibraryScan.Value.UserId)); + if (getLibraryScanProgressResult.IsError) + return getLibraryScanProgressResult.Errors; + libraryScanProgresses.Add(getLibraryScanProgressResult.Value.ToResponse()); + } + } + + return ErrorOrFactory.From(libraryScanProgresses.AsEnumerable()); + } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs index 5f1771cd..bf9c50df 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponse.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Enums.MediaLibrary; using System; using System.Diagnostics; #endregion @@ -9,6 +8,9 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// /// Represents a media library scan progress response. /// +/// The object representing the unique identifier of the media library scan. +/// The object representing the unique identifier of the user initiating this media library scan. +/// The object representing the unique identifier of the media library that is scanned. /// The total number of jobs to be processed by the scan. /// The number of jobs that have been processed. /// The progress of the currently processing job. @@ -16,9 +18,12 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// The ratio between the number of processed jobs and the total number of jobs to process, as percentage. [DebuggerDisplay("TotalJobs: {TotalJobs} CompletedJobs: {CompletedJobs}")] public record MediaLibraryScanProgressResponse( - int TotalJobs, - int CompletedJobs, - MediaLibraryScanJobProgressResponse? CurrentJobProgress, - LibraryScanJobStatus Status, - decimal OverallProgressPercentage + Guid ScanId, + Guid UserId, + Guid LibraryId, + int TotalJobs, + int CompletedJobs, + MediaLibraryScanJobProgressResponse? CurrentJobProgress, + string Status, + decimal OverallProgressPercentage ); diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs index 78fddd40..9e4d143b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs @@ -12,13 +12,13 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// Domain event raised when a libary scan has failed. /// /// The unique identifier of the domain event. -/// The unique identifier of the failed media library scan. /// The unique identifier of the library whose scan has failed. +/// Model for tracking media library scans. /// The date and time when the domain event occurred. [DebuggerDisplay("Id: {Id}")] public record LibraryScanFailedDomainEvent( Guid Id, - ScanId ScanId, LibraryId LibraryId, + MediaLibraryScanCompositeId MediaLibraryScanCompositeId, DateTime OccurredOnUtc ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs index 78fc407b..f984b3bd 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEvent.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Events; -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 System; using System.Diagnostics; #endregion @@ -13,13 +11,11 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// Domain event raised when a libary scan is finished. /// /// The unique identifier of the domain event. -/// The object representing the unique identifier of the media library scan. -/// The object representing the unique identifier of the user that started the library scan whose progress changes. +/// Model for tracking media library scans. /// The date and time when the domain event occurred. [DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] public record LibraryScanFinishedDomainEvent( Guid Id, - ScanId ScanId, - UserId UserId, + MediaLibraryScanCompositeId MediaLibraryScanCompositeId, DateTime OccurredOnUtc ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs index 711cfb7b..926bb6f5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEvent.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Events; +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 System; using System.Diagnostics; #endregion @@ -12,15 +12,15 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// Domain event raised when a libary's scan job progress changes. /// /// The unique identifier of the domain event. -/// The object representing the unique identifier of the media library scan. -/// The object representing the unique identifier of the user that started the library scan whose progress changes. +/// The object representing the unique identifier of the media library being scanned. +/// Model for tracking media library scans. /// The object representing the new media library scan job progress. /// The date and time when the domain event occurred. [DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] public record LibraryScanJobProgressChangedDomainEvent( Guid Id, - ScanId ScanId, - UserId UserId, + LibraryId LibraryId, + MediaLibraryScanCompositeId MediaLibraryScanCompositeId, MediaLibraryScanJobProgress Progress, DateTime OccurredOnUtc ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs index 579a33c7..5ec48c9b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEvent.cs @@ -2,7 +2,6 @@ using Lumina.Domain.Common.Events; 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 System; using System.Diagnostics; #endregion @@ -13,13 +12,13 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// Domain event raised when a libary's scan progress changes. /// /// The unique identifier of the domain event. -/// The object representing the unique identifier of the media library scan. -/// The object representing the unique identifier of the user that started the library scan whose progress changes. +/// The object representing the unique identifier of the media library being scanned. +/// Model for tracking media library scans. /// The date and time when the domain event occurred. -[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] +[DebuggerDisplay("ScanId: {MediaLibraryScanCompositeId.ScanId}; UserId: {MediaLibraryScanCompositeId.UserId}")] public record LibraryScanProgressChangedDomainEvent( Guid Id, - ScanId ScanId, - UserId UserId, + LibraryId LibraryId, + MediaLibraryScanCompositeId MediaLibraryScanCompositeId, DateTime OccurredOnUtc ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs index 857e17bb..d15cbd46 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -86,7 +86,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService // count total jobs in the chain by traversing the job graph int totalJobs = CountTotalJobs(jobs); - _mediaLibrariesScanProgressTracker.InitializeScanProgress(MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId), totalJobs); + _mediaLibrariesScanProgressTracker.InitializeScanProgress(scan.LibraryId, MediaLibraryScanCompositeId.Create(scan.Id, scan.UserId), totalJobs); // enqueue the jobs on the channel from where they will be processed foreach (IMediaLibraryScanJob job in jobs) diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs index 9a49b45b..be0333d2 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/IMediaLibrariesScanProgressTracker.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using ErrorOr; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; #endregion @@ -13,25 +14,28 @@ public interface IMediaLibrariesScanProgressTracker /// /// Initializes the the progress tracking of a media library scan. /// + /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The total number of jobs that this media library scan contains. /// An representing either a successful operation, or an error. - ErrorOr InitializeScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs); + ErrorOr InitializeScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs); /// /// Updates the progress tracking of the media library scan by incrementing the number of completed scan jobs. /// + /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// An representing either a successful operation, or an error. - ErrorOr UpdateScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + ErrorOr UpdateScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId); /// /// Updates the progress tracking of the media library scan by incrementing the number of completed items of a scan job. /// + /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The object representing the progress of the media library scan job. /// An representing either a successful operation, or an error. - ErrorOr UpdateScanJobProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress); + ErrorOr UpdateScanJobProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress); /// /// Gets the progress of a media library scan. @@ -41,4 +45,13 @@ public interface IMediaLibrariesScanProgressTracker /// An containing either a , or an error message. /// ErrorOr GetScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); + + /// + /// Removes the progress of a media library scan. + /// + /// Model for tracking media library scans. + /// + /// An containing either a , or an error message. + /// + ErrorOr RemoveScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs index 06f98a82..9b8b2fd0 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTracker.cs @@ -3,6 +3,7 @@ using ErrorOr; using Lumina.Domain.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System.Collections.Concurrent; #endregion @@ -19,16 +20,20 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// /// Initializes the the progress tracking of a media library scan. /// + /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The total number of jobs that this media library scan contains. /// An representing either a successful operation, or an error. - public ErrorOr InitializeScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs) + public ErrorOr InitializeScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, int totalJobs) { ErrorOr createLibraryScanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 0, "Initializing"); if (createLibraryScanJobProgressResult.IsError) return createLibraryScanJobProgressResult.Errors; ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + mediaLibraryScanCompositeId.ScanId, + mediaLibraryScanCompositeId.UserId, + libraryId, completedJobs: 0, totalJobs: totalJobs, LibraryScanJobStatus.Pending, @@ -45,13 +50,17 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// /// Updates the progress tracking of the media library scan by incrementing the number of completed scan jobs. /// + /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// An representing either a successful operation, or an error. - public ErrorOr UpdateScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + public ErrorOr UpdateScanProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId) { if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) { ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + mediaLibraryScanCompositeId.ScanId, + mediaLibraryScanCompositeId.UserId, + libraryId, progress.CompletedJobs + 1, progress.TotalJobs, progress.CompletedJobs + 1 == progress.TotalJobs ? LibraryScanJobStatus.Completed : LibraryScanJobStatus.Running, @@ -68,14 +77,18 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr /// /// Updates the progress tracking of the media library scan by incrementing the number of completed items of a scan job. /// + /// The object representing the unique identifier of the media library being scanned. /// Model for tracking media library scans. /// The object representing the progress of the media library scan job. /// An representing either a successful operation, or an error. - public ErrorOr UpdateScanJobProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress) + public ErrorOr UpdateScanJobProgress(LibraryId libraryId, MediaLibraryScanCompositeId mediaLibraryScanCompositeId, MediaLibraryScanJobProgress progress) { if (_scanProgresses.TryGetValue(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? scanProgress)) { ErrorOr createScanProgressResult = MediaLibraryScanProgress.Create( + mediaLibraryScanCompositeId.ScanId, + mediaLibraryScanCompositeId.UserId, + libraryId, scanProgress.CompletedJobs, scanProgress.TotalJobs, scanProgress.Status, @@ -103,4 +116,18 @@ internal class MediaLibrariesScanProgressTracker : IMediaLibrariesScanProgressTr return progress; return Errors.LibraryScanning.LibraryScanNotFound; } + + /// + /// Removes the progress of a media library scan. + /// + /// Model for tracking media library scans. + /// + /// An containing either a , or an error message. + /// + public ErrorOr RemoveScanProgress(MediaLibraryScanCompositeId mediaLibraryScanCompositeId) + { + if (_scanProgresses.TryRemove(mediaLibraryScanCompositeId, out MediaLibraryScanProgress? progress)) + return progress; + return Errors.LibraryScanning.LibraryScanNotFound; + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs index f47fef11..33b9fddf 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeId.cs @@ -10,7 +10,7 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// /// Value Object for the composite unique identifier of a media library scan. /// -[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}")] +[DebuggerDisplay("ScanId: {ScanId.Value}; UserId: {UserId.Value}")] public sealed class MediaLibraryScanCompositeId : ValueObject { /// @@ -51,4 +51,13 @@ public sealed class MediaLibraryScanCompositeId : ValueObject yield return ScanId; yield return UserId; } + + /// + /// Customized ToString() method. + /// + /// Custom string value showing relevant data for current class. + public override string ToString() + { + return $"{ScanId}-{UserId}"; + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs index 9001192c..852ac330 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgress.cs @@ -4,6 +4,8 @@ using Lumina.Domain.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -16,6 +18,21 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib [DebuggerDisplay("CompletedJobs: {CompletedJobs}; TotalJobs: {TotalJobs}; CurrentJobProgress: {CurrentJobProgress}")] public sealed class MediaLibraryScanProgress : ValueObject { + /// + /// Gets the object representing the unique identifier of the media library scan. + /// + public ScanId ScanId { get; } + + /// + /// Gets the object representing the unique identifier of the media library that is scanned. + /// + public LibraryId LibraryId { get; } + + /// + /// Gets the object representing the unique identifier of the user initiating this media library scan. + /// + public UserId UserId { get; } + /// /// Gets the number of completed jobs of the media library scan job. /// @@ -44,12 +61,25 @@ public sealed class MediaLibraryScanProgress : ValueObject /// /// Initializes a new instance of the class. /// + /// The object representing the unique identifier of the media library scan. + /// The object representing the unique identifier of the user initiating this media library scan. + /// The object representing the unique identifier of the media library that is scanned. /// The number of completed jobs of the media library scan job. /// The total number of jobs of the media library scan job. /// The status of the media library scan. /// The optional current job progress of the media library scan. - private MediaLibraryScanProgress(int completedJobs, int totalJobs, LibraryScanJobStatus status, Optional currentJobProgress) + private MediaLibraryScanProgress( + ScanId scanId, + UserId userId, + LibraryId libraryId, + int completedJobs, + int totalJobs, + LibraryScanJobStatus status, + Optional currentJobProgress) { + ScanId = scanId; + LibraryId = libraryId; + UserId = userId; CompletedJobs = completedJobs; TotalJobs = totalJobs; CurrentJobProgress = currentJobProgress; @@ -59,6 +89,9 @@ public sealed class MediaLibraryScanProgress : ValueObject /// /// Creates a new instance of the class. /// + /// The object representing the unique identifier of the media library scan. + /// The object representing the unique identifier of the user initiating this media library scan. + /// The object representing the unique identifier of the media library that is scanned. /// The number of completed jobs of the media library scan job. /// The total number of jobs of the media library scan job. /// The status of the media library scan. @@ -66,7 +99,14 @@ public sealed class MediaLibraryScanProgress : ValueObject /// /// An containing either a successfuly created , or an error message. /// - public static ErrorOr Create(int completedJobs, int totalJobs, LibraryScanJobStatus status, Optional currentJobProgress) + public static ErrorOr Create( + ScanId scanId, + UserId userId, + LibraryId libraryId, + int completedJobs, + int totalJobs, + LibraryScanJobStatus status, + Optional currentJobProgress) { if (totalJobs <= 0) return Errors.LibraryScanning.TotalScanJobsCountMustBePositive; @@ -75,7 +115,7 @@ public sealed class MediaLibraryScanProgress : ValueObject if (completedJobs > totalJobs) return Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount; - return new MediaLibraryScanProgress(completedJobs, totalJobs, status, currentJobProgress); + return new MediaLibraryScanProgress(scanId, userId, libraryId, completedJobs, totalJobs, status, currentJobProgress); } /// diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 0415f2a3..c132c75d 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -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(); services.AddTransient(); services.AddTransient(); + + services.AddSingleton(); return services; } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index ebd28609..fd21a1e6 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -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() .Bind(configuration.GetRequiredSection(CommonSettingsModel.SECTION_NAME)) .ValidateFluently() .ValidateOnStart(); - // bind the database connection string section services.AddOptions() .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME)) .ValidateFluently() @@ -56,6 +55,11 @@ public static class SharedConfiguration .ValidateFluently() .ValidateOnStart(); + services.AddOptions() + .Bind(configuration.GetRequiredSection(CorsSettingsModel.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + services.AddOptions() .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME)) .ValidateFluently() diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index 2ef61c98..fedbfc2a 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -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)); } } diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/CorsSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/CorsSettingsModel.cs new file mode 100644 index 00000000..7444ece6 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/CorsSettingsModel.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.Configuration; + +/// +/// Model for deserializing media settings. +/// +[DebuggerDisplay("{SECTION_NAME}")] +public class CorsSettingsModel +{ + public const string SECTION_NAME = "CorsSettings"; + + /// + /// The allowed hosts in regards to cross-origin resource sharing rules. + /// + public required string[] AllowedOrigins { get; init; } +} diff --git a/src/Lumina.Infrastructure/Common/Validators/CorsSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/CorsSettingsModelValidator.cs new file mode 100644 index 00000000..184542c8 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/CorsSettingsModelValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Infrastructure.Common.Models.Configuration; +using System; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the JwtSettings application configuration settings section. +/// +public class CorsSettingsModelValidator : AbstractValidator +{ + /// + /// Initializes validation rules for CORS configuration + /// + 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); + }); + } + + /// + /// Validates individual origin format + /// + 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('/'); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs index 8a439b93..93b063e6 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs @@ -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(); IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr 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 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 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 contentLocationTrees = []; foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations) { - await Task.Delay(5000); + await Task.Delay(1000); cancellationToken.ThrowIfCancellationRequested(); ErrorOr 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) { diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs index f0ed6e7c..f22d08fb 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs @@ -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(); IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr 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 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 scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "ComparingFileHashes"); + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 50, "ComparingFileHashes"); + //ErrorOr 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 ints = [1, 2, 3]; + List 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 diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs index 41fff526..0de89942 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs @@ -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(); IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr 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 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 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 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) { diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs index 1bc394f0..00a16d76 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs @@ -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(); IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr 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 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 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 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) { diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs index 4de40862..5d6abf05 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -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(); IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository ErrorOr 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 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 scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsDownload"); + ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload"); + //ErrorOr 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 ints = [1, 2, 3]; + List 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 diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs new file mode 100644 index 00000000..0ad19a8d --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifier.cs @@ -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; + +/// +/// Class used to notify SignalR clients about changes in the progress of a media library scan. +/// +public sealed class DebouncedMediaLibraryScanProgressNotifier : IMediaLibraryScanProgressNotifier +{ + private readonly IHubContext _hubContext; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; + + /// + /// Initializes a new instance of the class. + /// + /// SignalR hub context abstraction. + /// Injected service for tracking the progress of media library scans. + public DebouncedMediaLibraryScanProgressNotifier(IHubContext hubContext, IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker) + { + _hubContext = hubContext; + _mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker; + } + + /// + /// Notifies the SignalR clients about a change in the progress of a media library scan. + /// + /// The object representing the unique identifier for the media library scan whose progress changed. + /// Cancellation token that can be used to stop the execution. + public async Task SendLibraryProgressUpdateEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken) + { + if (!cancellationToken.IsCancellationRequested) + { + ErrorOr progressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(mediaLibraryScanCompositeId); + + if (!progressResult.IsError) + { + MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse(); + await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync("libraryScanProgressUpdateEvent", progress, cancellationToken).ConfigureAwait(false); + } + } + } + + /// + /// Notifies the SignalR clients about the completion of a media library scan. + /// + /// The object representing the unique identifier for the media library scan that completed. + /// Cancellation token that can be used to stop the execution. + public async Task SendLibraryScanFinishedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken) + { + if (!cancellationToken.IsCancellationRequested) + { + ErrorOr progressResult = _mediaLibrariesScanProgressTracker.RemoveScanProgress(mediaLibraryScanCompositeId); + + if (!progressResult.IsError) + { + MediaLibraryScanProgressResponse progress = progressResult.Value.ToResponse(); + await _hubContext.Clients.Group(mediaLibraryScanCompositeId.ToString()).SendAsync("libraryScanFinishedEvent", progress, cancellationToken).ConfigureAwait(false); + } + } + } + + /// + /// Notifies the SignalR clients about the failure of a media library scan. + /// + /// The object representing the unique identifier for the media library scan that failed. + /// Cancellation token that can be used to stop the execution. + public async Task SendLibraryScanFailedEventAsync(MediaLibraryScanCompositeId mediaLibraryScanCompositeId, CancellationToken cancellationToken) + { + if (!cancellationToken.IsCancellationRequested) + { + ErrorOr 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); + } + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs new file mode 100644 index 00000000..f25109ee --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHub.cs @@ -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; + +/// +/// SignalR hub for managing real-time media library scan progress updates. +/// +public class MediaLibraryScanProgressHub : Hub +{ + /// + /// Subscribes the current connection to scan progress notifications for a specific scan operation. + /// + /// Unique identifier of the scan operation. + /// Unique identifier of the requesting user. + public async Task SubscribeToScan(Guid scanId, Guid userId) + { + await Groups.AddToGroupAsync(Context.ConnectionId, $"{scanId}-{userId}"); + } +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index d2edaf63..978ca0bb 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -16,6 +16,8 @@ + + diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 35264a7b..aa914527 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -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("CorsSettings:AllowedOrigins") ?? []) + .AllowAnyMethod() + .AllowAnyHeader() + .AllowCredentials()); }); + services.AddSignalR() + .AddMessagePackProtocol(messagePackHubProtocolOptions => + messagePackHubProtocolOptions.SerializerOptions = MessagePackSerializerOptions.Standard.WithSecurity(MessagePackSecurity.UntrustedData)); + services.AddScoped(); return services; diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index e6294167..413c36ab 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -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"; } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs index ba1f29f3..6b46fd00 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointSummary.cs @@ -32,6 +32,9 @@ public class GetLibraryScanProgressEndpointSummary : Summary 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(r => r.ScanId, "The object representing the unique identifier of the media library scan."); + ResponseParam(r => r.UserId, "The object representing the unique identifier of the user initiating this media library scan."); + ResponseParam(r => r.LibraryId, "The object representing the unique identifier of the media library that is scanned."); ResponseParam(r => r.TotalJobs, "The total number of jobs to be processed by the scan."); ResponseParam(r => r.CompletedJobs, "The number of jobs that have been processed."); ResponseParam(r => r.CurrentJobProgress, "The progress of the currently processing job."); @@ -39,6 +42,9 @@ public class GetLibraryScanProgressEndpointSummary : Summary(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 +/// API endpoint for the /libraries/scans/running route. +/// +public class GetRunningLibraryScansEndpoint : BaseEndpoint +{ + private readonly ISender _sender; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for mediating commands and queries. + public GetRunningLibraryScansEndpoint(ISender sender) + { + _sender = sender; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_RUNNING_LIBRARIES_SCAN); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of ongoing media libraries scans. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + ErrorOr> result = await _sender.Send(new GetRunningLibraryScansQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index f2bbb0cf..db77a6f0 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -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(); + // 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()); // 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("MediaSettings:RootDirectory") ?? string.Empty; @@ -149,6 +152,8 @@ public class Program RequestPath = "/media" }); + app.MapHub("/scanProgressHub"); + await app.RunAsync().ConfigureAwait(false); } } diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json index 2db1c53f..85513e30 100644 --- a/src/Lumina.Presentation.Api/appsettings.json +++ b/src/Lumina.Presentation.Api/appsettings.json @@ -51,5 +51,17 @@ "Application": "LuminaApi" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "CorsSettings": { + "AllowedOrigins": [ + "http://localhost:5012" + ] + }, + "Kestrel": { + "Endpoints": { + "Http": { + "Url": "http://localhost:5214" + } + } + } } diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanJobProgressModel.cs b/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanJobProgressModel.cs new file mode 100644 index 00000000..b961d4d9 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanJobProgressModel.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Libraries; + +/// +/// Represents a media library scan job progress model. +/// +[DebuggerDisplay("CompletedItems: {CompletedItems}; TotalItems: {TotalItems}")] +public class LibraryScanJobProgressModel +{ + /// + /// Gets or sets the number of completed items of the media library scan job. + /// + public int CompletedItems { get; set; } + + /// + /// Gets or sets the total number of items of the media library scan job. + /// + public int TotalItems { get; set; } + + /// + /// Gets or sets the current operation being performed by the media library scan job. + /// + public string? CurrentOperation { get; set; } + + /// + /// Gets or sets the ratio between the total number and the completed number of items, as a percentage. + /// + public decimal ProgressPercentage { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanProgressModel.cs b/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanProgressModel.cs new file mode 100644 index 00000000..d9a8462e --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryScanProgressModel.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Models.Libraries; + +/// +/// Represents a media library scan progress model. +/// +[DebuggerDisplay("ScanId: {ScanId}; UserId: {UserId}; LibraryId: {LibraryId}")] +public class LibraryScanProgressModel +{ + /// + /// Gets or sets the unique identifier of the media library scan. + /// + public Guid ScanId { get; set; } + + /// + /// Gets or sets the unique identifier of the user initiating this media library scan. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets the unique identifier of the media library that is scanned. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets the number of completed jobs of the media library scan job. + /// + public int CompletedJobs { get; set; } + + /// + /// Gets or sets the total number of jobs of the media library scan job. + /// + public int TotalJobs { get; set; } + + /// + /// Gets or sets the optional current job progress of the media library scan. + /// + public LibraryScanJobProgressModel? CurrentJobProgress { get; set; } + + /// + /// Gets or sets the status of the media library scan. + /// + public string? Status { get; set; } + + /// + /// Gets or sets the ratio between the total number and the completed number of jobs, as a percentage. + /// + public decimal OverallProgressPercentage { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index 8e296e91..2e72d534 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -114,6 +114,17 @@ public class LibraryManagementController : Controller return Json(new { success = true }); } + /// + /// Gets the list of ongoing media library scans. + /// + /// Cancellation token that can be used to stop the execution. + [HttpGet("api-get-running-library-scans")] + public async Task GetRunningLibraryScans(CancellationToken cancellationToken = default) + { + LibraryScanProgressModel[] response = await _apiHttpClient.GetAsync($"libraries/scans/running/", cancellationToken).ConfigureAwait(false); + return Json(new { success = true, data = response }); + } + /// /// Initiates the scan of all media libraries. /// diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 997de722..c5328293 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -585,4 +585,10 @@ Anzahl der abgeschlossenen Scan-Aufträge darf die Gesamtanzahl der Scan-Aufträge nicht überschreiten! + + CORS-Origins dürfen nicht leer sein! + + + Ungültiger CORS-Origin! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 663b6837..53a1ee57 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -585,4 +585,10 @@ Completed scan jobs count can't exceed total scan jobs count! + + CORS origins cannot be empty! + + + CORS origin is invalid! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index bf9c4f11..5b86070e 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -585,4 +585,10 @@ ¡El número de trabajos de escaneo completados no puede exceder el número total de trabajos de escaneo! + + ¡Las origines CORS no pueden estar vacías! + + + ¡Origen CORS no válido! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 3770031b..b100f70c 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -585,4 +585,10 @@ Le nombre de tâches de scan terminées ne peut pas dépasser le nombre total de tâches de scan ! + + Les origines CORS ne peuvent pas être vides ! + + + Origine CORS invalide ! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 549b7380..16584872 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -585,4 +585,10 @@ Il numero dei lavori di scansione completati non può superare il numero totale dei lavori di scansione! + + Le origini CORS non possono essere vuote! + + + Origine CORS non valida! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 7e46ce3f..5f1e06e0 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -585,4 +585,10 @@ 完了したスキャンジョブ数は合計スキャンジョブ数を超えることはできません! + + CORSオリジンは空ではいけません! + + + CORSオリジンが無効です! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 1d656920..1c28604f 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -585,4 +585,10 @@ Completed scan jobs count can't exceed total scan jobs count! + + CORS origins cannot be empty! + + + CORS origin is invalid! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index 071ffba3..c526acfc 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -585,4 +585,10 @@ Numărul de job-uri de scanare completate nu poate depăși numărul total de job-uri de scanare! + + Originile CORS nu pot fi goale! + + + Origine CORS invalidă! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index c0c66dc1..0b91bfb2 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -585,4 +585,10 @@ Количество завершенных заданий сканирования не может превышать общее количество заданий сканирования! + + Список CORS-источников не может быть пустым! + + + Недействительный CORS-источник! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 65199c3c..bfc9dadc 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -585,4 +585,10 @@ 已完成扫描任务数量不能超过扫描任务总数! + + CORS来源不能为空! + + + CORS来源无效! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index 6cbb886f..90f4a3cf 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -135,6 +135,9 @@ Buchreihe + + Abgebrochen + Scan Abbrechen @@ -147,6 +150,9 @@ Datei-Hashes werden verglichen... + + Abgeschlossen + Konzert @@ -171,6 +177,9 @@ Aktiviert + + Fehlgeschlagen + Filmfranchise diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index 57f1569c..8627b6f0 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -135,6 +135,9 @@ Book Series + + Canceled + Cancel Scan @@ -147,6 +150,9 @@ Comparing file hashes... + + Completed + Concert @@ -171,6 +177,9 @@ Enabled + + Failed + Film Franchise diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index 83d46d20..fa7f4aa7 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -135,6 +135,9 @@ Serie de Libros + + Cancelado + Cancelar Escaneo @@ -147,6 +150,9 @@ Se están comparando hashes de archivos... + + Completado + Concierto @@ -171,6 +177,9 @@ Activado + + Fallido + Franquicia Cinematográfica diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 8ac0c837..9d5893fa 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -135,6 +135,9 @@ Série de Livres + + Annulé + Annuler Le Scan @@ -147,6 +150,9 @@ Comparer les hachages de fichiers... + + Terminé + Concert @@ -171,6 +177,9 @@ Activé + + Échec + Franchise Cinématographique diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index a2981966..bfafb1a1 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -135,6 +135,9 @@ Serie di Libri + + Annullato + Annulla Scansione @@ -147,6 +150,9 @@ Si stanno confrontando gli hash dei file... + + Completato + Concerto @@ -171,6 +177,9 @@ Attivato + + Fallito + Franchise Cinematografico diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index ccdce597..5ebc9838 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -135,6 +135,9 @@ 本シリーズ + + キャンセル済み + スキャンを中止 @@ -147,6 +150,9 @@ ファイルのハッシュを比較中... + + 完了 + コンサート @@ -171,6 +177,9 @@ 有効 + + 失敗 + 映画フランチャイズ diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index 57f1569c..8627b6f0 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -135,6 +135,9 @@ Book Series + + Canceled + Cancel Scan @@ -147,6 +150,9 @@ Comparing file hashes... + + Completed + Concert @@ -171,6 +177,9 @@ Enabled + + Failed + Film Franchise diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index a97bc684..5332c1de 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -135,6 +135,9 @@ Serie de Cărți + + Anulat + Anulează Scanarea @@ -147,6 +150,9 @@ Se compară hash-urile fișierelor... + + Finalizat + Concert @@ -171,6 +177,9 @@ Activat + + Eșuat + Franciză de Film diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index 5a0ce521..4b5596eb 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -135,6 +135,9 @@ Книжная Серия + + Отменено + Отменить Сканирование @@ -147,6 +150,9 @@ Сравнение хешей файлов... + + Завершено + Концерт @@ -171,6 +177,9 @@ Включено + + Ошибка + Кинофраншиза diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index 0bde7364..439ac7bd 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -135,6 +135,9 @@ 丛书 + + 已取消 + 取消扫描 @@ -147,6 +150,9 @@ 正在比较文件哈希值... + + 已完成 + 音乐会 @@ -171,6 +177,9 @@ 已启用 + + 失败 + 电影系列品牌 diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml index ee8383aa..b4f14f2e 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -5,6 +5,7 @@ @using Lumina.Presentation.Web.Common.Models.Libraries @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization +@using System.Security.Claims @{ // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler @@ -14,6 +15,90 @@ @inject IUrlService _urlService @inject IViewLocalizer _localizer + +
@@ -27,10 +112,10 @@ @_localizer["Title"] - @_localizer["LibraryType"] + @_localizer["LibraryType"] @_localizer["Enabled"] @_localizer["Locked"] - @_localizer["Actions"] + @_localizer["Actions"] @@ -49,6 +134,18 @@ // create cleanup registry for this view const cleanupFunctions = []; let isInitialized = false; + const jsLocalizedLibraryScanStatuses = { + Completed: '@_localizer["Completed"]', + Failed: '@_localizer["Failed"]', + Canceled: '@_localizer["Canceled"]' + }; + const jsLocalizedLibraryScanJobsStatuses = { + DiscoveringFiles: '@_localizer["DiscoveringFiles"]', + RetrievingPastScanData: '@_localizer["RetrievingPastScanData"]', + ComparingFileHashes: '@_localizer["ComparingFileHashes"]', + GoodReadsMetadataDownload: '@_localizer["GoodReadsMetadataDownload"]', + SavingScanData: '@_localizer["SavingScanData"]' + }; const jsLocalizedLibraryTypes = { Book: '@_localizer["Book"]', EBook: '@_localizer["EBook"]', @@ -87,7 +184,17 @@ const btnScanAllLibraries = document.getElementById('btn-scan-all-libraries'); const btnCancelLibrariesScan = document.getElementById('btn-cancel-libraries-scan'); - // on view load + // SignalR + const signalRConnection = new signalR.HubConnectionBuilder() + .withUrl('http://localhost:5214/scanProgressHub') + .withAutomaticReconnect({ + nextRetryDelayInMilliseconds: retryContext => + Math.min(retryContext.elapsedMilliseconds * 2, 10000) + }) + .configureLogging(signalR.LogLevel.Warning) + .build(); + + // get media libraries const loadLibrariesAsync = async function() { const response = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetLibraries", "LibraryManagement")'); const table = document.getElementById('media-libraries-table'); @@ -107,13 +214,29 @@ ${jsLocalizedLibraryTypes[library.libraryType]} ${library.isEnabled === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} ${library.isLocked === true ? `@_localizer["Yes"]` : `@_localizer["No"]`} - - - @_localizer[ - - @_localizer[ - - @_localizer[ + + + + +
+
+ + + +
+ +
+ + @_localizer[ + + @_localizer[ + + @_localizer[ +
+
`; @@ -125,6 +248,40 @@ } }; + // get which libraries have active scans + const getRunningLibraryScansAsync = async function() { + const response = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetRunningLibraryScans", "LibraryManagement")'); + if (response && response.length > 0) { + await Promise.all(response.map(async scan => { + const row = document.querySelector(`tr[data-library-id="${scan.libraryId}"]`); + if (row) { + // restore UI state + const scanProgress = row.querySelector('.scan-progress'); + const totalProgressDiv = row.querySelector('.scan-progress-total > div'); + const jobProgressDiv = row.querySelector('.scan-progress-job > div'); + const statusSpan = row.querySelector('.scan-job-status'); + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + + row.setAttribute('data-scan-id', scan.scanId); + + statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[scan.currentJobProgress.currentOperation]; + statusSpan.classList.remove('hidden'); + + scanProgress.classList.remove('hidden'); + totalProgressDiv.style.width = `${scan.overallProgressPercentage}%`; + jobProgressDiv.style.width = `${scan.currentJobProgress.progressPercentage}%`; + + scanIcon.classList.add('hidden'); + cancelScanIcon.classList.remove('hidden'); + + // re-subscribe to SignalR + await signalRConnection.invoke('SubscribeToScan', scan.scanId, '@User.FindFirst(ClaimTypes.NameIdentifier)?.Value'); + } + })); + } + }; + // on delete library icon click const handleDeleteLibraryClick = async function(e) { if (e.target.matches('img[src*="delete.svg"]')) { @@ -152,15 +309,27 @@ // toggle icons only for libraries that had their scan started const tbody = document.querySelector('tbody'); - data.forEach(scan => { + data.forEach(async scan => { const row = tbody.querySelector(`tr[data-library-id="${scan.libraryId}"]`); if (row) { row.setAttribute('data-scan-id', scan.scanId); const scanIcon = row.querySelector('img[src*="trigger.svg"]'); const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + const completedIdon = row.querySelector('img[src*="green.png"]'); + const failedIdon = row.querySelector('img[src*="red.png"]'); + const canceledIdon = row.querySelector('img[src*="yellow.png"]'); + // hide scan status icons + completedIdon.classList.add('hidden'); + failedIdon.classList.add('hidden'); + canceledIdon.classList.add('hidden'); + // toggle visibility on scan action icons scanIcon.classList.add('hidden'); cancelScanIcon.classList.remove('hidden'); + + const scanId = scan.scanId; + const userId = '@User.FindFirst(ClaimTypes.NameIdentifier)?.Value'; + await signalRConnection.invoke('SubscribeToScan', scanId, userId); } }); } @@ -179,9 +348,21 @@ row.setAttribute('data-scan-id', success.scanId); const scanIcon = e.target; const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + const completedIdon = row.querySelector('img[src*="green.png"]'); + const failedIdon = row.querySelector('img[src*="red.png"]'); + const canceledIdon = row.querySelector('img[src*="yellow.png"]'); + // hide scan status icons + completedIdon.classList.add('hidden'); + failedIdon.classList.add('hidden'); + canceledIdon.classList.add('hidden'); + // toggle visibility on scan action icons scanIcon.classList.add('hidden'); cancelScanIcon.classList.remove('hidden'); + + const scanId = success.scanId; + const userId = '@User.FindFirst(ClaimTypes.NameIdentifier)?.Value'; + await signalRConnection.invoke('SubscribeToScan', scanId, userId); } } }; @@ -192,14 +373,25 @@ btnCancelLibrariesScan.style.display = 'none'; btnScanAllLibraries.style.display = 'block'; - // toggle icons for all rows - const tbody = document.querySelector('tbody'); - const allRows = tbody.querySelectorAll('tr'); + // toggle icons for all active scan rows + const rows = document.querySelectorAll('tr[data-scan-id]'); - allRows.forEach(row => { + rows.forEach(row => { + // remove the scan Id, its no longer being scanned + row.removeAttribute('data-scan-id'); + + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`; + const scanProgress = row.querySelector('.scan-progress'); + scanProgress.classList.add('hidden'); + + // show scan status icon + const completedIdon = row.querySelector('img[src*="yellow.png"]'); + completedIdon.classList.remove('hidden'); + + // toggle scan action icons const scanIcon = row.querySelector('img[src*="trigger.svg"]'); const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); - scanIcon.classList.remove('hidden'); cancelScanIcon.classList.add('hidden'); }); @@ -228,14 +420,140 @@ ).join('/'); await callApiPostAsync(finalUrl); + + // remove the scan Id, its no longer being scanned + row.removeAttribute('data-scan-id'); + + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses['Canceled']}.`; + const scanProgress = row.querySelector('.scan-progress'); + scanProgress.classList.add('hidden'); + + // show scan status icon + const completedIdon = row.querySelector('img[src*="yellow.png"]'); + completedIdon.classList.remove('hidden'); + + // toggle scan action icons const scanIcon = row.querySelector('img[src*="trigger.svg"]'); const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); - scanIcon.classList.remove('hidden'); cancelScanIcon.classList.add('hidden'); + + // toggle scan action buttons + const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0; + btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none'; + btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block'; } }; + // handle all SignalR stuff + function setupSignalRHandlers() { + const onReconnecting = error => { + console.log(error ? `SignalR reconnected with error: ${error}` : "SignalR reconnecting..."); + }; + const onReconnected = connectionId => { + console.log('SignalR reconnected:', connectionId); + }; + const onClose = error => { + console.log(error ? `SignalR connection closed with error: ${error}` : "SignalR connection closed"); + }; + // progress update handler + const progressHandler = (progress) => { + const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`); + rows.forEach(row => { + // update status text + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = jsLocalizedLibraryScanJobsStatuses[progress.currentJobProgress.currentOperation]; + statusSpan.classList.remove('hidden'); + + // update progress bars + const scanProgress = row.querySelector('.scan-progress'); + const totalProgressDiv = row.querySelector('.scan-progress-total > div'); + const jobProgressDiv = row.querySelector('.scan-progress-job > div'); + scanProgress.classList.remove('hidden'); + totalProgressDiv.style.width = `${progress.overallProgressPercentage}%`; + jobProgressDiv.style.width = `${progress.currentJobProgress.progressPercentage}%`; + + // toggle scan action icons + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + scanIcon.classList.add('hidden'); + cancelScanIcon.classList.remove('hidden'); + }); + }; + + // scan completion handler + const completionHandler = (progress) => { + const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`); + rows.forEach(row => { + // remove the scan Id, its no longer being scanned + row.removeAttribute('data-scan-id'); + + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses[progress.status]}.`; + const scanProgress = row.querySelector('.scan-progress'); + scanProgress.classList.add('hidden'); + + // show scan status icon + const completedIdon = row.querySelector('img[src*="green.png"]'); + completedIdon.classList.remove('hidden'); + + // toggle scan action icons + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + scanIcon.classList.remove('hidden'); + cancelScanIcon.classList.add('hidden'); + }); + const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0; + btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none'; + btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block'; + }; + + // scan failure handler + const failureHandler = (progress) => { + const rows = document.querySelectorAll(`tr[data-scan-id="${progress.scanId}"]`); + rows.forEach(row => { + // remove the scan Id, its no longer being scanned + row.removeAttribute('data-scan-id'); + + const statusSpan = row.querySelector('.scan-job-status'); + statusSpan.textContent = `${jsLocalizedLibraryScanStatuses[progress.status]}.`; + const scanProgress = row.querySelector('.scan-progress'); + scanProgress.classList.add('hidden'); + + // show scan status icon + const completedIdon = row.querySelector('img[src*="red.png"]'); + completedIdon.classList.remove('hidden'); + + // toggle scan action icons + const scanIcon = row.querySelector('img[src*="trigger.svg"]'); + const cancelScanIcon = row.querySelector('img[src*="stop.svg"]'); + scanIcon.classList.remove('hidden'); + cancelScanIcon.classList.add('hidden'); + }); + const hasActiveScans = document.querySelectorAll('tr[data-scan-id]').length > 0; + btnCancelLibrariesScan.style.display = hasActiveScans ? 'block' : 'none'; + btnScanAllLibraries.style.display = hasActiveScans ? 'none' : 'block'; + }; + + // subscribe to events + signalRConnection.on("libraryScanProgressUpdateEvent", progressHandler); + signalRConnection.on("libraryScanFinishedEvent", completionHandler); + signalRConnection.on("libraryScanFailedEvent", failureHandler); + signalRConnection.onclose(onClose); + signalRConnection.onreconnecting(onReconnecting); + signalRConnection.onreconnected(onReconnected); + // add to cleanup + cleanupFunctions.push(() => { + signalRConnection.off("libraryScanProgressUpdateEvent", progressHandler); + signalRConnection.off("libraryScanFinishedEvent", completionHandler); + signalRConnection.off("libraryScanFailedEvent", failureHandler); + signalRConnection.off("close", onClose); + signalRConnection.off("reconnecting", onReconnecting); + signalRConnection.off("reconnected", onReconnected); + }); + } + // add listeners btnScanAllLibraries.addEventListener('click', handleScanAllLibrariesClick); btnCancelLibrariesScan.addEventListener('click', handleCancelLibrariesScanClick); @@ -245,7 +563,11 @@ document.addEventListener('DOMContentLoaded', InitializeAsync); // register cleanup for these listeners - cleanupFunctions.push(() => { + cleanupFunctions.push(() => { + // proper connection stop + if (signalRConnection.state === 'Connected') + signalRConnection.stop().then(() => console.log('SignalR connection stopped')); + btnScanAllLibraries.removeEventListener('click', handleScanAllLibrariesClick); btnCancelLibrariesScan.removeEventListener('click', handleCancelLibrariesScanClick); document.removeEventListener('click', handleDeleteLibraryClick); @@ -265,7 +587,14 @@ if (isInitialized) return; isInitialized = true; - await loadLibrariesAsync(); + try { + await loadLibrariesAsync(); + await signalRConnection.start(); + setupSignalRHandlers(); + await getRunningLibraryScansAsync(); + } catch (err) { + console.error('SignalR connection failed:', err); + } } console.log(`Loaded @scriptId`); diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml.css b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml.css new file mode 100644 index 00000000..5f282702 --- /dev/null +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml.css @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml index a827d0fc..3c6c2ad1 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_Layout.cshtml @@ -77,6 +77,7 @@ }; + diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index fa4a93cd..73c0a7f4 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -53,5 +53,12 @@ "ApiVersion": 1, "BaseAddress": "http://localhost", "Port": 5214 + }, + "Kestrel": { + "Endpoints": { + "Http": { + "Url": "http://localhost:5012" + } + } } } diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/green.png b/src/Lumina.Presentation.Web/wwwroot/images/ui/green.png new file mode 100644 index 00000000..aeeb2097 Binary files /dev/null and b/src/Lumina.Presentation.Web/wwwroot/images/ui/green.png differ diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/red.png b/src/Lumina.Presentation.Web/wwwroot/images/ui/red.png new file mode 100644 index 00000000..8c14d7cd Binary files /dev/null and b/src/Lumina.Presentation.Web/wwwroot/images/ui/red.png differ diff --git a/src/Lumina.Presentation.Web/wwwroot/images/ui/yellow.png b/src/Lumina.Presentation.Web/wwwroot/images/ui/yellow.png new file mode 100644 index 00000000..879c9555 Binary files /dev/null and b/src/Lumina.Presentation.Web/wwwroot/images/ui/yellow.png differ diff --git a/src/Lumina.Presentation.Web/wwwroot/libs/microsoft-signalr/signalr.js b/src/Lumina.Presentation.Web/wwwroot/libs/microsoft-signalr/signalr.js new file mode 100644 index 00000000..f650e100 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/libs/microsoft-signalr/signalr.js @@ -0,0 +1,2 @@ +var t, e; t = self, e = function () { return (() => { var t = { d: (e, s) => { for (var n in s) t.o(s, n) && !t.o(e, n) && Object.defineProperty(e, n, { enumerable: !0, get: s[n] }) } }; t.g = function () { if ("object" == typeof globalThis) return globalThis; try { return this || new Function("return this")() } catch (t) { if ("object" == typeof window) return window } }(), t.o = (t, e) => Object.prototype.hasOwnProperty.call(t, e), t.r = t => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "t", { value: !0 }) }; var e, s = {}; t.r(s), t.d(s, { AbortError: () => r, DefaultHttpClient: () => H, HttpClient: () => d, HttpError: () => n, HttpResponse: () => u, HttpTransportType: () => W, HubConnection: () => L, HubConnectionBuilder: () => Q, HubConnectionState: () => R, JsonHubProtocol: () => G, LogLevel: () => e, MessageType: () => A, NullLogger: () => f, Subject: () => U, TimeoutError: () => i, TransferFormat: () => O, VERSION: () => p }); class n extends Error { constructor(t, e) { const s = new.target.prototype; super(`${t}: Status code '${e}'`), this.statusCode = e, this.__proto__ = s } } class i extends Error { constructor(t = "A timeout occurred.") { const e = new.target.prototype; super(t), this.__proto__ = e } } class r extends Error { constructor(t = "An abort occurred.") { const e = new.target.prototype; super(t), this.__proto__ = e } } class o extends Error { constructor(t, e) { const s = new.target.prototype; super(t), this.transport = e, this.errorType = "UnsupportedTransportError", this.__proto__ = s } } class h extends Error { constructor(t, e) { const s = new.target.prototype; super(t), this.transport = e, this.errorType = "DisabledTransportError", this.__proto__ = s } } class c extends Error { constructor(t, e) { const s = new.target.prototype; super(t), this.transport = e, this.errorType = "FailedToStartTransportError", this.__proto__ = s } } class a extends Error { constructor(t) { const e = new.target.prototype; super(t), this.errorType = "FailedToNegotiateWithServerError", this.__proto__ = e } } class l extends Error { constructor(t, e) { const s = new.target.prototype; super(t), this.innerErrors = e, this.__proto__ = s } } class u { constructor(t, e, s) { this.statusCode = t, this.statusText = e, this.content = s } } class d { get(t, e) { return this.send({ ...e, method: "GET", url: t }) } post(t, e) { return this.send({ ...e, method: "POST", url: t }) } delete(t, e) { return this.send({ ...e, method: "DELETE", url: t }) } getCookieString(t) { return "" } } !function (t) { t[t.Trace = 0] = "Trace", t[t.Debug = 1] = "Debug", t[t.Information = 2] = "Information", t[t.Warning = 3] = "Warning", t[t.Error = 4] = "Error", t[t.Critical = 5] = "Critical", t[t.None = 6] = "None" }(e || (e = {})); class f { constructor() { } log(t, e) { } } f.instance = new f; const p = "6.0.1"; class w { static isRequired(t, e) { if (null == t) throw new Error(`The '${e}' argument is required.`) } static isNotEmpty(t, e) { if (!t || t.match(/^\s*$/)) throw new Error(`The '${e}' argument should not be empty.`) } static isIn(t, e, s) { if (!(t in e)) throw new Error(`Unknown ${s} value: ${t}.`) } } class g { static get isBrowser() { return "object" == typeof window } static get isWebWorker() { return "object" == typeof self && "importScripts" in self } static get isNode() { return !this.isBrowser && !this.isWebWorker } } function m(t, e) { let s = ""; return y(t) ? (s = `Binary data of length ${t.byteLength}`, e && (s += `. Content: '${function (t) { const e = new Uint8Array(t); let s = ""; return e.forEach((t => { s += `0x${t < 16 ? "0" : ""}${t.toString(16)} ` })), s.substr(0, s.length - 1) }(t)}'`)) : "string" == typeof t && (s = `String data of length ${t.length}`, e && (s += `. Content: '${t}'`)), s } function y(t) { return t && "undefined" != typeof ArrayBuffer && (t instanceof ArrayBuffer || t.constructor && "ArrayBuffer" === t.constructor.name) } async function b(t, s, n, i, r, o, h) { let c = {}; if (r) { const t = await r(); t && (c = { Authorization: `Bearer ${t}` }) } const [a, l] = $(); c[a] = l, t.log(e.Trace, `(${s} transport) sending data. ${m(o, h.logMessageContent)}.`); const u = y(o) ? "arraybuffer" : "text", d = await n.post(i, { content: o, headers: { ...c, ...h.headers }, responseType: u, timeout: h.timeout, withCredentials: h.withCredentials }); t.log(e.Trace, `(${s} transport) request complete. Response status: ${d.statusCode}.`) } class v { constructor(t, e) { this.i = t, this.h = e } dispose() { const t = this.i.observers.indexOf(this.h); t > -1 && this.i.observers.splice(t, 1), 0 === this.i.observers.length && this.i.cancelCallback && this.i.cancelCallback().catch((t => { })) } } class E { constructor(t) { this.l = t, this.out = console } log(t, s) { if (t >= this.l) { const n = `[${(new Date).toISOString()}] ${e[t]}: ${s}`; switch (t) { case e.Critical: case e.Error: this.out.error(n); break; case e.Warning: this.out.warn(n); break; case e.Information: this.out.info(n); break; default: this.out.log(n) } } } } function $() { let t = "X-SignalR-User-Agent"; return g.isNode && (t = "User-Agent"), [t, C(p, S(), g.isNode ? "NodeJS" : "Browser", k())] } function C(t, e, s, n) { let i = "Microsoft SignalR/"; const r = t.split("."); return i += `${r[0]}.${r[1]}`, i += ` (${t}; `, i += e && "" !== e ? `${e}; ` : "Unknown OS; ", i += `${s}`, i += n ? `; ${n}` : "; Unknown Runtime Version", i += ")", i } function S() { if (!g.isNode) return ""; switch (process.platform) { case "win32": return "Windows NT"; case "darwin": return "macOS"; case "linux": return "Linux"; default: return process.platform } } function k() { if (g.isNode) return process.versions.node } function P(t) { return t.stack ? t.stack : t.message ? t.message : `${t}` } class T extends d { constructor(e) { if (super(), this.u = e, "undefined" == typeof fetch) { const t = require; this.p = new (t("tough-cookie").CookieJar), this.m = t("node-fetch"), this.m = t("fetch-cookie")(this.m, this.p) } else this.m = fetch.bind(function () { if ("undefined" != typeof globalThis) return globalThis; if ("undefined" != typeof self) return self; if ("undefined" != typeof window) return window; if (void 0 !== t.g) return t.g; throw new Error("could not find global") }()); if ("undefined" == typeof AbortController) { const t = require; this.v = t("abort-controller") } else this.v = AbortController } async send(t) { if (t.abortSignal && t.abortSignal.aborted) throw new r; if (!t.method) throw new Error("No method defined."); if (!t.url) throw new Error("No url defined."); const s = new this.v; let o; t.abortSignal && (t.abortSignal.onabort = () => { s.abort(), o = new r }); let h, c = null; if (t.timeout) { const n = t.timeout; c = setTimeout((() => { s.abort(), this.u.log(e.Warning, "Timeout from HTTP request."), o = new i }), n) } try { h = await this.m(t.url, { body: t.content, cache: "no-cache", credentials: !0 === t.withCredentials ? "include" : "same-origin", headers: { "Content-Type": "text/plain;charset=UTF-8", "X-Requested-With": "XMLHttpRequest", ...t.headers }, method: t.method, mode: "cors", redirect: "follow", signal: s.signal }) } catch (t) { if (o) throw o; throw this.u.log(e.Warning, `Error from HTTP request. ${t}.`), t } finally { c && clearTimeout(c), t.abortSignal && (t.abortSignal.onabort = null) } if (!h.ok) { const t = await I(h, "text"); throw new n(t || h.statusText, h.status) } const a = I(h, t.responseType), l = await a; return new u(h.status, h.statusText, l) } getCookieString(t) { let e = ""; return g.isNode && this.p && this.p.getCookies(t, ((t, s) => e = s.join("; "))), e } } function I(t, e) { let s; switch (e) { case "arraybuffer": s = t.arrayBuffer(); break; case "text": s = t.text(); break; case "blob": case "document": case "json": throw new Error(`${e} is not supported.`); default: s = t.text() }return s } class _ extends d { constructor(t) { super(), this.u = t } send(t) { return t.abortSignal && t.abortSignal.aborted ? Promise.reject(new r) : t.method ? t.url ? new Promise(((s, o) => { const h = new XMLHttpRequest; h.open(t.method, t.url, !0), h.withCredentials = void 0 === t.withCredentials || t.withCredentials, h.setRequestHeader("X-Requested-With", "XMLHttpRequest"), h.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); const c = t.headers; c && Object.keys(c).forEach((t => { h.setRequestHeader(t, c[t]) })), t.responseType && (h.responseType = t.responseType), t.abortSignal && (t.abortSignal.onabort = () => { h.abort(), o(new r) }), t.timeout && (h.timeout = t.timeout), h.onload = () => { t.abortSignal && (t.abortSignal.onabort = null), h.status >= 200 && h.status < 300 ? s(new u(h.status, h.statusText, h.response || h.responseText)) : o(new n(h.response || h.responseText || h.statusText, h.status)) }, h.onerror = () => { this.u.log(e.Warning, `Error from HTTP request. ${h.status}: ${h.statusText}.`), o(new n(h.statusText, h.status)) }, h.ontimeout = () => { this.u.log(e.Warning, "Timeout from HTTP request."), o(new i) }, h.send(t.content || "") })) : Promise.reject(new Error("No url defined.")) : Promise.reject(new Error("No method defined.")) } } class H extends d { constructor(t) { if (super(), "undefined" != typeof fetch || g.isNode) this.$ = new T(t); else { if ("undefined" == typeof XMLHttpRequest) throw new Error("No usable HttpClient found."); this.$ = new _(t) } } send(t) { return t.abortSignal && t.abortSignal.aborted ? Promise.reject(new r) : t.method ? t.url ? this.$.send(t) : Promise.reject(new Error("No url defined.")) : Promise.reject(new Error("No method defined.")) } getCookieString(t) { return this.$.getCookieString(t) } } class D { static write(t) { return `${t}${D.RecordSeparator}` } static parse(t) { if (t[t.length - 1] !== D.RecordSeparator) throw new Error("Message is incomplete."); const e = t.split(D.RecordSeparator); return e.pop(), e } } D.RecordSeparatorCode = 30, D.RecordSeparator = String.fromCharCode(D.RecordSeparatorCode); class x { writeHandshakeRequest(t) { return D.write(JSON.stringify(t)) } parseHandshakeResponse(t) { let e, s; if (y(t)) { const n = new Uint8Array(t), i = n.indexOf(D.RecordSeparatorCode); if (-1 === i) throw new Error("Message is incomplete."); const r = i + 1; e = String.fromCharCode.apply(null, Array.prototype.slice.call(n.slice(0, r))), s = n.byteLength > r ? n.slice(r).buffer : null } else { const n = t, i = n.indexOf(D.RecordSeparator); if (-1 === i) throw new Error("Message is incomplete."); const r = i + 1; e = n.substring(0, r), s = n.length > r ? n.substring(r) : null } const n = D.parse(e), i = JSON.parse(n[0]); if (i.type) throw new Error("Expected a handshake response from the server."); return [s, i] } } var A, R; !function (t) { t[t.Invocation = 1] = "Invocation", t[t.StreamItem = 2] = "StreamItem", t[t.Completion = 3] = "Completion", t[t.StreamInvocation = 4] = "StreamInvocation", t[t.CancelInvocation = 5] = "CancelInvocation", t[t.Ping = 6] = "Ping", t[t.Close = 7] = "Close" }(A || (A = {})); class U { constructor() { this.observers = [] } next(t) { for (const e of this.observers) e.next(t) } error(t) { for (const e of this.observers) e.error && e.error(t) } complete() { for (const t of this.observers) t.complete && t.complete() } subscribe(t) { return this.observers.push(t), new v(this, t) } } !function (t) { t.Disconnected = "Disconnected", t.Connecting = "Connecting", t.Connected = "Connected", t.Disconnecting = "Disconnecting", t.Reconnecting = "Reconnecting" }(R || (R = {})); class L { constructor(t, s, n, i) { this.C = 0, this.S = () => { this.u.log(e.Warning, "The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep") }, w.isRequired(t, "connection"), w.isRequired(s, "logger"), w.isRequired(n, "protocol"), this.serverTimeoutInMilliseconds = 3e4, this.keepAliveIntervalInMilliseconds = 15e3, this.u = s, this.k = n, this.connection = t, this.P = i, this.T = new x, this.connection.onreceive = t => this.I(t), this.connection.onclose = t => this._(t), this.H = {}, this.D = {}, this.A = [], this.R = [], this.U = [], this.L = 0, this.N = !1, this.q = R.Disconnected, this.M = !1, this.W = this.k.writeMessage({ type: A.Ping }) } static create(t, e, s, n) { return new L(t, e, s, n) } get state() { return this.q } get connectionId() { return this.connection && this.connection.connectionId || null } get baseUrl() { return this.connection.baseUrl || "" } set baseUrl(t) { if (this.q !== R.Disconnected && this.q !== R.Reconnecting) throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url."); if (!t) throw new Error("The HubConnection url must be a valid url."); this.connection.baseUrl = t } start() { return this.O = this.j(), this.O } async j() { if (this.q !== R.Disconnected) return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state.")); this.q = R.Connecting, this.u.log(e.Debug, "Starting HubConnection."); try { await this.F(), g.isBrowser && document && document.addEventListener("freeze", this.S), this.q = R.Connected, this.M = !0, this.u.log(e.Debug, "HubConnection connected successfully.") } catch (t) { return this.q = R.Disconnected, this.u.log(e.Debug, `HubConnection failed to start successfully because of error '${t}'.`), Promise.reject(t) } } async F() { this.B = void 0, this.N = !1; const t = new Promise(((t, e) => { this.X = t, this.J = e })); await this.connection.start(this.k.transferFormat); try { const s = { protocol: this.k.name, version: this.k.version }; if (this.u.log(e.Debug, "Sending handshake request."), await this.V(this.T.writeHandshakeRequest(s)), this.u.log(e.Information, `Using HubProtocol '${this.k.name}'.`), this.G(), this.K(), this.Y(), await t, this.B) throw this.B } catch (t) { throw this.u.log(e.Debug, `Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`), this.G(), this.Z(), await this.connection.stop(t), t } } async stop() { const t = this.O; this.tt = this.et(), await this.tt; try { await t } catch (t) { } } et(t) { return this.q === R.Disconnected ? (this.u.log(e.Debug, `Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`), Promise.resolve()) : this.q === R.Disconnecting ? (this.u.log(e.Debug, `Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`), this.tt) : (this.q = R.Disconnecting, this.u.log(e.Debug, "Stopping HubConnection."), this.st ? (this.u.log(e.Debug, "Connection stopped during reconnect delay. Done reconnecting."), clearTimeout(this.st), this.st = void 0, this.nt(), Promise.resolve()) : (this.G(), this.Z(), this.B = t || new Error("The connection was stopped before the hub handshake could complete."), this.connection.stop(t))) } stream(t, ...e) { const [s, n] = this.it(e), i = this.rt(t, e, n); let r; const o = new U; return o.cancelCallback = () => { const t = this.ot(i.invocationId); return delete this.H[i.invocationId], r.then((() => this.ht(t))) }, this.H[i.invocationId] = (t, e) => { e ? o.error(e) : t && (t.type === A.Completion ? t.error ? o.error(new Error(t.error)) : o.complete() : o.next(t.item)) }, r = this.ht(i).catch((t => { o.error(t), delete this.H[i.invocationId] })), this.ct(s, r), o } V(t) { return this.Y(), this.connection.send(t) } ht(t) { return this.V(this.k.writeMessage(t)) } send(t, ...e) { const [s, n] = this.it(e), i = this.ht(this.at(t, e, !0, n)); return this.ct(s, i), i } invoke(t, ...e) { const [s, n] = this.it(e), i = this.at(t, e, !1, n); return new Promise(((t, e) => { this.H[i.invocationId] = (s, n) => { n ? e(n) : s && (s.type === A.Completion ? s.error ? e(new Error(s.error)) : t(s.result) : e(new Error(`Unexpected message type: ${s.type}`))) }; const n = this.ht(i).catch((t => { e(t), delete this.H[i.invocationId] })); this.ct(s, n) })) } on(t, e) { t && e && (t = t.toLowerCase(), this.D[t] || (this.D[t] = []), -1 === this.D[t].indexOf(e) && this.D[t].push(e)) } off(t, e) { if (!t) return; t = t.toLowerCase(); const s = this.D[t]; if (s) if (e) { const n = s.indexOf(e); -1 !== n && (s.splice(n, 1), 0 === s.length && delete this.D[t]) } else delete this.D[t] } onclose(t) { t && this.A.push(t) } onreconnecting(t) { t && this.R.push(t) } onreconnected(t) { t && this.U.push(t) } I(t) { if (this.G(), this.N || (t = this.lt(t), this.N = !0), t) { const s = this.k.parseMessages(t, this.u); for (const t of s) switch (t.type) { case A.Invocation: this.ut(t); break; case A.StreamItem: case A.Completion: { const s = this.H[t.invocationId]; if (s) { t.type === A.Completion && delete this.H[t.invocationId]; try { s(t) } catch (t) { this.u.log(e.Error, `Stream callback threw error: ${P(t)}`) } } break } case A.Ping: break; case A.Close: { this.u.log(e.Information, "Close message received from server."); const s = t.error ? new Error("Server returned an error on close: " + t.error) : void 0; !0 === t.allowReconnect ? this.connection.stop(s) : this.tt = this.et(s); break } default: this.u.log(e.Warning, `Invalid message type: ${t.type}.`) } } this.K() } lt(t) { let s, n; try { [n, s] = this.T.parseHandshakeResponse(t) } catch (t) { const s = "Error parsing handshake response: " + t; this.u.log(e.Error, s); const n = new Error(s); throw this.J(n), n } if (s.error) { const t = "Server returned handshake error: " + s.error; this.u.log(e.Error, t); const n = new Error(t); throw this.J(n), n } return this.u.log(e.Debug, "Server handshake complete."), this.X(), n } Y() { this.connection.features.inherentKeepAlive || (this.C = (new Date).getTime() + this.keepAliveIntervalInMilliseconds, this.Z()) } K() { if (!(this.connection.features && this.connection.features.inherentKeepAlive || (this.dt = setTimeout((() => this.serverTimeout()), this.serverTimeoutInMilliseconds), void 0 !== this.ft))) { let t = this.C - (new Date).getTime(); t < 0 && (t = 0), this.ft = setTimeout((async () => { if (this.q === R.Connected) try { await this.V(this.W) } catch { this.Z() } }), t) } } serverTimeout() { this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")) } ut(t) { const s = this.D[t.target.toLowerCase()]; if (s) { try { s.forEach((e => e.apply(this, t.arguments))) } catch (s) { this.u.log(e.Error, `A callback for the method ${t.target.toLowerCase()} threw error '${s}'.`) } if (t.invocationId) { const t = "Server requested a response, which is not supported in this version of the client."; this.u.log(e.Error, t), this.tt = this.et(new Error(t)) } } else this.u.log(e.Warning, `No client method with the name '${t.target}' found.`) } _(t) { this.u.log(e.Debug, `HubConnection.connectionClosed(${t}) called while in state ${this.q}.`), this.B = this.B || t || new Error("The underlying connection was closed before the hub handshake could complete."), this.X && this.X(), this.wt(t || new Error("Invocation canceled due to the underlying connection being closed.")), this.G(), this.Z(), this.q === R.Disconnecting ? this.nt(t) : this.q === R.Connected && this.P ? this.gt(t) : this.q === R.Connected && this.nt(t) } nt(t) { if (this.M) { this.q = R.Disconnected, this.M = !1, g.isBrowser && document && document.removeEventListener("freeze", this.S); try { this.A.forEach((e => e.apply(this, [t]))) } catch (s) { this.u.log(e.Error, `An onclose callback called with error '${t}' threw error '${s}'.`) } } } async gt(t) { const s = Date.now(); let n = 0, i = void 0 !== t ? t : new Error("Attempting to reconnect due to a unknown error."), r = this.yt(n++, 0, i); if (null === r) return this.u.log(e.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."), void this.nt(t); if (this.q = R.Reconnecting, t ? this.u.log(e.Information, `Connection reconnecting because of error '${t}'.`) : this.u.log(e.Information, "Connection reconnecting."), 0 !== this.R.length) { try { this.R.forEach((e => e.apply(this, [t]))) } catch (s) { this.u.log(e.Error, `An onreconnecting callback called with error '${t}' threw error '${s}'.`) } if (this.q !== R.Reconnecting) return void this.u.log(e.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.") } for (; null !== r;) { if (this.u.log(e.Information, `Reconnect attempt number ${n} will start in ${r} ms.`), await new Promise((t => { this.st = setTimeout(t, r) })), this.st = void 0, this.q !== R.Reconnecting) return void this.u.log(e.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting."); try { if (await this.F(), this.q = R.Connected, this.u.log(e.Information, "HubConnection reconnected successfully."), 0 !== this.U.length) try { this.U.forEach((t => t.apply(this, [this.connection.connectionId]))) } catch (t) { this.u.log(e.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`) } return } catch (t) { if (this.u.log(e.Information, `Reconnect attempt failed because of error '${t}'.`), this.q !== R.Reconnecting) return this.u.log(e.Debug, `Connection moved to the '${this.q}' from the reconnecting state during reconnect attempt. Done reconnecting.`), void (this.q === R.Disconnecting && this.nt()); i = t instanceof Error ? t : new Error(t.toString()), r = this.yt(n++, Date.now() - s, i) } } this.u.log(e.Information, `Reconnect retries have been exhausted after ${Date.now() - s} ms and ${n} failed attempts. Connection disconnecting.`), this.nt() } yt(t, s, n) { try { return this.P.nextRetryDelayInMilliseconds({ elapsedMilliseconds: s, previousRetryCount: t, retryReason: n }) } catch (n) { return this.u.log(e.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${s}) threw error '${n}'.`), null } } wt(t) { const s = this.H; this.H = {}, Object.keys(s).forEach((n => { const i = s[n]; try { i(null, t) } catch (s) { this.u.log(e.Error, `Stream 'error' callback called with '${t}' threw error: ${P(s)}`) } })) } Z() { this.ft && (clearTimeout(this.ft), this.ft = void 0) } G() { this.dt && clearTimeout(this.dt) } at(t, e, s, n) { if (s) return 0 !== n.length ? { arguments: e, streamIds: n, target: t, type: A.Invocation } : { arguments: e, target: t, type: A.Invocation }; { const s = this.L; return this.L++, 0 !== n.length ? { arguments: e, invocationId: s.toString(), streamIds: n, target: t, type: A.Invocation } : { arguments: e, invocationId: s.toString(), target: t, type: A.Invocation } } } ct(t, e) { if (0 !== t.length) { e || (e = Promise.resolve()); for (const s in t) t[s].subscribe({ complete: () => { e = e.then((() => this.ht(this.bt(s)))) }, error: t => { let n; n = t instanceof Error ? t.message : t && t.toString ? t.toString() : "Unknown error", e = e.then((() => this.ht(this.bt(s, n)))) }, next: t => { e = e.then((() => this.ht(this.vt(s, t)))) } }) } } it(t) { const e = [], s = []; for (let n = 0; n < t.length; n++) { const i = t[n]; if (this.Et(i)) { const r = this.L; this.L++, e[r] = i, s.push(r.toString()), t.splice(n, 1) } } return [e, s] } Et(t) { return t && t.subscribe && "function" == typeof t.subscribe } rt(t, e, s) { const n = this.L; return this.L++, 0 !== s.length ? { arguments: e, invocationId: n.toString(), streamIds: s, target: t, type: A.StreamInvocation } : { arguments: e, invocationId: n.toString(), target: t, type: A.StreamInvocation } } ot(t) { return { invocationId: t, type: A.CancelInvocation } } vt(t, e) { return { invocationId: t, item: e, type: A.StreamItem } } bt(t, e, s) { return e ? { error: e, invocationId: t, type: A.Completion } : { invocationId: t, result: s, type: A.Completion } } } const N = [0, 2e3, 1e4, 3e4, null]; class q { constructor(t) { this.$t = void 0 !== t ? [...t, null] : N } nextRetryDelayInMilliseconds(t) { return this.$t[t.previousRetryCount] } } class M { } var W, O; M.Authorization = "Authorization", M.Cookie = "Cookie", function (t) { t[t.None = 0] = "None", t[t.WebSockets = 1] = "WebSockets", t[t.ServerSentEvents = 2] = "ServerSentEvents", t[t.LongPolling = 4] = "LongPolling" }(W || (W = {})), function (t) { t[t.Text = 1] = "Text", t[t.Binary = 2] = "Binary" }(O || (O = {})); class j { constructor() { this.Ct = !1, this.onabort = null } abort() { this.Ct || (this.Ct = !0, this.onabort && this.onabort()) } get signal() { return this } get aborted() { return this.Ct } } class F { constructor(t, e, s, n) { this.$ = t, this.St = e, this.u = s, this.kt = new j, this.Pt = n, this.Tt = !1, this.onreceive = null, this.onclose = null } get pollAborted() { return this.kt.aborted } async connect(t, s) { if (w.isRequired(t, "url"), w.isRequired(s, "transferFormat"), w.isIn(s, O, "transferFormat"), this.It = t, this.u.log(e.Trace, "(LongPolling transport) Connecting."), s === O.Binary && "undefined" != typeof XMLHttpRequest && "string" != typeof (new XMLHttpRequest).responseType) throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); const [i, r] = $(), o = { [i]: r, ...this.Pt.headers }, h = { abortSignal: this.kt.signal, headers: o, timeout: 1e5, withCredentials: this.Pt.withCredentials }; s === O.Binary && (h.responseType = "arraybuffer"); const c = await this._t(); this.Ht(h, c); const a = `${t}&_=${Date.now()}`; this.u.log(e.Trace, `(LongPolling transport) polling: ${a}.`); const l = await this.$.get(a, h); 200 !== l.statusCode ? (this.u.log(e.Error, `(LongPolling transport) Unexpected response code: ${l.statusCode}.`), this.Dt = new n(l.statusText || "", l.statusCode), this.Tt = !1) : this.Tt = !0, this.xt = this.At(this.It, h) } async _t() { return this.St ? await this.St() : null } Ht(t, e) { t.headers || (t.headers = {}), e ? t.headers[M.Authorization] = `Bearer ${e}` : t.headers[M.Authorization] && delete t.headers[M.Authorization] } async At(t, s) { try { for (; this.Tt;) { const r = await this._t(); this.Ht(s, r); try { const i = `${t}&_=${Date.now()}`; this.u.log(e.Trace, `(LongPolling transport) polling: ${i}.`); const r = await this.$.get(i, s); 204 === r.statusCode ? (this.u.log(e.Information, "(LongPolling transport) Poll terminated by server."), this.Tt = !1) : 200 !== r.statusCode ? (this.u.log(e.Error, `(LongPolling transport) Unexpected response code: ${r.statusCode}.`), this.Dt = new n(r.statusText || "", r.statusCode), this.Tt = !1) : r.content ? (this.u.log(e.Trace, `(LongPolling transport) data received. ${m(r.content, this.Pt.logMessageContent)}.`), this.onreceive && this.onreceive(r.content)) : this.u.log(e.Trace, "(LongPolling transport) Poll timed out, reissuing.") } catch (t) { this.Tt ? t instanceof i ? this.u.log(e.Trace, "(LongPolling transport) Poll timed out, reissuing.") : (this.Dt = t, this.Tt = !1) : this.u.log(e.Trace, `(LongPolling transport) Poll errored after shutdown: ${t.message}`) } } } finally { this.u.log(e.Trace, "(LongPolling transport) Polling complete."), this.pollAborted || this.Rt() } } async send(t) { return this.Tt ? b(this.u, "LongPolling", this.$, this.It, this.St, t, this.Pt) : Promise.reject(new Error("Cannot send until the transport is connected")) } async stop() { this.u.log(e.Trace, "(LongPolling transport) Stopping polling."), this.Tt = !1, this.kt.abort(); try { await this.xt, this.u.log(e.Trace, `(LongPolling transport) sending DELETE request to ${this.It}.`); const t = {}, [s, n] = $(); t[s] = n; const i = { headers: { ...t, ...this.Pt.headers }, timeout: this.Pt.timeout, withCredentials: this.Pt.withCredentials }, r = await this._t(); this.Ht(i, r), await this.$.delete(this.It, i), this.u.log(e.Trace, "(LongPolling transport) DELETE request sent.") } finally { this.u.log(e.Trace, "(LongPolling transport) Stop finished."), this.Rt() } } Rt() { if (this.onclose) { let t = "(LongPolling transport) Firing onclose event."; this.Dt && (t += " Error: " + this.Dt), this.u.log(e.Trace, t), this.onclose(this.Dt) } } } class B { constructor(t, e, s, n) { this.$ = t, this.St = e, this.u = s, this.Pt = n, this.onreceive = null, this.onclose = null } async connect(t, s) { if (w.isRequired(t, "url"), w.isRequired(s, "transferFormat"), w.isIn(s, O, "transferFormat"), this.u.log(e.Trace, "(SSE transport) Connecting."), this.It = t, this.St) { const e = await this.St(); e && (t += (t.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(e)}`) } return new Promise(((n, i) => { let r, o = !1; if (s === O.Text) { if (g.isBrowser || g.isWebWorker) r = new this.Pt.EventSource(t, { withCredentials: this.Pt.withCredentials }); else { const e = this.$.getCookieString(t), s = {}; s.Cookie = e; const [n, i] = $(); s[n] = i, r = new this.Pt.EventSource(t, { withCredentials: this.Pt.withCredentials, headers: { ...s, ...this.Pt.headers } }) } try { r.onmessage = t => { if (this.onreceive) try { this.u.log(e.Trace, `(SSE transport) data received. ${m(t.data, this.Pt.logMessageContent)}.`), this.onreceive(t.data) } catch (t) { return void this.Ut(t) } }, r.onerror = t => { o ? this.Ut() : i(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled.")) }, r.onopen = () => { this.u.log(e.Information, `SSE connected to ${this.It}`), this.Lt = r, o = !0, n() } } catch (t) { return void i(t) } } else i(new Error("The Server-Sent Events transport only supports the 'Text' transfer format")) })) } async send(t) { return this.Lt ? b(this.u, "SSE", this.$, this.It, this.St, t, this.Pt) : Promise.reject(new Error("Cannot send until the transport is connected")) } stop() { return this.Ut(), Promise.resolve() } Ut(t) { this.Lt && (this.Lt.close(), this.Lt = void 0, this.onclose && this.onclose(t)) } } class X { constructor(t, e, s, n, i, r) { this.u = s, this.St = e, this.Nt = n, this.qt = i, this.$ = t, this.onreceive = null, this.onclose = null, this.Mt = r } async connect(t, s) { if (w.isRequired(t, "url"), w.isRequired(s, "transferFormat"), w.isIn(s, O, "transferFormat"), this.u.log(e.Trace, "(WebSockets transport) Connecting."), this.St) { const e = await this.St(); e && (t += (t.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(e)}`) } return new Promise(((n, i) => { let r; t = t.replace(/^http/, "ws"); const o = this.$.getCookieString(t); let h = !1; if (g.isNode) { const e = {}, [s, n] = $(); e[s] = n, o && (e[M.Cookie] = `${o}`), r = new this.qt(t, void 0, { headers: { ...e, ...this.Mt } }) } r || (r = new this.qt(t)), s === O.Binary && (r.binaryType = "arraybuffer"), r.onopen = s => { this.u.log(e.Information, `WebSocket connected to ${t}.`), this.Wt = r, h = !0, n() }, r.onerror = t => { let s = null; s = "undefined" != typeof ErrorEvent && t instanceof ErrorEvent ? t.error : "There was an error with the transport", this.u.log(e.Information, `(WebSockets transport) ${s}.`) }, r.onmessage = t => { if (this.u.log(e.Trace, `(WebSockets transport) data received. ${m(t.data, this.Nt)}.`), this.onreceive) try { this.onreceive(t.data) } catch (t) { return void this.Ut(t) } }, r.onclose = t => { if (h) this.Ut(t); else { let e = null; e = "undefined" != typeof ErrorEvent && t instanceof ErrorEvent ? t.error : "WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.", i(new Error(e)) } } })) } send(t) { return this.Wt && this.Wt.readyState === this.qt.OPEN ? (this.u.log(e.Trace, `(WebSockets transport) sending data. ${m(t, this.Nt)}.`), this.Wt.send(t), Promise.resolve()) : Promise.reject("WebSocket is not in the OPEN state") } stop() { return this.Wt && this.Ut(void 0), Promise.resolve() } Ut(t) { this.Wt && (this.Wt.onclose = () => { }, this.Wt.onmessage = () => { }, this.Wt.onerror = () => { }, this.Wt.close(), this.Wt = void 0), this.u.log(e.Trace, "(WebSockets transport) socket closed."), this.onclose && (!this.Ot(t) || !1 !== t.wasClean && 1e3 === t.code ? t instanceof Error ? this.onclose(t) : this.onclose() : this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason || "no reason given"}).`))) } Ot(t) { return t && "boolean" == typeof t.wasClean && "number" == typeof t.code } } class J { constructor(t, s = {}) { var n; if (this.jt = () => { }, this.features = {}, this.Ft = 1, w.isRequired(t, "url"), this.u = void 0 === (n = s.logger) ? new E(e.Information) : null === n ? f.instance : void 0 !== n.log ? n : new E(n), this.baseUrl = this.Bt(t), (s = s || {}).logMessageContent = void 0 !== s.logMessageContent && s.logMessageContent, "boolean" != typeof s.withCredentials && void 0 !== s.withCredentials) throw new Error("withCredentials option was not a 'boolean' or 'undefined' value"); s.withCredentials = void 0 === s.withCredentials || s.withCredentials, s.timeout = void 0 === s.timeout ? 1e5 : s.timeout; let i = null, r = null; if (g.isNode) { const t = require; i = t("ws"), r = t("eventsource") } g.isNode || "undefined" == typeof WebSocket || s.WebSocket ? g.isNode && !s.WebSocket && i && (s.WebSocket = i) : s.WebSocket = WebSocket, g.isNode || "undefined" == typeof EventSource || s.EventSource ? g.isNode && !s.EventSource && void 0 !== r && (s.EventSource = r) : s.EventSource = EventSource, this.$ = s.httpClient || new H(this.u), this.q = "Disconnected", this.M = !1, this.Pt = s, this.onreceive = null, this.onclose = null } async start(t) { if (t = t || O.Binary, w.isIn(t, O, "transferFormat"), this.u.log(e.Debug, `Starting connection with transfer format '${O[t]}'.`), "Disconnected" !== this.q) return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state.")); if (this.q = "Connecting", this.Xt = this.F(t), await this.Xt, "Disconnecting" === this.q) { const t = "Failed to start the HttpConnection before stop() was called."; return this.u.log(e.Error, t), await this.tt, Promise.reject(new Error(t)) } if ("Connected" !== this.q) { const t = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!"; return this.u.log(e.Error, t), Promise.reject(new Error(t)) } this.M = !0 } send(t) { return "Connected" !== this.q ? Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")) : (this.Jt || (this.Jt = new z(this.transport)), this.Jt.send(t)) } async stop(t) { return "Disconnected" === this.q ? (this.u.log(e.Debug, `Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`), Promise.resolve()) : "Disconnecting" === this.q ? (this.u.log(e.Debug, `Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`), this.tt) : (this.q = "Disconnecting", this.tt = new Promise((t => { this.jt = t })), await this.et(t), void await this.tt) } async et(t) { this.zt = t; try { await this.Xt } catch (t) { } if (this.transport) { try { await this.transport.stop() } catch (t) { this.u.log(e.Error, `HttpConnection.transport.stop() threw error '${t}'.`), this.Vt() } this.transport = void 0 } else this.u.log(e.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.") } async F(t) { let s = this.baseUrl; this.St = this.Pt.accessTokenFactory; try { if (this.Pt.skipNegotiation) { if (this.Pt.transport !== W.WebSockets) throw new Error("Negotiation can only be skipped when using the WebSocket transport directly."); this.transport = this.Gt(W.WebSockets), await this.Kt(s, t) } else { let e = null, n = 0; do { if (e = await this.Qt(s), "Disconnecting" === this.q || "Disconnected" === this.q) throw new Error("The connection was stopped during negotiation."); if (e.error) throw new Error(e.error); if (e.ProtocolVersion) throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."); if (e.url && (s = e.url), e.accessToken) { const t = e.accessToken; this.St = () => t } n++ } while (e.url && n < 100); if (100 === n && e.url) throw new Error("Negotiate redirection limit exceeded."); await this.Yt(s, this.Pt.transport, e, t) } this.transport instanceof F && (this.features.inherentKeepAlive = !0), "Connecting" === this.q && (this.u.log(e.Debug, "The HttpConnection connected successfully."), this.q = "Connected") } catch (t) { return this.u.log(e.Error, "Failed to start the connection: " + t), this.q = "Disconnected", this.transport = void 0, this.jt(), Promise.reject(t) } } async Qt(t) { const s = {}; if (this.St) { const t = await this.St(); t && (s[M.Authorization] = `Bearer ${t}`) } const [i, r] = $(); s[i] = r; const o = this.Zt(t); this.u.log(e.Debug, `Sending negotiation request: ${o}.`); try { const t = await this.$.post(o, { content: "", headers: { ...s, ...this.Pt.headers }, timeout: this.Pt.timeout, withCredentials: this.Pt.withCredentials }); if (200 !== t.statusCode) return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`)); const e = JSON.parse(t.content); return (!e.negotiateVersion || e.negotiateVersion < 1) && (e.connectionToken = e.connectionId), e } catch (t) { let s = "Failed to complete negotiation with the server: " + t; return t instanceof n && 404 === t.statusCode && (s += " Either this is not a SignalR endpoint or there is a proxy blocking the connection."), this.u.log(e.Error, s), Promise.reject(new a(s)) } } te(t, e) { return e ? t + (-1 === t.indexOf("?") ? "?" : "&") + `id=${e}` : t } async Yt(t, s, n, i) { let r = this.te(t, n.connectionToken); if (this.ee(s)) return this.u.log(e.Debug, "Connection was provided an instance of ITransport, using that directly."), this.transport = s, await this.Kt(r, i), void (this.connectionId = n.connectionId); const o = [], h = n.availableTransports || []; let a = n; for (const n of h) { const h = this.se(n, s, i); if (h instanceof Error) o.push(`${n.transport} failed:`), o.push(h); else if (this.ee(h)) { if (this.transport = h, !a) { try { a = await this.Qt(t) } catch (t) { return Promise.reject(t) } r = this.te(t, a.connectionToken) } try { return await this.Kt(r, i), void (this.connectionId = a.connectionId) } catch (t) { if (this.u.log(e.Error, `Failed to start the transport '${n.transport}': ${t}`), a = void 0, o.push(new c(`${n.transport} failed: ${t}`, W[n.transport])), "Connecting" !== this.q) { const t = "Failed to select transport before stop() was called."; return this.u.log(e.Debug, t), Promise.reject(new Error(t)) } } } } return o.length > 0 ? Promise.reject(new l(`Unable to connect to the server with any of the available transports. ${o.join(" ")}`, o)) : Promise.reject(new Error("None of the transports supported by the client are supported by the server.")) } Gt(t) { switch (t) { case W.WebSockets: if (!this.Pt.WebSocket) throw new Error("'WebSocket' is not supported in your environment."); return new X(this.$, this.St, this.u, this.Pt.logMessageContent, this.Pt.WebSocket, this.Pt.headers || {}); case W.ServerSentEvents: if (!this.Pt.EventSource) throw new Error("'EventSource' is not supported in your environment."); return new B(this.$, this.St, this.u, this.Pt); case W.LongPolling: return new F(this.$, this.St, this.u, this.Pt); default: throw new Error(`Unknown transport: ${t}.`) } } Kt(t, e) { return this.transport.onreceive = this.onreceive, this.transport.onclose = t => this.Vt(t), this.transport.connect(t, e) } se(t, s, n) { const i = W[t.transport]; if (null == i) return this.u.log(e.Debug, `Skipping transport '${t.transport}' because it is not supported by this client.`), new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`); if (!function (t, e) { return !t || 0 != (e & t) }(s, i)) return this.u.log(e.Debug, `Skipping transport '${W[i]}' because it was disabled by the client.`), new h(`'${W[i]}' is disabled by the client.`, i); if (!(t.transferFormats.map((t => O[t])).indexOf(n) >= 0)) return this.u.log(e.Debug, `Skipping transport '${W[i]}' because it does not support the requested transfer format '${O[n]}'.`), new Error(`'${W[i]}' does not support ${O[n]}.`); if (i === W.WebSockets && !this.Pt.WebSocket || i === W.ServerSentEvents && !this.Pt.EventSource) return this.u.log(e.Debug, `Skipping transport '${W[i]}' because it is not supported in your environment.'`), new o(`'${W[i]}' is not supported in your environment.`, i); this.u.log(e.Debug, `Selecting transport '${W[i]}'.`); try { return this.Gt(i) } catch (t) { return t } } ee(t) { return t && "object" == typeof t && "connect" in t } Vt(t) { if (this.u.log(e.Debug, `HttpConnection.stopConnection(${t}) called while in state ${this.q}.`), this.transport = void 0, t = this.zt || t, this.zt = void 0, "Disconnected" !== this.q) { if ("Connecting" === this.q) throw this.u.log(e.Warning, `Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`), new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`); if ("Disconnecting" === this.q && this.jt(), t ? this.u.log(e.Error, `Connection disconnected with error '${t}'.`) : this.u.log(e.Information, "Connection disconnected."), this.Jt && (this.Jt.stop().catch((t => { this.u.log(e.Error, `TransportSendQueue.stop() threw error '${t}'.`) })), this.Jt = void 0), this.connectionId = void 0, this.q = "Disconnected", this.M) { this.M = !1; try { this.onclose && this.onclose(t) } catch (s) { this.u.log(e.Error, `HttpConnection.onclose(${t}) threw error '${s}'.`) } } } else this.u.log(e.Debug, `Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`) } Bt(t) { if (0 === t.lastIndexOf("https://", 0) || 0 === t.lastIndexOf("http://", 0)) return t; if (!g.isBrowser || !window.document) throw new Error(`Cannot resolve '${t}'.`); const s = window.document.createElement("a"); return s.href = t, this.u.log(e.Information, `Normalizing '${t}' to '${s.href}'.`), s.href } Zt(t) { const e = t.indexOf("?"); let s = t.substring(0, -1 === e ? t.length : e); return "/" !== s[s.length - 1] && (s += "/"), s += "negotiate", s += -1 === e ? "" : t.substring(e), -1 === s.indexOf("negotiateVersion") && (s += -1 === e ? "?" : "&", s += "negotiateVersion=" + this.Ft), s } } class z { constructor(t) { this.ne = t, this.ie = [], this.re = !0, this.oe = new V, this.he = new V, this.ce = this.ae() } send(t) { return this.le(t), this.he || (this.he = new V), this.he.promise } stop() { return this.re = !1, this.oe.resolve(), this.ce } le(t) { if (this.ie.length && typeof this.ie[0] != typeof t) throw new Error(`Expected data to be of type ${typeof this.ie} but was of type ${typeof t}`); this.ie.push(t), this.oe.resolve() } async ae() { for (; ;) { if (await this.oe.promise, !this.re) { this.he && this.he.reject("Connection stopped."); break } this.oe = new V; const t = this.he; this.he = void 0; const e = "string" == typeof this.ie[0] ? this.ie.join("") : z.ue(this.ie); this.ie.length = 0; try { await this.ne.send(e), t.resolve() } catch (e) { t.reject(e) } } } static ue(t) { const e = t.map((t => t.byteLength)).reduce(((t, e) => t + e)), s = new Uint8Array(e); let n = 0; for (const e of t) s.set(new Uint8Array(e), n), n += e.byteLength; return s.buffer } } class V { constructor() { this.promise = new Promise(((t, e) => [this.de, this.fe] = [t, e])) } resolve() { this.de() } reject(t) { this.fe(t) } } class G { constructor() { this.name = "json", this.version = 1, this.transferFormat = O.Text } parseMessages(t, s) { if ("string" != typeof t) throw new Error("Invalid input for JSON hub protocol. Expected a string."); if (!t) return []; null === s && (s = f.instance); const n = D.parse(t), i = []; for (const t of n) { const n = JSON.parse(t); if ("number" != typeof n.type) throw new Error("Invalid payload."); switch (n.type) { case A.Invocation: this.pe(n); break; case A.StreamItem: this.we(n); break; case A.Completion: this.ge(n); break; case A.Ping: case A.Close: break; default: s.log(e.Information, "Unknown message type '" + n.type + "' ignored."); continue }i.push(n) } return i } writeMessage(t) { return D.write(JSON.stringify(t)) } pe(t) { this.me(t.target, "Invalid payload for Invocation message."), void 0 !== t.invocationId && this.me(t.invocationId, "Invalid payload for Invocation message.") } we(t) { if (this.me(t.invocationId, "Invalid payload for StreamItem message."), void 0 === t.item) throw new Error("Invalid payload for StreamItem message.") } ge(t) { if (t.result && t.error) throw new Error("Invalid payload for Completion message."); !t.result && t.error && this.me(t.error, "Invalid payload for Completion message."), this.me(t.invocationId, "Invalid payload for Completion message.") } me(t, e) { if ("string" != typeof t || "" === t) throw new Error(e) } } const K = { trace: e.Trace, debug: e.Debug, info: e.Information, information: e.Information, warn: e.Warning, warning: e.Warning, error: e.Error, critical: e.Critical, none: e.None }; class Q { configureLogging(t) { if (w.isRequired(t, "logging"), void 0 !== t.log) this.logger = t; else if ("string" == typeof t) { const e = function (t) { const e = K[t.toLowerCase()]; if (void 0 !== e) return e; throw new Error(`Unknown log level: ${t}`) }(t); this.logger = new E(e) } else this.logger = new E(t); return this } withUrl(t, e) { return w.isRequired(t, "url"), w.isNotEmpty(t, "url"), this.url = t, this.httpConnectionOptions = "object" == typeof e ? { ...this.httpConnectionOptions, ...e } : { ...this.httpConnectionOptions, transport: e }, this } withHubProtocol(t) { return w.isRequired(t, "protocol"), this.protocol = t, this } withAutomaticReconnect(t) { if (this.reconnectPolicy) throw new Error("A reconnectPolicy has already been set."); return t ? Array.isArray(t) ? this.reconnectPolicy = new q(t) : this.reconnectPolicy = t : this.reconnectPolicy = new q, this } build() { const t = this.httpConnectionOptions || {}; if (void 0 === t.logger && (t.logger = this.logger), !this.url) throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection."); const e = new J(this.url, t); return L.create(e, this.logger || f.instance, this.protocol || new G, this.reconnectPolicy) } } return Uint8Array.prototype.indexOf || Object.defineProperty(Uint8Array.prototype, "indexOf", { value: Array.prototype.indexOf, writable: !0 }), Uint8Array.prototype.slice || Object.defineProperty(Uint8Array.prototype, "slice", { value: function (t, e) { return new Uint8Array(Array.prototype.slice.call(this, t, e)) }, writable: !0 }), Uint8Array.prototype.forEach || Object.defineProperty(Uint8Array.prototype, "forEach", { value: Array.prototype.forEach, writable: !0 }), s })() }, "object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.signalR = e() : t.signalR = e(); +//# sourceMappingURL=signalr.js.map diff --git a/src/Lumina.Presentation.Web/wwwroot/libs/microsoft-signalr/signalr.min.js b/src/Lumina.Presentation.Web/wwwroot/libs/microsoft-signalr/signalr.min.js new file mode 100644 index 00000000..3bed86a1 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/libs/microsoft-signalr/signalr.min.js @@ -0,0 +1 @@ +var t, e; t = self, e = function () { return (() => { var t = { d: (e, n) => { for (var o in n) t.o(n, o) && !t.o(e, o) && Object.defineProperty(e, o, { enumerable: !0, get: n[o] }) } }; t.g = function () { if ("object" == typeof globalThis) return globalThis; try { return this || new Function("return this")() } catch (t) { if ("object" == typeof window) return window } }(), t.o = (t, e) => Object.prototype.hasOwnProperty.call(t, e), t.r = t => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "t", { value: !0 }) }; var e, n = {}; t.r(n), t.d(n, { AbortError: () => s, DefaultHttpClient: () => q, HttpClient: () => d, HttpError: () => o, HttpResponse: () => u, HttpTransportType: () => O, HubConnection: () => j, HubConnectionBuilder: () => Z, HubConnectionState: () => W, JsonHubProtocol: () => G, LogLevel: () => e, MessageType: () => H, NullLogger: () => p, Subject: () => L, TimeoutError: () => r, TransferFormat: () => _, VERSION: () => g }); class o extends Error { constructor(t, e) { const n = new.target.prototype; super(`${t}: Status code '${e}'`), this.statusCode = e, this.__proto__ = n } } class r extends Error { constructor(t = "A timeout occurred.") { const e = new.target.prototype; super(t), this.__proto__ = e } } class s extends Error { constructor(t = "An abort occurred.") { const e = new.target.prototype; super(t), this.__proto__ = e } } class i extends Error { constructor(t, e) { const n = new.target.prototype; super(t), this.transport = e, this.errorType = "UnsupportedTransportError", this.__proto__ = n } } class c extends Error { constructor(t, e) { const n = new.target.prototype; super(t), this.transport = e, this.errorType = "DisabledTransportError", this.__proto__ = n } } class a extends Error { constructor(t, e) { const n = new.target.prototype; super(t), this.transport = e, this.errorType = "FailedToStartTransportError", this.__proto__ = n } } class h extends Error { constructor(t) { const e = new.target.prototype; super(t), this.errorType = "FailedToNegotiateWithServerError", this.__proto__ = e } } class l extends Error { constructor(t, e) { const n = new.target.prototype; super(t), this.innerErrors = e, this.__proto__ = n } } class u { constructor(t, e, n) { this.statusCode = t, this.statusText = e, this.content = n } } class d { get(t, e) { return this.send({ ...e, method: "GET", url: t }) } post(t, e) { return this.send({ ...e, method: "POST", url: t }) } delete(t, e) { return this.send({ ...e, method: "DELETE", url: t }) } getCookieString(t) { return "" } } !function (t) { t[t.Trace = 0] = "Trace", t[t.Debug = 1] = "Debug", t[t.Information = 2] = "Information", t[t.Warning = 3] = "Warning", t[t.Error = 4] = "Error", t[t.Critical = 5] = "Critical", t[t.None = 6] = "None" }(e || (e = {})); class p { constructor() { } log(t, e) { } } p.instance = new p; const g = "6.0.1"; class f { static isRequired(t, e) { if (null == t) throw new Error(`The '${e}' argument is required.`) } static isNotEmpty(t, e) { if (!t || t.match(/^\s*$/)) throw new Error(`The '${e}' argument should not be empty.`) } static isIn(t, e, n) { if (!(t in e)) throw new Error(`Unknown ${n} value: ${t}.`) } } class w { static get isBrowser() { return "object" == typeof window } static get isWebWorker() { return "object" == typeof self && "importScripts" in self } static get isNode() { return !this.isBrowser && !this.isWebWorker } } function m(t, e) { let n = ""; return b(t) ? (n = `Binary data of length ${t.byteLength}`, e && (n += `. Content: '${function (t) { const e = new Uint8Array(t); let n = ""; return e.forEach((t => { n += `0x${t < 16 ? "0" : ""}${t.toString(16)} ` })), n.substr(0, n.length - 1) }(t)}'`)) : "string" == typeof t && (n = `String data of length ${t.length}`, e && (n += `. Content: '${t}'`)), n } function b(t) { return t && "undefined" != typeof ArrayBuffer && (t instanceof ArrayBuffer || t.constructor && "ArrayBuffer" === t.constructor.name) } async function y(t, n, o, r, s, i, c) { let a = {}; if (s) { const t = await s(); t && (a = { Authorization: `Bearer ${t}` }) } const [h, l] = S(); a[h] = l, t.log(e.Trace, `(${n} transport) sending data. ${m(i, c.logMessageContent)}.`); const u = b(i) ? "arraybuffer" : "text", d = await o.post(r, { content: i, headers: { ...a, ...c.headers }, responseType: u, timeout: c.timeout, withCredentials: c.withCredentials }); t.log(e.Trace, `(${n} transport) request complete. Response status: ${d.statusCode}.`) } class v { constructor(t, e) { this.i = t, this.h = e } dispose() { const t = this.i.observers.indexOf(this.h); t > -1 && this.i.observers.splice(t, 1), 0 === this.i.observers.length && this.i.cancelCallback && this.i.cancelCallback().catch((t => { })) } } class C { constructor(t) { this.l = t, this.out = console } log(t, n) { if (t >= this.l) { const o = `[${(new Date).toISOString()}] ${e[t]}: ${n}`; switch (t) { case e.Critical: case e.Error: this.out.error(o); break; case e.Warning: this.out.warn(o); break; case e.Information: this.out.info(o); break; default: this.out.log(o) } } } } function S() { let t = "X-SignalR-User-Agent"; return w.isNode && (t = "User-Agent"), [t, E(g, $(), w.isNode ? "NodeJS" : "Browser", T())] } function E(t, e, n, o) { let r = "Microsoft SignalR/"; const s = t.split("."); return r += `${s[0]}.${s[1]}`, r += ` (${t}; `, r += e && "" !== e ? `${e}; ` : "Unknown OS; ", r += `${n}`, r += o ? `; ${o}` : "; Unknown Runtime Version", r += ")", r } function $() { if (!w.isNode) return ""; switch (process.platform) { case "win32": return "Windows NT"; case "darwin": return "macOS"; case "linux": return "Linux"; default: return process.platform } } function T() { if (w.isNode) return process.versions.node } function k(t) { return t.stack ? t.stack : t.message ? t.message : `${t}` } class P extends d { constructor(e) { if (super(), this.u = e, "undefined" == typeof fetch) { const t = require; this.p = new (t("tough-cookie").CookieJar), this.m = t("node-fetch"), this.m = t("fetch-cookie")(this.m, this.p) } else this.m = fetch.bind(function () { if ("undefined" != typeof globalThis) return globalThis; if ("undefined" != typeof self) return self; if ("undefined" != typeof window) return window; if (void 0 !== t.g) return t.g; throw new Error("could not find global") }()); if ("undefined" == typeof AbortController) { const t = require; this.v = t("abort-controller") } else this.v = AbortController } async send(t) { if (t.abortSignal && t.abortSignal.aborted) throw new s; if (!t.method) throw new Error("No method defined."); if (!t.url) throw new Error("No url defined."); const n = new this.v; let i; t.abortSignal && (t.abortSignal.onabort = () => { n.abort(), i = new s }); let c, a = null; if (t.timeout) { const o = t.timeout; a = setTimeout((() => { n.abort(), this.u.log(e.Warning, "Timeout from HTTP request."), i = new r }), o) } try { c = await this.m(t.url, { body: t.content, cache: "no-cache", credentials: !0 === t.withCredentials ? "include" : "same-origin", headers: { "Content-Type": "text/plain;charset=UTF-8", "X-Requested-With": "XMLHttpRequest", ...t.headers }, method: t.method, mode: "cors", redirect: "follow", signal: n.signal }) } catch (t) { if (i) throw i; throw this.u.log(e.Warning, `Error from HTTP request. ${t}.`), t } finally { a && clearTimeout(a), t.abortSignal && (t.abortSignal.onabort = null) } if (!c.ok) { const t = await I(c, "text"); throw new o(t || c.statusText, c.status) } const h = I(c, t.responseType), l = await h; return new u(c.status, c.statusText, l) } getCookieString(t) { let e = ""; return w.isNode && this.p && this.p.getCookies(t, ((t, n) => e = n.join("; "))), e } } function I(t, e) { let n; switch (e) { case "arraybuffer": n = t.arrayBuffer(); break; case "text": n = t.text(); break; case "blob": case "document": case "json": throw new Error(`${e} is not supported.`); default: n = t.text() }return n } class D extends d { constructor(t) { super(), this.u = t } send(t) { return t.abortSignal && t.abortSignal.aborted ? Promise.reject(new s) : t.method ? t.url ? new Promise(((n, i) => { const c = new XMLHttpRequest; c.open(t.method, t.url, !0), c.withCredentials = void 0 === t.withCredentials || t.withCredentials, c.setRequestHeader("X-Requested-With", "XMLHttpRequest"), c.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); const a = t.headers; a && Object.keys(a).forEach((t => { c.setRequestHeader(t, a[t]) })), t.responseType && (c.responseType = t.responseType), t.abortSignal && (t.abortSignal.onabort = () => { c.abort(), i(new s) }), t.timeout && (c.timeout = t.timeout), c.onload = () => { t.abortSignal && (t.abortSignal.onabort = null), c.status >= 200 && c.status < 300 ? n(new u(c.status, c.statusText, c.response || c.responseText)) : i(new o(c.response || c.responseText || c.statusText, c.status)) }, c.onerror = () => { this.u.log(e.Warning, `Error from HTTP request. ${c.status}: ${c.statusText}.`), i(new o(c.statusText, c.status)) }, c.ontimeout = () => { this.u.log(e.Warning, "Timeout from HTTP request."), i(new r) }, c.send(t.content || "") })) : Promise.reject(new Error("No url defined.")) : Promise.reject(new Error("No method defined.")) } } class q extends d { constructor(t) { if (super(), "undefined" != typeof fetch || w.isNode) this.$ = new P(t); else { if ("undefined" == typeof XMLHttpRequest) throw new Error("No usable HttpClient found."); this.$ = new D(t) } } send(t) { return t.abortSignal && t.abortSignal.aborted ? Promise.reject(new s) : t.method ? t.url ? this.$.send(t) : Promise.reject(new Error("No url defined.")) : Promise.reject(new Error("No method defined.")) } getCookieString(t) { return this.$.getCookieString(t) } } class R { static write(t) { return `${t}${R.RecordSeparator}` } static parse(t) { if (t[t.length - 1] !== R.RecordSeparator) throw new Error("Message is incomplete."); const e = t.split(R.RecordSeparator); return e.pop(), e } } R.RecordSeparatorCode = 30, R.RecordSeparator = String.fromCharCode(R.RecordSeparatorCode); class x { writeHandshakeRequest(t) { return R.write(JSON.stringify(t)) } parseHandshakeResponse(t) { let e, n; if (b(t)) { const o = new Uint8Array(t), r = o.indexOf(R.RecordSeparatorCode); if (-1 === r) throw new Error("Message is incomplete."); const s = r + 1; e = String.fromCharCode.apply(null, Array.prototype.slice.call(o.slice(0, s))), n = o.byteLength > s ? o.slice(s).buffer : null } else { const o = t, r = o.indexOf(R.RecordSeparator); if (-1 === r) throw new Error("Message is incomplete."); const s = r + 1; e = o.substring(0, s), n = o.length > s ? o.substring(s) : null } const o = R.parse(e), r = JSON.parse(o[0]); if (r.type) throw new Error("Expected a handshake response from the server."); return [n, r] } } var H, W; !function (t) { t[t.Invocation = 1] = "Invocation", t[t.StreamItem = 2] = "StreamItem", t[t.Completion = 3] = "Completion", t[t.StreamInvocation = 4] = "StreamInvocation", t[t.CancelInvocation = 5] = "CancelInvocation", t[t.Ping = 6] = "Ping", t[t.Close = 7] = "Close" }(H || (H = {})); class L { constructor() { this.observers = [] } next(t) { for (const e of this.observers) e.next(t) } error(t) { for (const e of this.observers) e.error && e.error(t) } complete() { for (const t of this.observers) t.complete && t.complete() } subscribe(t) { return this.observers.push(t), new v(this, t) } } !function (t) { t.Disconnected = "Disconnected", t.Connecting = "Connecting", t.Connected = "Connected", t.Disconnecting = "Disconnecting", t.Reconnecting = "Reconnecting" }(W || (W = {})); class j { constructor(t, n, o, r) { this.C = 0, this.S = () => { this.u.log(e.Warning, "The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep") }, f.isRequired(t, "connection"), f.isRequired(n, "logger"), f.isRequired(o, "protocol"), this.serverTimeoutInMilliseconds = 3e4, this.keepAliveIntervalInMilliseconds = 15e3, this.u = n, this.k = o, this.connection = t, this.P = r, this.T = new x, this.connection.onreceive = t => this.I(t), this.connection.onclose = t => this._(t), this.H = {}, this.D = {}, this.A = [], this.R = [], this.U = [], this.L = 0, this.N = !1, this.q = W.Disconnected, this.M = !1, this.W = this.k.writeMessage({ type: H.Ping }) } static create(t, e, n, o) { return new j(t, e, n, o) } get state() { return this.q } get connectionId() { return this.connection && this.connection.connectionId || null } get baseUrl() { return this.connection.baseUrl || "" } set baseUrl(t) { if (this.q !== W.Disconnected && this.q !== W.Reconnecting) throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url."); if (!t) throw new Error("The HubConnection url must be a valid url."); this.connection.baseUrl = t } start() { return this.O = this.j(), this.O } async j() { if (this.q !== W.Disconnected) return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state.")); this.q = W.Connecting, this.u.log(e.Debug, "Starting HubConnection."); try { await this.F(), w.isBrowser && document && document.addEventListener("freeze", this.S), this.q = W.Connected, this.M = !0, this.u.log(e.Debug, "HubConnection connected successfully.") } catch (t) { return this.q = W.Disconnected, this.u.log(e.Debug, `HubConnection failed to start successfully because of error '${t}'.`), Promise.reject(t) } } async F() { this.B = void 0, this.N = !1; const t = new Promise(((t, e) => { this.X = t, this.J = e })); await this.connection.start(this.k.transferFormat); try { const n = { protocol: this.k.name, version: this.k.version }; if (this.u.log(e.Debug, "Sending handshake request."), await this.V(this.T.writeHandshakeRequest(n)), this.u.log(e.Information, `Using HubProtocol '${this.k.name}'.`), this.G(), this.K(), this.Y(), await t, this.B) throw this.B } catch (t) { throw this.u.log(e.Debug, `Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`), this.G(), this.Z(), await this.connection.stop(t), t } } async stop() { const t = this.O; this.tt = this.et(), await this.tt; try { await t } catch (t) { } } et(t) { return this.q === W.Disconnected ? (this.u.log(e.Debug, `Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`), Promise.resolve()) : this.q === W.Disconnecting ? (this.u.log(e.Debug, `Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`), this.tt) : (this.q = W.Disconnecting, this.u.log(e.Debug, "Stopping HubConnection."), this.st ? (this.u.log(e.Debug, "Connection stopped during reconnect delay. Done reconnecting."), clearTimeout(this.st), this.st = void 0, this.nt(), Promise.resolve()) : (this.G(), this.Z(), this.B = t || new Error("The connection was stopped before the hub handshake could complete."), this.connection.stop(t))) } stream(t, ...e) { const [n, o] = this.it(e), r = this.rt(t, e, o); let s; const i = new L; return i.cancelCallback = () => { const t = this.ot(r.invocationId); return delete this.H[r.invocationId], s.then((() => this.ht(t))) }, this.H[r.invocationId] = (t, e) => { e ? i.error(e) : t && (t.type === H.Completion ? t.error ? i.error(new Error(t.error)) : i.complete() : i.next(t.item)) }, s = this.ht(r).catch((t => { i.error(t), delete this.H[r.invocationId] })), this.ct(n, s), i } V(t) { return this.Y(), this.connection.send(t) } ht(t) { return this.V(this.k.writeMessage(t)) } send(t, ...e) { const [n, o] = this.it(e), r = this.ht(this.at(t, e, !0, o)); return this.ct(n, r), r } invoke(t, ...e) { const [n, o] = this.it(e), r = this.at(t, e, !1, o); return new Promise(((t, e) => { this.H[r.invocationId] = (n, o) => { o ? e(o) : n && (n.type === H.Completion ? n.error ? e(new Error(n.error)) : t(n.result) : e(new Error(`Unexpected message type: ${n.type}`))) }; const o = this.ht(r).catch((t => { e(t), delete this.H[r.invocationId] })); this.ct(n, o) })) } on(t, e) { t && e && (t = t.toLowerCase(), this.D[t] || (this.D[t] = []), -1 === this.D[t].indexOf(e) && this.D[t].push(e)) } off(t, e) { if (!t) return; t = t.toLowerCase(); const n = this.D[t]; if (n) if (e) { const o = n.indexOf(e); -1 !== o && (n.splice(o, 1), 0 === n.length && delete this.D[t]) } else delete this.D[t] } onclose(t) { t && this.A.push(t) } onreconnecting(t) { t && this.R.push(t) } onreconnected(t) { t && this.U.push(t) } I(t) { if (this.G(), this.N || (t = this.lt(t), this.N = !0), t) { const n = this.k.parseMessages(t, this.u); for (const o of n) switch (o.type) { case H.Invocation: this.ut(o); break; case H.StreamItem: case H.Completion: { const n = this.H[o.invocationId]; if (n) { o.type === H.Completion && delete this.H[o.invocationId]; try { n(o) } catch (t) { this.u.log(e.Error, `Stream callback threw error: ${k(t)}`) } } break } case H.Ping: break; case H.Close: { this.u.log(e.Information, "Close message received from server."); const t = o.error ? new Error("Server returned an error on close: " + o.error) : void 0; !0 === o.allowReconnect ? this.connection.stop(t) : this.tt = this.et(t); break } default: this.u.log(e.Warning, `Invalid message type: ${o.type}.`) } } this.K() } lt(t) { let n, o; try { [o, n] = this.T.parseHandshakeResponse(t) } catch (t) { const n = "Error parsing handshake response: " + t; this.u.log(e.Error, n); const o = new Error(n); throw this.J(o), o } if (n.error) { const t = "Server returned handshake error: " + n.error; this.u.log(e.Error, t); const o = new Error(t); throw this.J(o), o } return this.u.log(e.Debug, "Server handshake complete."), this.X(), o } Y() { this.connection.features.inherentKeepAlive || (this.C = (new Date).getTime() + this.keepAliveIntervalInMilliseconds, this.Z()) } K() { if (!(this.connection.features && this.connection.features.inherentKeepAlive || (this.dt = setTimeout((() => this.serverTimeout()), this.serverTimeoutInMilliseconds), void 0 !== this.ft))) { let t = this.C - (new Date).getTime(); t < 0 && (t = 0), this.ft = setTimeout((async () => { if (this.q === W.Connected) try { await this.V(this.W) } catch { this.Z() } }), t) } } serverTimeout() { this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")) } ut(t) { const n = this.D[t.target.toLowerCase()]; if (n) { try { n.forEach((e => e.apply(this, t.arguments))) } catch (n) { this.u.log(e.Error, `A callback for the method ${t.target.toLowerCase()} threw error '${n}'.`) } if (t.invocationId) { const t = "Server requested a response, which is not supported in this version of the client."; this.u.log(e.Error, t), this.tt = this.et(new Error(t)) } } else this.u.log(e.Warning, `No client method with the name '${t.target}' found.`) } _(t) { this.u.log(e.Debug, `HubConnection.connectionClosed(${t}) called while in state ${this.q}.`), this.B = this.B || t || new Error("The underlying connection was closed before the hub handshake could complete."), this.X && this.X(), this.wt(t || new Error("Invocation canceled due to the underlying connection being closed.")), this.G(), this.Z(), this.q === W.Disconnecting ? this.nt(t) : this.q === W.Connected && this.P ? this.gt(t) : this.q === W.Connected && this.nt(t) } nt(t) { if (this.M) { this.q = W.Disconnected, this.M = !1, w.isBrowser && document && document.removeEventListener("freeze", this.S); try { this.A.forEach((e => e.apply(this, [t]))) } catch (n) { this.u.log(e.Error, `An onclose callback called with error '${t}' threw error '${n}'.`) } } } async gt(t) { const n = Date.now(); let o = 0, r = void 0 !== t ? t : new Error("Attempting to reconnect due to a unknown error."), s = this.yt(o++, 0, r); if (null === s) return this.u.log(e.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."), void this.nt(t); if (this.q = W.Reconnecting, t ? this.u.log(e.Information, `Connection reconnecting because of error '${t}'.`) : this.u.log(e.Information, "Connection reconnecting."), 0 !== this.R.length) { try { this.R.forEach((e => e.apply(this, [t]))) } catch (n) { this.u.log(e.Error, `An onreconnecting callback called with error '${t}' threw error '${n}'.`) } if (this.q !== W.Reconnecting) return void this.u.log(e.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.") } for (; null !== s;) { if (this.u.log(e.Information, `Reconnect attempt number ${o} will start in ${s} ms.`), await new Promise((t => { this.st = setTimeout(t, s) })), this.st = void 0, this.q !== W.Reconnecting) return void this.u.log(e.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting."); try { if (await this.F(), this.q = W.Connected, this.u.log(e.Information, "HubConnection reconnected successfully."), 0 !== this.U.length) try { this.U.forEach((t => t.apply(this, [this.connection.connectionId]))) } catch (t) { this.u.log(e.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`) } return } catch (t) { if (this.u.log(e.Information, `Reconnect attempt failed because of error '${t}'.`), this.q !== W.Reconnecting) return this.u.log(e.Debug, `Connection moved to the '${this.q}' from the reconnecting state during reconnect attempt. Done reconnecting.`), void (this.q === W.Disconnecting && this.nt()); r = t instanceof Error ? t : new Error(t.toString()), s = this.yt(o++, Date.now() - n, r) } } this.u.log(e.Information, `Reconnect retries have been exhausted after ${Date.now() - n} ms and ${o} failed attempts. Connection disconnecting.`), this.nt() } yt(t, n, o) { try { return this.P.nextRetryDelayInMilliseconds({ elapsedMilliseconds: n, previousRetryCount: t, retryReason: o }) } catch (o) { return this.u.log(e.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${n}) threw error '${o}'.`), null } } wt(t) { const n = this.H; this.H = {}, Object.keys(n).forEach((o => { const r = n[o]; try { r(null, t) } catch (n) { this.u.log(e.Error, `Stream 'error' callback called with '${t}' threw error: ${k(n)}`) } })) } Z() { this.ft && (clearTimeout(this.ft), this.ft = void 0) } G() { this.dt && clearTimeout(this.dt) } at(t, e, n, o) { if (n) return 0 !== o.length ? { arguments: e, streamIds: o, target: t, type: H.Invocation } : { arguments: e, target: t, type: H.Invocation }; { const n = this.L; return this.L++, 0 !== o.length ? { arguments: e, invocationId: n.toString(), streamIds: o, target: t, type: H.Invocation } : { arguments: e, invocationId: n.toString(), target: t, type: H.Invocation } } } ct(t, e) { if (0 !== t.length) { e || (e = Promise.resolve()); for (const n in t) t[n].subscribe({ complete: () => { e = e.then((() => this.ht(this.bt(n)))) }, error: t => { let o; o = t instanceof Error ? t.message : t && t.toString ? t.toString() : "Unknown error", e = e.then((() => this.ht(this.bt(n, o)))) }, next: t => { e = e.then((() => this.ht(this.vt(n, t)))) } }) } } it(t) { const e = [], n = []; for (let o = 0; o < t.length; o++) { const r = t[o]; if (this.Et(r)) { const s = this.L; this.L++, e[s] = r, n.push(s.toString()), t.splice(o, 1) } } return [e, n] } Et(t) { return t && t.subscribe && "function" == typeof t.subscribe } rt(t, e, n) { const o = this.L; return this.L++, 0 !== n.length ? { arguments: e, invocationId: o.toString(), streamIds: n, target: t, type: H.StreamInvocation } : { arguments: e, invocationId: o.toString(), target: t, type: H.StreamInvocation } } ot(t) { return { invocationId: t, type: H.CancelInvocation } } vt(t, e) { return { invocationId: t, item: e, type: H.StreamItem } } bt(t, e, n) { return e ? { error: e, invocationId: t, type: H.Completion } : { invocationId: t, result: n, type: H.Completion } } } const A = [0, 2e3, 1e4, 3e4, null]; class N { constructor(t) { this.$t = void 0 !== t ? [...t, null] : A } nextRetryDelayInMilliseconds(t) { return this.$t[t.previousRetryCount] } } class U { } var O, _; U.Authorization = "Authorization", U.Cookie = "Cookie", function (t) { t[t.None = 0] = "None", t[t.WebSockets = 1] = "WebSockets", t[t.ServerSentEvents = 2] = "ServerSentEvents", t[t.LongPolling = 4] = "LongPolling" }(O || (O = {})), function (t) { t[t.Text = 1] = "Text", t[t.Binary = 2] = "Binary" }(_ || (_ = {})); class M { constructor() { this.Ct = !1, this.onabort = null } abort() { this.Ct || (this.Ct = !0, this.onabort && this.onabort()) } get signal() { return this } get aborted() { return this.Ct } } class B { constructor(t, e, n, o) { this.$ = t, this.St = e, this.u = n, this.kt = new M, this.Pt = o, this.Tt = !1, this.onreceive = null, this.onclose = null } get pollAborted() { return this.kt.aborted } async connect(t, n) { if (f.isRequired(t, "url"), f.isRequired(n, "transferFormat"), f.isIn(n, _, "transferFormat"), this.It = t, this.u.log(e.Trace, "(LongPolling transport) Connecting."), n === _.Binary && "undefined" != typeof XMLHttpRequest && "string" != typeof (new XMLHttpRequest).responseType) throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); const [r, s] = S(), i = { [r]: s, ...this.Pt.headers }, c = { abortSignal: this.kt.signal, headers: i, timeout: 1e5, withCredentials: this.Pt.withCredentials }; n === _.Binary && (c.responseType = "arraybuffer"); const a = await this._t(); this.Ht(c, a); const h = `${t}&_=${Date.now()}`; this.u.log(e.Trace, `(LongPolling transport) polling: ${h}.`); const l = await this.$.get(h, c); 200 !== l.statusCode ? (this.u.log(e.Error, `(LongPolling transport) Unexpected response code: ${l.statusCode}.`), this.Dt = new o(l.statusText || "", l.statusCode), this.Tt = !1) : this.Tt = !0, this.xt = this.At(this.It, c) } async _t() { return this.St ? await this.St() : null } Ht(t, e) { t.headers || (t.headers = {}), e ? t.headers[U.Authorization] = `Bearer ${e}` : t.headers[U.Authorization] && delete t.headers[U.Authorization] } async At(t, n) { try { for (; this.Tt;) { const s = await this._t(); this.Ht(n, s); try { const r = `${t}&_=${Date.now()}`; this.u.log(e.Trace, `(LongPolling transport) polling: ${r}.`); const s = await this.$.get(r, n); 204 === s.statusCode ? (this.u.log(e.Information, "(LongPolling transport) Poll terminated by server."), this.Tt = !1) : 200 !== s.statusCode ? (this.u.log(e.Error, `(LongPolling transport) Unexpected response code: ${s.statusCode}.`), this.Dt = new o(s.statusText || "", s.statusCode), this.Tt = !1) : s.content ? (this.u.log(e.Trace, `(LongPolling transport) data received. ${m(s.content, this.Pt.logMessageContent)}.`), this.onreceive && this.onreceive(s.content)) : this.u.log(e.Trace, "(LongPolling transport) Poll timed out, reissuing.") } catch (t) { this.Tt ? t instanceof r ? this.u.log(e.Trace, "(LongPolling transport) Poll timed out, reissuing.") : (this.Dt = t, this.Tt = !1) : this.u.log(e.Trace, `(LongPolling transport) Poll errored after shutdown: ${t.message}`) } } } finally { this.u.log(e.Trace, "(LongPolling transport) Polling complete."), this.pollAborted || this.Rt() } } async send(t) { return this.Tt ? y(this.u, "LongPolling", this.$, this.It, this.St, t, this.Pt) : Promise.reject(new Error("Cannot send until the transport is connected")) } async stop() { this.u.log(e.Trace, "(LongPolling transport) Stopping polling."), this.Tt = !1, this.kt.abort(); try { await this.xt, this.u.log(e.Trace, `(LongPolling transport) sending DELETE request to ${this.It}.`); const t = {}, [n, o] = S(); t[n] = o; const r = { headers: { ...t, ...this.Pt.headers }, timeout: this.Pt.timeout, withCredentials: this.Pt.withCredentials }, s = await this._t(); this.Ht(r, s), await this.$.delete(this.It, r), this.u.log(e.Trace, "(LongPolling transport) DELETE request sent.") } finally { this.u.log(e.Trace, "(LongPolling transport) Stop finished."), this.Rt() } } Rt() { if (this.onclose) { let t = "(LongPolling transport) Firing onclose event."; this.Dt && (t += " Error: " + this.Dt), this.u.log(e.Trace, t), this.onclose(this.Dt) } } } class F { constructor(t, e, n, o) { this.$ = t, this.St = e, this.u = n, this.Pt = o, this.onreceive = null, this.onclose = null } async connect(t, n) { if (f.isRequired(t, "url"), f.isRequired(n, "transferFormat"), f.isIn(n, _, "transferFormat"), this.u.log(e.Trace, "(SSE transport) Connecting."), this.It = t, this.St) { const e = await this.St(); e && (t += (t.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(e)}`) } return new Promise(((o, r) => { let s, i = !1; if (n === _.Text) { if (w.isBrowser || w.isWebWorker) s = new this.Pt.EventSource(t, { withCredentials: this.Pt.withCredentials }); else { const e = this.$.getCookieString(t), n = {}; n.Cookie = e; const [o, r] = S(); n[o] = r, s = new this.Pt.EventSource(t, { withCredentials: this.Pt.withCredentials, headers: { ...n, ...this.Pt.headers } }) } try { s.onmessage = t => { if (this.onreceive) try { this.u.log(e.Trace, `(SSE transport) data received. ${m(t.data, this.Pt.logMessageContent)}.`), this.onreceive(t.data) } catch (t) { return void this.Ut(t) } }, s.onerror = t => { i ? this.Ut() : r(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled.")) }, s.onopen = () => { this.u.log(e.Information, `SSE connected to ${this.It}`), this.Lt = s, i = !0, o() } } catch (t) { return void r(t) } } else r(new Error("The Server-Sent Events transport only supports the 'Text' transfer format")) })) } async send(t) { return this.Lt ? y(this.u, "SSE", this.$, this.It, this.St, t, this.Pt) : Promise.reject(new Error("Cannot send until the transport is connected")) } stop() { return this.Ut(), Promise.resolve() } Ut(t) { this.Lt && (this.Lt.close(), this.Lt = void 0, this.onclose && this.onclose(t)) } } class J { constructor(t, e, n, o, r, s) { this.u = n, this.St = e, this.Nt = o, this.qt = r, this.$ = t, this.onreceive = null, this.onclose = null, this.Mt = s } async connect(t, n) { if (f.isRequired(t, "url"), f.isRequired(n, "transferFormat"), f.isIn(n, _, "transferFormat"), this.u.log(e.Trace, "(WebSockets transport) Connecting."), this.St) { const e = await this.St(); e && (t += (t.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(e)}`) } return new Promise(((o, r) => { let s; t = t.replace(/^http/, "ws"); const i = this.$.getCookieString(t); let c = !1; if (w.isNode) { const e = {}, [n, o] = S(); e[n] = o, i && (e[U.Cookie] = `${i}`), s = new this.qt(t, void 0, { headers: { ...e, ...this.Mt } }) } s || (s = new this.qt(t)), n === _.Binary && (s.binaryType = "arraybuffer"), s.onopen = n => { this.u.log(e.Information, `WebSocket connected to ${t}.`), this.Wt = s, c = !0, o() }, s.onerror = t => { let n = null; n = "undefined" != typeof ErrorEvent && t instanceof ErrorEvent ? t.error : "There was an error with the transport", this.u.log(e.Information, `(WebSockets transport) ${n}.`) }, s.onmessage = t => { if (this.u.log(e.Trace, `(WebSockets transport) data received. ${m(t.data, this.Nt)}.`), this.onreceive) try { this.onreceive(t.data) } catch (t) { return void this.Ut(t) } }, s.onclose = t => { if (c) this.Ut(t); else { let e = null; e = "undefined" != typeof ErrorEvent && t instanceof ErrorEvent ? t.error : "WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.", r(new Error(e)) } } })) } send(t) { return this.Wt && this.Wt.readyState === this.qt.OPEN ? (this.u.log(e.Trace, `(WebSockets transport) sending data. ${m(t, this.Nt)}.`), this.Wt.send(t), Promise.resolve()) : Promise.reject("WebSocket is not in the OPEN state") } stop() { return this.Wt && this.Ut(void 0), Promise.resolve() } Ut(t) { this.Wt && (this.Wt.onclose = () => { }, this.Wt.onmessage = () => { }, this.Wt.onerror = () => { }, this.Wt.close(), this.Wt = void 0), this.u.log(e.Trace, "(WebSockets transport) socket closed."), this.onclose && (!this.Ot(t) || !1 !== t.wasClean && 1e3 === t.code ? t instanceof Error ? this.onclose(t) : this.onclose() : this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason || "no reason given"}).`))) } Ot(t) { return t && "boolean" == typeof t.wasClean && "number" == typeof t.code } } class X { constructor(t, n = {}) { var o; if (this.jt = () => { }, this.features = {}, this.Ft = 1, f.isRequired(t, "url"), this.u = void 0 === (o = n.logger) ? new C(e.Information) : null === o ? p.instance : void 0 !== o.log ? o : new C(o), this.baseUrl = this.Bt(t), (n = n || {}).logMessageContent = void 0 !== n.logMessageContent && n.logMessageContent, "boolean" != typeof n.withCredentials && void 0 !== n.withCredentials) throw new Error("withCredentials option was not a 'boolean' or 'undefined' value"); n.withCredentials = void 0 === n.withCredentials || n.withCredentials, n.timeout = void 0 === n.timeout ? 1e5 : n.timeout; let r = null, s = null; if (w.isNode) { const t = require; r = t("ws"), s = t("eventsource") } w.isNode || "undefined" == typeof WebSocket || n.WebSocket ? w.isNode && !n.WebSocket && r && (n.WebSocket = r) : n.WebSocket = WebSocket, w.isNode || "undefined" == typeof EventSource || n.EventSource ? w.isNode && !n.EventSource && void 0 !== s && (n.EventSource = s) : n.EventSource = EventSource, this.$ = n.httpClient || new q(this.u), this.q = "Disconnected", this.M = !1, this.Pt = n, this.onreceive = null, this.onclose = null } async start(t) { if (t = t || _.Binary, f.isIn(t, _, "transferFormat"), this.u.log(e.Debug, `Starting connection with transfer format '${_[t]}'.`), "Disconnected" !== this.q) return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state.")); if (this.q = "Connecting", this.Xt = this.F(t), await this.Xt, "Disconnecting" === this.q) { const t = "Failed to start the HttpConnection before stop() was called."; return this.u.log(e.Error, t), await this.tt, Promise.reject(new Error(t)) } if ("Connected" !== this.q) { const t = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!"; return this.u.log(e.Error, t), Promise.reject(new Error(t)) } this.M = !0 } send(t) { return "Connected" !== this.q ? Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")) : (this.Jt || (this.Jt = new V(this.transport)), this.Jt.send(t)) } async stop(t) { return "Disconnected" === this.q ? (this.u.log(e.Debug, `Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`), Promise.resolve()) : "Disconnecting" === this.q ? (this.u.log(e.Debug, `Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`), this.tt) : (this.q = "Disconnecting", this.tt = new Promise((t => { this.jt = t })), await this.et(t), void await this.tt) } async et(t) { this.zt = t; try { await this.Xt } catch (t) { } if (this.transport) { try { await this.transport.stop() } catch (t) { this.u.log(e.Error, `HttpConnection.transport.stop() threw error '${t}'.`), this.Vt() } this.transport = void 0 } else this.u.log(e.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.") } async F(t) { let n = this.baseUrl; this.St = this.Pt.accessTokenFactory; try { if (this.Pt.skipNegotiation) { if (this.Pt.transport !== O.WebSockets) throw new Error("Negotiation can only be skipped when using the WebSocket transport directly."); this.transport = this.Gt(O.WebSockets), await this.Kt(n, t) } else { let e = null, o = 0; do { if (e = await this.Qt(n), "Disconnecting" === this.q || "Disconnected" === this.q) throw new Error("The connection was stopped during negotiation."); if (e.error) throw new Error(e.error); if (e.ProtocolVersion) throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."); if (e.url && (n = e.url), e.accessToken) { const t = e.accessToken; this.St = () => t } o++ } while (e.url && o < 100); if (100 === o && e.url) throw new Error("Negotiate redirection limit exceeded."); await this.Yt(n, this.Pt.transport, e, t) } this.transport instanceof B && (this.features.inherentKeepAlive = !0), "Connecting" === this.q && (this.u.log(e.Debug, "The HttpConnection connected successfully."), this.q = "Connected") } catch (t) { return this.u.log(e.Error, "Failed to start the connection: " + t), this.q = "Disconnected", this.transport = void 0, this.jt(), Promise.reject(t) } } async Qt(t) { const n = {}; if (this.St) { const t = await this.St(); t && (n[U.Authorization] = `Bearer ${t}`) } const [r, s] = S(); n[r] = s; const i = this.Zt(t); this.u.log(e.Debug, `Sending negotiation request: ${i}.`); try { const t = await this.$.post(i, { content: "", headers: { ...n, ...this.Pt.headers }, timeout: this.Pt.timeout, withCredentials: this.Pt.withCredentials }); if (200 !== t.statusCode) return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`)); const e = JSON.parse(t.content); return (!e.negotiateVersion || e.negotiateVersion < 1) && (e.connectionToken = e.connectionId), e } catch (t) { let n = "Failed to complete negotiation with the server: " + t; return t instanceof o && 404 === t.statusCode && (n += " Either this is not a SignalR endpoint or there is a proxy blocking the connection."), this.u.log(e.Error, n), Promise.reject(new h(n)) } } te(t, e) { return e ? t + (-1 === t.indexOf("?") ? "?" : "&") + `id=${e}` : t } async Yt(t, n, o, r) { let s = this.te(t, o.connectionToken); if (this.ee(n)) return this.u.log(e.Debug, "Connection was provided an instance of ITransport, using that directly."), this.transport = n, await this.Kt(s, r), void (this.connectionId = o.connectionId); const i = [], c = o.availableTransports || []; let h = o; for (const o of c) { const c = this.se(o, n, r); if (c instanceof Error) i.push(`${o.transport} failed:`), i.push(c); else if (this.ee(c)) { if (this.transport = c, !h) { try { h = await this.Qt(t) } catch (t) { return Promise.reject(t) } s = this.te(t, h.connectionToken) } try { return await this.Kt(s, r), void (this.connectionId = h.connectionId) } catch (t) { if (this.u.log(e.Error, `Failed to start the transport '${o.transport}': ${t}`), h = void 0, i.push(new a(`${o.transport} failed: ${t}`, O[o.transport])), "Connecting" !== this.q) { const t = "Failed to select transport before stop() was called."; return this.u.log(e.Debug, t), Promise.reject(new Error(t)) } } } } return i.length > 0 ? Promise.reject(new l(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`, i)) : Promise.reject(new Error("None of the transports supported by the client are supported by the server.")) } Gt(t) { switch (t) { case O.WebSockets: if (!this.Pt.WebSocket) throw new Error("'WebSocket' is not supported in your environment."); return new J(this.$, this.St, this.u, this.Pt.logMessageContent, this.Pt.WebSocket, this.Pt.headers || {}); case O.ServerSentEvents: if (!this.Pt.EventSource) throw new Error("'EventSource' is not supported in your environment."); return new F(this.$, this.St, this.u, this.Pt); case O.LongPolling: return new B(this.$, this.St, this.u, this.Pt); default: throw new Error(`Unknown transport: ${t}.`) } } Kt(t, e) { return this.transport.onreceive = this.onreceive, this.transport.onclose = t => this.Vt(t), this.transport.connect(t, e) } se(t, n, o) { const r = O[t.transport]; if (null == r) return this.u.log(e.Debug, `Skipping transport '${t.transport}' because it is not supported by this client.`), new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`); if (!function (t, e) { return !t || 0 != (e & t) }(n, r)) return this.u.log(e.Debug, `Skipping transport '${O[r]}' because it was disabled by the client.`), new c(`'${O[r]}' is disabled by the client.`, r); if (!(t.transferFormats.map((t => _[t])).indexOf(o) >= 0)) return this.u.log(e.Debug, `Skipping transport '${O[r]}' because it does not support the requested transfer format '${_[o]}'.`), new Error(`'${O[r]}' does not support ${_[o]}.`); if (r === O.WebSockets && !this.Pt.WebSocket || r === O.ServerSentEvents && !this.Pt.EventSource) return this.u.log(e.Debug, `Skipping transport '${O[r]}' because it is not supported in your environment.'`), new i(`'${O[r]}' is not supported in your environment.`, r); this.u.log(e.Debug, `Selecting transport '${O[r]}'.`); try { return this.Gt(r) } catch (t) { return t } } ee(t) { return t && "object" == typeof t && "connect" in t } Vt(t) { if (this.u.log(e.Debug, `HttpConnection.stopConnection(${t}) called while in state ${this.q}.`), this.transport = void 0, t = this.zt || t, this.zt = void 0, "Disconnected" !== this.q) { if ("Connecting" === this.q) throw this.u.log(e.Warning, `Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`), new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`); if ("Disconnecting" === this.q && this.jt(), t ? this.u.log(e.Error, `Connection disconnected with error '${t}'.`) : this.u.log(e.Information, "Connection disconnected."), this.Jt && (this.Jt.stop().catch((t => { this.u.log(e.Error, `TransportSendQueue.stop() threw error '${t}'.`) })), this.Jt = void 0), this.connectionId = void 0, this.q = "Disconnected", this.M) { this.M = !1; try { this.onclose && this.onclose(t) } catch (n) { this.u.log(e.Error, `HttpConnection.onclose(${t}) threw error '${n}'.`) } } } else this.u.log(e.Debug, `Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`) } Bt(t) { if (0 === t.lastIndexOf("https://", 0) || 0 === t.lastIndexOf("http://", 0)) return t; if (!w.isBrowser || !window.document) throw new Error(`Cannot resolve '${t}'.`); const n = window.document.createElement("a"); return n.href = t, this.u.log(e.Information, `Normalizing '${t}' to '${n.href}'.`), n.href } Zt(t) { const e = t.indexOf("?"); let n = t.substring(0, -1 === e ? t.length : e); return "/" !== n[n.length - 1] && (n += "/"), n += "negotiate", n += -1 === e ? "" : t.substring(e), -1 === n.indexOf("negotiateVersion") && (n += -1 === e ? "?" : "&", n += "negotiateVersion=" + this.Ft), n } } class V { constructor(t) { this.ne = t, this.ie = [], this.re = !0, this.oe = new z, this.he = new z, this.ce = this.ae() } send(t) { return this.le(t), this.he || (this.he = new z), this.he.promise } stop() { return this.re = !1, this.oe.resolve(), this.ce } le(t) { if (this.ie.length && typeof this.ie[0] != typeof t) throw new Error(`Expected data to be of type ${typeof this.ie} but was of type ${typeof t}`); this.ie.push(t), this.oe.resolve() } async ae() { for (; ;) { if (await this.oe.promise, !this.re) { this.he && this.he.reject("Connection stopped."); break } this.oe = new z; const t = this.he; this.he = void 0; const e = "string" == typeof this.ie[0] ? this.ie.join("") : V.ue(this.ie); this.ie.length = 0; try { await this.ne.send(e), t.resolve() } catch (e) { t.reject(e) } } } static ue(t) { const e = t.map((t => t.byteLength)).reduce(((t, e) => t + e)), n = new Uint8Array(e); let o = 0; for (const e of t) n.set(new Uint8Array(e), o), o += e.byteLength; return n.buffer } } class z { constructor() { this.promise = new Promise(((t, e) => [this.de, this.fe] = [t, e])) } resolve() { this.de() } reject(t) { this.fe(t) } } class G { constructor() { this.name = "json", this.version = 1, this.transferFormat = _.Text } parseMessages(t, n) { if ("string" != typeof t) throw new Error("Invalid input for JSON hub protocol. Expected a string."); if (!t) return []; null === n && (n = p.instance); const o = R.parse(t), r = []; for (const t of o) { const o = JSON.parse(t); if ("number" != typeof o.type) throw new Error("Invalid payload."); switch (o.type) { case H.Invocation: this.pe(o); break; case H.StreamItem: this.we(o); break; case H.Completion: this.ge(o); break; case H.Ping: case H.Close: break; default: n.log(e.Information, "Unknown message type '" + o.type + "' ignored."); continue }r.push(o) } return r } writeMessage(t) { return R.write(JSON.stringify(t)) } pe(t) { this.me(t.target, "Invalid payload for Invocation message."), void 0 !== t.invocationId && this.me(t.invocationId, "Invalid payload for Invocation message.") } we(t) { if (this.me(t.invocationId, "Invalid payload for StreamItem message."), void 0 === t.item) throw new Error("Invalid payload for StreamItem message.") } ge(t) { if (t.result && t.error) throw new Error("Invalid payload for Completion message."); !t.result && t.error && this.me(t.error, "Invalid payload for Completion message."), this.me(t.invocationId, "Invalid payload for Completion message.") } me(t, e) { if ("string" != typeof t || "" === t) throw new Error(e) } } const K = { trace: e.Trace, debug: e.Debug, info: e.Information, information: e.Information, warn: e.Warning, warning: e.Warning, error: e.Error, critical: e.Critical, none: e.None }; class Z { configureLogging(t) { if (f.isRequired(t, "logging"), void 0 !== t.log) this.logger = t; else if ("string" == typeof t) { const e = function (t) { const e = K[t.toLowerCase()]; if (void 0 !== e) return e; throw new Error(`Unknown log level: ${t}`) }(t); this.logger = new C(e) } else this.logger = new C(t); return this } withUrl(t, e) { return f.isRequired(t, "url"), f.isNotEmpty(t, "url"), this.url = t, this.httpConnectionOptions = "object" == typeof e ? { ...this.httpConnectionOptions, ...e } : { ...this.httpConnectionOptions, transport: e }, this } withHubProtocol(t) { return f.isRequired(t, "protocol"), this.protocol = t, this } withAutomaticReconnect(t) { if (this.reconnectPolicy) throw new Error("A reconnectPolicy has already been set."); return t ? Array.isArray(t) ? this.reconnectPolicy = new N(t) : this.reconnectPolicy = t : this.reconnectPolicy = new N, this } build() { const t = this.httpConnectionOptions || {}; if (void 0 === t.logger && (t.logger = this.logger), !this.url) throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection."); const e = new X(this.url, t); return j.create(e, this.logger || p.instance, this.protocol || new G, this.reconnectPolicy) } } return Uint8Array.prototype.indexOf || Object.defineProperty(Uint8Array.prototype, "indexOf", { value: Array.prototype.indexOf, writable: !0 }), Uint8Array.prototype.slice || Object.defineProperty(Uint8Array.prototype, "slice", { value: function (t, e) { return new Uint8Array(Array.prototype.slice.call(this, t, e)) }, writable: !0 }), Uint8Array.prototype.forEach || Object.defineProperty(Uint8Array.prototype, "forEach", { value: Array.prototype.forEach, writable: !0 }), n })() }, "object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.signalR = e() : t.signalR = e(); diff --git a/src/Lumina.sln b/src/Lumina.sln index 7273bc7b..742b2154 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -32,7 +32,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{ACD16983-F1BD-4A92-B282-95BA8C456F6A}" ProjectSection(SolutionItems) = preProject ..\docs\CONTRIBUTING.md = ..\docs\CONTRIBUTING.md - INSTALL.md = INSTALL.md + ..\docs\INSTALL.md = ..\docs\INSTALL.md ..\LICENSE.md = ..\LICENSE.md ..\README.md = ..\README.md ..\docs\SOURCES.md = ..\docs\SOURCES.md