From 3192b9c58530c6a44b97aa6b6c2ac832a5f29ea3 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 29 Aug 2026 13:11:16 +0300 Subject: [PATCH 1/5] Falls back to the unstyled application views when a theme template is missing --- .../Infrastructure/Themes/IThemeService.cs | 2 +- .../GetThemeTemplateQueryHandler.cs | 62 +++-- .../Common/Errors/Errors.Themes.cs | 1 + .../Core/Themes/ThemeDetectionSyncJob.cs | 73 +++-- .../Core/Themes/ThemeService.cs | 60 +++- .../Core/Themes/ThemeLayoutRenderer.cs | 22 +- .../Core/Views/Shared/_NavMenu.cshtml | 257 +++--------------- .../GetThemeTemplateQueryHandlerTests.cs | 51 +++- .../Core/Themes/ThemeDetectionSyncJobTests.cs | 20 ++ .../Core/Themes/ThemeServiceTests.cs | 95 ++++++- .../Core/Themes/ThemeLayoutRendererTests.cs | 24 ++ 11 files changed, 366 insertions(+), 301 deletions(-) diff --git a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs index e9c2bd4a..67884731 100644 --- a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs @@ -57,7 +57,7 @@ public interface IThemeService Task> LoadManifestAsync(string themeId, CancellationToken cancellationToken); /// - /// Gets the sanitized content of the template selected by a page key, falling back to the default template when the key is missing. + /// Gets the sanitized content of the template selected by a page key, returning an error when the theme provides no template for the page. /// /// The manifest id of the theme. /// The page key that selects the template. diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs index e547d303..419d1d9a 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs @@ -14,6 +14,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Microsoft.Extensions.Logging; #endregion namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate; @@ -26,6 +27,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler _validator; + private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -33,11 +35,13 @@ public class GetThemeTemplateQueryHandler : IQueryHandlerInjected unit of work for interacting with the data access layer repositories. /// Injected service for the server-side storage and serving of theme packs. /// Injected validator for application validation rules. - public GetThemeTemplateQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator validator) + /// Injected logger for the handler. + public GetThemeTemplateQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator validator, ILogger logger) { _unitOfWork = unitOfWork; _themeService = themeService; _validator = validator; + _logger = logger; } /// @@ -66,8 +70,12 @@ public class GetThemeTemplateQueryHandler : IQueryHandler when the theme was restored; otherwise. private async Task TryRestoreBundledThemeAsync(ThemeEntity theme, CancellationToken cancellationToken) { - Result restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); - if (restoreResult.IsFailure) - return false; - - if (theme.IsCurrent == true) + try { - Result getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false); - if (getDefaultResult.IsFailure) - return true; + Result restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); + if (restoreResult.IsFailure) + return false; - ThemeEntity? defaultTheme = getDefaultResult.Value; - if (defaultTheme is not null && !defaultTheme.IsDeleted && defaultTheme.Id != theme.Id) + if (theme.IsCurrent == true) { - theme.IsCurrent = null; - await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); + Result getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false); + if (getDefaultResult.IsFailure) + return true; - defaultTheme.IsCurrent = true; - await _unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); + ThemeEntity? defaultTheme = getDefaultResult.Value; + if (defaultTheme is not null && !defaultTheme.IsDeleted && defaultTheme.Id != theme.Id) + { + theme.IsCurrent = null; + await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + defaultTheme.IsCurrent = true; + await _unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } } - } - return true; + return true; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) + { + // the restore is best effort: an unexpected failure must not fail the request, so the caller falls back to + // the application view instead of returning an error to the browser + _logger.LogWarning(exception, "Failed to restore the files of bundled theme '{ThemeId}'.", theme.ThemeId); + return false; + } } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs index 3c32d711..b86cbc82 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs @@ -21,6 +21,7 @@ public static partial class Errors public static Error ThemeCannotBeRestored => Error.Forbidden(description: nameof(ThemeCannotBeRestored)); public static Error ThemeArchiveNotReadable => Error.Failure(description: nameof(ThemeArchiveNotReadable)); public static Error ThemeFilesUnreadable => Error.Failure(description: nameof(ThemeFilesUnreadable)); + public static Error ThemeTemplateNotFound => Error.NotFound(description: nameof(ThemeTemplateNotFound)); public static Error ThemeNotAvailable => Error.Failure(description: nameof(ThemeNotAvailable)); } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index 46777467..272832ec 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -147,41 +147,54 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService foreach (ThemeEntity brokenTheme in brokenThemes) { - if (brokenTheme.InstallSource == ThemeInstallSource.Bundled) + try { - // the files of a bundled theme that was not deleted by the user are restored from its shipped archive - Result restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken); - if (restoreResult.IsSuccess) - continue; - - _logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); - - // at least one bundled theme must always remain available, so the application never ends up without any theme; - // the last remaining bundled theme is kept even when its files cannot be recovered - int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled); - if (availableBundledThemes <= 1) + if (brokenTheme.InstallSource == ThemeInstallSource.Bundled) { - _logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); - continue; - } + // the files of a bundled theme that was not deleted by the user are restored from its shipped archive + Result restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken); + if (restoreResult.IsSuccess) + continue; - // a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later - brokenTheme.IsDeleted = true; - brokenTheme.IsCurrent = null; - brokenTheme.UpdatedOnUtc = DateTime.UtcNow; - brokenTheme.UpdatedBy = default; - Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken); - if (updateResult.IsFailure) - _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); + _logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); + + // at least one bundled theme must always remain available, so the application never ends up without any theme; + // the last remaining bundled theme is kept even when its files cannot be recovered + int availableBundledThemes = themes.Count(availableTheme => !availableTheme.IsDeleted && availableTheme.InstallSource == ThemeInstallSource.Bundled); + if (availableBundledThemes <= 1) + { + _logger.LogWarning("Bundled theme '{ThemeId}' is the last remaining bundled theme and its files could not be restored, so it is kept.", brokenTheme.ThemeId); + continue; + } + + // a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later + brokenTheme.IsDeleted = true; + brokenTheme.IsCurrent = null; + brokenTheme.UpdatedOnUtc = DateTime.UtcNow; + brokenTheme.UpdatedBy = default; + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken); + if (updateResult.IsFailure) + _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); + } + else + { + // a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely + _logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); + brokenTheme.IsCurrent = null; + Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken); + if (deleteResult.IsFailure) + _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); + } } - else + catch (OperationCanceledException) { - // a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely - _logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); - brokenTheme.IsCurrent = null; - Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken); - if (deleteResult.IsFailure) - _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); + throw; + } + catch (Exception exception) + { + // repairing a broken theme is best effort: an unexpected failure on one theme must not crash the host, + // so it is logged and the remaining broken themes are still processed + _logger.LogWarning(exception, "Failed to repair the broken theme '{ThemeId}'.", brokenTheme.ThemeId); } } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index 11c3a0e1..b26fe59c 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -158,15 +158,49 @@ public sealed class ThemeService : IThemeService _logger.LogWarning(exception, "An uploaded theme archive could not be read."); return Errors.Themes.ThemeArchiveNotReadable; } + catch (IOException exception) + { + // the extracted pack could not be moved into place; the install is best effort, so the caller receives an error + // instead of an unhandled exception that would crash the host or fail the request + _logger.LogWarning(exception, "The theme pack could not be installed."); + return Errors.Themes.ThemeFilesUnreadable; + } + catch (UnauthorizedAccessException exception) + { + _logger.LogWarning(exception, "The theme pack could not be installed."); + return Errors.Themes.ThemeFilesUnreadable; + } finally { - if (File.Exists(temporaryArchivePath)) - File.Delete(temporaryArchivePath); + try + { + if (File.Exists(temporaryArchivePath)) + File.Delete(temporaryArchivePath); - if (Directory.Exists(extractionPath)) - Directory.Delete(extractionPath, recursive: true); + if (Directory.Exists(extractionPath)) + Directory.Delete(extractionPath, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // a locked staging file must not turn the install into an unhandled exception; the stale staging + // directory is removed on the next install attempt + _logger.LogTrace(exception, "Failed to clean up the theme staging directory."); + } } } + catch (IOException exception) + { + // a file system failure before or during the install (for example a locked storage or staging directory) + // must not escape as an unhandled exception, which would crash the host or fail the request; the install + // is best effort and returns an error instead + _logger.LogWarning(exception, "The theme pack could not be installed."); + return Errors.Themes.ThemeFilesUnreadable; + } + catch (UnauthorizedAccessException exception) + { + _logger.LogWarning(exception, "The theme pack could not be installed."); + return Errors.Themes.ThemeFilesUnreadable; + } finally { _mutationGate.Release(); @@ -242,7 +276,7 @@ public sealed class ThemeService : IThemeService } /// - /// Gets the sanitized content of the template selected by a page key, falling back to the default template when the key is missing. + /// Gets the sanitized content of the template selected by a page key, returning an error when the theme provides no template for the page. /// /// The manifest id of the theme. /// The page key that selects the template. @@ -259,7 +293,10 @@ public sealed class ThemeService : IThemeService string? templatePath = manifest.Templates.TryGetValue(pageKey, out string? explicitPath) ? explicitPath : ResolveMirroredTemplatePath(themePath, pageKey); - templatePath ??= manifest.Templates["default"]; // the manifest validation guarantees a default template + + // a template is used for a page only when the theme provides one explicitly or as a mirrored file + if (templatePath is null) + return Errors.Themes.ThemeTemplateNotFound; Result fullPathResult = ResolveContainedPath(themePath, templatePath); if (fullPathResult.IsFailure) @@ -607,8 +644,8 @@ public sealed class ThemeService : IThemeService 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."); + if (manifest.Templates is null || manifest.Templates.Count > 32) + return PackageInvalid("A theme must declare at most 32 templates."); Dictionary normalizedTemplates = new(StringComparer.OrdinalIgnoreCase); foreach ((string key, string path) in manifest.Templates) @@ -634,9 +671,6 @@ public sealed class ThemeService : IThemeService 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)) @@ -796,7 +830,7 @@ public sealed class ThemeService : IThemeService else File.Delete(path); } - catch (IOException exception) + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { _logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path); } @@ -829,7 +863,7 @@ public sealed class ThemeService : IThemeService Directory.Move(extractionPath, destination); return; } - catch (IOException) when (attempt < MAX_ATTEMPTS) + catch (Exception exception) when (attempt < MAX_ATTEMPTS && exception is IOException or UnauthorizedAccessException) { await Task.Delay(100 * attempt, cancellationToken); } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs index 69540cac..ecb86226 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs @@ -92,7 +92,7 @@ public class ThemeLayoutRenderer } /// - /// Renders the navigation menu of the active theme, falling back to the application Razor menu when the theme template cannot be rendered. + /// Renders the navigation menu of the active theme, falling back to the application Razor menu when the theme navigation template cannot be loaded or rendered. /// /// The manifest id of the active theme. /// Cancellation token that can be used to stop the execution. @@ -100,10 +100,22 @@ public class ThemeLayoutRenderer private async Task RenderNavAsync(string themeId, CancellationToken cancellationToken) { ThemeNavMenuDto navModel = await _navBuilder.BuildAsync(cancellationToken); - ThemeRenderDocumentDto navDocument = await _themeService.GetRenderDocumentAsync(NAV_PAGE_KEY, themeId, cancellationToken); - Result navRenderResult = _templateEngine.RenderPage(navDocument.Template, navModel); - if (navRenderResult.IsSuccess) - return navRenderResult.Value.Content; + try + { + ThemeRenderDocumentDto navDocument = await _themeService.GetRenderDocumentAsync(NAV_PAGE_KEY, themeId, cancellationToken); + Result navRenderResult = _templateEngine.RenderPage(navDocument.Template, navModel); + if (navRenderResult.IsSuccess) + return navRenderResult.Value.Content; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // the navigation menu is best effort: when the theme navigation template cannot be loaded or rendered, + // the application navigation menu is rendered instead, keeping the themed shell of the page intact + } return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken); } diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml index ca18e84b..0dd25cd8 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml @@ -1,230 +1,53 @@ -@using Lumina.Presentation.Web.Common.Authorization -@using Lumina.Presentation.Web.Common.Enums.Authorization -@using Lumina.Presentation.Web.Common.Services -@using Microsoft.AspNetCore.Mvc.Localization +@* + FALLBACK NAVIGATION MENU - READ BEFORE EDITING + + This view is rendered ONLY when the active theme's navigation template + (shared/nav-menu.html) cannot be rendered, for example when the theme is + broken, missing or unavailable. On a healthy site, the navigation menu is + built by ThemeNavBuilder and rendered by the theme's shared/nav-menu.html + template, so changes made in this file do NOT show up on a working site. + + To change the menu, edit ThemeNavBuilder. To restyle the menu, edit the + theme. This fallback is intentionally plain, unstyled HTML, so that a + broken theme is obvious to the user while navigation still works. +*@ +@using Lumina.Presentation.Web.Common.DTO.Themes +@using Lumina.Presentation.Web.Core.Themes @using System.Threading +@inject ThemeNavBuilder _navBuilder -@inject IUrlService _urlService -@inject IViewLocalizer _localizer -@inject IAuthorizationService _auth +@{ + ThemeNavMenuDto menu = await _navBuilder.BuildAsync(CancellationToken.None); +} - - -