Falls back to the unstyled application views when a theme template is missing

This commit is contained in:
BinaryAlley committed 2026-08-29 13:11:16 +03:00
1 parent f4b90a5aea
commit 3192b9c585
11 files changed
+366 -301

No files matched your search

@@ -57,7 +57,7 @@ public interface IThemeService
Task<Result<ThemeManifestDto>> LoadManifestAsync(string themeId, CancellationToken cancellationToken);
/// <summary>
/// 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.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key that selects the template.</param>
@@ -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<GetThemeTemplateQuery,
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeTemplateQuery> _validator;
private readonly ILogger<GetThemeTemplateQueryHandler> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateQueryHandler"/> class.
@@ -33,11 +35,13 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetThemeTemplateQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeTemplateQuery> validator)
/// <param name="logger">Injected logger for the handler.</param>
public GetThemeTemplateQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeTemplateQuery> validator, ILogger<GetThemeTemplateQueryHandler> logger)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
_logger = logger;
}
/// <summary>
@@ -66,8 +70,12 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
if (templateResult.IsFailure)
{
// the stored files of a bundled theme removed externally are restored, and if the broken theme was the
// active one, the configured default theme is activated, so clients always have a renderable theme
if (theme.InstallSource == ThemeInstallSource.Bundled && await TryRestoreBundledThemeAsync(theme, cancellationToken).ConfigureAwait(false))
// active one, the configured default theme is activated, so clients always have a renderable theme; a
// theme that simply does not provide a template for the page is not broken, so it is not restored and the
// caller falls back to the application's default unstyled Razor view instead
if (templateResult.FirstError != DomainErrors.Themes.ThemeTemplateNotFound
&& theme.InstallSource == ThemeInstallSource.Bundled
&& await TryRestoreBundledThemeAsync(theme, cancellationToken).ConfigureAwait(false))
templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false);
if (templateResult.IsFailure)
@@ -85,29 +93,43 @@ public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery,
/// <returns><see langword="true"/> when the theme was restored; <see langword="false"/> otherwise.</returns>
private async Task<bool> TryRestoreBundledThemeAsync(ThemeEntity theme, CancellationToken cancellationToken)
{
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (restoreResult.IsFailure)
return false;
if (theme.IsCurrent == true)
try
{
Result<ThemeEntity?> getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false);
if (getDefaultResult.IsFailure)
return true;
Result<Success> 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<ThemeEntity?> 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;
}
}
}
@@ -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));
}
}
@@ -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<Success> 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<Success> 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<Updated> 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<Updated> 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<Deleted> 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<Deleted> 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);
}
}
}
@@ -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
}
/// <summary>
/// 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.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key that selects the template.</param>
@@ -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<string> 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<string, string> 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);
}
@@ -92,7 +92,7 @@ public class ThemeLayoutRenderer
}
/// <summary>
/// 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.
/// </summary>
/// <param name="themeId">The manifest id of the active theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -100,10 +100,22 @@ public class ThemeLayoutRenderer
private async Task<string> RenderNavAsync(string themeId, CancellationToken cancellationToken)
{
ThemeNavMenuDto navModel = await _navBuilder.BuildAsync(cancellationToken);
ThemeRenderDocumentDto navDocument = await _themeService.GetRenderDocumentAsync(NAV_PAGE_KEY, themeId, cancellationToken);
Result<ThemePageRenderResultDto> 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<ThemePageRenderResultDto> 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);
}
@@ -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);
}
<input type="checkbox" id="hamburger-input" class="burger-shower" />
<label id="hamburger-menu" for="hamburger-input">
<span></span>
<span></span>
<span></span>
<nav id="mobile-menu">
<div id="mobile-menu-content">
<div class="mobile-menu-heading">
Lumina
</div>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)" class="nav-link"><span>@_localizer["Home"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
@_localizer["Account"]
</div>
<ul>
@if (User?.Identity?.IsAuthenticated == false)
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)"><span>@_localizer["Login"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)"><span>@_localizer["RecoverPassword"]</span></a></li>
}
else
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT)"><span>@_localizer["Logout"]</span></a></li>
}
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW)" class="nav-link"><span>@_localizer["Register"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW)" class="nav-link"><span>@_localizer["ChangePassword"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW)" class="nav-link"><span>@_localizer["Profile"]</span></a></li>
}
</ul>
@if (User?.Identity?.IsAuthenticated == true)
{
@if (await _auth.IsInRoleAsync("Admin", CancellationToken.None))
{
<div class="mobile-menu-heading">
@_localizer["Administrator"]
</div>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES)" class="nav-link"><span>@_localizer["ManageRoles"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS)" class="nav-link"><span>@_localizer["ManagePermissions"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX)" class="nav-link"><span>@_localizer["Plugins"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES)" class="nav-link"><span>@_localizer["Themes"]</span></a></li>
</ul>
}
<div class="mobile-menu-heading">
@_localizer["Library"]
</div>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX)" class="nav-link"><span>@_localizer["ManageLibraries"]</span></a></li>
@if (await _auth.IsInRoleAsync("Admin", CancellationToken.None) || await _auth.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None))
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY)" class="nav-link"><span>@_localizer["AddNewLibrary"]</span></a></li>
}
</ul>
<div class="mobile-menu-heading">
@_localizer["WrittenContent"]
</div>
<ul>
<li><a href="library/written-content-library/books-library/books" class="nav-link"><span>@_localizer["Books"]</span></a></li>
<li><a href="library/written-content/magazines" class="nav-link"><span>@_localizer["Magazines"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
@_localizer["Audio"]
</div>
<ul>
<li><a href="library/audio/music" class="nav-link"><span>@_localizer["Music"]</span></a></li>
<li><a href="library/audio/interviews" class="nav-link"><span>@_localizer["Interviews"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
@_localizer["Video"]
</div>
<ul>
<li><a href="library/video/movies" class="nav-link"><span>@_localizer["Movies"]</span></a></li>
<li><a href="library/video/tvshows" class="nav-link"><span>@_localizer["TvShows"]</span></a></li>
</ul>
}
<div class="mobile-menu-heading">
@_localizer["Language"]
</div>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=ar-sa&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>العربية</span></a></li><!--AR-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=zh-cn&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>简体中文</span></a></li><!--CN-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=de-de&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>Deutsch</span></a></li><!--DE-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=en-us&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>English</span></a></li><!--EN-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=es-es&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>Español</span></a></li><!--ES-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=fr-fr&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>Français</span></a></li><!--FR-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=it-it&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>Italiano</span></a></li><!--IT-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=ja-jp&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>日本語</span></a></li><!--JP-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=ro-ro&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>Română</span></a></li><!--RO-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=uk-ua&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set"><span>Українська</span></a></li><!--UK-->
</ul>
@if (User?.Identity?.IsAuthenticated == true)
{
<div class="mobile-menu-heading">
@_localizer["Tools"]
</div>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX)" class="nav-link"><span>@_localizer["Settings"]</span></a></li>
</ul>
}
<div class="mobile-menu-heading">
@_localizer["Help"]
</div>
<ul>
<li><a href="help/documentation" class="nav-link"><span>@_localizer["Documentation"]</span></a></li>
<li><a href="help/about" class="nav-link"><span>@_localizer["About"]</span></a></li>
</ul>
</div>
</nav>
</label>
<nav class="menubar">
<nav>
<ul>
<li tabindex="0" class="top-level-menuitem">
<label for="account-menu">Lumina</label>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)" class="nav-link">@_localizer["Home"]</a></li>
</ul>
</li>
<li tabindex="0" class="top-level-menuitem">
<label for="account-menu">@_localizer["Account"]</label>
<ul>
@if (User?.Identity?.IsAuthenticated == false)
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW)">@_localizer["Login"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW)">@_localizer["RecoverPassword"]</a></li>
}
else
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT)">@_localizer["Logout"]</a></li>
}
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW)" class="nav-link">@_localizer["Register"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW)" class="nav-link">@_localizer["ChangePassword"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW)" class="nav-link">@_localizer["Profile"]</a></li>
}
</ul>
</li>
@if (User?.Identity?.IsAuthenticated == true)
@foreach (ThemeNavSectionDto menuSection in menu.MenubarSections)
{
@if (await _auth.IsInRoleAsync("Admin", CancellationToken.None))
{
<li tabindex="1" class="top-level-menuitem">
<label for="administrator-menu">@_localizer["Administrator"]</label>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES)" class="nav-link">@_localizer["ManageRoles"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS)" class="nav-link">@_localizer["ManagePermissions"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX)" class="nav-link">@_localizer["Plugins"]</a></li>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES)" class="nav-link">@_localizer["Themes"]</a></li>
</ul>
</li>
}
<li tabindex="2" class="top-level-menuitem">
<label for="library-menu">@_localizer["Library"]</label>
<li>
<span>@menuSection.Label</span>
<ul>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX)" class="nav-link">@_localizer["ManageLibraries"]</a></li>
@if (await _auth.IsInRoleAsync("Admin", CancellationToken.None) || await _auth.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None))
@foreach (ThemeNavEntryDto item in menuSection.Items)
{
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY)" class="nav-link">@_localizer["AddNewLibrary"]</a></li>
<li>
@if (item.Children.Count > 0)
{
<span>@item.Label</span>
<ul>
@foreach (ThemeNavEntryDto child in item.Children)
{
<li><a href="@child.Url">@child.Label</a></li>
}
</ul>
}
else
{
<a href="@item.Url">@item.Label</a>
}
</li>
}
<li class="has-submenu" tabindex="0">
<label>@_localizer["WrittenContent"]</label>
<ul>
<li><a href="library/written-content-library/books-library/books" class="nav-link">@_localizer["Books"]</a></li>
<li><a href="library/written-content/magazines" class="nav-link">@_localizer["Magazines"]</a></li>
</ul>
</li>
<li class="has-submenu" tabindex="0">
<label>@_localizer["Audio"]</label>
<ul>
<li><a href="library/audio/music" class="nav-link">@_localizer["Music"]</a></li>
<li><a href="library/audio/interviews" class="nav-link">@_localizer["Interviews"]</a></li>
</ul>
</li>
<li class="has-submenu" tabindex="0">
<label>@_localizer["Video"]</label>
<ul>
<li><a href="library/video/movies" class="nav-link">@_localizer["Movies"]</a></li>
<li><a href="library/video/tvshows" class="nav-link">@_localizer["TvShows"]</a></li>
</ul>
</li>
</ul>
</li>
}
<li tabindex="3" class="top-level-menuitem">
<label for="tools-menu">@_localizer["Tools"]</label>
<ul>
<li class="has-submenu" tabindex="0">
<label>@_localizer["Language"]</label>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=ar-sa&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">العربية</a></li><!--AR-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=zh-cn&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">简体中文</a></li><!--CN-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=de-de&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">Deutsch</a></li><!--DE-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=en-us&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">English</a></li><!--EN-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=es-es&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">Español</a></li><!--ES-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=fr-fr&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">Français</a></li><!--FR-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=it-it&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">Italiano</a></li><!--IT-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=ja-jp&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">日本語</a></li><!--JP-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=ro-ro&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">Română</a></li><!--RO-->
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE)?newCulture=uk-ua&returnUrl=@Uri.EscapeDataString(Context.Request.Path + Context.Request.QueryString)" class="lang-set">Українська</a></li><!--UK-->
</ul>
</li>
@if (User?.Identity?.IsAuthenticated == true)
{
<li><a href="@_urlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX)" class="nav-link">@_localizer["Settings"]</a></li>
}
</ul>
</li>
<li tabindex="4" class="top-level-menuitem">
<label for="help-menu">@_localizer["Help"]</label>
<ul>
<li><a href="help/documentation" class="nav-link">@_localizer["Documentation"]</a></li>
<li><a href="help/about" class="nav-link">@_localizer["About"]</a></li>
</ul>
</li>
</ul>
</nav>
@@ -11,10 +11,12 @@ using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -31,6 +33,7 @@ public class GetThemeTemplateQueryHandlerTests
private readonly IThemeService _mockThemeService;
private readonly IValidator<GetThemeTemplateQuery> _mockValidator;
private readonly IThemeRepository _mockThemeRepository;
private readonly ILogger<GetThemeTemplateQueryHandler> _mockLogger;
private readonly GetThemeTemplateQueryHandler _sut;
private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new();
private readonly ThemeEntityFixture _themeEntityFixture = new();
@@ -44,12 +47,13 @@ public class GetThemeTemplateQueryHandlerTests
_mockThemeService = Substitute.For<IThemeService>();
_mockValidator = Substitute.For<IValidator<GetThemeTemplateQuery>>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockLogger = Substitute.For<ILogger<GetThemeTemplateQueryHandler>>();
_mockValidator.Validate(Arg.Any<GetThemeTemplateQuery>())
.Returns([]);
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_sut = new GetThemeTemplateQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator);
_sut = new GetThemeTemplateQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator, _mockLogger);
}
[Fact]
@@ -166,6 +170,51 @@ public class GetThemeTemplateQueryHandlerTests
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateIsNotFoundForBundledTheme_ShouldNotRestoreBundledTheme()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(Errors.Themes.ThemeTemplateNotFound);
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRestoreThrowsForBundledTheme_ShouldReturnTemplateErrorInsteadOfThrowing()
{
// Arrange
GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create();
ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false);
Error templateError = Errors.Themes.ThemeFilesUnreadable;
_mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any<CancellationToken>())
.Returns(Result.From<ThemeEntity?>(theme));
_mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>())
.Returns(templateError);
_mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new IOException("The theme storage is locked.")));
// Act
Result<ThemeTemplateResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(templateError, result.FirstError);
await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeService.Received(1).GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTemplateLoadFailsAndRestoreFails_ShouldReturnTemplateError()
{
@@ -275,6 +275,26 @@ public class ThemeDetectionSyncJobTests : IDisposable
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenRestoringBundledThemeThrows_ShouldNotCrashTheJob()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(Result.From<IEnumerable<ThemeEntity>>([brokenTheme]));
_mockThemeService.HasThemePack("bundled-theme").Returns(false);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new IOException("The theme storage is locked.")));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.From(Result.Updated));
// Act
await StartAndWaitForExecutionAsync(CreateSut());
// Assert
await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenLastBundledThemePackCannotBeRestored_ShouldKeepAndActivateTheTheme()
{
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
@@ -200,7 +201,7 @@ public class ThemeServiceTests : IDisposable
// Act
await InstallValidThemeAsync(firstArchive);
await InstallValidThemeAsync(secondArchive);
Result<string> templateResult = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None);
Result<string> templateResult = await _sut.GetTemplateAsync("test-theme", "default", CancellationToken.None);
// Assert
Assert.True(templateResult.IsSuccess);
@@ -210,6 +211,23 @@ public class ThemeServiceTests : IDisposable
Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0]));
}
[Fact]
public async Task InstallAsync_WhenThemeDestinationIsBlocked_ShouldReturnThemeFilesUnreadableInsteadOfThrowing()
{
// Arrange
byte[] archive = _themePackFixture.Create(themeId: "test-theme");
// the destination path is blocked by an existing file, so the extracted pack cannot be moved into place
Directory.CreateDirectory(_options.StoragePath);
File.WriteAllText(Path.Combine(_options.StoragePath, "test-theme"), "blocked");
// Act
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description);
}
[Fact]
public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError()
{
@@ -558,7 +576,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldReturnPackageInvalidError()
public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldInstallSuccessfully()
{
// Arrange
byte[] archive = _themePackFixture.Create(templates: new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));
@@ -567,7 +585,7 @@ public class ThemeServiceTests : IDisposable
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
AssertPackageInvalid(result, "between 1 and 32");
Assert.True(result.IsSuccess);
}
[Fact]
@@ -583,7 +601,7 @@ public class ThemeServiceTests : IDisposable
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
AssertPackageInvalid(result, "between 1 and 32");
AssertPackageInvalid(result, "at most 32");
}
[Fact]
@@ -641,7 +659,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldReturnPackageInvalidError()
public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldInstallSuccessfully()
{
// Arrange
Dictionary<string, string> templates = new(StringComparer.OrdinalIgnoreCase)
@@ -654,7 +672,7 @@ public class ThemeServiceTests : IDisposable
Result<ThemeManifestDto> result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None);
// Assert
AssertPackageInvalid(result, "default");
Assert.True(result.IsSuccess);
}
[Fact]
@@ -889,7 +907,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldFallBackToDefaultTemplate()
public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
@@ -899,15 +917,15 @@ public class ThemeServiceTests : IDisposable
Result<string> result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Theory]
[InlineData("../secret")] // parent scope traversal attempt
[InlineData("/etc/passwd")] // rooted path attempt
[InlineData("templates//nested")] // empty segment attempt
public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldFallBackToDefaultTemplate(string pageKey)
public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldReturnThemeTemplateNotFound(string pageKey)
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
@@ -916,9 +934,58 @@ public class ThemeServiceTests : IDisposable
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
public async Task GetTemplateAsync_WhenSharedLayoutTemplateIsMissing_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "shared/layout", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
public async Task GetTemplateAsync_WhenSharedNavMenuTemplateIsMissing_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
public async Task GetTemplateAsync_WhenSharedNavMenuMirrorExists_ShouldReturnTheMirroredTemplate()
{
// Arrange
const string NAV_TEMPLATE = "<html><body>nav menu</body></html>";
byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary<string, string>
{
["templates/shared/nav-menu.html"] = NAV_TEMPLATE
});
await InstallValidThemeAsync(archive);
// Act
Result<string> result = await _sut.GetTemplateAsync("test-theme", "shared/nav-menu", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
Assert.Equal(NAV_TEMPLATE, result.Value);
}
[Fact]
@@ -953,7 +1020,7 @@ public class ThemeServiceTests : IDisposable
}
[Fact]
public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldFallBackToDefaultTemplate()
public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldReturnThemeTemplateNotFound()
{
// Arrange
byte[] archive = CreateThemeWithTemplates();
@@ -964,8 +1031,8 @@ public class ThemeServiceTests : IDisposable
Result<string> result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(DEFAULT_TEMPLATE, result.Value);
Assert.True(result.IsFailure);
Assert.Equal(Errors.Themes.ThemeTemplateNotFound, result.FirstError);
}
[Fact]
@@ -20,6 +20,7 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -139,6 +140,29 @@ public class ThemeLayoutRendererTests
_mockViewEngine.Received(1).FindView(Arg.Any<ActionContext>(), "_NavMenu", false);
}
[Fact]
public async Task RenderAsync_WhenNavDocumentCannotBeLoaded_ShouldFallBackToApplicationNavMenu()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null));
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "nav:{{siteName}}");
string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial")
.Replace("{*pageKey}", "shared/nav-menu");
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(navEndpoint, Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThemeTemplateResponseDto>(new HttpRequestException("The navigation template is unavailable.")));
ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "<main>", script: string.Empty);
// Act
Result<string> result = await _sut.RenderAsync(page, "editorial", CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("My Page|<nav-menu-fragment>", result.Value);
_mockViewEngine.Received(1).FindView(Arg.Any<ActionContext>(), "_NavMenu", false);
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldResolveLayoutAndNavDocumentsFromTheme()
{