Adds the server-side theme repository and reworks the web theme engine onto it

This commit is contained in:
BinaryAlley committed 2026-08-19 22:50:07 -07:00
1 parent 85928f7c3c
commit bf8faba24d
136 files changed
+6942 -1197

No files matched your search

@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme;
/// <summary>
/// API endpoint for the <c>/{culture}/admin/themes/api-delete-theme/{themeId}</c> route.
/// </summary>
public class DeleteThemeEndpoint : BaseEndpoint<DeleteThemeRequest, IResult>
{
private readonly ThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeEndpoint"/> class.
/// </summary>
/// <param name="themeService">Injected service for interactions with the remote theme endpoints.</param>
public DeleteThemeEndpoint(ThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.DELETE);
Routes(WebRoutes.Themes.DELETE_THEME);
DontAutoTag();
Options(options => options.WithTags("Themes"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
/// Deletes the theme identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(DeleteThemeRequest request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.ThemeId))
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty.");
await _themeService.DeleteThemeAsync(request.ThemeId, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeleteThemeEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeEndpointSummary : Summary<DeleteThemeEndpoint, DeleteThemeRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeEndpointSummary"/> class.
/// </summary>
public DeleteThemeEndpointSummary()
{
Summary = "Deletes a theme.";
Description = "Deletes the theme identified by the request, switching to another available theme when the deleted theme was the active one.";
RequestParam(r => r.ThemeId, "The manifest id of the theme to delete.");
Response(200, "The theme was successfully deleted.", example: new SuccessResponse(true));
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme;
/// <summary>
/// API endpoint for the <c>/{culture}/admin/themes/api-download-theme/{themeId}</c> route.
/// </summary>
public class DownloadThemeEndpoint : BaseEndpoint<GetThemeArchiveRequest, IResult>
{
private readonly ThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="DownloadThemeEndpoint"/> class.
/// </summary>
/// <param name="themeService">Injected service for interactions with the remote theme endpoints.</param>
public DownloadThemeEndpoint(ThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Themes.DOWNLOAD_THEME);
DontAutoTag();
Options(options => options.WithTags("Themes"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
}
/// <summary>
/// Downloads the archive of the theme identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme to download.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThemeArchiveRequest request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.ThemeId))
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty.");
ThemeArchiveDto archive = await _themeService.BuildArchiveAsync(request.ThemeId, cancellationToken).ConfigureAwait(false);
return Results.File(archive.Content, "application/zip", archive.FileName);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Requests.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="DownloadThemeEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DownloadThemeEndpointSummary : Summary<DownloadThemeEndpoint, GetThemeArchiveRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DownloadThemeEndpointSummary"/> class.
/// </summary>
public DownloadThemeEndpointSummary()
{
Summary = "Downloads the archive of a theme.";
Description = "Downloads the ZIP archive of the installed theme identified by the request.";
RequestParam(r => r.ThemeId, "The manifest id of the theme to download.");
Response(200, "The ZIP archive of the theme is returned.", "application/zip");
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes;
/// <summary>
/// API endpoint for the <c>/{culture}/admin/themes/api-get-themes</c> route.
/// </summary>
public class GetThemesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpoint"/> class.
/// </summary>
/// <param name="themeService">Injected service for interactions with the remote theme endpoints.</param>
public GetThemesEndpoint(ThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Themes.GET_THEMES);
DontAutoTag();
Options(options => options.WithTags("Themes"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
}
/// <summary>
/// Gets the installed themes together with the current theme and the theme engine settings.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
IReadOnlyList<ThemeInfoDto> themes = await _themeService.GetThemesAsync(cancellationToken).ConfigureAwait(false);
ThemeInfoDto currentTheme = await _themeService.GetCurrentThemeAsync(cancellationToken).ConfigureAwait(false);
ThemeSettingsResponseDto settings = await _themeService.GetThemeSettingsAsync(cancellationToken).ConfigureAwait(false);
ThemeAdminDto themeAdmin = new()
{
Themes = themes,
CurrentThemeId = currentTheme.Id,
AllowThemeScripts = settings.AllowThemeScripts,
MaxArchiveBytes = settings.MaxArchiveBytes
};
return JsonSuccess(themeAdmin);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThemesEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesEndpointSummary : Summary<GetThemesEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpointSummary"/> class.
/// </summary>
public GetThemesEndpointSummary()
{
Summary = "Retrieves the theme administration data.";
Description = "Retrieves the installed themes, together with the current theme and the theme engine settings.";
Response(200, "The theme administration data is returned.", example: new SuccessResponse<ThemeAdminDto>(true, default));
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme;
/// <summary>
/// API endpoint for the <c>/{culture}/admin/themes/api-install-theme</c> route.
/// </summary>
public class InstallThemeEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeEndpoint"/> class.
/// </summary>
/// <param name="themeService">Injected service for interactions with the remote theme endpoints.</param>
public InstallThemeEndpoint(ThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.POST);
Routes(WebRoutes.Themes.INSTALL_THEME);
DontAutoTag();
Options(options => options.WithTags("Themes"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
/// Installs the theme pack uploaded in the multipart form of the request.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault();
if (archive is null)
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The uploaded theme archive is missing.");
await using Stream archiveStream = archive.OpenReadStream();
ThemeInfoDto theme = await _themeService.InstallAsync(archiveStream, archive.FileName, cancellationToken).ConfigureAwait(false);
return JsonSuccess(theme);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="InstallThemeEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeEndpointSummary : Summary<InstallThemeEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeEndpointSummary"/> class.
/// </summary>
public InstallThemeEndpointSummary()
{
Summary = "Installs a theme pack.";
Description = "Installs the theme pack uploaded in the multipart form of the request, replacing the files of an existing theme with the same manifest id.";
Response(200, "The theme was successfully installed.", example: new SuccessResponse<ThemeInfoDto>(true, default));
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme;
/// <summary>
/// API endpoint for the <c>/{culture}/admin/themes/api-set-current-theme</c> route.
/// </summary>
public class SetCurrentThemeEndpoint : BaseEndpoint<SetCurrentThemeRequest, IResult>
{
private readonly ThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpoint"/> class.
/// </summary>
/// <param name="themeService">Injected service for interactions with the remote theme endpoints.</param>
public SetCurrentThemeEndpoint(ThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.PUT);
Routes(WebRoutes.Themes.SET_CURRENT_THEME);
DontAutoTag();
Options(options => options.WithTags("Themes"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
/// Sets the theme identified by <paramref name="request"/> as the currently active theme.
/// </summary>
/// <param name="request">The request containing the theme to activate.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SetCurrentThemeRequest request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.ThemeId))
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty.");
await _themeService.SetCurrentThemeAsync(request.ThemeId, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetCurrentThemeEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeEndpointSummary : Summary<SetCurrentThemeEndpoint, SetCurrentThemeRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpointSummary"/> class.
/// </summary>
public SetCurrentThemeEndpointSummary()
{
Summary = "Sets the currently active theme.";
Description = "Sets the theme identified by the request as the currently active theme.";
RequestParam(r => r.ThemeId, "The manifest id of the theme to activate.");
Response(200, "The theme was successfully activated.", example: new SuccessResponse(true));
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets;
/// <summary>
/// API endpoint for the <c>/theme-assets/{themeId}/{path}</c> route.
/// </summary>
public class ThemeAssetsEndpoint : BaseEndpoint<GetThemeAssetRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeAssetsEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public ThemeAssetsEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Themes.THEME_ASSETS);
AllowAnonymous();
DontAutoTag();
Options(options => options.WithTags("Themes"));
}
/// <summary>
/// Serves the asset of the theme stored in <paramref name="request"/>, fetched from the remote API.
/// </summary>
/// <param name="request">The request containing the theme and the path of the asset.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThemeAssetRequest request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.ThemeId) || string.IsNullOrWhiteSpace(request.Path))
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id and the asset path are required.");
BlobDataDto blob = await _apiHttpClient.GetBlobAsync(
ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{assetPath}", request.Path), cancellationToken).ConfigureAwait(false);
return Results.File(blob.Data, blob.ContentType);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Requests.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets;
/// <summary>
/// Class used for providing a textual description for the <see cref="ThemeAssetsEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeAssetsEndpointSummary : Summary<ThemeAssetsEndpoint, GetThemeAssetRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ThemeAssetsEndpointSummary"/> class.
/// </summary>
public ThemeAssetsEndpointSummary()
{
Summary = "Retrieves an asset file of a theme.";
Description = "Serves the binary content of an asset file of a theme, fetched from the remote API.";
RequestParam(r => r.ThemeId, "The manifest id of the theme.");
RequestParam(r => r.Path, "The asset path relative to the theme pack root.");
Response(200, "The asset file of the theme is returned.", "application/octet-stream");
}
}
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Eigenname der Sprache darf maximal 50 Zeichen lang sein!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>Das letzte mitgelieferte Theme kann nicht gelöscht werden!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>Bibliothek existiert bereits!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Seitenzahl muss größer als null sein!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>Der Seiten-Schlüssel darf nicht leer sein!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Übergeordneter Knoten darf nicht null sein!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>Das Buch ist nicht in der Serie!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>Das Theme-Archiv darf nicht null sein!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>Das Theme-Archiv konnte nicht gelesen werden!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Der Theme-Asset-Pfad darf nicht leer sein!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>Das Theme kann nicht gelöscht werden!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>Die Theme-Dateien konnten nicht gelesen werden!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>Die Theme-ID darf nicht leer sein!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>Das Theme ist nicht verfügbar!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>Das angegebene Theme wurde nicht gefunden!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Titel darf nicht leer sein!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Language native name must be maximum 50 characters long!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>The last bundled theme cannot be deleted!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>Library already exists!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Page count must be greater than zero!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>Page key cannot be empty!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Parent node cannot be null!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>The book is not in the series!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>Theme archive cannot be null!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>The theme archive could not be read!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Theme asset path cannot be empty!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>The theme cannot be deleted!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>The theme files could not be read!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>Theme id cannot be empty!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>The theme is not available!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>The specified theme was not found!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Title cannot be empty!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>¡El nombre nativo del idioma debe tener máximo 50 caracteres!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>¡El último tema incluido no se puede eliminar!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>¡La biblioteca ya existe!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>¡El número de páginas debe ser mayor que cero!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>¡La clave de página no puede estar vacía!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>¡El nodo padre no puede ser nulo!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>¡El libro no está en la serie!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>¡El archivo del tema no puede ser nulo!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>¡No se pudo leer el archivo del tema!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>¡La ruta del recurso del tema no puede estar vacía!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>¡El tema no se puede eliminar!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>¡No se pudieron leer los archivos del tema!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>¡El id del tema no puede estar vacío!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>¡El tema no está disponible!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>¡El tema especificado no fue encontrado!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>¡El título no puede estar vacío!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Le nom natif de la langue ne doit pas dépasser 50 caractères !</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>Le dernier thème inclus ne peut pas être supprimé !</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>La bibliothèque existe déjà !</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Le nombre de pages doit être supérieur à zéro !</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>La clé de page ne peut pas être vide !</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Le nœud parent ne peut pas être nul!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>Le livre n'est pas dans la série !</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>L'archive du thème ne peut pas être nulle !</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>L'archive du thème n'a pas pu être lue !</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Le chemin de la ressource du thème ne peut pas être vide !</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>Le thème ne peut pas être supprimé !</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>Les fichiers du thème n'ont pas pu être lus !</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>L'identifiant du thème ne peut pas être vide !</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>Le thème n'est pas disponible !</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>Le thème spécifié est introuvable !</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Le titre ne peut pas être vide !</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Il nome nativo della lingua deve essere lungo al massimo 50 caratteri!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>L'ultimo tema incluso non può essere eliminato!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>La libreria esiste già!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Il numero di pagine deve essere maggiore di zero!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>La chiave di pagina non può essere vuota!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Il nodo padre non può essere nullo!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>Il libro non è presente nella serie!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>L'archivio del tema non può essere nullo!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>L'archivio del tema non può essere letto!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Il percorso della risorsa del tema non può essere vuoto!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>Il tema non può essere eliminato!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>I file del tema non possono essere letti!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>L'id del tema non può essere vuoto!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>Il tema non è disponibile!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>Il tema specificato non è stato trovato!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Il titolo non può essere vuoto!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>言語の固有名は最大50文字までです!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>最後の同梱テーマは削除できません!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>ライブラリはすでに存在します!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>ページ数は0より大きくなければなりません!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>ページキーは空にできません!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>親ノードをnullにすることはできません!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>この本はシリーズに含まれていません!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>テーマアーカイブは null にできません!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>テーマアーカイブを読み取れませんでした!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>テーマアセットのパスは空にできません!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>テーマは削除できません!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>テーマのファイルを読み取れませんでした!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>テーマ ID は空にできません!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>テーマを利用できません!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>指定されたテーマが見つかりませんでした!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>タイトルを空にすることはできません!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Language native name must be maximum 50 characters long!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>The last bundled theme cannot be deleted!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>Library already exists!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Page count must be greater than zero!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>Page key cannot be empty!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Parent node cannot be null!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>The book is not in the series!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>Theme archive cannot be null!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>The theme archive could not be read!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Theme asset path cannot be empty!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>The theme cannot be deleted!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>The theme files could not be read!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>Theme id cannot be empty!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>The theme is not available!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>The specified theme was not found!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Title cannot be empty!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Numele nativ al limbii trebuie să aibă maximum 50 caractere!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>Ultima temă inclusă nu poate fi ștearsă!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>Biblioteca există deja!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Numărul de pagini trebuie să fie mai mare decât zero!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>Cheia de pagină nu poate fi goală!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Nodul părinte nu poate fi nul!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>Cartea nu este în serie!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>Arhiva temei nu poate fi nulă!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>Arhiva temei nu a putut fi citită!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Calea resursei temei nu poate fi goală!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>Tema nu poate fi ștearsă!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>Fișierele temei nu au putut fi citite!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>Id-ul temei nu poate fi gol!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>Tema nu este disponibilă!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>Tema specificată nu a fost găsită!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Titlul nu poate fi gol!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>Исходное название языка не должно превышать 50 символов!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>Последнюю встроенную тему нельзя удалить!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>Библиотека уже существует!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>Количество страниц должно быть больше нуля!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>Ключ страницы не может быть пустым!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>Родительский узел не может быть пустым!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>Книга не входит в серию!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>Архив темы не может быть пустым!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>Не удалось прочитать архив темы!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>Путь к ресурсу темы не может быть пустым!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>Тему нельзя удалить!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>Не удалось прочитать файлы темы!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>Идентификатор темы не может быть пустым!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>Тема недоступна!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>Указанная тема не найдена!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>Название не может быть пустым!</value>
</data>
@@ -321,6 +321,9 @@
<data name="LanguageNativeNameMustBeMaximum50CharactersLong" xml:space="preserve">
<value>语言本地名称最多只能有50个字符!</value>
</data>
<data name="LastBundledThemeCannotBeDeleted" xml:space="preserve">
<value>不能删除最后一个内置主题!</value>
</data>
<data name="LibraryAlreadyExists" xml:space="preserve">
<value>库已存在!</value>
</data>
@@ -378,6 +381,9 @@
<data name="PageCountMustBeGreaterThanZero" xml:space="preserve">
<value>页数必须大于零!</value>
</data>
<data name="PageKeyCannotBeEmpty" xml:space="preserve">
<value>页面键不能为空!</value>
</data>
<data name="ParentNodeCannotBeNull" xml:space="preserve">
<value>父节点不能为空!</value>
</data>
@@ -489,6 +495,30 @@
<data name="TheBookIsNotInTheSeries" xml:space="preserve">
<value>该图书不在系列中!</value>
</data>
<data name="ThemeArchiveCannotBeNull" xml:space="preserve">
<value>主题存档不能为空!</value>
</data>
<data name="ThemeArchiveNotReadable" xml:space="preserve">
<value>无法读取主题存档!</value>
</data>
<data name="ThemeAssetPathCannotBeEmpty" xml:space="preserve">
<value>主题资源路径不能为空!</value>
</data>
<data name="ThemeCannotBeDeleted" xml:space="preserve">
<value>主题不能删除!</value>
</data>
<data name="ThemeFilesUnreadable" xml:space="preserve">
<value>无法读取主题文件!</value>
</data>
<data name="ThemeIdCannotBeEmpty" xml:space="preserve">
<value>主题 ID 不能为空!</value>
</data>
<data name="ThemeNotAvailable" xml:space="preserve">
<value>主题不可用!</value>
</data>
<data name="ThemeNotFound" xml:space="preserve">
<value>未找到指定的主题!</value>
</data>
<data name="TitleCannotBeEmpty" xml:space="preserve">
<value>标题不能为空!</value>
</data>
@@ -36,11 +36,7 @@ public sealed class ThemePageRenderer
/// <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;
ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken);
model.ThemeId = document.Theme.Id;
model.ThemeName = document.Theme.Name;
@@ -1,20 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
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 Lumina.Presentation.Web.Common.Routes;
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
@@ -22,185 +14,51 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Web.Core.Themes;
/// <summary>
/// Manages the installed theme packages: installation, selection, rendering documents and archives.
/// Facade over the theme endpoints of the remote API, which stores and serves the theme packs, while the rendering logic stays in this project.
/// </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;
private readonly IApiHttpClient _apiHttpClient;
/// <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)
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public ThemeService(IApiHttpClient apiHttpClient)
{
_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();
}
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Gets the display metadata of all installed themes.
/// </summary>
/// <returns>The list of installed theme metadata.</returns>
public IReadOnlyList<ThemeInfoDto> GetThemes()
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of installed themes.</returns>
public async Task<IReadOnlyList<ThemeInfoDto>> GetThemesAsync(CancellationToken cancellationToken = default)
{
return [.. _themes.Values
.Select(theme => theme.Info)
.OrderByDescending(theme => theme.IsBundled)
.ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)];
ThemeResponseDto[] themes = await _apiHttpClient.GetAsync<ThemeResponseDto[]>(ApiRoutes.Themes.GET_THEMES, cancellationToken).ConfigureAwait(false);
return [.. themes.Select(ToThemeInfo)];
}
/// <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.
/// Gets the display metadata of the currently active theme.
/// </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)
/// <returns>The current theme.</returns>
public async Task<ThemeInfoDto> GetCurrentThemeAsync(CancellationToken cancellationToken = default)
{
string? current = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken);
if (current is not null && _themes.ContainsKey(current))
return current;
ThemeResponseDto theme = await _apiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, cancellationToken).ConfigureAwait(false);
return ToThemeInfo(theme);
}
return await EnsureValidCurrentThemeAsync(cancellationToken);
/// <summary>
/// Gets the theme engine settings used by the administration interface.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The theme engine settings.</returns>
public async Task<ThemeSettingsResponseDto> GetThemeSettingsAsync(CancellationToken cancellationToken = default)
{
return await _apiHttpClient.GetAsync<ThemeSettingsResponseDto>(ApiRoutes.Themes.GET_THEME_SETTINGS, cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -208,37 +66,32 @@ public sealed class ThemeService
/// </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)
public async Task SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(themeId) || !_themes.ContainsKey(themeId))
return ThemeNotFound(themeId);
await _settingsStore.SetCurrentThemeIdAsync(themeId, cancellationToken);
return Result.Success;
await _apiHttpClient.PutAsync<ThemeResponseDto, object>(ApiRoutes.Themes.SET_CURRENT_THEME, new { ThemeId = themeId }, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Installs a theme from the provided archive.
/// Installs a theme from the provided archive, replacing the files of an existing theme with the same manifest id.
/// </summary>
/// <param name="archive">The ZIP archive stream of the theme package.</param>
/// <param name="archive">The ZIP archive stream of the theme pack.</param>
/// <param name="fileName">The file name of the uploaded 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 installed theme metadata, or an error.</returns>
public async Task<Result<ThemeInfoDto>> InstallAsync(Stream archive, CancellationToken cancellationToken = default)
/// <returns>The installed theme metadata.</returns>
public async Task<ThemeInfoDto> InstallAsync(Stream archive, string fileName, 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);
ThemeResponseDto theme = await _apiHttpClient.PostMultipartAsync<ThemeResponseDto>(ApiRoutes.Themes.INSTALL_THEME, archive, fileName, "archive", cancellationToken).ConfigureAwait(false);
return ToThemeInfo(theme);
}
return installedResult.Value.Info;
}
finally
{
_mutationGate.Release();
}
/// <summary>
/// Deletes a theme.
/// </summary>
/// <param name="themeId">The identifier of the theme to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async Task DeleteThemeAsync(string themeId, CancellationToken cancellationToken = default)
{
await _apiHttpClient.DeleteAsync(ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false);
}
/// <summary>
@@ -247,68 +100,18 @@ public sealed class ThemeService
/// <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)
/// <returns>The render document.</returns>
public async Task<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;
}
string themeId;
if (string.IsNullOrWhiteSpace(requestedThemeId))
themeId = (await GetCurrentThemeAsync(cancellationToken).ConfigureAwait(false)).Id;
else
{
string currentThemeId = await GetCurrentThemeIdAsync(cancellationToken);
installedTheme = _themes[currentThemeId];
}
themeId = requestedThemeId;
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;
ThemeTemplateResponseDto response = await _apiHttpClient.GetAsync<ThemeTemplateResponseDto>(
ApiRoutes.Themes.GET_THEME_TEMPLATE.Replace("{themeId}", themeId).Replace("{pageKey}", pageKey), cancellationToken).ConfigureAwait(false);
return new ThemeRenderDocumentDto(ToThemeInfo(response.Theme), response.Template);
}
/// <summary>
@@ -316,574 +119,21 @@ public sealed class ThemeService
/// </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)
/// <returns>The theme archive.</returns>
public async Task<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);
BlobDataDto blob = await _apiHttpClient.GetBlobAsync(ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false);
return new ThemeArchiveDto($"{themeId}.zip", new MemoryStream(blob.Data));
}
/// <summary>
/// Installs a theme package from an archive stream into the storage root.
/// Converts a theme response from the remote API to the display metadata of the theme.
/// </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)
/// <param name="theme">The theme response to convert.</param>
/// <returns>The converted theme display metadata.</returns>
private static ThemeInfoDto ToThemeInfo(ThemeResponseDto theme)
{
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));
string previewUrl = string.IsNullOrWhiteSpace(theme.PreviewPath) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{theme.ThemeId}/{theme.PreviewPath}";
return new ThemeInfoDto(theme.ThemeId, theme.Name, theme.Description, theme.Author, theme.Version, previewUrl, theme.InstallSource == ThemeInstallSource.Bundled);
}
}
@@ -1,115 +0,0 @@
#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));
}
}
@@ -36,7 +36,7 @@ public sealed class ThemeTemplateEngine
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 parseResult.Errors;
return Result.Success;
}
@@ -55,12 +55,12 @@ public sealed class ThemeTemplateEngine
int cursor = 0;
Result<IReadOnlyList<ThemeTemplateNodeDto>> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0);
if (parseResult.IsFailure)
return Result<string>.Failure(parseResult.Errors);
return 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 renderResult.Errors;
return output.ToString();
}
@@ -103,7 +103,7 @@ public sealed class ThemeTemplateEngine
string expression = template[(opening + 3)..closing].Trim();
Result<Success> expressionResult = ValidateExpression(expression);
if (expressionResult.IsFailure)
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(expressionResult.Errors);
return expressionResult.Errors;
nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false));
cursor = closing + 3;
@@ -129,11 +129,11 @@ public sealed class ThemeTemplateEngine
string expression = tag[1..].Trim();
Result<Success> sectionExpressionResult = ValidateExpression(expression);
if (sectionExpressionResult.IsFailure)
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(sectionExpressionResult.Errors);
return sectionExpressionResult.Errors;
Result<IReadOnlyList<ThemeTemplateNodeDto>> childrenResult = ParseNodes(template, ref cursor, expression, depth + 1);
if (childrenResult.IsFailure)
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(childrenResult.Errors);
return childrenResult.Errors;
nodes.Add(new ThemeSectionNodeDto(expression, Inverted: tag[0] == '^', Children: childrenResult.Value));
break;
@@ -143,7 +143,7 @@ public sealed class ThemeTemplateEngine
string closingName = tag[1..].Trim();
Result<Success> closingNameResult = ValidateExpression(closingName);
if (closingNameResult.IsFailure)
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(closingNameResult.Errors);
return closingNameResult.Errors;
if (expectedClosingName is null)
return TemplateInvalid($"Closing section '{closingName}' has no matching opening section.");
@@ -158,7 +158,7 @@ public sealed class ThemeTemplateEngine
string expression = tag[1..].Trim();
Result<Success> unescapedExpressionResult = ValidateExpression(expression);
if (unescapedExpressionResult.IsFailure)
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(unescapedExpressionResult.Errors);
return unescapedExpressionResult.Errors;
nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false));
break;
@@ -167,7 +167,7 @@ public sealed class ThemeTemplateEngine
{
Result<Success> variableResult = ValidateExpression(tag);
if (variableResult.IsFailure)
return Result<IReadOnlyList<ThemeTemplateNodeDto>>.Failure(variableResult.Errors);
return variableResult.Errors;
nodes.Add(new ThemeVariableNodeDto(tag, ShouldBeEscaped: true));
break;
@@ -198,7 +198,7 @@ public sealed class ThemeTemplateEngine
{
Result<Success> textResult = AppendChecked(output, text.Value);
if (textResult.IsFailure)
return Result<Success>.Failure(textResult.Errors);
return textResult.Errors;
break;
}
@@ -208,7 +208,7 @@ public sealed class ThemeTemplateEngine
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);
return variableResult.Errors;
break;
}
@@ -216,7 +216,7 @@ public sealed class ThemeTemplateEngine
{
Result<Success> sectionResult = RenderSection(section, scope, output);
if (sectionResult.IsFailure)
return Result<Success>.Failure(sectionResult.Errors);
return sectionResult.Errors;
break;
}
@@ -257,7 +257,7 @@ public sealed class ThemeTemplateEngine
{
Result<Success> itemResult = RenderNodes(section.Children, new ThemeRenderScopeDto(item, scope), output);
if (itemResult.IsFailure)
return Result<Success>.Failure(itemResult.Errors);
return itemResult.Errors;
}
return Result.Success;