Formats code comments as sentences in the production sources.

Capitalizes the first word and adds the terminal period across the domain, application, data access, infrastructure, API and web layers and the plugins. No comment is reworded. The change also normalizes the TODO bodies to lowercase, leaves commented-out code untouched, corrects the Threat/Treat typo and the dangling hyphen in the exception middleware, and collapses two accidental repeated terminal periods.
This commit is contained in:
BinaryAlley committed 2026-11-16 18:16:17 +02:00
1 parent 88455fec9c
commit 727aa33318
142 files changed
+403 -403

No files matched your search

@@ -66,7 +66,7 @@ public class AuthorizationService : IAuthorizationService
/// <returns>The user's authorization details.</returns>
private async Task<GetAuthorizationResponse> GetUserAuthorizationAsync(CancellationToken cancellationToken)
{
// anonymous users and users without an identifier claim have no role or permissions, so deny without querying the API
// Anonymous users and users without an identifier claim have no role or permissions, so deny without querying the API.
string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId))
return new GetAuthorizationResponse(Guid.Empty, string.Empty, []);
@@ -43,11 +43,11 @@ public class InitializationHandler : AuthorizationHandler<InitializationRequirem
HttpContext? httpContext = authorizationHandlerContext.Resource as HttpContext;
if (result.IsInitialized)
{
// admin account was registered, remove this requirement from the session
// 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
else // Store in session that super admin setup is needed.
httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true");
}
catch (Exception exception)
@@ -39,7 +39,7 @@ public class ReleaseInfoDto
public ReleaseCountry? ReleaseCountry { get; set; }
/// <summary>
/// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0")
/// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0").
/// </summary>
public string? ReleaseVersion { get; set; }
}
@@ -11,7 +11,7 @@ namespace Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
public class FileDto : FileSystemItemDto
{
/// <summary>
/// Gets or sets the size of the file, in bytes
/// Gets or sets the size of the file, in bytes.
/// </summary>
public long Size { get; set; }
}
@@ -71,7 +71,7 @@ public class BookDto
public ReleaseCountry? ReleaseCountry { get; init; }
/// <summary>
/// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0")
/// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0").
/// </summary>
public string? ReleaseVersion { get; init; }
@@ -22,10 +22,10 @@ internal static class PresentationWebLayerConfiguration
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection BindConfiguration(this IServiceCollection serviceCollection, IConfigurationManager configuration)
{
// add the configuration sources to the configuration builder
// Add the configuration sources to the configuration builder.
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
configuration.AddEnvironmentVariables(); // Environment variables should override the configuration files.
serviceCollection.AddOptions<ServerConfigurationDto>()
.Bind(configuration.GetRequiredSection(ServerConfigurationDto.SECTION_NAME))
@@ -139,7 +139,7 @@ public static class PresentationWebLayerServices
requestLocalizationOptions.RequestCultureProviders =
[
routeDataRequestCultureProvider, // Keep route-based culture handling,
new CookieRequestCultureProvider(), // but also add cookie option, so the application "remembers" the last used language the next time it's opened.
new CookieRequestCultureProvider(), // But also add cookie option, so the application "remembers" the last used language the next time it's opened.
new AcceptLanguageHeaderRequestCultureProvider()
];
});
@@ -7,13 +7,13 @@ public enum IsbnFormat
{
/// <summary>
/// The 10-digit ISBN format used for books published before 2007.
/// Example: 0-306-40615-2
/// Example: 0-306-40615-2.
/// </summary>
Isbn10,
/// <summary>
/// The 13-digit ISBN format introduced in 2007, now the standard for all new books.
/// Example: 978-0-306-40615-7
/// Example: 978-0-306-40615-7.
/// </summary>
Isbn13
}
@@ -45,20 +45,20 @@ public sealed class RazorViewResult : IResult
/// <param name="httpContext">The <see cref="HttpContext"/> for the current request.</param>
public async Task ExecuteAsync(HttpContext httpContext)
{
// the only accessible ViewDataDictionary constructors require either a model state or an existing dictionary, so start from an empty one and assign the model
// The only accessible ViewDataDictionary constructors require either a model state or an existing dictionary, so start from an empty one and assign the model
// through the Model setter; the setter rebases the model metadata on the runtime type of the value, which is what makes the asp-for tag helpers resolve the
// properties of the actual model type instead of a plain object
// properties of the actual model type instead of a plain object.
IModelMetadataProvider metadataProvider = httpContext.RequestServices.GetRequiredService<IModelMetadataProvider>();
ViewDataDictionary viewData = new(metadataProvider, new ModelStateDictionary()) { Model = _model };
foreach ((string key, object? value) in _viewData)
viewData[key] = value;
// delegate to the MVC view execution machinery instead of rendering the view manually: it discovers the layout and _ViewStart, evaluates the sections,
// and resolves the view components and tag helpers, none of which the Results class can do since it has no view rendering support
// Delegate to the MVC view execution machinery instead of rendering the view manually: it discovers the layout and _ViewStart, evaluates the sections,
// and resolves the view components and tag helpers, none of which the Results class can do since it has no view rendering support.
ViewResult viewResult = new() { ViewName = _viewName, ViewData = viewData };
IActionResultExecutor<ViewResult> executor = httpContext.RequestServices.GetRequiredService<IActionResultExecutor<ViewResult>>();
// the view engine needs an ActionContext, which FastEndpoints does not provide; synthesize one that carries over the current route data, so that the
// culture route value (and therefore the URL-based localization) keeps working while the view is rendered
// The view engine needs an ActionContext, which FastEndpoints does not provide; synthesize one that carries over the current route data, so that the
// culture route value (and therefore the URL-based localization) keeps working while the view is rendered.
ActionContext actionContext = new(httpContext, httpContext.GetRouteData() ?? new RouteData(), new ActionDescriptor());
await executor.ExecuteAsync(actionContext, viewResult).ConfigureAwait(false);
}
@@ -28,17 +28,17 @@ public class CultureRedirectMiddleware
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
public async Task InvokeAsync(HttpContext context)
{
// check if the request path starts with "/" and does not contain any culture
// Check if the request path starts with "/" and does not contain any culture.
string? path = context.Request.Path.Value?.ToLowerInvariant();
// redirect routes that would lead to the home page
// Redirect routes that would lead to the home page.
if (path == "/" || path == "/home" || path == "/index")
{
// try to get the user's preferred culture from cookies
// Try to get the user's preferred culture from cookies.
IRequestCultureFeature? feature = context.Features.Get<IRequestCultureFeature>();
string? userCulture = feature?.RequestCulture.Culture.Name;
// if no specific culture is found, use "en-US" as fallback
// If no specific culture is found, use "en-US" as fallback.
string redirectCulture = userCulture ?? "en-US";
// redirect the user to their preferred culture route
// Redirect the user to their preferred culture route.
context.Response.Redirect($"/{redirectCulture.ToLower()}/");
return;
}
@@ -57,11 +57,11 @@ public class ExceptionHandlingMiddleware
// The client went away while its request or response was being processed, so there is nobody left to answer.
context.Abort();
}
catch (ApiException apiException) // threat API exceptions differently - they contain Problem Details properties
catch (ApiException apiException) // Treat API exceptions differently - they contain Problem Details properties.
{
await HandleApiExceptionAsync(context, apiException);
}
catch (Exception ex) // other cases -
catch (Exception ex) // Other cases.
{
_logger.LogError(ex, "Unexpected exception occurred: {Message}", ex.Message);
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced: the connection
@@ -104,7 +104,7 @@ public class ExceptionHandlingMiddleware
/// </summary>
private async Task HandleApiExceptionAsync(HttpContext context, ApiException apiException)
{
// log all available details for debugging/monitoring
// Log all available details for debugging/monitoring.
_logger.LogError(
apiException,
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
@@ -121,8 +121,8 @@ public class ExceptionHandlingMiddleware
return;
}
// handle unauthorized errors by prompting the user to re-login
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
// Handle unauthorized errors by prompting the user to re-login.
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in).
await HandleUnauthorizedAsync(context);
else if (apiException.HttpStatusCode == HttpStatusCode.NotFound) //
await HandleNotFoundAsync(context, apiException);
@@ -137,8 +137,8 @@ public class ExceptionHandlingMiddleware
/// </summary>
private async Task HandleNotFoundAsync(HttpContext context, ApiException apiException)
{
// when the API reports the currently logged-in user no longer exists (404 from the current-user authorization check),
// the stored session is stale: sign out and send the user to the login page instead of the not-found page
// When the API reports the currently logged-in user no longer exists (404 from the current-user authorization check),
// the stored session is stale: sign out and send the user to the login page instead of the not-found page.
if (context.User?.Identity?.IsAuthenticated == true && IsCurrentUserAuthorizationCheck(apiException))
{
await HandleUnauthorizedAsync(context).ConfigureAwait(false);
@@ -161,7 +161,7 @@ public class ExceptionHandlingMiddleware
string culture = context.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
string notFoundUrl = $"/{culture}/not-found";
_logger.LogInformation("Redirecting user to NotFound url");
context.Response.Redirect(notFoundUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
context.Response.Redirect(notFoundUrl); // Force an entire refresh of the current location, so that header and footer are re-rendered too.
}
else
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.NotFound).ConfigureAwait(false);
@@ -265,7 +265,7 @@ public class ExceptionHandlingMiddleware
/// </summary>
private async Task HandleUnauthorizedAsync(HttpContext context)
{
// when API JWT tokens expire, the client app is still logged in, so, sign out the user and delete the authentication cookie and token
// When API JWT tokens expire, the client app is still logged in, so, sign out the user and delete the authentication cookie and token.
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
context.Response.Cookies.Delete("Token");
@@ -284,7 +284,7 @@ public class ExceptionHandlingMiddleware
string returnUrl = $"{context.Request.Path}{context.Request.QueryString}";
string loginUrl = $"/{culture}/auth/login?returnUrl={Uri.EscapeDataString(returnUrl)}";
_logger.LogInformation("Redirecting unauthorized user to {Url}", loginUrl);
context.Response.Redirect(loginUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
context.Response.Redirect(loginUrl); // Force an entire refresh of the current location, so that header and footer are re-rendered too.
}
else
await WriteStatusOnlyResponseAsync(context, (int)HttpStatusCode.Unauthorized).ConfigureAwait(false);
@@ -299,7 +299,7 @@ public class ExceptionHandlingMiddleware
if (apiException.ProblemDetails is not null)
{
// only show the meaningful error message to the user
// Only show the meaningful error message to the user.
if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail))
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Detail]}</b><br>");
else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title))
@@ -40,7 +40,7 @@ public class NotFoundRedirectMiddleware
context.Features.Get<IRequestCultureFeature>()?.RequestCulture.Culture.Name?.ToLower() ??
"en-us";
// re-execute the request so the user gets the error page
// Re-execute the request so the user gets the error page.
string? originalPath = context.Request.Path.Value;
context.Items["originalPath"] = originalPath;
_logger.LogInformation("Redirecting user to NotFound url");
@@ -35,7 +35,7 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
if (string.IsNullOrEmpty(plaintext))
throw new ArgumentException("Value cannot be null or empty", nameof(plaintext));
// generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts
// Generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts.
byte[] iv = new byte[16];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
rng.GetBytes(iv);
@@ -50,7 +50,7 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
// combine IV and ciphertext
// Combine IV and ciphertext.
byte[] combined = new byte[iv.Length + ciphertext.Length];
Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length);
@@ -69,13 +69,13 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
if (string.IsNullOrEmpty(ciphertext))
throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext));
// decode the combined data (IV + ciphertext) from Base64
// Decode the combined data (IV + ciphertext) from Base64.
byte[] combined = Convert.FromBase64String(ciphertext);
if (combined.Length < 16)
throw new ArgumentException("Invalid ciphertext");
// extract IV and ciphertext
// Extract IV and ciphertext.
byte[] iv = new byte[16];
byte[] encryptedData = new byte[combined.Length - 16];
Buffer.BlockCopy(combined, 0, iv, 0, 16);
@@ -41,25 +41,25 @@ public class CachedAuthorizationHandler : DelegatingHandler
/// <returns>The HTTP response message from either the cache or the original API call.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// get the called API endpoint
// Get the called API endpoint.
string requestPath = request.RequestUri!.AbsolutePath;
string cacheKey = GetAuthorizationCacheKey();
// if it's any endpoint other than the one for the authorization request, fire it away towards the original API service
// If it's any endpoint other than the one for the authorization request, fire it away towards the original API service.
if (!requestPath.EndsWith(AUTHORIZATION_ENDPOINT, StringComparison.OrdinalIgnoreCase))
{
if (requestPath.EndsWith(LOGIN_ENDPOINT)) // if login endpoint was hit, a new user is now present, delete previous cached permissions
if (requestPath.EndsWith(LOGIN_ENDPOINT)) // If login endpoint was hit, a new user is now present, delete previous cached permissions.
await _hybridCache.RemoveAsync(cacheKey, cancellationToken).ConfigureAwait(false);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
// otherwise, check the hybrid cache to see if there is a cached authorization
// Otherwise, check the hybrid cache to see if there is a cached authorization.
CachedResponse response = await _hybridCache.GetOrCreateAsync(
cacheKey,
async (cancellationToken) =>
{
// perform the actual API call if cache is empty or expired
// Perform the actual API call if cache is empty or expired.
HttpResponseMessage result = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
string content = await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// cache both status code and content
// Cache both status code and content.
return new CachedResponse
{
Content = content,
@@ -68,11 +68,11 @@ public class CachedAuthorizationHandler : DelegatingHandler
},
new HybridCacheEntryOptions()
{
Expiration = TimeSpan.FromMinutes(5) // cache for the next five minutes
Expiration = TimeSpan.FromMinutes(5) // Cache for the next five minutes.
},
cancellationToken: cancellationToken
);
// if the API returned 401 Unauthorized (i.e. token expired), DO NOT cache this response - it will be used for authorization endpoints even after successful login,
// If the API returned 401 Unauthorized (i.e. token expired), DO NOT cache this response - it will be used for authorization endpoints even after successful login,
// resulting in incorrect login redirection cycles!
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.NotFound)
await _hybridCache.RemoveAsync(cacheKey, cancellationToken).ConfigureAwait(false);
@@ -88,7 +88,7 @@ public class CachedAuthorizationHandler : DelegatingHandler
/// <returns>The cache key for the currently authenticated user's authorization response.</returns>
private string GetAuthorizationCacheKey()
{
// key the cache entry by the authenticated user's id to prevent one user's authorization response from being served to another user
// Key the cache entry by the authenticated user's id to prevent one user's authorization response from being served to another user.
string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return userId is null ? AUTHORIZATION_ENDPOINT : $"{AUTHORIZATION_ENDPOINT}:{userId}";
}
@@ -18,7 +18,7 @@ public static class ScriptIdentifierHelper
/// <summary>
/// Generates a unique script identifier using a GUID.
/// </summary>
/// <returns>A unique identifier in format "script_{guid}"</returns>
/// <returns>A unique identifier in format "script_{guid}".</returns>
/// <exception cref="InvalidOperationException">Thrown if a duplicate identifier is detected.</exception>
public static string GenerateScriptId()
{
@@ -22,7 +22,7 @@ public static class OptionsBuilderValidationUtilities
/// <returns>The same <see cref="OptionsBuilder{TOptions}"/> instance, to allow for chaining.</returns>
public static OptionsBuilder<TOptions> ValidateFluently<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
{
// register a singleton instance of IValidateOptions<TOptions> using the validator
// Register a singleton instance of IValidateOptions<TOptions> using the validator.
optionsBuilder.Services.AddSingleton<IValidateOptions<TOptions>>(
serviceProvider => new ValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
return optionsBuilder;
@@ -40,22 +40,22 @@ public class ValidationOptions<TOptions> : IValidateOptions<TOptions> where TOpt
/// <returns>A <see cref="ValidateOptionsResult"/> that indicates whether the validation was successful or not.</returns>
public ValidateOptionsResult Validate(string? name, TOptions options)
{
// check if the name of the options is specified and matches the provided one
// Check if the name of the options is specified and matches the provided one.
if (Name is not null && Name != name)
return ValidateOptionsResult.Skip;
ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null
ArgumentNullException.ThrowIfNull(options, nameof(options)); // Don't go further if the options are null.
List<Error> validationResult = _validator.Validate(options); // validate the options using the validator
List<Error> validationResult = _validator.Validate(options); // Validate the options using the validator.
// return a response based on the validation result
// Return a response based on the validation result.
if (validationResult.Count == 0)
return ValidateOptionsResult.Success;
// if the validation fails, collect the error messages
// If the validation fails, collect the error messages.
string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")];
// and return them with a failure result
// And return them with a failure result.
return ValidateOptionsResult.Fail(errors);
}
}
@@ -21,7 +21,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
private readonly List<Func<TProperty, bool>> _predicates = [];
private readonly List<Error> _predicateErrors = [];
// instance-aware predicates get their own separate pair of lists instead of being merged into the
// Instance-aware predicates get their own separate pair of lists instead of being merged into the
// lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty).
// Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
private readonly List<Func<TRequest, TProperty, bool>> _instanceAwarePredicates = [];
@@ -132,7 +132,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
/// <returns>The <see cref="Error"/> of every predicate that fails; empty if the rule passes.</returns>
public IEnumerable<Error> Validate(TRequest instance)
{
// evaluate the condition first, if it returns false, skip validation entirely.
// Evaluate the condition first, if it returns false, skip validation entirely.
if (condition is not null && !condition(instance))
yield break;
@@ -106,7 +106,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
/// <returns>One <see cref="Error"/> per failing predicate, per item; empty if every item passes.</returns>
public IEnumerable<Error> Validate(TRequest instance)
{
// Evaluate the condition first, if it returns false, skip validation entirely..
// Evaluate the condition first, if it returns false, skip validation entirely.
if (condition is not null && !condition(instance))
yield break;
@@ -47,7 +47,7 @@ public class SetLanguageEndpoint : BaseEndpoint<SetLanguageRequest, IResult>
Expires = DateTimeOffset.UtcNow.AddYears(1),
IsEssential = true,
SameSite = SameSiteMode.Lax,
Path = "/" // ensure the cookie works across all paths
Path = "/" // Ensure the cookie works across all paths.
}
);
// Determine the URL to return to, defaulting to the localized home page when no return URL is supplied.
@@ -93,7 +93,7 @@ public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
string currentCulture = Culture;
// Handle ReturnUrl and ensure it includes the correct culture.
string redirectUrl;
if (!string.IsNullOrEmpty(request.ReturnUrl) && IsLocalUrl(request.ReturnUrl)) // ensure that return URL contains the correct culture
if (!string.IsNullOrEmpty(request.ReturnUrl) && IsLocalUrl(request.ReturnUrl)) // Ensure that return URL contains the correct culture.
redirectUrl = request.ReturnUrl.StartsWith($"/{currentCulture}/") ? request.ReturnUrl : $"/{currentCulture}{request.ReturnUrl}";
else
{
@@ -123,7 +123,7 @@ public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray())
if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(request.TotpCode))
return JsonSuccess(new { isTotpRequired = true }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error
return JsonSuccess(new { isTotpRequired = true }); // Only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error.
throw;
}
}
@@ -49,7 +49,7 @@ public sealed class RazorViewToStringRenderer
/// <returns>The rendered HTML of the partial.</returns>
public async Task<string> RenderPartialAsync(string partialName, CancellationToken cancellationToken = default)
{
// the theme shell reuses the application's Razor chrome as strings, so the same markup stays in one place
// The theme shell reuses the application's Razor chrome as strings, so the same markup stays in one place.
HttpContext httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("The current HTTP context is unavailable.");
ActionContext actionContext = new(httpContext, httpContext.GetRouteData() ?? new RouteData(), new ActionDescriptor());
IView view = _viewEngine.FindView(actionContext, partialName, isMainPage: false).View
@@ -12,7 +12,7 @@ namespace Lumina.Presentation.Web.Core.Themes;
/// </summary>
public sealed class ThemeFileSystemBrowserBuilder
{
// the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath
// The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath.
private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared.Components.FileSystemBrowser.Default";
private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web";
@@ -14,7 +14,7 @@ namespace Lumina.Presentation.Web.Core.Themes;
/// </summary>
public class ThemeFileSystemBrowserRenderer
{
// the page keys mirror the template files of the theme packs, pinned in each theme manifest so that a missing sub template does not resolve to the component shell template
// The page keys mirror the template files of the theme packs, pinned in each theme manifest so that a missing sub template does not resolve to the component shell template.
private const string SHELL_PAGE_KEY = "shared/file-system-browser";
private const string TREE_NODE_PAGE_KEY = "shared/file-system-browser/tree-node";
private const string EXPLORER_ITEM_PAGE_KEY = "shared/file-system-browser/explorer-item";
@@ -73,7 +73,7 @@ public class ThemeFileSystemBrowserRenderer
}
catch (Exception)
{
// the file system browser is best effort: when the component template of the active theme cannot be loaded or rendered, the application Razor fallback is rendered instead
// The file system browser is best effort: when the component template of the active theme cannot be loaded or rendered, the application Razor fallback is rendered instead.
return Error.NotFound(code: "Theme.Template.Unavailable", description: "The file system browser theme template could not be loaded.");
}
}
@@ -91,8 +91,8 @@ public class ThemeFileSystemBrowserRenderer
try
{
ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(pageKey, themeId, cancellationToken).ConfigureAwait(false);
// when the theme does not ship the sub template, the mirrored template resolution walks up the path scopes
// and returns the component shell template instead, which the client script must not render as dynamic content
// When the theme does not ship the sub template, the mirrored template resolution walks up the path scopes
// and returns the component shell template instead, which the client script must not render as dynamic content.
if (string.Equals(document.Template, shellTemplate, StringComparison.Ordinal))
return string.Empty;
@@ -104,7 +104,7 @@ public class ThemeFileSystemBrowserRenderer
}
catch (Exception)
{
// each sub template is best effort: when the theme omits one, the client script renders that part with its built-in markup instead
// Each sub template is best effort: when the theme omits one, the client script renders that part with its built-in markup instead.
return string.Empty;
}
}
@@ -16,7 +16,7 @@ namespace Lumina.Presentation.Web.Core.Themes;
/// </summary>
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
// 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";
@@ -101,7 +101,7 @@ public class ThemeLayoutRenderer
}
catch (Exception)
{
// the themed shell is best effort: when the active theme cannot be loaded, the application layout renders the
// The themed shell is best effort: when the active theme cannot be loaded, the application layout renders the
// page instead. The exception must not propagate, otherwise the exception handling middleware turns the page
// into a JSON error instead of the fallback layout, so any page breaks whenever the theme API is unavailable.
return Error.NotFound(code: "Theme.Template.Unavailable", description: "The active theme could not be loaded.");
@@ -130,8 +130,8 @@ public class ThemeLayoutRenderer
}
catch (Exception)
{
// the navigation menu is best effort: when the theme navigation template cannot be loaded or rendered,
// the application navigation menu is rendered instead, keeping the themed shell of the page intact
// The navigation menu is best effort: when the theme navigation template cannot be loaded or rendered,
// the application navigation menu is rendered instead, keeping the themed shell of the page intact.
}
return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken);
@@ -17,7 +17,7 @@ public static class ThemePageDataFactory
/// <returns>The localized strings keyed by their resource names.</returns>
public static Dictionary<string, object?> CreateLocalizedStrings(IStringLocalizer localizer)
{
// expose the page's full resource set, so templates can pull any localized string without the page enumerating keys
// Expose the page's full resource set, so templates can pull any localized string without the page enumerating keys.
Dictionary<string, object?> strings = [];
foreach (LocalizedString localizedString in localizer.GetAllStrings(includeParentCultures: true))
strings[localizedString.Name] = localizedString.Value;
@@ -43,7 +43,7 @@ public class ThemePageRenderer
model.ThemeId = document.Theme.Id;
model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets";
// a fresh script id per render lets the AJAX navigator unload this view's script when navigating away
// A fresh script id per render lets the AJAX navigator unload this view's script when navigating away.
model.ScriptId = ScriptIdentifierHelper.GenerateScriptId();
return _templateEngine.RenderPage(document.Template, model);
@@ -54,7 +54,7 @@ public class ThemePageRenderer
}
catch (Exception)
{
// themed rendering is best effort: when the active theme cannot be loaded, the caller falls back to the Razor
// Themed rendering is best effort: when the active theme cannot be loaded, the caller falls back to the Razor
// view. The exception must not propagate, otherwise the exception handling middleware turns the page into a
// JSON error instead of the Razor fallback, so any themed page breaks whenever the theme API is unavailable.
return Error.NotFound(code: "Theme.Template.Unavailable", description: "The active theme could not be loaded.");
@@ -18,7 +18,7 @@ namespace Lumina.Presentation.Web.Core.Themes;
/// </summary>
public sealed class ThemeTemplateEngine
{
// bound template nesting and rendered output, so a single theme cannot exhaust the server memory
// Bound template nesting and rendered output, so a single theme cannot exhaust the server memory.
private const int MAX_NESTING_DEPTH = 32;
private const int MAX_RENDERED_CHARACTERS = 4 * 1024 * 1024;
@@ -42,9 +42,9 @@ public sealed class ThemeTemplateEngine
if (parseResult.IsFailure)
return parseResult.Errors;
// the reserved top-level 'scripts' section holds the script of the page and is rendered separately, mirroring the
// The reserved top-level 'scripts' section holds the script of the page and is rendered separately, mirroring the
// 'Scripts' section of a Razor view, so that the layout can host it in the scripts container of the navigator;
// every other top-level node is the content of the page section
// every other top-level node is the content of the page section.
List<ThemeTemplateNodeDto> contentNodes = [];
ThemeSectionNodeDto? scriptsSection = null;
foreach (ThemeTemplateNodeDto node in parseResult.Value)
@@ -35,7 +35,7 @@ public class FileSystemBrowserViewComponent : ViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
ThemeFileSystemBrowserConfigurationDto configuration = new(
ClientBasePath: "http://localhost:5012/", // TODO: take from appsettings or environment
ClientBasePath: "http://localhost:5012/", // TODO: take from appsettings or environment.
Path: RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\",
ViewMode: FileSystemViewMode.List.ToString().ToLower(),
IconSize: FileSystemIconSize.Large.ToString().ToLower());
+18 -18
View File
@@ -42,19 +42,19 @@ public class Program
builder.Services.AddHealthChecks()
.AddCheck<ApiReachabilityHealthCheck>("api", HealthStatus.Unhealthy, ["ready"]);
// determine log path based on environment
// Determine log path based on environment.
string logPath;
if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true")
{
logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path
builder.WebHost.ConfigureKestrel(options => options.ListenAnyIP(5012)); // HTTP only
logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // Use docker volume path.
builder.WebHost.ConfigureKestrel(options => options.ListenAnyIP(5012)); // HTTP only.
}
else
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // Use local binary path.
Directory.CreateDirectory(logPath);
if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
logPath = logPath += Path.DirectorySeparatorChar;
// set environment variable for Serilog configuration
// Set environment variable for Serilog configuration.
Environment.SetEnvironmentVariable("LOG_PATH", logPath);
builder.Host.UseSerilog((context, services, configuration) =>
@@ -70,7 +70,7 @@ public class Program
app.UseRequestLocalization();
app.UseSerilogRequestLogging();
// configure the HTTP request pipeline.
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment() && Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") != "true")
{
app.UseExceptionHandler("/home/error");
@@ -83,33 +83,33 @@ public class Program
{
OnPrepareResponse = staticFileResponseContext =>
{
// disable static file caching during development
// Disable static file caching during development.
if (app.Environment.IsDevelopment())
{
staticFileResponseContext.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store");
staticFileResponseContext.Context.Response.Headers.Append("Expires", "-1");
}
},
// prevent static files from being processed by routing
// Prevent static files from being processed by routing.
ServeUnknownFileTypes = true
});
app.UseCultureRedirect(); // if the user attempts to go to a localized route without providing a culture, redirect to default culture
app.UseApiExceptionHandling(); // handle any problem details returned by the API
app.UseCultureRedirect(); // If the user attempts to go to a localized route without providing a culture, redirect to default culture.
app.UseApiExceptionHandling(); // Handle any problem details returned by the API.
app.UseRouting();
app.UseRequestLocalization(); // set the culture from the localized routes
// restore the Cache-Control chosen by the endpoint after the antiforgery and session middlewares overwrite it
app.UseRequestLocalization(); // Set the culture from the localized routes.
// Restore the Cache-Control chosen by the endpoint after the antiforgery and session middlewares overwrite it.
app.UseCacheControlHeader();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
// The rate limiting policies are evaluated after authentication, because the track stream limit is partitioned per authenticated user.
app.UseRateLimiter();
// validate the antiforgery token after authentication, because the token is bound to the authenticated user and
// validating it before the user is known would reject every request made by a logged-in user
// Validate the antiforgery token after authentication, because the token is bound to the authenticated user and
// validating it before the user is known would reject every request made by a logged-in user.
app.UseAntiforgeryFE(additionalContentTypes: ["application/json"]);
app.UseForwardedHeaders();
// handle path base from reverse proxies
// Handle path base from reverse proxies.
app.Use((context, next) =>
{
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
@@ -121,7 +121,7 @@ public class Program
app.UseFastEndpoints();
// add API documentation (OpenApi/Scalar), so that the endpoints exposed by the web application are discoverable and their contracts are visible
// Add API documentation (OpenApi/Scalar), so that the endpoints exposed by the web application are discoverable and their contracts are visible.
app.MapOpenApi();
app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json");
app.MapScalarApiReference(scalarOptions =>
@@ -132,8 +132,8 @@ public class Program
.WithDotNetFlag(true);
});
// liveness and readiness probes, probed by container orchestrators and load balancers; the readiness probe also
// verifies that the API is reachable, so the web application is only reported ready when it can actually serve requests
// Liveness and readiness probes, probed by container orchestrators and load balancers; the readiness probe also
// verifies that the API is reachable, so the web application is only reported ready when it can actually serve requests.
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = healthCheck => healthCheck.Tags.Contains("ready") });