mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 13:01:10 +00:00
Shows a connection-lost indicator when the SignalR connection closes.
This commit is contained in:
1 parent
0abf8d4aea
commit
e2c705d822
44 files changed
+1254
-78
No files matched your search
Binary file not shown.
Binary file not shown.
@@ -1,10 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Responses.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -66,6 +70,38 @@ public class AuthorizationService : IAuthorizationService
|
||||
string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
return new GetAuthorizationResponse(Guid.Empty, string.Empty, []);
|
||||
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken);
|
||||
try
|
||||
{
|
||||
return await _apiHttpClient.GetAsync<GetAuthorizationResponse>($"auth/get-authorization?userId={Uri.EscapeDataString(userId)}", cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HttpContext? httpContext = _httpContextAccessor.HttpContext;
|
||||
if (httpContext is null || httpContext.RequestAborted.IsCancellationRequested)
|
||||
throw;
|
||||
if (!IsApiOutage(exception))
|
||||
throw;
|
||||
bool isPageNavigation = (httpContext.Request.Headers.Accept.Count == 0 && httpContext.Request.Headers.Range.Count == 0)
|
||||
|| httpContext.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
|
||||
if (!isPageNavigation)
|
||||
throw;
|
||||
// The page is still rendered while the API is unreachable, with no role and no permissions, and the request is marked so
|
||||
// that the page reports the failure to the user. API requests keep propagating the failure as a JSON error.
|
||||
httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
return new GetAuthorizationResponse(Guid.Empty, string.Empty, []);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the exception means that the API could not answer, as opposed to an authorization answer from the API.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception thrown by the API call.</param>
|
||||
/// <returns><see langword="true"/> for a connection, timeout, circuit breaker or server failure; otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsApiOutage(Exception exception)
|
||||
{
|
||||
return exception is HttpRequestException or BrokenCircuitException or TaskCanceledException
|
||||
|| (exception is ApiException apiException && (int)apiException.HttpStatusCode >= 500);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Responses.UsersManagement;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Polly.CircuitBreaker;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
@@ -32,15 +37,51 @@ public class InitializationHandler : AuthorizationHandler<InitializationRequirem
|
||||
/// <param name="initializationRequirement">The initialization requirement to be evaluated.</param>
|
||||
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, InitializationRequirement initializationRequirement)
|
||||
{
|
||||
InitializationResponse result = await _apiHttpClient.GetAsync<InitializationResponse>("initialization/").ConfigureAwait(false);
|
||||
HttpContext? httpContext = authorizationHandlerContext.Resource as HttpContext;
|
||||
if (result.IsInitialized)
|
||||
try
|
||||
{
|
||||
// admin account was registered, remove this requirement from the session
|
||||
httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
|
||||
InitializationResponse result = await _apiHttpClient.GetAsync<InitializationResponse>("initialization/").ConfigureAwait(false);
|
||||
HttpContext? httpContext = authorizationHandlerContext.Resource as HttpContext;
|
||||
if (result.IsInitialized)
|
||||
{
|
||||
// admin account was registered, remove this requirement from the session
|
||||
httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
|
||||
authorizationHandlerContext.Succeed(initializationRequirement);
|
||||
}
|
||||
else // store in session that super admin setup is needed
|
||||
httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HttpContext? httpContext = GetPageNavigationDuringApiOutage(authorizationHandlerContext, exception);
|
||||
if (httpContext is null)
|
||||
throw;
|
||||
// The initialization state cannot be read while the API is unreachable, but the requested page is still rendered, and
|
||||
// the failure is reported to the user there. The data calls of the page keep failing on their own.
|
||||
httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] = true;
|
||||
authorizationHandlerContext.Succeed(initializationRequirement);
|
||||
}
|
||||
else // store in session that super admin setup is needed
|
||||
httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current HTTP context when the provided exception is an API outage on a page navigation, and <see langword="null"/> otherwise.
|
||||
/// </summary>
|
||||
/// <param name="authorizationHandlerContext">The authorization context whose resource holds the HTTP context.</param>
|
||||
/// <param name="exception">The exception thrown by the initialization check against the API.</param>
|
||||
/// <returns>The HTTP context of the page navigation, or <see langword="null"/> when the exception must propagate.</returns>
|
||||
private static HttpContext? GetPageNavigationDuringApiOutage(AuthorizationHandlerContext authorizationHandlerContext, Exception exception)
|
||||
{
|
||||
if (authorizationHandlerContext.Resource is not HttpContext httpContext)
|
||||
return null;
|
||||
if (httpContext.RequestAborted.IsCancellationRequested)
|
||||
return null;
|
||||
if (exception is not ApiException and not HttpRequestException and not BrokenCircuitException and not TaskCanceledException)
|
||||
return null;
|
||||
if (exception is ApiException apiException && (int)apiException.HttpStatusCode < 500)
|
||||
return null;
|
||||
bool isPageNavigation = (httpContext.Request.Headers.Accept.Count == 0 && httpContext.Request.Headers.Range.Count == 0)
|
||||
|| httpContext.Request.Headers.Accept.Any(accept => accept?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true)
|
||||
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Mode"].ToString(), "navigate", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(httpContext.Request.Headers["Sec-Fetch-Dest"].ToString(), "document", StringComparison.OrdinalIgnoreCase);
|
||||
return isPageNavigation ? httpContext : null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -13,14 +15,17 @@ namespace Lumina.Presentation.Web.Common.Authorization;
|
||||
public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
|
||||
{
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PermissionAuthorizationHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization checks against the remote API.</param>
|
||||
public PermissionAuthorizationHandler(IAuthorizationService authorizationService)
|
||||
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
|
||||
public PermissionAuthorizationHandler(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -44,5 +49,13 @@ public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionReq
|
||||
return;
|
||||
}
|
||||
}
|
||||
// The authorization service marks a page navigation when the API could not answer. The page itself is still rendered, with
|
||||
// no permission granted, and it reports the failure to the user; the API remains the enforcement point for every data call.
|
||||
// Endpoint routing passes the Endpoint, not the HttpContext, as the authorization resource, so the current request is read
|
||||
// from the accessor instead. Only an authenticated user is allowed through, because the outage is not a reason to expose a
|
||||
// page to an anonymous visitor.
|
||||
HttpContext? httpContext = _httpContextAccessor.HttpContext;
|
||||
if (httpContext?.User.Identity?.IsAuthenticated == true && httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true)
|
||||
authorizationHandlerContext.Succeed(permissionRequirement);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -13,14 +14,17 @@ namespace Lumina.Presentation.Web.Common.Authorization;
|
||||
public class RoleAuthorizationHandler : AuthorizationHandler<RoleRequirement>
|
||||
{
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RoleAuthorizationHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization checks against the remote API.</param>
|
||||
public RoleAuthorizationHandler(IAuthorizationService authorizationService)
|
||||
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
|
||||
public RoleAuthorizationHandler(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -38,5 +42,13 @@ public class RoleAuthorizationHandler : AuthorizationHandler<RoleRequirement>
|
||||
return;
|
||||
}
|
||||
}
|
||||
// The authorization service marks a page navigation when the API could not answer. The page itself is still rendered, with
|
||||
// no role granted, and it reports the failure to the user; the API remains the enforcement point for every data call.
|
||||
// Endpoint routing passes the Endpoint, not the HttpContext, as the authorization resource, so the current request is read
|
||||
// from the accessor instead. Only an authenticated user is allowed through, because the outage is not a reason to expose a
|
||||
// page to an anonymous visitor.
|
||||
HttpContext? httpContext = _httpContextAccessor.HttpContext;
|
||||
if (httpContext?.User.Identity?.IsAuthenticated == true && httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true)
|
||||
authorizationHandlerContext.Succeed(roleRequirement);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
/// <param name="Nav">The rendered navigation menu of the page.</param>
|
||||
/// <param name="Content">The rendered content section of the page.</param>
|
||||
/// <param name="AudioPlayer">The rendered audio player, when the current user is authenticated.</param>
|
||||
/// <param name="ServerUnreachableBanner">The rendered server unreachable banner, placed by the layout.</param>
|
||||
/// <param name="AppScripts">The application global scripts, such as its client libraries and configuration.</param>
|
||||
/// <param name="Scripts">The rendered script section of the page.</param>
|
||||
/// <param name="MainStyle">The inline style of the main content area, used to fill the viewport when the user is not authenticated.</param>
|
||||
@@ -24,6 +25,7 @@ public sealed record ThemeLayoutModelDto(
|
||||
string Nav,
|
||||
string Content,
|
||||
string AudioPlayer,
|
||||
string ServerUnreachableBanner,
|
||||
string AppScripts,
|
||||
string Scripts,
|
||||
string MainStyle
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the model available to the themed server unreachable banner template.
|
||||
/// </summary>
|
||||
/// <param name="Message">The localized message that tells the user that the server is unreachable.</param>
|
||||
[DebuggerDisplay("Message: {Message}")]
|
||||
public sealed record ThemeServerUnreachableBannerDto(
|
||||
string Message
|
||||
);
|
||||
@@ -9,6 +9,11 @@ public static class HttpContextItemKeys
|
||||
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
|
||||
public const string LAST_DISPLAYED_VIEW = "LastViewUrl";
|
||||
|
||||
/// <summary>
|
||||
/// Marks a rendered page whose authorization could not reach the API, so that the page reports the failure to the user.
|
||||
/// </summary>
|
||||
public const string SERVER_UNREACHABLE = "ServerUnreachable";
|
||||
|
||||
/// <summary>
|
||||
/// The <c>Cache-Control</c> value chosen by the endpoint, restored when the response starts.
|
||||
/// </summary>
|
||||
|
||||
@@ -6,12 +6,16 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Polly.CircuitBreaker;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Middlewares;
|
||||
@@ -67,12 +71,20 @@ public class ExceptionHandlingMiddleware
|
||||
context.Abort();
|
||||
return;
|
||||
}
|
||||
// return a JSON result with the error details
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
errorMessage = ex.Message
|
||||
});
|
||||
// A page navigation is answered with an HTML error page at the same address, so the browser never leaves the page the user
|
||||
// asked for and never shows raw JSON. A JSON caller still receives the JSON error, and any other caller, like a media request,
|
||||
// receives a bare status code, because neither an HTML page nor a JSON body is a representation such a caller can consume.
|
||||
if (IsJsonRequest(context))
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
serverUnreachable = IsApiOutage(ex),
|
||||
errorMessage = _stringLocalizer["InternalServerError"].Value
|
||||
});
|
||||
else if (IsNavigationRequest(context))
|
||||
await WriteHtmlErrorResponseAsync(context, (int)HttpStatusCode.InternalServerError, _stringLocalizer["InternalServerError"].Value).ConfigureAwait(false);
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.InternalServerError).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,21 +181,74 @@ public class ExceptionHandlingMiddleware
|
||||
/// </summary>
|
||||
private async Task HandleGenericApiErrorAsync(HttpContext context, ApiException apiException)
|
||||
{
|
||||
// JSON callers and page navigations get the localized error message; any other caller, like an audio request, is answered with
|
||||
// a bare status code, because a JSON body is not a representation such a caller can consume.
|
||||
if (IsJsonRequest(context) || IsNavigationRequest(context))
|
||||
// JSON callers get the localized error message, page navigations get an HTML error page at the same address, so the browser never
|
||||
// leaves the page the user asked for and never shows raw JSON, and any other caller, like an audio request, is answered with a
|
||||
// bare status code, because neither a JSON body nor an HTML page is a representation such a caller can consume.
|
||||
if (IsJsonRequest(context))
|
||||
{
|
||||
string errorMessage = BuildErrorMessage(apiException);
|
||||
await WriteJsonResponseAsync(context, new
|
||||
{
|
||||
success = false,
|
||||
serverUnreachable = (int)apiException.HttpStatusCode >= 500,
|
||||
errorMessage
|
||||
});
|
||||
}
|
||||
else if (IsNavigationRequest(context))
|
||||
{
|
||||
bool isServerError = (int)apiException.HttpStatusCode >= 500;
|
||||
string message = isServerError ? _stringLocalizer["InternalServerError"].Value : BuildErrorMessage(apiException);
|
||||
await WriteHtmlErrorResponseAsync(context, (int)apiException.HttpStatusCode, message).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
await WriteStatusOnlyResponseAsync(context, (int)apiException.HttpStatusCode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the exception means that the server could not answer, as opposed to an answer the server produced.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception thrown while handling the request.</param>
|
||||
/// <returns><see langword="true"/> for a connection, timeout, circuit breaker or server failure; otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsApiOutage(Exception exception)
|
||||
{
|
||||
return exception is HttpRequestException or BrokenCircuitException or TaskCanceledException
|
||||
|| (exception is ApiException apiException && (int)apiException.HttpStatusCode >= 500);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a standalone HTML error page to the client, keeping the browser on the requested address.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
/// <param name="statusCode">The status code to answer with.</param>
|
||||
/// <param name="message">The localized message to show on the page.</param>
|
||||
private async Task WriteHtmlErrorResponseAsync(HttpContext context, int statusCode, string message)
|
||||
{
|
||||
context.Response.StatusCode = statusCode;
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
string encodedMessage = HtmlEncoder.Default.Encode(message);
|
||||
string encodedTitle = HtmlEncoder.Default.Encode(_stringLocalizer["Error"].Value);
|
||||
string language = CultureInfo.CurrentUICulture.Name;
|
||||
await context.Response.WriteAsync($$"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="{{language}}">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>{{encodedTitle}}</title>
|
||||
<style>
|
||||
body { font-family: sans-serif; margin: 2rem; }
|
||||
h1 { color: #c62828; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{{encodedTitle}}</h1>
|
||||
<p>{{encodedMessage}}</p>
|
||||
</body>
|
||||
</html>
|
||||
""").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles unauthorized exceptions.
|
||||
/// </summary>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>إعادة المحاولة</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>الخادم غير قابل للوصول</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>توسيع المشغل أو طيه</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Wiederholen</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Der Server ist nicht erreichbar</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Player ein- oder ausklappen</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Retry</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Server is unreachable</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Expand or collapse player</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Reintentar</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>El servidor no está disponible</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Expandir o contraer el reproductor</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Réessayer</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Le serveur est injoignable</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Développer ou réduire le lecteur</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Riprova</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Il server non è raggiungibile</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Espandi o comprimi il lettore</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>再試行</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>サーバーに接続できません</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>プレーヤーを展開または折りたたむ</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Retry</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Server is unreachable</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Expand or collapse player</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Reîncercare</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Serverul nu este disponibil</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Extinde sau restrânge playerul</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>Повторити</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>Сервер недоступний</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>Розгорнути або згорнути плеєр</value>
|
||||
</data>
|
||||
|
||||
@@ -168,6 +168,9 @@
|
||||
<data name="Retry" xml:space="preserve">
|
||||
<value>重试</value>
|
||||
</data>
|
||||
<data name="ServerUnreachable" xml:space="preserve">
|
||||
<value>服务器不可访问</value>
|
||||
</data>
|
||||
<data name="ToggleExpanded" xml:space="preserve">
|
||||
<value>展开或折叠播放器</value>
|
||||
</data>
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -17,6 +19,13 @@ public class ThemeLayoutRenderer
|
||||
// the page keys mirror the paths of the corresponding Razor views under Core/Views, so that theme templates can override them at the page, section or default scope
|
||||
private const string LAYOUT_PAGE_KEY = "shared/layout";
|
||||
private const string NAV_PAGE_KEY = "shared/nav-menu";
|
||||
private const string SERVER_UNREACHABLE_BANNER_PAGE_KEY = "shared/server-unreachable-banner";
|
||||
|
||||
// The banner template is static for a theme, so it is cached, including the negative result of a theme that does not
|
||||
// provide one, so a missing template does not cost an API round trip and a 404 log on every page render.
|
||||
private static readonly ConcurrentDictionary<string, (string Template, DateTime ExpiresOnUtc)> s_bannerTemplateCache = [];
|
||||
private static readonly TimeSpan s_bannerTemplateCacheDuration = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan s_missingBannerTemplateCacheDuration = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly ThemeService _themeService;
|
||||
private readonly ThemeTemplateEngine _templateEngine;
|
||||
@@ -24,6 +33,7 @@ public class ThemeLayoutRenderer
|
||||
private readonly ThemeNavBuilder _navBuilder;
|
||||
private readonly ThemeAudioPlayerRenderer _audioPlayerRenderer;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IStringLocalizer _layoutLocalizer;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeLayoutRenderer"/> class.
|
||||
@@ -34,7 +44,8 @@ public class ThemeLayoutRenderer
|
||||
/// <param name="navBuilder">The builder used to produce the navigation menu model.</param>
|
||||
/// <param name="audioPlayerRenderer">The renderer used to produce the themed audio player bar.</param>
|
||||
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
|
||||
public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor)
|
||||
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the layout resources.</param>
|
||||
public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor, IStringLocalizerFactory stringLocalizerFactory)
|
||||
{
|
||||
_themeService = themeService;
|
||||
_templateEngine = templateEngine;
|
||||
@@ -42,6 +53,7 @@ public class ThemeLayoutRenderer
|
||||
_navBuilder = navBuilder;
|
||||
_audioPlayerRenderer = audioPlayerRenderer;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_layoutLocalizer = stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -62,6 +74,7 @@ public class ThemeLayoutRenderer
|
||||
string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken);
|
||||
string nav = await RenderNavAsync(themeId, cancellationToken);
|
||||
string audioPlayer = isAuthenticated ? await RenderAudioPlayerAsync(themeId, cancellationToken) : string.Empty;
|
||||
string serverUnreachableBanner = await RenderServerUnreachableBannerAsync(themeId, cancellationToken);
|
||||
string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken);
|
||||
|
||||
ThemeLayoutModelDto layoutModel = new(
|
||||
@@ -71,6 +84,7 @@ public class ThemeLayoutRenderer
|
||||
nav,
|
||||
page.Content,
|
||||
audioPlayer,
|
||||
serverUnreachableBanner,
|
||||
appScripts,
|
||||
page.Script,
|
||||
isAuthenticated ? string.Empty : "bottom: 0px;");
|
||||
@@ -139,4 +153,51 @@ public class ThemeLayoutRenderer
|
||||
|
||||
return await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders the server unreachable banner of the active theme, falling back to the application Razor markup when the theme does not provide a template.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The manifest id of the theme the layout was resolved with, so that the banner always matches the shell.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The rendered server unreachable banner HTML.</returns>
|
||||
private async Task<string> RenderServerUnreachableBannerAsync(string themeId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (s_bannerTemplateCache.TryGetValue(themeId, out (string Template, DateTime ExpiresOnUtc) cached) && cached.ExpiresOnUtc > DateTime.UtcNow)
|
||||
return await RenderBannerTemplateAsync(cached.Template, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
string template = string.Empty;
|
||||
try
|
||||
{
|
||||
ThemeRenderDocumentDto bannerDocument = await _themeService.GetRenderDocumentAsync(SERVER_UNREACHABLE_BANNER_PAGE_KEY, themeId, cancellationToken);
|
||||
template = bannerDocument.Template;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// The banner is best effort: when the theme template cannot be loaded or rendered, the application Razor fallback is rendered instead.
|
||||
}
|
||||
s_bannerTemplateCache[themeId] = (template, DateTime.UtcNow + (string.IsNullOrEmpty(template) ? s_missingBannerTemplateCacheDuration : s_bannerTemplateCacheDuration));
|
||||
return await RenderBannerTemplateAsync(template, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a banner template, or the application fallback when the theme does not provide one.
|
||||
/// </summary>
|
||||
/// <param name="template">The raw banner template source, or an empty string when the theme does not provide one.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The rendered server unreachable banner HTML.</returns>
|
||||
private async Task<string> RenderBannerTemplateAsync(string template, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(template))
|
||||
return await _viewRenderer.RenderPartialAsync("_ServerUnreachableBanner", cancellationToken);
|
||||
|
||||
ThemeServerUnreachableBannerDto bannerModel = new(_layoutLocalizer["ServerUnreachable"].Value);
|
||||
Result<ThemePageRenderResultDto> renderResult = _templateEngine.RenderPage(template, bannerModel);
|
||||
return renderResult.IsSuccess
|
||||
? renderResult.Value.Content
|
||||
: await _viewRenderer.RenderPartialAsync("_ServerUnreachableBanner", cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -737,10 +737,15 @@ It keeps the DOM contract the client script binds to, without any images or colo
|
||||
schedulerHubConnection.on('ScheduledJobExecutionCompletedAsync', execution => {
|
||||
loadJobsAsync();
|
||||
});
|
||||
schedulerHubConnection.onreconnecting(() => window.serverConnectionStatus.markUnreachable('scheduledJobsHub'));
|
||||
schedulerHubConnection.onreconnected(() => window.serverConnectionStatus.markReachable('scheduledJobsHub'));
|
||||
schedulerHubConnection.onclose(() => window.serverConnectionStatus.markUnreachable('scheduledJobsHub'));
|
||||
|
||||
try {
|
||||
await schedulerHubConnection.start();
|
||||
window.serverConnectionStatus.markReachable('scheduledJobsHub');
|
||||
} catch (error) {
|
||||
window.serverConnectionStatus.markUnreachable('scheduledJobsHub');
|
||||
console.error('Failed to connect to the scheduled jobs hub:', error);
|
||||
}
|
||||
}
|
||||
@@ -805,7 +810,7 @@ It keeps the DOM contract the client script binds to, without any images or colo
|
||||
updateTimespanButton.removeEventListener('click', updateTimeSpanAsync);
|
||||
addJobButton.removeEventListener('click', addJobAsync);
|
||||
if (schedulerHubConnection)
|
||||
schedulerHubConnection.stop();
|
||||
schedulerHubConnection.stop().finally(() => window.serverConnectionStatus.markReachable('scheduledJobsHub'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -529,12 +529,15 @@
|
||||
// Handle all SignalR stuff.
|
||||
function setupSignalRHandlers() {
|
||||
const onReconnecting = error => {
|
||||
console.log(error ? `SignalR reconnected with error: ${error}` : "SignalR reconnecting...");
|
||||
window.serverConnectionStatus.markUnreachable('scanProgressHub');
|
||||
console.log(error ? `SignalR reconnecting with error: ${error}` : "SignalR reconnecting...");
|
||||
};
|
||||
const onReconnected = connectionId => {
|
||||
window.serverConnectionStatus.markReachable('scanProgressHub');
|
||||
console.log('SignalR reconnected:', connectionId);
|
||||
};
|
||||
const onClose = error => {
|
||||
window.serverConnectionStatus.markUnreachable('scanProgressHub');
|
||||
console.log(error ? `SignalR connection closed with error: ${error}` : "SignalR connection closed");
|
||||
};
|
||||
// Progress update handler.
|
||||
@@ -678,8 +681,9 @@
|
||||
// Register cleanup for these listeners.
|
||||
cleanupFunctions.push(() => {
|
||||
// Proper connection stop.
|
||||
if (signalRConnection.state === 'Connected')
|
||||
signalRConnection.stop().then(() => console.log('SignalR connection stopped'));
|
||||
window.serverConnectionStatus.markReachable('scanProgressHub');
|
||||
if (signalRConnection.state !== 'Disconnected')
|
||||
signalRConnection.stop().finally(() => window.serverConnectionStatus.markReachable('scanProgressHub'));
|
||||
|
||||
btnScanAllLibraries.removeEventListener('click', handleScanAllLibrariesClick);
|
||||
btnCancelLibrariesScan.removeEventListener('click', handleCancelLibrariesScanClick);
|
||||
@@ -702,11 +706,18 @@
|
||||
isInitialized = true;
|
||||
try {
|
||||
await loadLibrariesAsync();
|
||||
await signalRConnection.start();
|
||||
try {
|
||||
await signalRConnection.start();
|
||||
window.serverConnectionStatus.markReachable('scanProgressHub');
|
||||
} catch (err) {
|
||||
window.serverConnectionStatus.markUnreachable('scanProgressHub');
|
||||
console.error('SignalR connection failed:', err);
|
||||
return;
|
||||
}
|
||||
setupSignalRHandlers();
|
||||
await getRunningLibraryScansAsync();
|
||||
} catch (err) {
|
||||
console.error('SignalR connection failed:', err);
|
||||
console.error('Failed to initialize the libraries page:', err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,38 @@
|
||||
@using Lumina.Presentation.Web.Common.DTO.Common
|
||||
@using Lumina.Presentation.Web.Common.Services
|
||||
@using Microsoft.Extensions.Localization
|
||||
|
||||
@model ErrorViewDto
|
||||
@inject IStringLocalizerFactory _stringLocalizerFactory
|
||||
|
||||
@{
|
||||
ViewData["Title"] = "Error";
|
||||
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
|
||||
var localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
<h1 class="text-danger">Error.</h1>
|
||||
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
||||
<div style="display: grid; grid-template-rows: auto 1fr;">
|
||||
<div style="min-height: 1rem;"></div>
|
||||
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-55 mb-10" style="min-width: 320px;">
|
||||
<div class="shine-effect"></div>
|
||||
<div class="text-center w-100">
|
||||
<p class="invalid-feedback f-18 w-100"><b>@localizer["Error"]</b></p>
|
||||
<p class="invalid-feedback f-18 w-100"><b>@localizer["NavigationFailed"]</b></p>
|
||||
@if (Model.ShouldShowRequestId)
|
||||
{
|
||||
<p class="text-disabled w-100">
|
||||
<strong>Request ID:</strong> <code>@Model.RequestId</code>
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (Model.ShouldShowRequestId)
|
||||
{
|
||||
<p>
|
||||
<strong>Request ID:</strong> <code>@Model.RequestId</code>
|
||||
</p>
|
||||
@section Scripts {
|
||||
<script type="text/plain" data-form="@scriptId">
|
||||
// The page is the navigation failure fallback, so the user is told that the page could not be loaded. When a marker
|
||||
// driven notification was already shown for this page, it is not repeated.
|
||||
if (!window.isServerUnreachable)
|
||||
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);
|
||||
</script>
|
||||
}
|
||||
|
||||
<h3>Development Mode</h3>
|
||||
<p>
|
||||
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
|
||||
</p>
|
||||
<p>
|
||||
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
|
||||
It can result in displaying sensitive information from exceptions to end users.
|
||||
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
|
||||
and restarting the app.
|
||||
</p>
|
||||
@@ -1,4 +1,5 @@
|
||||
@using Lumina.Presentation.Web.Common.DTO.Themes
|
||||
@using Lumina.Presentation.Web.Common.Http
|
||||
@using Lumina.Presentation.Web.Common.Primitives
|
||||
@using Lumina.Presentation.Web.Core.Themes
|
||||
@using Microsoft.AspNetCore.Html
|
||||
@@ -17,6 +18,11 @@
|
||||
bodyHtml = bodyWriter.ToString();
|
||||
}
|
||||
|
||||
// The page renders even when the API was unreachable during its authorization check. The marker is carried inside the main content,
|
||||
// so the global script reports the failed navigation both on a full page load and after an AJAX navigation swapped the content.
|
||||
if (ViewContext.HttpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true)
|
||||
bodyHtml = "<div id=\"server-unreachable-marker\" hidden></div>" + bodyHtml;
|
||||
|
||||
string scriptsHtml;
|
||||
using (StringWriter scriptsWriter = new())
|
||||
{
|
||||
@@ -63,6 +69,7 @@ else
|
||||
@await Html.PartialAsync("_AudioPlayer")
|
||||
}
|
||||
</div>
|
||||
@await Html.PartialAsync("_ServerUnreachableBanner")
|
||||
<div id="modal-background-menu"></div>
|
||||
@await Html.PartialAsync("_ThemeLayoutScripts")
|
||||
<div data-section="scripts">
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
@using Microsoft.Extensions.Localization
|
||||
|
||||
@inject IStringLocalizerFactory _stringLocalizerFactory
|
||||
|
||||
@{
|
||||
var localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web");
|
||||
}
|
||||
|
||||
<div id="server-unreachable-banner" class="server-unreachable-banner" data-server-unreachable-banner role="status" aria-live="polite" aria-atomic="true"><span class="server-unreachable-banner-text">@localizer["ServerUnreachable"]</span></div>
|
||||
@@ -1 +1,7 @@
|
||||
@using Lumina.Presentation.Web.Common.Http
|
||||
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
|
||||
<script>
|
||||
// Set before any page script runs, so the API helpers suppress their duplicate error notifications when the page was
|
||||
// rendered while the API was unreachable, and the page only shows the single navigation failed notification.
|
||||
window.isServerUnreachable = @(ViewContext.HttpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true ? "true" : "false");
|
||||
</script>
|
||||
@@ -16,9 +16,11 @@
|
||||
var globalConfiguration = {
|
||||
serverBasePath: '@(_serverConfigurationModel.Value.BaseAddress):@(_serverConfigurationModel.Value.Port)',
|
||||
apiBasePath: '@(_serverConfigurationModel.Value.BaseAddress):@(_serverConfigurationModel.Value.Port)/api/v@(_serverConfigurationModel.Value.ApiVersion)',
|
||||
healthCheckUrl: '@Url.Content("~/health/ready")'
|
||||
};
|
||||
var jsLocalizedMessages = {
|
||||
navigationFailed: '@localizer["NavigationFailed"]',
|
||||
serverUnreachable: @Json.Serialize(localizer["ServerUnreachable"].Value)
|
||||
};
|
||||
var jsLocalizedDialogs = {
|
||||
ok: '@localizer["Ok"]',
|
||||
@@ -139,6 +141,7 @@
|
||||
<script defer src="~/js/notifications.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/dialogs.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/image-viewer.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/server-connection-status.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/site.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/playlists.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/favorites.js" asp-append-version="true"></script>
|
||||
|
||||
@@ -2470,3 +2470,49 @@ html.audio-player-initializing .audio-player-container {
|
||||
.statistics-delete-button {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The global server unreachable banner is rendered by the active theme, or by the application fallback, and is toggled
|
||||
by server-connection-status.js. A theme can restyle it by overriding this class or the custom properties in its own
|
||||
stylesheet, which loads after this one. */
|
||||
.server-unreachable-banner {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 2px 16px;
|
||||
background-color: var(--server-unreachable-background-color, #c62828);
|
||||
color: var(--server-unreachable-text-color, #ffffff);
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.server-unreachable-banner.is-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* The text pulses slowly, so the bar catches the eye without flashing. A theme can replace this with its own animation
|
||||
by targeting the server-unreachable-banner-text class, or by rendering its own text wrapper. */
|
||||
.server-unreachable-banner.is-visible .server-unreachable-banner-text {
|
||||
animation: server-unreachable-fade 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes server-unreachable-fade {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.server-unreachable-banner.is-visible .server-unreachable-banner-text {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Shows the global server unreachable banner while the health probe or a SignalR connection reports the server as
|
||||
* unreachable. The banner markup comes from the theme template, with a fallback created here for themes that do not
|
||||
* provide one.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const unreachableSources = new Set();
|
||||
let banner = null;
|
||||
|
||||
/**
|
||||
* Creates the banner the first time it is needed, and appends it to the body, so it survives the AJAX navigation
|
||||
* that only swaps the content of the main element.
|
||||
* @returns {HTMLElement} The banner element.
|
||||
*/
|
||||
function getBanner() {
|
||||
if (banner !== null && banner.isConnected)
|
||||
return banner;
|
||||
// A theme renders the banner through its shared/server-unreachable-banner template, and the application renders a fallback
|
||||
// when it does not. The data hook is the contract the script toggles.
|
||||
banner = document.querySelector('[data-server-unreachable-banner]');
|
||||
if (banner !== null)
|
||||
return banner;
|
||||
banner = document.createElement('div');
|
||||
banner.id = 'server-unreachable-banner';
|
||||
banner.className = 'server-unreachable-banner';
|
||||
banner.setAttribute('data-server-unreachable-banner', '');
|
||||
banner.setAttribute('role', 'status');
|
||||
banner.setAttribute('aria-live', 'polite');
|
||||
banner.setAttribute('aria-atomic', 'true');
|
||||
banner.textContent = window.jsLocalizedMessages?.serverUnreachable ?? 'Server is unreachable';
|
||||
document.body.appendChild(banner);
|
||||
return banner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the banner while at least one live connection is unreachable, and hides it once every connection recovered.
|
||||
*/
|
||||
function refreshBanner() {
|
||||
getBanner().classList.toggle('is-visible', unreachableSources.size > 0);
|
||||
}
|
||||
|
||||
window.serverConnectionStatus = {
|
||||
/**
|
||||
* Marks a live connection as unreachable, showing the global banner.
|
||||
* @param {string} source - The name of the connection that lost its connection.
|
||||
*/
|
||||
markUnreachable: function (source) {
|
||||
unreachableSources.add(source);
|
||||
refreshBanner();
|
||||
},
|
||||
|
||||
/**
|
||||
* Marks a live connection as reachable again, hiding the global banner when no other connection is unreachable.
|
||||
* @param {string} source - The name of the connection that reconnected.
|
||||
*/
|
||||
markReachable: function (source) {
|
||||
unreachableSources.delete(source);
|
||||
refreshBanner();
|
||||
}
|
||||
};
|
||||
|
||||
// The health endpoint is the page independent source of the banner: it reports the API as unreachable even on pages
|
||||
// that have no SignalR connection, so the banner appears on every page while the server cannot serve requests.
|
||||
const HEALTH_CHECK_INTERVAL_MS = 5000;
|
||||
const HEALTH_CHECK_TIMEOUT_MS = 4000;
|
||||
const HEALTH_CHECK_SOURCE = 'healthCheck';
|
||||
let isHealthCheckInFlight = false;
|
||||
|
||||
/**
|
||||
* Schedules the next health probe, with a little jitter so many open tabs do not probe in lockstep.
|
||||
*/
|
||||
function scheduleNextHealthCheck() {
|
||||
const jitter = Math.round((Math.random() * 2 - 1) * HEALTH_CHECK_INTERVAL_MS * 0.2);
|
||||
setTimeout(() => {
|
||||
if (document.visibilityState === 'visible')
|
||||
checkServerHealthAsync();
|
||||
else
|
||||
scheduleNextHealthCheck();
|
||||
}, Math.max(1000, HEALTH_CHECK_INTERVAL_MS + jitter));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the server can reach the API and updates the global banner accordingly.
|
||||
*/
|
||||
async function checkServerHealthAsync() {
|
||||
const healthCheckUrl = window.globalConfiguration?.healthCheckUrl;
|
||||
if (!healthCheckUrl || isHealthCheckInFlight) {
|
||||
scheduleNextHealthCheck();
|
||||
return;
|
||||
}
|
||||
isHealthCheckInFlight = true;
|
||||
const controller = new AbortController();
|
||||
const timeoutHandle = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(healthCheckUrl, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
cache: 'no-store',
|
||||
signal: controller.signal
|
||||
});
|
||||
if (response.ok) {
|
||||
// The API is reachable. Only the sources that describe server reachability are cleared; a disconnected
|
||||
// SignalR hub keeps its own source until it reconnects.
|
||||
unreachableSources.delete(HEALTH_CHECK_SOURCE);
|
||||
unreachableSources.delete('api');
|
||||
window.isServerUnreachable = false;
|
||||
refreshBanner();
|
||||
} else {
|
||||
unreachableSources.add(HEALTH_CHECK_SOURCE);
|
||||
refreshBanner();
|
||||
}
|
||||
} catch {
|
||||
unreachableSources.add(HEALTH_CHECK_SOURCE);
|
||||
refreshBanner();
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle);
|
||||
isHealthCheckInFlight = false;
|
||||
scheduleNextHealthCheck();
|
||||
}
|
||||
}
|
||||
|
||||
checkServerHealthAsync();
|
||||
|
||||
refreshBanner();
|
||||
})();
|
||||
@@ -10,6 +10,58 @@ let enableConsoleDebugMessages = false; // whether to display debug messages at
|
||||
|
||||
var ajaxCallCounter = 0;
|
||||
|
||||
/**
|
||||
* Shows the server unreachable notification once, and marks the API source as unreachable. A later successful call
|
||||
* clears the state. It is used for network failures, never for an HTTP status the server actually answered with.
|
||||
*/
|
||||
function showServerUnreachableOnce() {
|
||||
window.serverConnectionStatus?.markUnreachable('api');
|
||||
if (window.isServerUnreachable)
|
||||
return;
|
||||
window.isServerUnreachable = true;
|
||||
notificationService.show(jsLocalizedMessages.serverUnreachable, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the API as reachable again after a response the server produced, whether it was successful or a client error.
|
||||
*/
|
||||
function markApiReachable() {
|
||||
window.isServerUnreachable = false;
|
||||
window.serverConnectionStatus?.markReachable('api');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an unsuccessful JSON response. An outage response marks the server unreachable and shows the single unreachable
|
||||
* notification; any other failure shows the message the server provided.
|
||||
* @param {Object} jsonResponse - The unsuccessful response payload.
|
||||
*/
|
||||
function handleApiFailure(jsonResponse) {
|
||||
if (jsonResponse.serverUnreachable === true) {
|
||||
showServerUnreachableOnce();
|
||||
return;
|
||||
}
|
||||
markApiReachable();
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles an HTTP response with an unsuccessful status, showing the message the server provided when it can be read.
|
||||
* The server answered, so this is not treated as an unreachable server.
|
||||
* @param {Response} response - The unsuccessful response.
|
||||
*/
|
||||
async function showHttpErrorAsync(response) {
|
||||
markApiReachable();
|
||||
let message = response.statusText || `HTTP ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body && typeof body.errorMessage === 'string' && body.errorMessage.length > 0)
|
||||
message = body.errorMessage;
|
||||
} catch {
|
||||
// The body was not JSON, so the status text is the best message available.
|
||||
}
|
||||
notificationService.show(message, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
|
||||
//+======================================================================================+
|
||||
//| API interaction |
|
||||
@@ -32,17 +84,31 @@ async function callApiGetAsync(url) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error('Network response was not ok');
|
||||
const jsonResponse = await response.json();
|
||||
if (jsonResponse.success)
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return;
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
// The server answered, but not with the expected JSON, so this is not an unreachable server.
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return;
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
return jsonResponse.data;
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,20 +151,32 @@ async function callApiPostAsync(url, data, options = {}) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const jsonResponse = await response.json();
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return;
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return;
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
if (jsonResponse.message)
|
||||
notificationService.show(jsonResponse.message, NotificationType.SUCCESS);
|
||||
return jsonResponse.data;
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,20 +219,32 @@ async function callApiPutAsync(url, data, options = {}) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const jsonResponse = await response.json();
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return { success: false };
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return { success: false };
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
if (jsonResponse.message)
|
||||
notificationService.show(jsonResponse.message, NotificationType.SUCCESS);
|
||||
return { success: jsonResponse.success === true, data: jsonResponse.data };
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
return { success: false };
|
||||
}
|
||||
@@ -196,20 +286,32 @@ async function callApiDeleteAsync(url, options = {}) {
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else {
|
||||
if (!response.ok)
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const jsonResponse = await response.json();
|
||||
if (!response.ok) {
|
||||
await showHttpErrorAsync(response);
|
||||
return;
|
||||
}
|
||||
let jsonResponse;
|
||||
try {
|
||||
jsonResponse = await response.json();
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
markApiReachable();
|
||||
notificationService.show(error.message, NotificationType.ERROR);
|
||||
return;
|
||||
}
|
||||
if (jsonResponse.success) {
|
||||
markApiReachable();
|
||||
if (jsonResponse.message)
|
||||
notificationService.show(jsonResponse.message, NotificationType.SUCCESS);
|
||||
return jsonResponse.success;
|
||||
}
|
||||
else
|
||||
notificationService.show(jsonResponse.errorMessage, NotificationType.ERROR);
|
||||
handleApiFailure(jsonResponse);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fetch itself failed, which means the Web application or the network is not answering.
|
||||
console.error('Error:', error);
|
||||
notificationService.show(error, NotificationType.ERROR);
|
||||
showServerUnreachableOnce();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,9 +339,28 @@ function initializeNavigation() {
|
||||
|
||||
// execute the view scripts of the initially loaded page, now that the application scripts are loaded; the view scripts are
|
||||
// stored with a non-executable type, so the browser does not run them before the application scripts are available
|
||||
showServerUnreachableNotificationIfNeeded();
|
||||
processViewScriptsAsync(document.querySelector('[data-section="scripts"]'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the navigation failed notification when the rendered page reports that its authorization could not reach the API,
|
||||
* then removes the marker so the notification is shown once per failed navigation. While the page is marked unreachable,
|
||||
* the API helpers suppress their own error notifications, because they all report the same outage.
|
||||
*/
|
||||
function showServerUnreachableNotificationIfNeeded() {
|
||||
const marker = document.getElementById('server-unreachable-marker');
|
||||
if (!marker) {
|
||||
window.isServerUnreachable = false;
|
||||
window.serverConnectionStatus?.markReachable('api');
|
||||
return;
|
||||
}
|
||||
marker.remove();
|
||||
window.isServerUnreachable = true;
|
||||
window.serverConnectionStatus?.markUnreachable('api');
|
||||
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds AJAX navigation behavior to links marked with .nav-link class.
|
||||
*/
|
||||
@@ -375,6 +496,17 @@ async function updateContentAsync(url, addToHistory) {
|
||||
});
|
||||
if (response.redirected) // if a redirect is requested, perform it
|
||||
window.location.href = response.url;
|
||||
else if (!response.ok) {
|
||||
// The server answered with an error page for the requested address. Keep the address the user asked for in the bar
|
||||
// and report the failed navigation once, instead of leaving the previous address and letting the missing content throw.
|
||||
const failedState = { url, content: document.querySelector('main').innerHTML, title: document.title };
|
||||
if (addToHistory)
|
||||
history.pushState(failedState, document.title, url);
|
||||
else
|
||||
history.replaceState(failedState, document.title, url);
|
||||
notificationService.show(jsLocalizedMessages.navigationFailed, NotificationType.ERROR);
|
||||
console.error('Navigation failed with status:', response.status);
|
||||
}
|
||||
else {
|
||||
const html = await response.text();
|
||||
|
||||
@@ -387,6 +519,8 @@ async function updateContentAsync(url, addToHistory) {
|
||||
// update the page content
|
||||
document.querySelector('main').innerHTML = content;
|
||||
document.title = title;
|
||||
// The page scripts may start calling the API immediately, so the outage flag must be set before they run.
|
||||
showServerUnreachableNotificationIfNeeded();
|
||||
|
||||
// process all scripts in order: component scripts first, then view scripts
|
||||
const componentScripts = doc.querySelectorAll('script[data-component-script]');
|
||||
|
||||
Reference in new issue
Block a user