mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #157 from BinaryAlley/feature/web-theme-engine
Adds the web theme engine
This commit is contained in:
29 files changed
+2254
-4
No files matched your search
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for deserializing theme engine settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Section name: {SECTION_NAME}")]
|
||||
public sealed class ThemeEngineOptionsDto
|
||||
{
|
||||
public const string SECTION_NAME = "ThemeEngine";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the directory where installed theme packages are stored.
|
||||
/// </summary>
|
||||
public string StoragePath { get; set; } = "Themes";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the file name of the persisted theme settings.
|
||||
/// </summary>
|
||||
public string SettingsPath { get; set; } = "theme-settings.json";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the identifier of the theme selected when no valid current theme is persisted.
|
||||
/// </summary>
|
||||
public string DefaultThemeId { get; set; } = "lumina-default";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum allowed size of an uploaded theme archive, in bytes.
|
||||
/// </summary>
|
||||
public long MaxArchiveBytes { get; set; } = 8 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum allowed total size of an extracted theme archive, in bytes.
|
||||
/// </summary>
|
||||
public long MaxExpandedBytes { get; set; } = 24 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum allowed size of a single file within a theme archive, in bytes.
|
||||
/// </summary>
|
||||
public long MaxSingleFileBytes { get; set; } = 6 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum allowed number of entries in a theme archive.
|
||||
/// </summary>
|
||||
public int MaxEntries { get; set; } = 250;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether theme templates may load script files.
|
||||
/// </summary>
|
||||
public bool AllowThemeScripts { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a content entry rendered by a theme.
|
||||
/// </summary>
|
||||
/// <param name="Number">The ordering number of the content entry.</param>
|
||||
/// <param name="Title">The title of the content entry.</param>
|
||||
/// <param name="Description">The description of the content entry.</param>
|
||||
/// <param name="Meta">The metadata line of the content entry.</param>
|
||||
/// <param name="Badge">The badge text of the content entry.</param>
|
||||
/// <param name="Accent">The accent color of the content entry.</param>
|
||||
/// <param name="Glyph">The glyph or icon of the content entry.</param>
|
||||
/// <param name="Url">The URL the content entry links to.</param>
|
||||
[DebuggerDisplay("Number: {Number}, Title: {Title}")]
|
||||
public sealed record ContentItemDto(
|
||||
string Number,
|
||||
string Title,
|
||||
string Description,
|
||||
string Meta,
|
||||
string Badge,
|
||||
string Accent,
|
||||
string Glyph,
|
||||
string Url
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for an installed theme.
|
||||
/// </summary>
|
||||
/// <param name="Manifest">The validated theme manifest.</param>
|
||||
/// <param name="Info">The display metadata of the theme.</param>
|
||||
/// <param name="RootPath">The absolute path of the installed theme directory.</param>
|
||||
[DebuggerDisplay("Manifest name: {Manifest.Name}")]
|
||||
public sealed record InstalledThemeDto(
|
||||
ThemeManifestDto Manifest,
|
||||
ThemeInfoDto Info,
|
||||
string RootPath
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a navigation entry rendered by a theme.
|
||||
/// </summary>
|
||||
/// <param name="Key">The unique key of the navigation entry.</param>
|
||||
/// <param name="Label">The display label of the navigation entry.</param>
|
||||
/// <param name="Url">The URL the navigation entry links to.</param>
|
||||
/// <param name="IsCurrent">Whether the navigation entry represents the currently displayed page.</param>
|
||||
[DebuggerDisplay("Key: {Key}, Label: {Label}")]
|
||||
public sealed record NavigationItemDto(
|
||||
string Key,
|
||||
string Label,
|
||||
string Url,
|
||||
bool IsCurrent
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the settings persisted for the theme engine.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentThemeId: {CurrentThemeId}")]
|
||||
public sealed class PersistedThemeSettingsDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier of the currently selected theme.
|
||||
/// </summary>
|
||||
public string CurrentThemeId { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a statistic rendered by a theme.
|
||||
/// </summary>
|
||||
/// <param name="Value">The numeric or textual value of the statistic.</param>
|
||||
/// <param name="Label">The label of the statistic.</param>
|
||||
/// <param name="Detail">The additional detail of the statistic.</param>
|
||||
[DebuggerDisplay("Value: {Value}, Label: {Label}")]
|
||||
public sealed record StatItemDto(
|
||||
string Value,
|
||||
string Label,
|
||||
string Detail
|
||||
);
|
||||
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the data shown on the theme administration page.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentThemeId: {CurrentThemeId}")]
|
||||
public sealed class ThemeAdminDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the metadata of all installed themes.
|
||||
/// </summary>
|
||||
public required IReadOnlyList<ThemeInfoDto> Themes { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier of the currently selected theme.
|
||||
/// </summary>
|
||||
public required string CurrentThemeId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether theme templates may load script files.
|
||||
/// </summary>
|
||||
public required bool AllowThemeScripts { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum allowed size of a theme archive, in bytes.
|
||||
/// </summary>
|
||||
public required long MaxArchiveBytes { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum allowed size of a theme archive, in megabytes.
|
||||
/// </summary>
|
||||
public double MaxArchiveMegabytes => Math.Round(MaxArchiveBytes / 1024d / 1024d, 1);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for an in-memory ZIP archive of an installed theme.
|
||||
/// </summary>
|
||||
/// <param name="FileName">The file name to expose when downloading the archive.</param>
|
||||
/// <param name="Content">The ZIP archive stream positioned at its start.</param>
|
||||
[DebuggerDisplay("FileName: {FileName}")]
|
||||
public sealed record ThemeArchiveDto(
|
||||
string FileName,
|
||||
Stream Content
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the display metadata of a theme.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the theme.</param>
|
||||
/// <param name="Name">The display name of the theme.</param>
|
||||
/// <param name="Description">The description of the theme.</param>
|
||||
/// <param name="Author">The author of the theme.</param>
|
||||
/// <param name="Version">The version of the theme, using semantic version form.</param>
|
||||
/// <param name="PreviewUrl">The URL of the theme preview image.</param>
|
||||
/// <param name="IsBundled">Whether the theme ships with the application or noy.</param>
|
||||
[DebuggerDisplay("Id: {Id}, Name: {Name}")]
|
||||
public sealed record ThemeInfoDto(
|
||||
string Id,
|
||||
string Name,
|
||||
string Description,
|
||||
string Author,
|
||||
string Version,
|
||||
string PreviewUrl,
|
||||
bool IsBundled
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Themes;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the metadata persisted alongside an installed theme.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Source: {Source}")]
|
||||
public sealed class ThemeInstallationMetadataDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the source the theme was installed from.
|
||||
/// </summary>
|
||||
public ThemeInstallSource Source { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the UTC timestamp at which the theme was installed.
|
||||
/// </summary>
|
||||
public DateTimeOffset InstalledAtUtc { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the theme.json manifest of a theme package.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}, Name: {Name}")]
|
||||
public sealed class ThemeManifestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the supported schema version of the manifest.
|
||||
/// </summary>
|
||||
public int SchemaVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier of the theme, a lowercase kebab-case value.
|
||||
/// </summary>
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the display name of the theme.
|
||||
/// </summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the theme.
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the author of the theme.
|
||||
/// </summary>
|
||||
public string Author { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the version of the theme, using semantic version form.
|
||||
/// </summary>
|
||||
public string Version { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the preview image path relative to the theme package root, or <see langword="null"/> when the theme has no preview.
|
||||
/// </summary>
|
||||
public string? Preview { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the template mappings from template key to an HTML file path under templates/.
|
||||
/// </summary>
|
||||
public Dictionary<string, string> Templates { get; set; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the full model available to a theme template while rendering a page.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public sealed class ThemePageDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the key of the page, used to select the template to render.
|
||||
/// </summary>
|
||||
public required string PageKey { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the site displayed by the theme.
|
||||
/// </summary>
|
||||
public required string SiteName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the title of the page.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the page.
|
||||
/// </summary>
|
||||
public required string Description { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the eyebrow text shown above the page title.
|
||||
/// </summary>
|
||||
public required string Eyebrow { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the label of the primary call to action.
|
||||
/// </summary>
|
||||
public required string PrimaryActionLabel { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the URL of the primary call to action.
|
||||
/// </summary>
|
||||
public required string PrimaryActionUrl { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the label of the secondary call to action.
|
||||
/// </summary>
|
||||
public required string SecondaryActionLabel { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the URL of the secondary call to action.
|
||||
/// </summary>
|
||||
public required string SecondaryActionUrl { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the navigation entries rendered by the theme.
|
||||
/// </summary>
|
||||
public required IReadOnlyList<NavigationItemDto> Navigation { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the content entries rendered by the theme.
|
||||
/// </summary>
|
||||
public required IReadOnlyList<ContentItemDto> Items { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the statistics rendered by the theme.
|
||||
/// </summary>
|
||||
public required IReadOnlyList<StatItemDto> Stats { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the page is a theme preview.
|
||||
/// </summary>
|
||||
public bool IsPreview { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the identifier of the theme rendering the page. Populated immediately before rendering.
|
||||
/// </summary>
|
||||
public string ThemeId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the theme rendering the page. Populated immediately before rendering.
|
||||
/// </summary>
|
||||
public string ThemeName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the version of the theme rendering the page. Populated immediately before rendering.
|
||||
/// </summary>
|
||||
public string ThemeVersion { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the base URL of the theme assets. Populated immediately before rendering.
|
||||
/// </summary>
|
||||
public string AssetBase { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current year. Populated immediately before rendering.
|
||||
/// </summary>
|
||||
public int CurrentYear { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a rendered document.
|
||||
/// </summary>
|
||||
/// <param name="Theme">The metadata of the resolved theme.</param>
|
||||
/// <param name="Template">The raw template source to render.</param>
|
||||
[DebuggerDisplay("Theme name: {Theme.Name}")]
|
||||
public sealed record ThemeRenderDocumentDto(
|
||||
ThemeInfoDto Theme,
|
||||
string Template
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the model resolution context used while rendering a theme template.
|
||||
/// </summary>
|
||||
/// <param name="Value">The model value this scope resolves expressions against.</param>
|
||||
/// <param name="Parent">The parent scope, or <see langword="null"/> for the root scope.</param>
|
||||
[DebuggerDisplay("Value: {Value}")]
|
||||
public sealed record ThemeRenderScopeDto(
|
||||
object? Value,
|
||||
ThemeRenderScopeDto? Parent
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a conditional or repeating section in a theme template.
|
||||
/// </summary>
|
||||
/// <param name="Expression">The property path expression that controls the section.</param>
|
||||
/// <param name="Inverted">Whether the section renders when the resolved value is falsy instead of truthy.</param>
|
||||
/// <param name="Children">The template nodes rendered when the section is active.</param>
|
||||
[DebuggerDisplay("Expression: {Expression}")]
|
||||
public sealed record ThemeSectionNodeDto(
|
||||
string Expression,
|
||||
bool Inverted,
|
||||
IReadOnlyList<ThemeTemplateNodeDto> Children
|
||||
) : ThemeTemplateNodeDto;
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Base type for all nodes of a parsed theme template.
|
||||
/// </summary>
|
||||
public abstract record ThemeTemplateNodeDto;
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a literal text segment of a theme template.
|
||||
/// </summary>
|
||||
/// <param name="Value">The literal text to render as-is.</param>
|
||||
[DebuggerDisplay("Value: {Value}")]
|
||||
public sealed record ThemeTextNodeDto(
|
||||
string Value
|
||||
) : ThemeTemplateNodeDto;
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a variable expression in a theme template.
|
||||
/// </summary>
|
||||
/// <param name="Expression">The property path expression to resolve.</param>
|
||||
/// <param name="ShouldBeEscaped">Whether the rendered value should be HTML encoded.</param>
|
||||
[DebuggerDisplay("Expression: {Expression}")]
|
||||
public sealed record ThemeVariableNodeDto(
|
||||
string Expression,
|
||||
bool ShouldBeEscaped
|
||||
) : ThemeTemplateNodeDto;
|
||||
+5
@@ -36,6 +36,11 @@ internal static class PresentationWebLayerConfiguration
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
serviceCollection.AddOptions<ThemeEngineOptionsDto>()
|
||||
.Bind(configuration.GetRequiredSection(ThemeEngineOptionsDto.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
return serviceCollection;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ using Lumina.Presentation.Web.Common.Localization;
|
||||
using Lumina.Presentation.Web.Common.Security;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Common.Validation;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
@@ -300,6 +301,11 @@ public static class PresentationWebLayerServices
|
||||
services.AddHttpContextAccessor();
|
||||
services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024);
|
||||
|
||||
services.AddSingleton<ThemeSettingsStore>();
|
||||
services.AddSingleton<ThemeService>();
|
||||
services.AddSingleton<ThemeTemplateEngine>();
|
||||
services.AddSingleton<ThemePageRenderer>();
|
||||
|
||||
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
|
||||
services.AddScoped<IAuthorizationHandler, RoleAuthorizationHandler>();
|
||||
services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Lumina.Presentation.Web.Common.Enums.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the source a theme was installed from.
|
||||
/// </summary>
|
||||
public enum ThemeInstallSource
|
||||
{
|
||||
/// <summary>
|
||||
/// The theme was uploaded by a user.
|
||||
/// </summary>
|
||||
Uploaded,
|
||||
|
||||
/// <summary>
|
||||
/// The theme is bundled with the application.
|
||||
/// </summary>
|
||||
Bundled
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Utilities;
|
||||
using Lumina.Presentation.Web.Common.Validation;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for the ThemeEngine application configuration settings section.
|
||||
/// </summary>
|
||||
public class ThemeEngineOptionsDtoValidator : AbstractValidator<ThemeEngineOptionsDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeEngineOptionsDtoValidator"/> class.
|
||||
/// </summary>
|
||||
public ThemeEngineOptionsDtoValidator()
|
||||
{
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.StoragePath)
|
||||
.NotEmpty()
|
||||
.WithError(Error.Validation(description: "Theme storage path cannot be empty!"));
|
||||
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.SettingsPath)
|
||||
.NotEmpty()
|
||||
.WithError(Error.Validation(description: "Theme settings path cannot be empty!"));
|
||||
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.DefaultThemeId)
|
||||
.NotEmpty()
|
||||
.WithError(Error.Validation(description: "Default theme Id cannot be empty!"));
|
||||
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.MaxArchiveBytes)
|
||||
.GreaterThan(0)
|
||||
.WithError(Error.Validation(description: "Maximum archive size must be greater than 0!"));
|
||||
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.MaxExpandedBytes)
|
||||
.GreaterThan(0)
|
||||
.WithError(Error.Validation(description: "Maximum expanded size must be greater than 0!"));
|
||||
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.MaxSingleFileBytes)
|
||||
.GreaterThan(0)
|
||||
.WithError(Error.Validation(description: "Maximum single file size must be greater than 0!"));
|
||||
|
||||
RuleFor(themeEngineOptions => themeEngineOptions.MaxEntries)
|
||||
.GreaterThan(0)
|
||||
.WithError(Error.Validation(description: "Maximum entries count must be greater than 0!"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Renders a theme template against a page model, populating the theme metadata before rendering.
|
||||
/// </summary>
|
||||
public sealed class ThemePageRenderer
|
||||
{
|
||||
private readonly ThemeService _themeService;
|
||||
private readonly ThemeTemplateEngine _templateEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemePageRenderer"/> class.
|
||||
/// </summary>
|
||||
/// <param name="themeService">The service that resolves the render document.</param>
|
||||
/// <param name="templateEngine">The template engine used to render the document.</param>
|
||||
public ThemePageRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine)
|
||||
{
|
||||
_themeService = themeService;
|
||||
_templateEngine = templateEngine;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders the page model with the theme selected for the requested theme identifier.
|
||||
/// </summary>
|
||||
/// <param name="model">The page model to render.</param>
|
||||
/// <param name="requestedThemeId">The optional unique identifier of the theme to render with, falling back to the current theme when <see langword="null"/>.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the rendered HTML, or an error.</returns>
|
||||
public async Task<Result<string>> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Result<ThemeRenderDocumentDto> documentResult = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken);
|
||||
if (documentResult.IsFailure)
|
||||
return Result<string>.Failure(documentResult.Errors);
|
||||
|
||||
ThemeRenderDocumentDto document = documentResult.Value;
|
||||
|
||||
model.ThemeId = document.Theme.Id;
|
||||
model.ThemeName = document.Theme.Name;
|
||||
model.ThemeVersion = document.Theme.Version;
|
||||
model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets";
|
||||
model.CurrentYear = DateTime.UtcNow.Year;
|
||||
|
||||
return _templateEngine.Render(document.Template, model);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,889 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Enums.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Manages the installed theme packages: installation, selection, rendering documents and archives.
|
||||
/// </summary>
|
||||
public sealed class ThemeService
|
||||
{
|
||||
private const string MANIFEST_FILE_NAME = "theme.json";
|
||||
private const string INSTALLATION_FILE_NAME = ".theme-install.json";
|
||||
private const long MAX_MANIFEST_BYTES = 64 * 1024;
|
||||
|
||||
private static readonly Regex s_themeIdPattern = new(
|
||||
"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex s_templateKeyPattern = new(
|
||||
"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex s_versionPattern = new(
|
||||
"^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly Regex s_pathSegmentPattern = new(
|
||||
"^[A-Za-z0-9][A-Za-z0-9._ -]*$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
private static readonly HashSet<string> s_assetExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
".css", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico",
|
||||
".woff", ".woff2", ".ttf"
|
||||
};
|
||||
|
||||
private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
MaxDepth = 16
|
||||
};
|
||||
|
||||
private static readonly JsonSerializerOptions s_metadataJsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private readonly ThemeEngineOptionsDto _options;
|
||||
private readonly ThemeSettingsStore _settingsStore;
|
||||
private readonly ThemeTemplateEngine _templateEngine;
|
||||
private readonly ILogger<ThemeService> _logger;
|
||||
private readonly string _contentRoot;
|
||||
private readonly string _storageRoot;
|
||||
private readonly string _stagingRoot;
|
||||
private readonly ConcurrentDictionary<string, InstalledThemeDto> _themes = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly SemaphoreSlim _mutationGate = new(1, 1);
|
||||
private bool _initialized;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environment">The web host environment, used to resolve the content root.</param>
|
||||
/// <param name="options">The theme engine configuration options.</param>
|
||||
/// <param name="settingsStore">The store that persists the current theme selection.</param>
|
||||
/// <param name="templateEngine">The template engine used to validate installed templates.</param>
|
||||
/// <param name="logger">The logger for this service.</param>
|
||||
public ThemeService(
|
||||
IWebHostEnvironment environment,
|
||||
IOptions<ThemeEngineOptionsDto> options,
|
||||
ThemeSettingsStore settingsStore,
|
||||
ThemeTemplateEngine templateEngine,
|
||||
ILogger<ThemeService> logger)
|
||||
{
|
||||
_contentRoot = environment.ContentRootPath;
|
||||
_options = options.Value;
|
||||
_settingsStore = settingsStore;
|
||||
_templateEngine = templateEngine;
|
||||
_logger = logger;
|
||||
_storageRoot = ResolvePath(_contentRoot, _options.StoragePath);
|
||||
_stagingRoot = Path.Combine(_storageRoot, ".staging");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether theme templates may load script files.
|
||||
/// </summary>
|
||||
public bool AllowThemeScripts => _options.AllowThemeScripts;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum allowed size of a theme archive, in bytes.
|
||||
/// </summary>
|
||||
public long MaxArchiveBytes => _options.MaxArchiveBytes;
|
||||
|
||||
/// <summary>
|
||||
/// Loads the bundled and previously installed themes into memory and selects a valid current theme.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> InitializeAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _mutationGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (_initialized)
|
||||
return Result.Success;
|
||||
|
||||
Directory.CreateDirectory(_storageRoot);
|
||||
Directory.CreateDirectory(_stagingRoot);
|
||||
CleanStagingDirectory();
|
||||
|
||||
string sampleThemeDirectory = Path.Combine(_contentRoot, "SampleThemes");
|
||||
if (Directory.Exists(sampleThemeDirectory))
|
||||
{
|
||||
foreach (string? archivePath in Directory.EnumerateFiles(sampleThemeDirectory, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
await using FileStream archive = File.OpenRead(archivePath);
|
||||
Result<InstalledThemeDto> installResult = await InstallCoreAsync(archive, skipIfInstalled: true, source: ThemeInstallSource.Bundled, cancellationToken);
|
||||
if (installResult.IsFailure)
|
||||
return Result<Success>.Failure(installResult.Errors);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (string themeDirectory in Directory.EnumerateDirectories(_storageRoot))
|
||||
{
|
||||
if (Path.GetFileName(themeDirectory).StartsWith('.'))
|
||||
continue;
|
||||
|
||||
Result<InstalledThemeDto> loadResult = await LoadInstalledThemeAsync(themeDirectory, cancellationToken);
|
||||
if (loadResult.IsFailure)
|
||||
{
|
||||
_logger.LogWarning("Skipping invalid installed theme directory {ThemeDirectory}. {Error}", themeDirectory, loadResult.FirstError.Description);
|
||||
continue;
|
||||
}
|
||||
|
||||
_themes[loadResult.Value.Manifest.Id] = loadResult.Value;
|
||||
}
|
||||
|
||||
if (_themes.IsEmpty)
|
||||
return Error.Failure(code: "Theme.NoInstalledThemes", description: "No valid themes are installed. Ensure the SampleThemes archives are present.");
|
||||
|
||||
string? currentThemeId = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken);
|
||||
if (currentThemeId is null || !_themes.ContainsKey(currentThemeId))
|
||||
await EnsureValidCurrentThemeAsync(cancellationToken);
|
||||
_initialized = true;
|
||||
return Result.Success;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_mutationGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display metadata of all installed themes.
|
||||
/// </summary>
|
||||
/// <returns>The list of installed theme metadata.</returns>
|
||||
public IReadOnlyList<ThemeInfoDto> GetThemes()
|
||||
{
|
||||
return [.. _themes.Values
|
||||
.Select(theme => theme.Info)
|
||||
.OrderByDescending(theme => theme.IsBundled)
|
||||
.ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a theme with the specified identifier is installed.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The theme identifier to look up.</param>
|
||||
/// <returns>true when the theme is installed; otherwise, false.</returns>
|
||||
public bool IsInstalled(string themeId)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(themeId) && _themes.ContainsKey(themeId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the identifier of the currently selected theme, resolving a valid selection when needed.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The identifier of the current theme.</returns>
|
||||
public async Task<string> GetCurrentThemeIdAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
string? current = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken);
|
||||
if (current is not null && _themes.ContainsKey(current))
|
||||
return current;
|
||||
|
||||
return await EnsureValidCurrentThemeAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects the theme with the specified identifier as the current theme.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The identifier of the theme to select.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Success>> SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(themeId) || !_themes.ContainsKey(themeId))
|
||||
return ThemeNotFound(themeId);
|
||||
|
||||
await _settingsStore.SetCurrentThemeIdAsync(themeId, cancellationToken);
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs a theme from the provided archive.
|
||||
/// </summary>
|
||||
/// <param name="archive">The ZIP archive stream of the theme package.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the installed theme metadata, or an error.</returns>
|
||||
public async Task<Result<ThemeInfoDto>> InstallAsync(Stream archive, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _mutationGate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
Result<InstalledThemeDto> installedResult = await InstallCoreAsync(archive, skipIfInstalled: false, source: ThemeInstallSource.Uploaded, cancellationToken);
|
||||
if (installedResult.IsFailure)
|
||||
return Result<ThemeInfoDto>.Failure(installedResult.Errors);
|
||||
|
||||
return installedResult.Value.Info;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_mutationGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the theme and raw template source selected for a page key.
|
||||
/// </summary>
|
||||
/// <param name="pageKey">The page key that selects the template to render.</param>
|
||||
/// <param name="requestedThemeId">The optional theme to render with, falling back to the current theme when null.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the render document, or an error.</returns>
|
||||
public async Task<Result<ThemeRenderDocumentDto>> GetRenderDocumentAsync(string pageKey, string? requestedThemeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
InstalledThemeDto installedTheme;
|
||||
if (!string.IsNullOrWhiteSpace(requestedThemeId))
|
||||
{
|
||||
if (!_themes.TryGetValue(requestedThemeId, out InstalledThemeDto? requestedTheme))
|
||||
return ThemeNotFound(requestedThemeId);
|
||||
|
||||
installedTheme = requestedTheme;
|
||||
}
|
||||
else
|
||||
{
|
||||
string currentThemeId = await GetCurrentThemeIdAsync(cancellationToken);
|
||||
installedTheme = _themes[currentThemeId];
|
||||
}
|
||||
|
||||
if (!installedTheme.Manifest.Templates.TryGetValue(pageKey, out string? templatePath))
|
||||
templatePath = installedTheme.Manifest.Templates["default"];
|
||||
|
||||
Result<string> fullTemplatePathResult = ResolveContainedPath(installedTheme.RootPath, templatePath);
|
||||
if (fullTemplatePathResult.IsFailure)
|
||||
return Result<ThemeRenderDocumentDto>.Failure(fullTemplatePathResult.Errors);
|
||||
|
||||
string template = await File.ReadAllTextAsync(fullTemplatePathResult.Value, cancellationToken);
|
||||
return new ThemeRenderDocumentDto(installedTheme.Info, template);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the absolute path of an allowed theme asset, when it exists.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The theme identifier.</param>
|
||||
/// <param name="assetPath">The asset path relative to the theme package root.</param>
|
||||
/// <param name="fullPath">The resolved absolute path of the asset, empty when not resolved.</param>
|
||||
/// <returns>true when the asset was resolved; otherwise, false.</returns>
|
||||
public bool TryResolveAsset(string themeId, string assetPath, out string fullPath)
|
||||
{
|
||||
fullPath = string.Empty;
|
||||
if (!_themes.TryGetValue(themeId, out InstalledThemeDto? installedTheme))
|
||||
return false;
|
||||
|
||||
Result<string> normalizedPathResult = NormalizeRelativePath(assetPath);
|
||||
if (normalizedPathResult.IsFailure)
|
||||
return false;
|
||||
|
||||
string normalizedPath = normalizedPathResult.Value;
|
||||
if (!normalizedPath.StartsWith("assets/", StringComparison.Ordinal))
|
||||
return false;
|
||||
|
||||
string extension = Path.GetExtension(normalizedPath);
|
||||
if (!IsAllowedAssetExtension(extension))
|
||||
return false;
|
||||
|
||||
Result<string> candidateResult = ResolveContainedPath(installedTheme.RootPath, normalizedPath);
|
||||
if (candidateResult.IsFailure)
|
||||
return false;
|
||||
|
||||
if (!File.Exists(candidateResult.Value))
|
||||
return false;
|
||||
|
||||
fullPath = candidateResult.Value;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a downloadable ZIP archive of an installed theme.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The identifier of the theme to archive.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the theme archive, or an error.</returns>
|
||||
public async Task<Result<ThemeArchiveDto>> BuildArchiveAsync(string themeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_themes.TryGetValue(themeId, out InstalledThemeDto? installedTheme))
|
||||
return ThemeNotFound(themeId);
|
||||
|
||||
MemoryStream output = new();
|
||||
using (ZipArchive archive = new(output, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
foreach (string? filePath in Directory.EnumerateFiles(installedTheme.RootPath, "*", SearchOption.AllDirectories)
|
||||
.Where(path => !string.Equals(Path.GetFileName(path), INSTALLATION_FILE_NAME, StringComparison.Ordinal))
|
||||
.OrderBy(path => path, StringComparer.Ordinal))
|
||||
{
|
||||
string relativePath = Path.GetRelativePath(installedTheme.RootPath, filePath).Replace(Path.DirectorySeparatorChar, '/');
|
||||
ZipArchiveEntry entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal);
|
||||
await using FileStream input = File.OpenRead(filePath);
|
||||
await using Stream outputStream = entry.Open();
|
||||
await input.CopyToAsync(outputStream, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
output.Position = 0;
|
||||
string safeVersion = installedTheme.Manifest.Version.Replace('+', '-');
|
||||
return new ThemeArchiveDto($"{installedTheme.Manifest.Id}-{safeVersion}.zip", output);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs a theme package from an archive stream into the storage root.
|
||||
/// </summary>
|
||||
/// <param name="sourceArchive">The ZIP archive stream of the theme package.</param>
|
||||
/// <param name="skipIfInstalled">Whether an already installed theme with the same id is accepted without reinstalling.</param>
|
||||
/// <param name="source">The source the theme is installed from.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the installed theme, or an error.</returns>
|
||||
private async Task<Result<InstalledThemeDto>> InstallCoreAsync(Stream sourceArchive, bool skipIfInstalled, ThemeInstallSource source, CancellationToken cancellationToken)
|
||||
{
|
||||
string workId = Guid.NewGuid().ToString("N");
|
||||
string temporaryArchivePath = Path.Combine(_stagingRoot, $"{workId}.zip");
|
||||
string extractionPath = Path.Combine(_stagingRoot, workId);
|
||||
|
||||
try
|
||||
{
|
||||
Result<Success> copyResult = await CopyArchiveWithLimitAsync(sourceArchive, temporaryArchivePath, cancellationToken);
|
||||
if (copyResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(copyResult.Errors);
|
||||
|
||||
Directory.CreateDirectory(extractionPath);
|
||||
Result<Success> extractResult = await ExtractArchiveAsync(temporaryArchivePath, extractionPath, cancellationToken);
|
||||
if (extractResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(extractResult.Errors);
|
||||
|
||||
Result<InstalledThemeDto> stagedResult = await LoadInstalledThemeAsync(extractionPath, cancellationToken, sourceOverride: source);
|
||||
if (stagedResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(stagedResult.Errors);
|
||||
|
||||
InstalledThemeDto stagedTheme = stagedResult.Value;
|
||||
string destination = Path.Combine(_storageRoot, stagedTheme.Manifest.Id);
|
||||
|
||||
if (Directory.Exists(destination))
|
||||
{
|
||||
if (!skipIfInstalled)
|
||||
return Error.Conflict(code: "Theme.AlreadyInstalled", description: $"A theme with id '{stagedTheme.Manifest.Id}' is already installed.");
|
||||
|
||||
Result<InstalledThemeDto> existingResult = await LoadInstalledThemeAsync(destination, cancellationToken);
|
||||
if (existingResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(existingResult.Errors);
|
||||
|
||||
_themes[existingResult.Value.Manifest.Id] = existingResult.Value;
|
||||
return existingResult.Value;
|
||||
}
|
||||
|
||||
ThemeInstallationMetadataDto metadata = new()
|
||||
{
|
||||
Source = source,
|
||||
InstalledAtUtc = DateTimeOffset.UtcNow
|
||||
};
|
||||
string metadataJson = JsonSerializer.Serialize(metadata, s_metadataJsonOptions);
|
||||
await File.WriteAllTextAsync(Path.Combine(extractionPath, INSTALLATION_FILE_NAME), metadataJson, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken);
|
||||
|
||||
Directory.Move(extractionPath, destination);
|
||||
Result<InstalledThemeDto> installedResult = await LoadInstalledThemeAsync(destination, cancellationToken);
|
||||
if (installedResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(installedResult.Errors);
|
||||
|
||||
_themes[installedResult.Value.Manifest.Id] = installedResult.Value;
|
||||
return installedResult.Value;
|
||||
}
|
||||
catch (InvalidDataException exception)
|
||||
{
|
||||
_logger.LogWarning(exception, "An uploaded theme archive could not be read.");
|
||||
return Error.Failure(code: "Theme.Archive.ReadFailed", description: "The uploaded file is not a readable ZIP archive.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temporaryArchivePath))
|
||||
File.Delete(temporaryArchivePath);
|
||||
|
||||
if (Directory.Exists(extractionPath))
|
||||
Directory.Delete(extractionPath, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the source archive to the staging directory while enforcing the maximum archive size.
|
||||
/// </summary>
|
||||
/// <param name="source">The archive stream to copy.</param>
|
||||
/// <param name="destinationPath">The temporary file to copy the archive into.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> CopyArchiveWithLimitAsync(Stream source, string destinationPath, CancellationToken cancellationToken)
|
||||
{
|
||||
await using FileStream destination = new(destinationPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 64 * 1024, useAsync: true);
|
||||
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
long totalBytes = 0;
|
||||
while (true)
|
||||
{
|
||||
int read = await source.ReadAsync(buffer.AsMemory(), cancellationToken);
|
||||
if (read == 0)
|
||||
break;
|
||||
|
||||
totalBytes += read;
|
||||
if (totalBytes > _options.MaxArchiveBytes)
|
||||
return Error.Validation(code: "Theme.Archive.TooLarge", description: $"The theme archive exceeds the {_options.MaxArchiveBytes / 1024 / 1024} MB limit.");
|
||||
|
||||
await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
|
||||
}
|
||||
|
||||
if (totalBytes == 0)
|
||||
return Error.Validation(code: "Theme.Archive.Empty", description: "The uploaded theme archive is empty.");
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts a staged theme archive into the staging extraction directory after validating its entries.
|
||||
/// </summary>
|
||||
/// <param name="archivePath">The path of the staged ZIP archive.</param>
|
||||
/// <param name="extractionPath">The directory the archive is extracted into.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<Result<Success>> ExtractArchiveAsync(string archivePath, string extractionPath, CancellationToken cancellationToken)
|
||||
{
|
||||
using ZipArchive archive = ZipFile.OpenRead(archivePath);
|
||||
if (archive.Entries.Count == 0)
|
||||
return Error.Validation(code: "Theme.Archive.Empty", description: "The theme archive contains no files.");
|
||||
|
||||
if (archive.Entries.Count > _options.MaxEntries)
|
||||
return Error.Validation(code: "Theme.Archive.TooManyEntries", description: $"The theme archive contains more than {_options.MaxEntries} entries.");
|
||||
|
||||
HashSet<string> seenPaths = new(StringComparer.OrdinalIgnoreCase);
|
||||
long expandedBytes = 0;
|
||||
|
||||
foreach (ZipArchiveEntry entry in archive.Entries)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
int unixFileType = (entry.ExternalAttributes >> 16) & 0xF000;
|
||||
if (unixFileType == 0xA000)
|
||||
return PackageInvalid("Symbolic links are not allowed in theme archives.");
|
||||
|
||||
Result<string> normalizedPathResult = NormalizeRelativePath(entry.FullName, allowTrailingSlash: true);
|
||||
if (normalizedPathResult.IsFailure)
|
||||
return Result<Success>.Failure(normalizedPathResult.Errors);
|
||||
|
||||
string normalizedPath = normalizedPathResult.Value;
|
||||
if (!seenPaths.Add(normalizedPath))
|
||||
return PackageInvalid($"The archive contains a duplicate path: {normalizedPath}");
|
||||
|
||||
bool isDirectory = entry.FullName.EndsWith('/') || string.IsNullOrEmpty(entry.Name);
|
||||
if (isDirectory)
|
||||
{
|
||||
Result<Success> directoryValidationResult = ValidatePackageDirectory(normalizedPath);
|
||||
if (directoryValidationResult.IsFailure)
|
||||
return Result<Success>.Failure(directoryValidationResult.Errors);
|
||||
|
||||
Result<string> directoryPathResult = ResolveContainedPath(extractionPath, normalizedPath);
|
||||
if (directoryPathResult.IsFailure)
|
||||
return Result<Success>.Failure(directoryPathResult.Errors);
|
||||
|
||||
Directory.CreateDirectory(directoryPathResult.Value);
|
||||
continue;
|
||||
}
|
||||
|
||||
Result<Success> fileValidationResult = ValidatePackageFile(normalizedPath);
|
||||
if (fileValidationResult.IsFailure)
|
||||
return Result<Success>.Failure(fileValidationResult.Errors);
|
||||
|
||||
if (entry.Length > _options.MaxSingleFileBytes)
|
||||
return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large.");
|
||||
|
||||
expandedBytes += entry.Length;
|
||||
if (expandedBytes > _options.MaxExpandedBytes)
|
||||
return Error.Validation(code: "Theme.Archive.ExpandedTooLarge", description: "The expanded theme archive is too large.");
|
||||
|
||||
Result<string> outputPathResult = ResolveContainedPath(extractionPath, normalizedPath);
|
||||
if (outputPathResult.IsFailure)
|
||||
return Result<Success>.Failure(outputPathResult.Errors);
|
||||
|
||||
string outputPath = outputPathResult.Value;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
|
||||
|
||||
await using Stream input = entry.Open();
|
||||
await using FileStream output = new(outputPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 64 * 1024, useAsync: true);
|
||||
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
long entryBytes = 0;
|
||||
while (true)
|
||||
{
|
||||
int read = await input.ReadAsync(buffer.AsMemory(), cancellationToken);
|
||||
if (read == 0)
|
||||
break;
|
||||
|
||||
entryBytes += read;
|
||||
if (entryBytes > _options.MaxSingleFileBytes)
|
||||
return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large.");
|
||||
|
||||
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
if (!File.Exists(Path.Combine(extractionPath, MANIFEST_FILE_NAME)))
|
||||
return PackageInvalid("The archive must contain theme.json at its root.");
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads and validates the manifest, templates and metadata of an installed theme directory.
|
||||
/// </summary>
|
||||
/// <param name="themeRoot">The absolute path of the installed theme directory.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <param name="sourceOverride">The install source to report, overriding the persisted metadata when provided.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the installed theme, or an error.</returns>
|
||||
private async Task<Result<InstalledThemeDto>> LoadInstalledThemeAsync(string themeRoot, CancellationToken cancellationToken, ThemeInstallSource? sourceOverride = null)
|
||||
{
|
||||
string manifestPath = Path.Combine(themeRoot, MANIFEST_FILE_NAME);
|
||||
if (!File.Exists(manifestPath))
|
||||
return PackageInvalid("The theme is missing theme.json.");
|
||||
|
||||
if (new FileInfo(manifestPath).Length > MAX_MANIFEST_BYTES)
|
||||
return Error.Validation(code: "Theme.Manifest.TooLarge", description: "theme.json exceeds the 64 KB limit.");
|
||||
|
||||
string json;
|
||||
ThemeManifestDto? manifest;
|
||||
try
|
||||
{
|
||||
json = await File.ReadAllTextAsync(manifestPath, cancellationToken);
|
||||
manifest = JsonSerializer.Deserialize<ThemeManifestDto>(json, s_manifestJsonOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json is not valid JSON.");
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return Error.Failure(code: "Theme.Files.Unreadable", description: "The theme files could not be read.");
|
||||
}
|
||||
|
||||
if (manifest is null)
|
||||
return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json contains no manifest object.");
|
||||
|
||||
Result<Success> manifestValidationResult = ValidateManifest(themeRoot, manifest);
|
||||
if (manifestValidationResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(manifestValidationResult.Errors);
|
||||
|
||||
foreach (string templatePath in manifest.Templates.Values.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
Result<string> fullTemplatePathResult = ResolveContainedPath(themeRoot, templatePath);
|
||||
if (fullTemplatePathResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(fullTemplatePathResult.Errors);
|
||||
|
||||
try
|
||||
{
|
||||
string template = await File.ReadAllTextAsync(fullTemplatePathResult.Value, cancellationToken);
|
||||
Result<Success> templateValidationResult = _templateEngine.Validate(template);
|
||||
if (templateValidationResult.IsFailure)
|
||||
return Result<InstalledThemeDto>.Failure(templateValidationResult.Errors);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return Error.Failure(code: "Theme.Files.Unreadable", description: "The theme files could not be read.");
|
||||
}
|
||||
}
|
||||
|
||||
ThemeInstallSource source = sourceOverride ?? await ReadInstallSourceAsync(themeRoot, cancellationToken);
|
||||
string previewUrl = string.IsNullOrWhiteSpace(manifest.Preview) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{manifest.Id}/{manifest.Preview}";
|
||||
ThemeInfoDto info = new(manifest.Id, manifest.Name, manifest.Description, manifest.Author, manifest.Version, previewUrl, source == ThemeInstallSource.Bundled);
|
||||
|
||||
return new InstalledThemeDto(manifest, info, Path.GetFullPath(themeRoot));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the manifest fields and template mappings, normalizing the referenced paths.
|
||||
/// </summary>
|
||||
/// <param name="themeRoot">The absolute path of the theme package root.</param>
|
||||
/// <param name="manifest">The manifest to validate.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private Result<Success> ValidateManifest(string themeRoot, ThemeManifestDto manifest)
|
||||
{
|
||||
if (manifest.SchemaVersion != 1)
|
||||
return PackageInvalid("Only theme schemaVersion 1 is supported.");
|
||||
|
||||
if (manifest.Id is null || !s_themeIdPattern.IsMatch(manifest.Id) || manifest.Id.Length > 64)
|
||||
return PackageInvalid("Theme id must be a lowercase kebab-case value up to 64 characters.");
|
||||
|
||||
Result<Success> nameResult = ValidateText(manifest.Name, "name", 80);
|
||||
if (nameResult.IsFailure)
|
||||
return nameResult;
|
||||
|
||||
Result<Success> descriptionResult = ValidateText(manifest.Description, "description", 300);
|
||||
if (descriptionResult.IsFailure)
|
||||
return descriptionResult;
|
||||
|
||||
Result<Success> authorResult = ValidateText(manifest.Author, "author", 80);
|
||||
if (authorResult.IsFailure)
|
||||
return authorResult;
|
||||
|
||||
Result<Success> versionResult = ValidateText(manifest.Version, "version", 40);
|
||||
if (versionResult.IsFailure)
|
||||
return versionResult;
|
||||
|
||||
if (!s_versionPattern.IsMatch(manifest.Version))
|
||||
return PackageInvalid("Theme version must use semantic version form, for example 1.0.0.");
|
||||
|
||||
if (manifest.Templates is null || manifest.Templates.Count == 0 || manifest.Templates.Count > 32)
|
||||
return PackageInvalid("A theme must declare between 1 and 32 templates.");
|
||||
|
||||
Dictionary<string, string> normalizedTemplates = new(StringComparer.OrdinalIgnoreCase);
|
||||
foreach ((string key, string path) in manifest.Templates)
|
||||
{
|
||||
if (!s_templateKeyPattern.IsMatch(key) || key.Length > 40)
|
||||
return PackageInvalid($"Template key '{key}' is invalid.");
|
||||
|
||||
Result<string> normalizedPathResult = NormalizeRelativePath(path);
|
||||
if (normalizedPathResult.IsFailure)
|
||||
return Result<Success>.Failure(normalizedPathResult.Errors);
|
||||
|
||||
string normalizedPath = normalizedPathResult.Value;
|
||||
if (!normalizedPath.StartsWith("templates/", StringComparison.Ordinal) || !string.Equals(Path.GetExtension(normalizedPath), ".html", StringComparison.OrdinalIgnoreCase))
|
||||
return PackageInvalid($"Template '{key}' must point to an HTML file under templates/.");
|
||||
|
||||
Result<string> fullTemplatePathResult = ResolveContainedPath(themeRoot, normalizedPath);
|
||||
if (fullTemplatePathResult.IsFailure)
|
||||
return Result<Success>.Failure(fullTemplatePathResult.Errors);
|
||||
|
||||
if (!File.Exists(fullTemplatePathResult.Value))
|
||||
return PackageInvalid($"Template '{key}' points to missing file '{normalizedPath}'.");
|
||||
|
||||
normalizedTemplates[key] = normalizedPath;
|
||||
}
|
||||
|
||||
if (!normalizedTemplates.ContainsKey("default"))
|
||||
return PackageInvalid("The manifest must define a 'default' template fallback.");
|
||||
|
||||
manifest.Templates = normalizedTemplates;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(manifest.Preview))
|
||||
{
|
||||
Result<string> previewPathResult = NormalizeRelativePath(manifest.Preview);
|
||||
if (previewPathResult.IsFailure)
|
||||
return Result<Success>.Failure(previewPathResult.Errors);
|
||||
|
||||
string previewPath = previewPathResult.Value;
|
||||
Result<string> fullPreviewPathResult = ResolveContainedPath(themeRoot, previewPath);
|
||||
if (fullPreviewPathResult.IsFailure)
|
||||
return Result<Success>.Failure(fullPreviewPathResult.Errors);
|
||||
|
||||
if (!previewPath.StartsWith("assets/", StringComparison.Ordinal) || !IsAllowedAssetExtension(Path.GetExtension(previewPath)) || !File.Exists(fullPreviewPathResult.Value))
|
||||
return PackageInvalid("The preview must reference an existing asset file.");
|
||||
|
||||
manifest.Preview = previewPath;
|
||||
}
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the persisted install source of a theme directory, defaulting to Uploaded when absent or invalid.
|
||||
/// </summary>
|
||||
/// <param name="themeRoot">The absolute path of the installed theme directory.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The install source of the theme.</returns>
|
||||
private static async Task<ThemeInstallSource> ReadInstallSourceAsync(string themeRoot, CancellationToken cancellationToken)
|
||||
{
|
||||
string metadataPath = Path.Combine(themeRoot, INSTALLATION_FILE_NAME);
|
||||
if (!File.Exists(metadataPath))
|
||||
return ThemeInstallSource.Uploaded;
|
||||
|
||||
try
|
||||
{
|
||||
string json = await File.ReadAllTextAsync(metadataPath, cancellationToken);
|
||||
return JsonSerializer.Deserialize<ThemeInstallationMetadataDto>(json, s_metadataJsonOptions)?.Source ?? ThemeInstallSource.Uploaded;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return ThemeInstallSource.Uploaded;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects and persists a valid current theme, preferring the configured default theme.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The identifier of the selected theme.</returns>
|
||||
private async Task<string> EnsureValidCurrentThemeAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
string preferred = _options.DefaultThemeId;
|
||||
string selected = _themes.ContainsKey(preferred) ? preferred : _themes.Values.OrderBy(theme => theme.Info.Name, StringComparer.OrdinalIgnoreCase).First().Manifest.Id;
|
||||
await _settingsStore.SetCurrentThemeIdAsync(selected, cancellationToken);
|
||||
return selected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates that a package file resides in the manifest, template or asset locations.
|
||||
/// </summary>
|
||||
/// <param name="normalizedPath">The normalized package-relative path of the file.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private Result<Success> ValidatePackageFile(string normalizedPath)
|
||||
{
|
||||
if (string.Equals(normalizedPath, MANIFEST_FILE_NAME, StringComparison.Ordinal))
|
||||
return Result.Success;
|
||||
|
||||
if (normalizedPath.StartsWith("templates/", StringComparison.Ordinal) && string.Equals(Path.GetExtension(normalizedPath), ".html", StringComparison.OrdinalIgnoreCase))
|
||||
return Result.Success;
|
||||
|
||||
if (normalizedPath.StartsWith("assets/", StringComparison.Ordinal) && IsAllowedAssetExtension(Path.GetExtension(normalizedPath)))
|
||||
return Result.Success;
|
||||
|
||||
return PackageInvalid($"Theme file '{normalizedPath}' is outside the allowed manifest, template, or asset locations.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates that a package directory resides under the templates or assets locations.
|
||||
/// </summary>
|
||||
/// <param name="normalizedPath">The normalized package-relative path of the directory.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> ValidatePackageDirectory(string normalizedPath)
|
||||
{
|
||||
if (normalizedPath.Equals("templates", StringComparison.Ordinal) ||
|
||||
normalizedPath.StartsWith("templates/", StringComparison.Ordinal) ||
|
||||
normalizedPath.Equals("assets", StringComparison.Ordinal) ||
|
||||
normalizedPath.StartsWith("assets/", StringComparison.Ordinal))
|
||||
return Result.Success;
|
||||
|
||||
return PackageInvalid($"Theme directory '{normalizedPath}' is not allowed.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the file extension is an allowed theme asset extension.
|
||||
/// </summary>
|
||||
/// <param name="extension">The file extension, including the leading dot.</param>
|
||||
/// <returns>true when the extension is allowed; otherwise, false.</returns>
|
||||
private bool IsAllowedAssetExtension(string extension)
|
||||
{
|
||||
return s_assetExtensions.Contains(extension) || (_options.AllowThemeScripts && string.Equals(extension, ".js", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes a package-relative path, rejecting paths that escape the package or violate the path rules.
|
||||
/// </summary>
|
||||
/// <param name="path">The package-relative path to normalize.</param>
|
||||
/// <param name="allowTrailingSlash">Whether a trailing slash, used for directory entries, is permitted.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the normalized path, or an error.</returns>
|
||||
private static Result<string> NormalizeRelativePath(string path, bool allowTrailingSlash = false)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || path.Length > 240 || path.Contains('\\') || path.Contains('\0') || path.StartsWith('/') || path.Contains("//"))
|
||||
return PackageInvalid("The theme contains an invalid path.");
|
||||
|
||||
string candidate = allowTrailingSlash ? path.TrimEnd('/') : path;
|
||||
if (string.IsNullOrWhiteSpace(candidate))
|
||||
return PackageInvalid("The theme contains an invalid path.");
|
||||
|
||||
string[] segments = candidate.Split('/');
|
||||
if (segments.Length > 12)
|
||||
return PackageInvalid("A theme path is nested too deeply.");
|
||||
|
||||
foreach (string segment in segments)
|
||||
if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.') || !s_pathSegmentPattern.IsMatch(segment))
|
||||
return PackageInvalid($"Theme path segment '{segment}' is invalid.");
|
||||
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a package-relative path against a package root, rejecting paths that escape the root.
|
||||
/// </summary>
|
||||
/// <param name="root">The absolute path of the package root.</param>
|
||||
/// <param name="relativePath">The package-relative path to resolve.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path, or an error.</returns>
|
||||
private static Result<string> ResolveContainedPath(string root, string relativePath)
|
||||
{
|
||||
string normalized = relativePath.Replace('/', Path.DirectorySeparatorChar);
|
||||
string rootPath = Path.GetFullPath(root);
|
||||
string candidate = Path.GetFullPath(Path.Combine(rootPath, normalized));
|
||||
string rootWithSeparator = rootPath.EndsWith(Path.DirectorySeparatorChar) ? rootPath : rootPath + Path.DirectorySeparatorChar;
|
||||
StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
if (!candidate.StartsWith(rootWithSeparator, comparison))
|
||||
return PackageInvalid("A theme path escapes its package root.");
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a manifest text field: required, within the maximum length and without control characters.
|
||||
/// </summary>
|
||||
/// <param name="value">The field value to validate.</param>
|
||||
/// <param name="fieldName">The name of the manifest field, used in error messages.</param>
|
||||
/// <param name="maxLength">The maximum allowed length of the field.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> ValidateText(string value, string fieldName, int maxLength)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value) || value.Length > maxLength || value.Any(char.IsControl))
|
||||
return PackageInvalid($"Theme manifest field '{fieldName}' is required and must be at most {maxLength} characters.");
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a validation error for an invalid theme package.
|
||||
/// </summary>
|
||||
/// <param name="description">The human-readable description of the package error.</param>
|
||||
/// <returns>The validation error describing the invalid theme package.</returns>
|
||||
private static Error PackageInvalid(string description)
|
||||
{
|
||||
return Error.Validation(code: "Theme.Package.Invalid", description: description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a not found error for a theme identifier that is not installed.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The missing theme identifier.</param>
|
||||
/// <returns>The not found error describing the missing theme.</returns>
|
||||
private static Error ThemeNotFound(string themeId)
|
||||
{
|
||||
return Error.NotFound(code: "Theme.NotFound", description: $"The theme '{themeId}' is not installed.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes stale files and directories left over in the staging directory.
|
||||
/// </summary>
|
||||
private void CleanStagingDirectory()
|
||||
{
|
||||
foreach (string path in Directory.EnumerateFileSystemEntries(_stagingRoot))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
Directory.Delete(path, recursive: true);
|
||||
else
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
_logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a configured path to an absolute path, rooted against the content root when relative.
|
||||
/// </summary>
|
||||
/// <param name="contentRoot">The content root of the application.</param>
|
||||
/// <param name="configuredPath">The path from the configuration.</param>
|
||||
/// <returns>The absolute path.</returns>
|
||||
private static string ResolvePath(string contentRoot, string configuredPath)
|
||||
{
|
||||
return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(contentRoot, configuredPath));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// Persists and reads the theme settings file that stores the current theme selection.
|
||||
/// </summary>
|
||||
public sealed class ThemeSettingsStore
|
||||
{
|
||||
private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private readonly string _settingsPath;
|
||||
private readonly ILogger<ThemeSettingsStore> _logger;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThemeSettingsStore"/> class.
|
||||
/// </summary>
|
||||
/// <param name="webHostEnvironment">The web host environment, used to resolve the content root.</param>
|
||||
/// <param name="themeEngineOptions">The theme engine configuration options.</param>
|
||||
/// <param name="logger">The logger for this store.</param>
|
||||
public ThemeSettingsStore(IWebHostEnvironment webHostEnvironment, IOptions<ThemeEngineOptionsDto> themeEngineOptions, ILogger<ThemeSettingsStore> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_settingsPath = ResolvePath(webHostEnvironment.ContentRootPath, themeEngineOptions.Value.SettingsPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the unique identifier of the currently selected theme.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The current theme identifier, or <see langword="null"/> when no selection is persisted.</returns>
|
||||
public async Task<string?> GetCurrentThemeIdAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _gate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(_settingsPath))
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
string json = await File.ReadAllTextAsync(_settingsPath, cancellationToken);
|
||||
return JsonSerializer.Deserialize<PersistedThemeSettingsDto>(json, s_jsonOptions)?.CurrentThemeId;
|
||||
}
|
||||
catch (JsonException exception)
|
||||
{
|
||||
_logger.LogWarning(exception, "Ignoring an invalid theme settings file at {SettingsPath}.", _settingsPath);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the unique identifier of the currently selected theme.
|
||||
/// </summary>
|
||||
/// <param name="themeId">The theme unique identifier to persist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public async Task SetCurrentThemeIdAsync(string themeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _gate.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
string? directory = Path.GetDirectoryName(_settingsPath) ?? throw new InvalidOperationException("The theme settings path has no parent directory.");
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
string temporaryPath = Path.Combine(directory, $".theme-settings-{Guid.NewGuid():N}.tmp");
|
||||
try
|
||||
{
|
||||
string json = JsonSerializer.Serialize(new PersistedThemeSettingsDto { CurrentThemeId = themeId }, s_jsonOptions);
|
||||
await File.WriteAllTextAsync(temporaryPath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken);
|
||||
File.Move(temporaryPath, _settingsPath, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temporaryPath))
|
||||
File.Delete(temporaryPath);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a configured path to an absolute path, rooted against the content root when relative.
|
||||
/// </summary>
|
||||
/// <param name="contentRoot">The content root of the application.</param>
|
||||
/// <param name="configuredPath">The path from the configuration.</param>
|
||||
/// <returns>The absolute path.</returns>
|
||||
private static string ResolvePath(string contentRoot, string configuredPath)
|
||||
{
|
||||
return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(contentRoot, configuredPath));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.RegularExpressions;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Core.Themes;
|
||||
|
||||
/// <summary>
|
||||
/// A small, non-executable Mustache-style renderer. Theme templates can place values, iterate collections and test truthiness, but cannot execute C#.
|
||||
/// </summary>
|
||||
public sealed class ThemeTemplateEngine
|
||||
{
|
||||
private const int MAX_NESTING_DEPTH = 32;
|
||||
private const int MAX_RENDERED_CHARACTERS = 4 * 1024 * 1024;
|
||||
|
||||
private static readonly Regex s_namePartPattern = new(
|
||||
"^[A-Za-z_][A-Za-z0-9_]*$",
|
||||
RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>
|
||||
/// Validates the structure and expressions of a theme template.
|
||||
/// </summary>
|
||||
/// <param name="template">The template source to validate.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Success> Validate(string template)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
int cursor = 0;
|
||||
Result<IReadOnlyList<ThemeTemplateNodeDto>> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0);
|
||||
if (parseResult.IsFailure)
|
||||
return Result<Success>.Failure(parseResult.Errors);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a theme template against the provided model.
|
||||
/// </summary>
|
||||
/// <param name="template">The template source to render.</param>
|
||||
/// <param name="model">The model the template expressions resolve against.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the rendered output, or an error.</returns>
|
||||
public Result<string> Render(string template, object model)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(model);
|
||||
|
||||
int cursor = 0;
|
||||
Result<IReadOnlyList<ThemeTemplateNodeDto>> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0);
|
||||
if (parseResult.IsFailure)
|
||||
return Result<string>.Failure(parseResult.Errors);
|
||||
|
||||
StringBuilder output = new(Math.Min(template.Length * 2, 256 * 1024));
|
||||
Result<Success> renderResult = RenderNodes(parseResult.Value, new ThemeRenderScopeDto(model, Parent: null), output);
|
||||
if (renderResult.IsFailure)
|
||||
return Result<string>.Failure(renderResult.Errors);
|
||||
|
||||
return output.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a template fragment into template nodes until the closing section or end of the template.
|
||||
/// </summary>
|
||||
/// <param name="template">The template source to parse.</param>
|
||||
/// <param name="cursor">The current position in the template, advanced as nodes are consumed.</param>
|
||||
/// <param name="expectedClosingName">The name of the section that closes the fragment, or <see langword="null"/> at the top level.</param>
|
||||
/// <param name="depth">The current section nesting depth.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed nodes, or an error.</returns>
|
||||
private static Result<IReadOnlyList<ThemeTemplateNodeDto>> ParseNodes(string template, ref int cursor, string? expectedClosingName, int depth)
|
||||
{
|
||||
if (depth > MAX_NESTING_DEPTH)
|
||||
return TemplateInvalid($"Template sections may not be nested more than {MAX_NESTING_DEPTH} levels.");
|
||||
|
||||
List<ThemeTemplateNodeDto> nodes = [];
|
||||
while (cursor < template.Length)
|
||||
{
|
||||
int opening = template.IndexOf("{{", cursor, StringComparison.Ordinal);
|
||||
if (opening < 0)
|
||||
{
|
||||
if (cursor < template.Length)
|
||||
nodes.Add(new ThemeTextNodeDto(template[cursor..]));
|
||||
|
||||
cursor = template.Length;
|
||||
break;
|
||||
}
|
||||
|
||||
if (opening > cursor)
|
||||
nodes.Add(new ThemeTextNodeDto(template[cursor..opening]));
|
||||
|
||||
if (template.AsSpan(opening).StartsWith("{{{".AsSpan(), StringComparison.Ordinal))
|
||||
{
|
||||
int closing = template.IndexOf("}}}", opening + 3, StringComparison.Ordinal);
|
||||
if (closing < 0)
|
||||
return TemplateInvalid("An unescaped variable tag is not closed.");
|
||||
|
||||
string expression = template[(opening + 3)..closing].Trim();
|
||||
Result<Success> expressionResult = ValidateExpression(expression);
|
||||
if (expressionResult.IsFailure)
|
||||
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(expressionResult.Errors);
|
||||
|
||||
nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false));
|
||||
cursor = closing + 3;
|
||||
continue;
|
||||
}
|
||||
|
||||
int tagClosing = template.IndexOf("}}", opening + 2, StringComparison.Ordinal);
|
||||
if (tagClosing < 0)
|
||||
return TemplateInvalid("A template tag is not closed.");
|
||||
|
||||
string tag = template[(opening + 2)..tagClosing].Trim();
|
||||
cursor = tagClosing + 2;
|
||||
if (tag.Length == 0)
|
||||
return TemplateInvalid("Empty template tags are not allowed.");
|
||||
|
||||
switch (tag[0])
|
||||
{
|
||||
case '!':
|
||||
continue;
|
||||
case '#':
|
||||
case '^':
|
||||
{
|
||||
string expression = tag[1..].Trim();
|
||||
Result<Success> sectionExpressionResult = ValidateExpression(expression);
|
||||
if (sectionExpressionResult.IsFailure)
|
||||
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(sectionExpressionResult.Errors);
|
||||
|
||||
Result<IReadOnlyList<ThemeTemplateNodeDto>> childrenResult = ParseNodes(template, ref cursor, expression, depth + 1);
|
||||
if (childrenResult.IsFailure)
|
||||
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(childrenResult.Errors);
|
||||
|
||||
nodes.Add(new ThemeSectionNodeDto(expression, Inverted: tag[0] == '^', Children: childrenResult.Value));
|
||||
break;
|
||||
}
|
||||
case '/':
|
||||
{
|
||||
string closingName = tag[1..].Trim();
|
||||
Result<Success> closingNameResult = ValidateExpression(closingName);
|
||||
if (closingNameResult.IsFailure)
|
||||
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(closingNameResult.Errors);
|
||||
|
||||
if (expectedClosingName is null)
|
||||
return TemplateInvalid($"Closing section '{closingName}' has no matching opening section.");
|
||||
|
||||
if (!string.Equals(closingName, expectedClosingName, StringComparison.Ordinal))
|
||||
return TemplateInvalid($"Section '{expectedClosingName}' is closed by '{closingName}'.");
|
||||
|
||||
return nodes;
|
||||
}
|
||||
case '&':
|
||||
{
|
||||
string expression = tag[1..].Trim();
|
||||
Result<Success> unescapedExpressionResult = ValidateExpression(expression);
|
||||
if (unescapedExpressionResult.IsFailure)
|
||||
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(unescapedExpressionResult.Errors);
|
||||
|
||||
nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
Result<Success> variableResult = ValidateExpression(tag);
|
||||
if (variableResult.IsFailure)
|
||||
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(variableResult.Errors);
|
||||
|
||||
nodes.Add(new ThemeVariableNodeDto(tag, ShouldBeEscaped: true));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (expectedClosingName is not null)
|
||||
return TemplateInvalid($"Section '{expectedClosingName}' is not closed.");
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a list of template nodes into the output.
|
||||
/// </summary>
|
||||
/// <param name="nodes">The template nodes to render.</param>
|
||||
/// <param name="scope">The model scope the expressions resolve against.</param>
|
||||
/// <param name="output">The output the rendered text is appended to.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> RenderNodes(IReadOnlyList<ThemeTemplateNodeDto> nodes, ThemeRenderScopeDto scope, StringBuilder output)
|
||||
{
|
||||
foreach (ThemeTemplateNodeDto node in nodes)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case ThemeTextNodeDto text:
|
||||
{
|
||||
Result<Success> textResult = AppendChecked(output, text.Value);
|
||||
if (textResult.IsFailure)
|
||||
return Result<Success>.Failure(textResult.Errors);
|
||||
|
||||
break;
|
||||
}
|
||||
case ThemeVariableNodeDto variable:
|
||||
{
|
||||
object? resolved = Resolve(variable.Expression, scope);
|
||||
string value = ConvertToString(resolved);
|
||||
Result<Success> variableResult = AppendChecked(output, variable.ShouldBeEscaped ? HtmlEncoder.Default.Encode(value) : value);
|
||||
if (variableResult.IsFailure)
|
||||
return Result<Success>.Failure(variableResult.Errors);
|
||||
|
||||
break;
|
||||
}
|
||||
case ThemeSectionNodeDto section:
|
||||
{
|
||||
Result<Success> sectionResult = RenderSection(section, scope, output);
|
||||
if (sectionResult.IsFailure)
|
||||
return Result<Success>.Failure(sectionResult.Errors);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders a section by evaluating its expression and iterating or conditionally rendering its children.
|
||||
/// </summary>
|
||||
/// <param name="section">The section node to render.</param>
|
||||
/// <param name="scope">The model scope the section expression resolves against.</param>
|
||||
/// <param name="output">The output the rendered text is appended to.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> RenderSection(ThemeSectionNodeDto section, ThemeRenderScopeDto scope, StringBuilder output)
|
||||
{
|
||||
object? value = Resolve(section.Expression, scope);
|
||||
bool truthy = IsTruthy(value);
|
||||
if (section.Inverted)
|
||||
{
|
||||
if (!truthy)
|
||||
return RenderNodes(section.Children, scope, output);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
if (!truthy)
|
||||
return Result.Success;
|
||||
|
||||
if (value is bool)
|
||||
return RenderNodes(section.Children, scope, output);
|
||||
|
||||
if (value is System.Collections.IEnumerable enumerable and not string)
|
||||
{
|
||||
foreach (object? item in enumerable)
|
||||
{
|
||||
Result<Success> itemResult = RenderNodes(section.Children, new ThemeRenderScopeDto(item, scope), output);
|
||||
if (itemResult.IsFailure)
|
||||
return Result<Success>.Failure(itemResult.Errors);
|
||||
}
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
return RenderNodes(section.Children, new ThemeRenderScopeDto(value, scope), output);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a dotted expression against the scope chain, honoring explicit parent traversal.
|
||||
/// </summary>
|
||||
/// <param name="expression">The dotted property expression to resolve.</param>
|
||||
/// <param name="startingScope">The scope the expression is resolved from.</param>
|
||||
/// <returns>The resolved value, or <see langword="null"/> when no scope in the chain exposes it.</returns>
|
||||
private static object? Resolve(string expression, ThemeRenderScopeDto startingScope)
|
||||
{
|
||||
int explicitParentCount = 0;
|
||||
while (expression.StartsWith("../", StringComparison.Ordinal))
|
||||
{
|
||||
explicitParentCount++;
|
||||
expression = expression[3..];
|
||||
}
|
||||
|
||||
ThemeRenderScopeDto scope = startingScope;
|
||||
for (int index = 0; index < explicitParentCount; index++)
|
||||
scope = scope.Parent ?? scope;
|
||||
|
||||
if (expression == ".")
|
||||
return scope.Value;
|
||||
|
||||
if (explicitParentCount > 0)
|
||||
return TryResolvePath(scope.Value, expression, out object? explicitValue) ? explicitValue : null;
|
||||
|
||||
for (ThemeRenderScopeDto? candidate = scope; candidate is not null; candidate = candidate.Parent)
|
||||
if (TryResolvePath(candidate.Value, expression, out object? value))
|
||||
return value;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a dotted property path against a value, member by member.
|
||||
/// </summary>
|
||||
/// <param name="value">The value the path is resolved against.</param>
|
||||
/// <param name="expression">The dotted property path to resolve.</param>
|
||||
/// <param name="resolved">The resolved value, or <see langword="null"/> when any part of the path is missing.</param>
|
||||
/// <returns><see langword="true"/> when the full path resolved; <see langword="false"/> otherwise.</returns>
|
||||
private static bool TryResolvePath(object? value, string expression, out object? resolved)
|
||||
{
|
||||
resolved = value;
|
||||
foreach (string part in expression.Split('.'))
|
||||
{
|
||||
if (!TryReadMember(resolved, part, out resolved))
|
||||
{
|
||||
resolved = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a single member from a value, supporting dictionaries, collections and public properties.
|
||||
/// </summary>
|
||||
/// <param name="target">The value the member is read from.</param>
|
||||
/// <param name="name">The member name to read, matched case-insensitively.</param>
|
||||
/// <param name="value">The member value, or <see langword="null"/> when the member is not found.</param>
|
||||
/// <returns><see langword="true"/> when the member was found; <see langword="false"/> otherwise.</returns>
|
||||
private static bool TryReadMember(object? target, string name, out object? value)
|
||||
{
|
||||
value = null;
|
||||
if (target is null)
|
||||
return false;
|
||||
|
||||
if (target is IReadOnlyDictionary<string, object?> readOnlyDictionary)
|
||||
{
|
||||
foreach (KeyValuePair<string, object?> pair in readOnlyDictionary)
|
||||
{
|
||||
if (string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = pair.Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (target is IDictionary<string, object?> dictionary)
|
||||
{
|
||||
foreach (KeyValuePair<string, object?> pair in dictionary)
|
||||
{
|
||||
if (string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = pair.Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (string.Equals(name, "Count", StringComparison.OrdinalIgnoreCase) && target is System.Collections.ICollection collection)
|
||||
{
|
||||
value = collection.Count;
|
||||
return true;
|
||||
}
|
||||
|
||||
PropertyInfo? property = target.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
||||
if (property is null || property.GetIndexParameters().Length != 0)
|
||||
return false;
|
||||
|
||||
value = property.GetValue(target);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the truthiness of a value: <see langword="null"/> and <see langword="false"/> are falsy, empty strings and empty collections are falsy.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to evaluate.</param>
|
||||
/// <returns><see langword="true"/> when the value is truthy; <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsTruthy(object? value)
|
||||
{
|
||||
if (value is null or false)
|
||||
return false;
|
||||
|
||||
if (value is string text)
|
||||
return text.Length > 0;
|
||||
|
||||
if (value is System.Collections.IEnumerable enumerable)
|
||||
{
|
||||
System.Collections.IEnumerator enumerator = enumerable.GetEnumerator();
|
||||
try
|
||||
{
|
||||
return enumerator.MoveNext();
|
||||
}
|
||||
finally
|
||||
{
|
||||
(enumerator as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a resolved value to its rendered string representation.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to convert.</param>
|
||||
/// <returns>The rendered string, or an empty string for <see langword="null"/> values.</returns>
|
||||
private static string ConvertToString(object? value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
null => string.Empty,
|
||||
bool boolean => boolean ? "true" : "false",
|
||||
DateTime dateTime => dateTime.ToString("O", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset dateTimeOffset => dateTimeOffset.ToString("O", CultureInfo.InvariantCulture),
|
||||
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty,
|
||||
_ => value.ToString() ?? string.Empty
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a template expression: non-empty, within the length limit and composed of dotted name parts.
|
||||
/// </summary>
|
||||
/// <param name="expression">The expression to validate.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> ValidateExpression(string expression)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(expression) || expression.Length > 120)
|
||||
return TemplateInvalid("A template expression is empty or too long.");
|
||||
|
||||
string remaining = expression;
|
||||
while (remaining.StartsWith("../", StringComparison.Ordinal))
|
||||
remaining = remaining[3..];
|
||||
|
||||
if (remaining == ".")
|
||||
return Result.Success;
|
||||
|
||||
if (remaining.Length == 0 || remaining.Split('.').Any(part => !s_namePartPattern.IsMatch(part)))
|
||||
return TemplateInvalid($"Expression '{expression}' is invalid. Use property names separated by dots.");
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a value to the output, enforcing the maximum rendered character limit.
|
||||
/// </summary>
|
||||
/// <param name="output">The output the value is appended to.</param>
|
||||
/// <param name="value">The value to append.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private static Result<Success> AppendChecked(StringBuilder output, string value)
|
||||
{
|
||||
if (output.Length + value.Length > MAX_RENDERED_CHARACTERS)
|
||||
return TemplateInvalid("Rendered output exceeds the 4 MB safety limit.");
|
||||
|
||||
output.Append(value);
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a validation error for an invalid theme template.
|
||||
/// </summary>
|
||||
/// <param name="description">The human-readable description of the template error.</param>
|
||||
/// <returns>The validation error describing the invalid theme template.</returns>
|
||||
private static Error TemplateInvalid(string description)
|
||||
{
|
||||
return Error.Validation(code: "Theme.Template.Invalid", description: description);
|
||||
}
|
||||
}
|
||||
@@ -41,10 +41,7 @@ public class Program
|
||||
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
|
||||
});
|
||||
builder.WebHost.ConfigureKestrel(options => options.ListenAnyIP(5012)); // HTTP only
|
||||
}
|
||||
else
|
||||
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path
|
||||
@@ -103,6 +100,8 @@ public class Program
|
||||
// handle path base from reverse proxies
|
||||
app.Use((context, next) =>
|
||||
{
|
||||
context.Response.Headers["X-Content-Type-Options"] = "nosniff";
|
||||
context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
|
||||
if (context.Request.Headers.TryGetValue("X-Forwarded-Prefix", out StringValues pathBase))
|
||||
context.Request.PathBase = pathBase.ToString();
|
||||
return next();
|
||||
|
||||
@@ -2,6 +2,16 @@
|
||||
"EncryptionSettings": {
|
||||
"SecretKey": "" // base64 string
|
||||
},
|
||||
"ThemeEngine": {
|
||||
"StoragePath": "Themes",
|
||||
"SettingsPath": "theme-settings.json",
|
||||
"DefaultThemeId": "editorial-paper",
|
||||
"MaxArchiveBytes": 8388608,
|
||||
"MaxExpandedBytes": 25165824,
|
||||
"MaxSingleFileBytes": 6291456,
|
||||
"MaxEntries": 250,
|
||||
"AllowThemeScripts": false
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
|
||||
"MinimumLevel": {
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Configuration;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Validators;
|
||||
using Lumina.Presentation.Web.UnitTests.Common.Setup;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ThemeEngineOptionsDtoValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ThemeEngineOptionsDtoValidatorTests
|
||||
{
|
||||
private readonly ThemeEngineOptionsDtoValidator _validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { StoragePath = string.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Theme storage path cannot be empty!"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenSettingsPathIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { SettingsPath = string.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Theme settings path cannot be empty!"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenDefaultThemeIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { DefaultThemeId = string.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Default theme Id cannot be empty!"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0L)] // zero, not positive
|
||||
[InlineData(-1L)] // negative
|
||||
public void Validate_WhenMaxArchiveBytesIsNotPositive_ShouldHaveValidationError(long maxArchiveBytes)
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { MaxArchiveBytes = maxArchiveBytes };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Maximum archive size must be greater than 0!"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0L)] // zero, not positive
|
||||
[InlineData(-1L)] // negative
|
||||
public void Validate_WhenMaxExpandedBytesIsNotPositive_ShouldHaveValidationError(long maxExpandedBytes)
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { MaxExpandedBytes = maxExpandedBytes };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Maximum expanded size must be greater than 0!"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0L)] // zero, not positive
|
||||
[InlineData(-1L)] // negative
|
||||
public void Validate_WhenMaxSingleFileBytesIsNotPositive_ShouldHaveValidationError(long maxSingleFileBytes)
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { MaxSingleFileBytes = maxSingleFileBytes };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Maximum single file size must be greater than 0!"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)] // zero, not positive
|
||||
[InlineData(-1)] // negative
|
||||
public void Validate_WhenMaxEntriesIsNotPositive_ShouldHaveValidationError(int maxEntries)
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new() { MaxEntries = maxEntries };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Error.Validation(description: "Maximum entries count must be greater than 0!"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOptionsAreValid_ShouldNotHaveAnyValidationErrors()
|
||||
{
|
||||
// Arrange
|
||||
ThemeEngineOptionsDto options = new();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(options);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user