Renders themed pages as swappable sections with path-mirrored template scopes and a Razor fallback

This commit is contained in:
BinaryAlley committed 2026-08-20 06:50:17 -07:00
1 parent f17e685239
commit e37bb3ecc6
24 files changed
+351 -187

No files matched your search

@@ -99,9 +99,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken);
if (insertResult.IsFailure)
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
else
themes.Add(themeEntity);
}
await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken);
await EnsureCurrentThemeExistsAsync(unitOfWork, themes, stoppingToken);
await unitOfWork.SaveChangesAsync(stoppingToken);
}
@@ -112,12 +115,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List<ThemeEntity> themes, CancellationToken cancellationToken)
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
// a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored
// automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed
// externally, and is the only case where the files are restored
List<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
IReadOnlyList<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
if (brokenThemes.Count is 0)
return;
@@ -151,22 +154,30 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
_logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
}
}
}
// if the deleted theme was the active one, switch to another available theme, preferring the configured default
/// <summary>
/// Activates the configured default theme when no theme is currently active, so the application always has an active theme.
/// </summary>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return;
ThemeEntity? replacementTheme = themes
ThemeEntity? defaultTheme = themes
.Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId))
.OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (replacementTheme is null)
if (defaultTheme is null)
return;
replacementTheme.IsCurrent = true;
replacementTheme.UpdatedOnUtc = DateTime.UtcNow;
replacementTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken);
defaultTheme.IsCurrent = true;
defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
defaultTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken);
}
}
@@ -260,10 +260,13 @@ public sealed class ThemeService : IThemeService
return manifestResult.Errors;
ThemeManifestDto manifest = manifestResult.Value;
if (!manifest.Templates.TryGetValue(pageKey, out string? templatePath))
templatePath = manifest.Templates["default"]; // the manifest validation guarantees a default template
string themePath = ResolveThemePath(themeId);
string? templatePath = manifest.Templates.TryGetValue(pageKey, out string? explicitPath)
? explicitPath
: ResolveMirroredTemplatePath(themePath, pageKey);
templatePath ??= manifest.Templates["default"]; // the manifest validation guarantees a default template
Result<string> fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), templatePath);
Result<string> fullPathResult = ResolveContainedPath(themePath, templatePath);
if (fullPathResult.IsFailure)
return fullPathResult.Errors;
@@ -277,6 +280,33 @@ public sealed class ThemeService : IThemeService
return template;
}
/// <summary>
/// Resolves the mirrored template path of a page key, walking up the scopes of the path when the exact mirror does not exist.
/// </summary>
/// <param name="themePath">The absolute path of the theme pack directory.</param>
/// <param name="pageKey">The page key that selects the template.</param>
/// <returns>The mirrored template path, or <see langword="null"/> when no mirrored template exists.</returns>
private static string? ResolveMirroredTemplatePath(string themePath, string pageKey)
{
string? candidate = pageKey;
while (candidate is not null)
{
// normalize the mirrored candidate so that malicious page keys cannot escape the theme pack
Result<string> normalizedResult = NormalizeRelativePath($"templates/{candidate}.html");
if (normalizedResult.IsSuccess)
{
Result<string> fullPathResult = ResolveContainedPath(themePath, normalizedResult.Value);
if (fullPathResult.IsSuccess && File.Exists(fullPathResult.Value))
return normalizedResult.Value;
}
int lastSlash = candidate.LastIndexOf('/');
candidate = lastSlash < 0 ? null : candidate[..lastSlash];
}
return null;
}
/// <summary>
/// Gets a theme asset file.
/// </summary>
@@ -14,7 +14,7 @@
"MaxExpandedBytes": 25165824,
"MaxSingleFileBytes": 6291456,
"MaxEntries": 250,
"AllowThemeScripts": false
"AllowThemeScripts": true
},
"ConnectionStrings": {
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"