diff --git a/README.md b/README.md index 34f826e7..2bf76a5b 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ To explore more about Enlightenment and their contributions to the open-source c ### Icons -Most icons were taken from [Lyra Icon Theme](https://github.com/yeyushengfan258/Lyra-icon-theme/tree/master/src), a beautiful icon theme for Linux desktops. +Most icons were taken from [Lyra Icon Theme](https://github.com/yeyushengfan258/Lyra-icon-theme/tree/master/src), a beautiful icon theme for Linux desktops. They ship as part of some of the bundled themes, in the `assets/images/icons/` directory of the theme pack. Several icons used in this project were adapted from icons sourced from [svgrepo](https://www.svgrepo.com/). diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index eb45aaae..3712232a 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -162,6 +162,10 @@ Known page keys: | `shared/nav-menu` | The navigation menu of the theme. | | `shared/not-found` | The 404 page. | | `library/written-content-library/book-library/books/index` | The books browsing page. | +| `shared/file-system-browser` | The file system browser component shell. | +| `shared/file-system-browser/tree-node` | The tree view node of the file system browser. | +| `shared/file-system-browser/explorer-item` | The file system entry of the file system browser. | +| `shared/file-system-browser/path-segment` | The address bar path segment of the file system browser. | ### The Layout Template (shared/layout) @@ -229,6 +233,62 @@ The navigation template renders the menu of the active theme. Its model contains The navigation template is also best effort: when its template cannot be rendered, the application menu is used instead. +### The File System Browser Templates (shared/file-system-browser) + +The file system browser is a modal component hosted by the library editing page. Like the navigation menu, it is rendered from theme templates and is best effort: when its component template cannot be loaded, the application renders its own unstyled fallback. + +The component is split into a shell template and three sub templates, all provided as mirrored files under `templates/shared/file-system-browser/`. Because the sub template page keys live under the shell page key, the engine would resolve a missing sub template to the shell template by walking up the path scopes; the application detects this fallback and treats it as a missing sub template, so a theme can omit any sub template and keep the built-in rendering of that part. + +The shell template receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `appBase` | The absolute base URL of the Web application, used to reference the application scripts, for example `{{appBase}}js/file-system-browser-dialog.js`. | +| `assetBase` | The base URL of the theme assets. | +| `iconBaseUrl` | The base URL of the file type icons of the theme, derived from `assetBase`. | +| `fileIconsUrl` | The URL of the file icons mapping of the theme, derived from `assetBase`. | +| `treeNodeTemplate` | The raw source of the `shared/file-system-browser/tree-node` template, inlined by the application into a plain text script element. | +| `explorerItemTemplate` | The raw source of the `shared/file-system-browser/explorer-item` template, inlined by the application into a plain text script element. | +| `pathSegmentTemplate` | The raw source of the `shared/file-system-browser/path-segment` template, inlined by the application into a plain text script element. | +| `strings` | The localized strings of the component, keyed by their resource names. | + +The shell template owns the whole dialog markup: the header with the view mode, navigation and address bar controls, the tree view and explorer panes and the action bar. It must keep the DOM contract the application script binds to (the element ids such as `file-system-browser-dialog`, `navigator-*`, `file-system-browser-treeview`, `file-system-browser-file-system-explorer` and the two selection rectangles), and it must include the application component scripts with their `data-component-script` attributes: + +```html + + + + + +``` + +The sub template sources are inlined into plain text script elements, whose content the browser never parses into elements, so the theme markup cannot be loaded or requested before the application script renders it. The application script reads the raw source from the script element text and renders it for each dynamic entry. + +The application appends the initialization script of the component after the rendered shell, so the theme does not author it. + +The sub templates are rendered client side by the application script for each dynamic entry, using the same Mustache syntax as the server side engine. They receive the following fields: + +| Template | Fields | +| --- | --- | +| `tree-node` | `path`, `name`, `itemType` (`Root`, `Directory` or `File`), `isRoot`, `isDirectory`, `isFile`, `isExpanded` and `icon`. The node must keep the `.tree-node` root with its `data-path`, the `.node-content`, `.expand-button` (or `.spacer` for files), `.node-icon` and `.node-name` elements, and the `.child-nodes` container. | +| `explorer-item` | `path`, `name`, `itemType` (`Directory` or `File`), `isDirectory`, `isFile`, `cssClass` (the active view mode, such as `large-icons`) and `iconUrl`. The item must keep the `.e` root with its `data-path` and `data-type`, and an `` element, which the script replaces with thumbnails for image files. | +| `path-segment` | `id`, `path` (the segment name), `dataPath` (the full path up to and including the segment), `toggleId` and `dropdownId`. The segment must keep the combobox structure with its `.navigator-combobox` (`data-path`), `.navigator-toggle-checkbox`, `.navigator-selected-text`, `.navigator-arrow` and `.navigator-dropdown` elements. | + +#### The file icons mapping (assets/file-icons.json) + +The icons of the file system entries are owned by the theme. The theme ships its icon files under `assets/images/icons/`, and maps file extensions to icon paths in an optional `assets/file-icons.json`: + +```json +{ + "default": "file.svg", + "directory": "directory.svg", + "pdf": "application-pdf.svg", + "zip": "application-x-7z-ace.svg" +} +``` + +The application fetches this mapping when the component initializes and resolves icon URLs against `iconBaseUrl`. Extensions without an entry fall back to `default`, directories use `directory`. When the theme does not ship the mapping or the icons, the component renders without icons rather than failing. + ### Page Templates The remaining templates render individual pages. Each page exposes its own data, so the available fields depend on the page. In addition to page specific values, pages expose a `strings` dictionary with the localized strings of the page, keyed by their resource names, so templates can pull any label without hardcoding text. @@ -299,7 +359,7 @@ The theme engine is configured through the `ThemeEngine` section of the API conf 1. Create a directory for the theme with `theme.json`, a `templates/` directory and an `assets/` directory, following the layout of `editorial-paper`. 2. Write the manifest following the field rules in [The Manifest (theme.json)](#the-manifest-themejson). -3. Author the templates. Start with `templates/shared/layout.html` and `templates/shared/nav-menu.html`, then add page templates. +3. Author the templates. Start with `templates/shared/layout.html` and `templates/shared/nav-menu.html`, then add page templates and the optional `templates/shared/file-system-browser*.html` component templates. 4. Add the static files under `assets/`, for example a stylesheet referenced from the layout. 5. Keep the pack within the size limits: the archive at most 8 MB, the extracted pack at most 24 MB, no single file larger than 6 MB and at most 250 entries. 6. Compress the directory into a ZIP archive with `theme.json` at the root of the archive, not nested inside an extra folder. diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index a858bbdc..69c696c1 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index e9b1df3e..0fbe47c7 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip differ diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDto.cs new file mode 100644 index 00000000..46f81276 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeFileSystemBrowserConfigurationDto.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the runtime configuration of the file system browser component. +/// +/// The base URL of the Web application used for file system API calls. +/// The initial path displayed by the file system browser. +/// The initial view mode of the file system browser. +/// The initial icon size of the file system browser. +[DebuggerDisplay("Path: {Path}, ViewMode: {ViewMode}")] +public sealed record ThemeFileSystemBrowserConfigurationDto( + string ClientBasePath, + string Path, + string ViewMode, + string IconSize +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeFileSystemBrowserDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeFileSystemBrowserDto.cs new file mode 100644 index 00000000..25b1cb62 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeFileSystemBrowserDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed file system browser template. +/// +/// The absolute base URL of the Web application, used to reference the application scripts from the theme template. +/// The base URL of the theme assets, used by the theme template to reference its own assets. +/// The base URL of the file type icons of the theme. +/// The URL of the theme file icons mapping, mapping file extensions to icon paths. +/// The raw template source of the tree view node, rendered client side for each node. +/// The raw template source of the explorer item, rendered client side for each file system entry. +/// The raw template source of the address bar path segment, rendered client side for each segment. +/// The localized strings of the file system browser, keyed by resource name. +[DebuggerDisplay("AssetBase: {AssetBase}")] +public sealed record ThemeFileSystemBrowserDto( + string AppBase, + string AssetBase, + string IconBaseUrl, + string FileIconsUrl, + string TreeNodeTemplate, + string ExplorerItemTemplate, + string PathSegmentTemplate, + IReadOnlyDictionary Strings +); diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 7570bc1b..8391fee4 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -311,6 +311,8 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs new file mode 100644 index 00000000..78885a93 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails; + +/// +/// Represents a request for retrieving the thumbnail of a file system file. +/// +/// The path of the file for which the thumbnail is retrieved. +/// The quality to use for the thumbnail. +[DebuggerDisplay("Path: {Path}")] +public record GetThumbnailRequest( + string? Path, + int Quality +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Thumbnails.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Thumbnails.cs new file mode 100644 index 00000000..f0f3f206 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Thumbnails.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the thumbnail endpoints of the remote API. + /// + public static class Thumbnails + { + public const string GET_THUMBNAIL = "thumbnails/get-thumbnail"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Thumbnails.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Thumbnails.cs new file mode 100644 index 00000000..7f14febb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Thumbnails.cs @@ -0,0 +1,15 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the thumbnail endpoints. + /// + public static class Thumbnails + { + public const string GET_THUMBNAIL = "thumbnails/api-get-thumbnail"; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs new file mode 100644 index 00000000..d0230562 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; + +/// +/// API endpoint for the /thumbnails/api-get-thumbnail route. +/// +public class GetThumbnailEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetThumbnailEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Thumbnails.GET_THUMBNAIL); + DontAutoTag(); + Options(options => options.WithTags("Thumbnails")); + } + + /// + /// Retrieves the thumbnail of the file located at the path identified by the request. + /// + /// The request containing the file system path of the file for which to get the thumbnail. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken) + { + // the thumbnail is proxied through the Web application, so that the request carries the authentication of the current user + BlobDataDto blob = await _apiHttpClient.GetBlobAsync($"{ApiRoutes.Thumbnails.GET_THUMBNAIL}?path={Uri.EscapeDataString(request.Path!)}&quality={request.Quality}", cancellationToken).ConfigureAwait(false); + return Results.File(blob.Data, blob.ContentType); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeFileSystemBrowserBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeFileSystemBrowserBuilder.cs new file mode 100644 index 00000000..1160cb46 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeFileSystemBrowserBuilder.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the file system browser model for the themed component template, resolving the localized strings and theme asset URLs server side. +/// +public sealed class ThemeFileSystemBrowserBuilder +{ + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared.Components.FileSystemBrowser.Default"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory used to create the localizer of the file system browser resources. + /// Injected accessor for the current HTTP context. + public ThemeFileSystemBrowserBuilder(IStringLocalizerFactory stringLocalizerFactory, IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Builds the model of the file system browser component for the given theme. + /// + /// The base URL of the assets of the active theme. + /// The raw template source of the tree view node, or an empty string when the theme does not provide one. + /// The raw template source of the explorer item, or an empty string when the theme does not provide one. + /// The raw template source of the address bar path segment, or an empty string when the theme does not provide one. + /// The model available to the themed file system browser template. + public ThemeFileSystemBrowserDto Build( + string assetBase, + string treeNodeTemplate, + string explorerItemTemplate, + string pathSegmentTemplate) + { + Dictionary strings = new() + { + ["listView"] = Localize("ListView"), + ["detailsView"] = Localize("DetailsView"), + ["smallIconsView"] = Localize("SmallIconsView"), + ["mediumIconsView"] = Localize("MediumIconsView"), + ["largeIconsView"] = Localize("LargeIconsView"), + ["extraLargeIconsView"] = Localize("ExtraLargeIconsView"), + ["back"] = Localize("Back"), + ["forward"] = Localize("Forward"), + ["upOneLevel"] = Localize("UpOneLevel"), + ["toggleTreeView"] = Localize("ToggleTreeView"), + ["toggleThumbnails"] = Localize("ToggleThumbanils"), + ["toggleHiddenItems"] = Localize("ToggleHiddenItems"), + ["toggleSelectionMode"] = Localize("ToggleSelectionMode"), + ["editPath"] = Localize("EditPath"), + ["navigate"] = Localize("Navigate"), + ["newDirectory"] = Localize("NewDirectory"), + ["favoriteDirectory"] = Localize("FavoriteDirectory"), + ["name"] = Localize("Name"), + ["directory"] = Localize("Directory"), + ["cancel"] = Localize("Cancel"), + ["open"] = Localize("Open") + }; + + return new ThemeFileSystemBrowserDto( + AppBase: GetAppBaseUrl(), + AssetBase: assetBase, + IconBaseUrl: $"{assetBase}/images/icons", + FileIconsUrl: $"{assetBase}/file-icons.json", + TreeNodeTemplate: treeNodeTemplate, + ExplorerItemTemplate: explorerItemTemplate, + PathSegmentTemplate: pathSegmentTemplate, + Strings: strings); + } + + /// + /// Gets the absolute base URL of the current Web application request, used to reference the application scripts from a static theme template. + /// + /// The absolute base URL with a trailing slash, or an empty string when the current HTTP context is unavailable. + private string GetAppBaseUrl() + { + HttpRequest? request = _httpContextAccessor.HttpContext?.Request; + if (request is null) + return string.Empty; + + return $"{request.Scheme}://{request.Host}{request.PathBase}/"; + } + + /// + /// Resolves a localized file system browser string. + /// + /// The resource key of the string. + /// The localized string. + private string Localize(string key) + { + return _localizer[key].Value; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeFileSystemBrowserRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeFileSystemBrowserRenderer.cs new file mode 100644 index 00000000..1acedba3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeFileSystemBrowserRenderer.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders the file system browser component with the active theme, inlining the sub templates of its dynamic content so that the client script can render nodes, items and path segments from theme markup. +/// +public class ThemeFileSystemBrowserRenderer +{ + // the page keys mirror the template files of the theme packs, pinned in each theme manifest so that a missing sub template does not resolve to the component shell template + private const string SHELL_PAGE_KEY = "shared/file-system-browser"; + private const string TREE_NODE_PAGE_KEY = "shared/file-system-browser/tree-node"; + private const string EXPLORER_ITEM_PAGE_KEY = "shared/file-system-browser/explorer-item"; + private const string PATH_SEGMENT_PAGE_KEY = "shared/file-system-browser/path-segment"; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + private readonly ThemeService _themeService; + private readonly ThemeTemplateEngine _templateEngine; + private readonly ThemeFileSystemBrowserBuilder _builder; + + /// + /// Initializes a new instance of the class. + /// + /// The service that resolves the render documents. + /// The template engine used to render the component shell template. + /// The builder used to produce the component model. + public ThemeFileSystemBrowserRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, ThemeFileSystemBrowserBuilder builder) + { + _themeService = themeService; + _templateEngine = templateEngine; + _builder = builder; + } + + /// + /// Renders the themed file system browser component. + /// + /// The runtime configuration of the file system browser. + /// Cancellation token that can be used to stop the execution. + /// An containing either the component HTML, or an error. + public virtual async Task> RenderAsync(ThemeFileSystemBrowserConfigurationDto configuration, CancellationToken cancellationToken) + { + try + { + ThemeRenderDocumentDto shellDocument = await _themeService.GetRenderDocumentAsync(SHELL_PAGE_KEY, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + string themeId = shellDocument.Theme.Id; + string assetBase = $"/theme-assets/{themeId}/assets"; + + string treeNodeTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, TREE_NODE_PAGE_KEY, cancellationToken).ConfigureAwait(false); + string explorerItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, EXPLORER_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false); + string pathSegmentTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, PATH_SEGMENT_PAGE_KEY, cancellationToken).ConfigureAwait(false); + + ThemeFileSystemBrowserDto model = _builder.Build(assetBase, treeNodeTemplate, explorerItemTemplate, pathSegmentTemplate); + Result renderResult = _templateEngine.RenderPage(shellDocument.Template, model); + if (renderResult.IsFailure) + return renderResult.Errors; + + return renderResult.Value.Content + renderResult.Value.Script + BuildInitializationScript(configuration, assetBase); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // the file system browser is best effort: when the component template of the active theme cannot be loaded or rendered, the application Razor fallback is rendered instead + return Error.NotFound(code: "Theme.Template.Unavailable", description: "The file system browser theme template could not be loaded."); + } + } + + /// + /// Gets the raw template source of a file system browser sub template, degrading to an empty string when the theme does not provide one. + /// + /// The manifest id of the active theme. + /// The raw template source of the component shell, used to detect the mirrored resolution falling back to the shell when a sub template is missing. + /// The page key of the sub template. + /// Cancellation token that can be used to stop the execution. + /// The raw template source, or an empty string when the theme does not provide the template. + private async Task GetSubTemplateAsync(string themeId, string shellTemplate, string pageKey, CancellationToken cancellationToken) + { + try + { + ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(pageKey, themeId, cancellationToken).ConfigureAwait(false); + // when the theme does not ship the sub template, the mirrored template resolution walks up the path scopes + // and returns the component shell template instead, which the client script must not render as dynamic content + if (string.Equals(document.Template, shellTemplate, StringComparison.Ordinal)) + return string.Empty; + + return document.Template; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // each sub template is best effort: when the theme omits one, the client script renders that part with its built-in markup instead + return string.Empty; + } + } + + /// + /// Builds the initialization script of the file system browser, which passes the runtime configuration to the client script. + /// + /// The runtime configuration of the file system browser. + /// The base URL of the assets of the active theme. + /// The initialization script element. + private static string BuildInitializationScript(ThemeFileSystemBrowserConfigurationDto configuration, string assetBase) + { + string initConfigJson = JsonSerializer.Serialize(new + { + ClientBasePath = configuration.ClientBasePath, + Path = configuration.Path, + ViewMode = configuration.ViewMode, + IconSize = configuration.IconSize, + IconBaseUrl = $"{assetBase}/images/icons", + FileIconsUrl = $"{assetBase}/file-icons.json" + }, s_camelCaseJsonOptions); + + return $""; + } +} diff --git a/src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs b/src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs index dfc458f3..99dfd237 100644 --- a/src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs +++ b/src/Lumina.Presentation.Web/Core/ViewComponents/FileSystemBrowserViewComponent.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Enums.FileSystem; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Core.Themes; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; #endregion @@ -14,32 +17,39 @@ namespace Lumina.Presentation.Web.Core.ViewComponents; /// public class FileSystemBrowserViewComponent : ViewComponent { - private readonly ServerConfigurationDto _serverConfiguration; + private readonly ThemeFileSystemBrowserRenderer _renderer; /// /// Initializes a new instance of the class. /// - /// Injected service for retrieving . - public FileSystemBrowserViewComponent(IOptions serverConfigurationOptions) + /// Injected renderer of the themed file system browser component. + public FileSystemBrowserViewComponent(ThemeFileSystemBrowserRenderer renderer) { - _serverConfiguration = serverConfigurationOptions.Value; + _renderer = renderer; } /// - /// Invokes the view component. + /// Invokes the view component, rendering the theme template of the file system browser when available. /// - /// - /// An that renders the view with file system browsing configuration. - /// - public IViewComponentResult Invoke() + /// An that renders the themed component, or the application fallback view when the theme template is unavailable. + public async Task InvokeAsync() { + ThemeFileSystemBrowserConfigurationDto configuration = new( + ClientBasePath: "http://localhost:5012/", // TODO: take from appsettings or environment + Path: RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\", + ViewMode: FileSystemViewMode.List.ToString().ToLower(), + IconSize: FileSystemIconSize.Large.ToString().ToLower()); + + Result themedResult = await _renderer.RenderAsync(configuration, CancellationToken.None).ConfigureAwait(false); + if (themedResult.IsSuccess) + return View("Themed", themedResult.Value); + return View(new - { - Path = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\", - ServerBasePath = $"{_serverConfiguration.BaseAddress}:{_serverConfiguration.Port}/api/v{_serverConfiguration.ApiVersion}/", - ClientBasePath = "http://localhost:5012/", // TODO: take from appsettings or environment - ViewMode = FileSystemViewMode.List, - IconSize = FileSystemIconSize.Large + { + Path = configuration.Path, + ClientBasePath = configuration.ClientBasePath, + ViewMode = configuration.ViewMode, + IconSize = configuration.IconSize }); } } diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml index ac082b75..a116da6f 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/Components/FileSystemBrowser/Default.cshtml @@ -1,488 +1,51 @@ -@using Lumina.Presentation.Web.Common.DTO.Common -@using Lumina.Presentation.Web.Common.Api -@using Lumina.Presentation.Web.Common.Enums.FileSystem -@using Lumina.Presentation.Web.Common.Enums.Notifications -@using Lumina.Presentation.Web.Common.Exceptions -@using Lumina.Presentation.Web.Common.DTO.FileSystemManagement -@using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization -@using Microsoft.AspNetCore.Components -@using System.Text.Json -@using System.Text - -@{ - var componentScriptId = ScriptIdentifierHelper.GenerateScriptId(); -} @inject IViewLocalizer _localizer +@* + This view is the application fallback of the file system browser component, rendered only when the theme template of the component cannot be loaded. + It is intentionally plain and unstyled: on a healthy site the component comes from the theme's shared/file-system-browser template. + It keeps the DOM contract the client script binds to, without any images, so that the active theme cannot leak into the fallback. +*@ +
-
-
+
@@ -510,23 +73,19 @@
- - + +
- - + +
- @*
- - - @_localizer["Cancel"] - @_localizer["Confirm"] *@
+
themed
"); + RegisterThemeTemplate(theme, "shared/file-system-browser/tree-node", "
{{name}}
"); + RegisterThemeTemplate(theme, "shared/file-system-browser/explorer-item", "
{{name}}
"); + RegisterThemeTemplate(theme, "shared/file-system-browser/path-segment", "
  • {{path}}
  • "); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("id=\"fsb-template-tree-node\"", content); + Assert.Contains("initFileSystemBrowser(", content); + Assert.Contains("themed", content); + } + + [Fact] + public async Task EditLibraryView_WhenThemeDoesNotProvideFileSystemBrowserTemplate_ShouldRenderApplicationFallbackComponent() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("id=\"file-system-browser-dialog\"", content); + Assert.DoesNotContain("fsb-template-tree-node", content); + Assert.Contains("initFileSystemBrowser(", content); + } + + /// + /// Registers the theme template response returned for the specified page key of the given theme. + /// + /// The theme the template belongs to. + /// The page key of the template. + /// The template source returned for the document. + private void RegisterThemeTemplate(ThemeResponseDto theme, string pageKey, string template) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", theme.ThemeId) + .Replace("{*pageKey}", pageKey); + _apiFactory.ApiClientStub.RegisterGetResponse(endpoint, _themeTemplateResponseDtoFixture.Create(theme: theme, template: template)); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs new file mode 100644 index 00000000..d053ef48 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; + +/// +/// Contains security tests for the /thumbnails/api-get-thumbnail route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetThumbnailEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetThumbnail_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/thumbnails/api-get-thumbnail?path=%2Fmedia%2Fphoto.png&quality=70"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Thumbnails--")] // destructive SQL injection + [InlineData("..\\..\\appsettings.json")] // path traversal + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetThumbnail_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: [0x89, 0x50, 0x4E, 0x47], contentType: "image/png")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/thumbnails/api-get-thumbnail?path={Uri.EscapeDataString(maliciousPath)}&quality=70"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs new file mode 100644 index 00000000..591ac32d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnail/GetThumbnailEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Thumbnails; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Thumbnails; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetThumbnailEndpoint _sut; + private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new(); + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThumbnailEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsThumbnail_ShouldReturnFileWithThumbnailBytes() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create(path: "/media/photo.png", quality: 70); + byte[] expectedBytes = [0x89, 0x50, 0x4E, 0x47]; + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "image/png")); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Thumbnails.GET_THUMBNAIL}?path={Uri.EscapeDataString(request.Path!)}&quality={request.Quality}"; + await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); + FileContentHttpResult fileResult = Assert.IsType(result); + Assert.Equal(expectedBytes, fileResult.FileContents); + Assert.Equal("image/png", fileResult.ContentType); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestThumbnailAtTheSpecifiedQuality() + { + // Arrange + GetThumbnailRequest request = _getThumbnailRequestFixture.Create(path: "/media/photo.png", quality: 30); + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(_blobDataDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + string expectedEndpoint = $"{ApiRoutes.Thumbnails.GET_THUMBNAIL}?path={Uri.EscapeDataString(request.Path!)}&quality=30"; + await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeFileSystemBrowserBuilderTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeFileSystemBrowserBuilderTests.cs new file mode 100644 index 00000000..ffd83b2b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeFileSystemBrowserBuilderTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeFileSystemBrowserBuilderTests +{ + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly ThemeFileSystemBrowserBuilder _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeFileSystemBrowserBuilderTests() + { + _mockStringLocalizer = CreateLocalizer(); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockHttpContextAccessor = Substitute.For(); + _sut = new ThemeFileSystemBrowserBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor); + } + + [Fact] + public void Build_WhenCalled_ShouldResolveThemeAssetUrlsFromAssetBase() + { + // Arrange + // Act + ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", "
    {{name}}
    ", "
    {{name}}
    ", "
  • {{path}}
  • "); + + // Assert + Assert.Equal("/theme-assets/editorial/assets", model.AssetBase); + Assert.Equal("/theme-assets/editorial/assets/images/icons", model.IconBaseUrl); + Assert.Equal("/theme-assets/editorial/assets/file-icons.json", model.FileIconsUrl); + } + + [Fact] + public void Build_WhenCalled_ShouldKeepTheSubTemplatesOfTheDynamicContent() + { + // Arrange + // Act + ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", "
    {{name}}
    ", "
    {{name}}
    ", "
  • {{path}}
  • "); + + // Assert + Assert.Equal("
    {{name}}
    ", model.TreeNodeTemplate); + Assert.Equal("
    {{name}}
    ", model.ExplorerItemTemplate); + Assert.Equal("
  • {{path}}
  • ", model.PathSegmentTemplate); + } + + [Fact] + public void Build_WhenCalled_ShouldLocalizeAllFileSystemBrowserStrings() + { + // Arrange + // Act + ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty); + + // Assert + string[] expectedKeys = + [ + "listView", "detailsView", "smallIconsView", "mediumIconsView", "largeIconsView", "extraLargeIconsView", + "back", "forward", "upOneLevel", "toggleTreeView", "toggleThumbnails", "toggleHiddenItems", + "toggleSelectionMode", "editPath", "navigate", "newDirectory", "favoriteDirectory", + "name", "directory", "cancel", "open" + ]; + foreach (string key in expectedKeys) + { + Assert.True(model.Strings.TryGetValue(key, out object? value), $"The '{key}' string is missing."); + Assert.StartsWith("Localized-", Assert.IsType(value)); + } + } + + [Fact] + public void Build_WhenRequestIsAvailable_ShouldResolveAppBaseFromCurrentRequest() + { + // Arrange + DefaultHttpContext httpContext = TestHttpContextFactory.Create(); + httpContext.Request.Scheme = "https"; + httpContext.Request.Host = new HostString("localhost", 5001); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + // Act + ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty); + + // Assert + Assert.Equal("https://localhost:5001/", model.AppBase); + } + + [Fact] + public void Build_WhenRequestIsUnavailable_ShouldReturnEmptyAppBase() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null); + // Act + ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty); + + // Assert + Assert.Equal(string.Empty, model.AppBase); + } + + /// + /// Creates a substitute string localizer that returns a string prefixed with "Localized-". + /// + /// The created substitute string localizer. + private static IStringLocalizer CreateLocalizer() + { + IStringLocalizer localizer = Substitute.For(); + localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + return localizer; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeFileSystemBrowserRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeFileSystemBrowserRendererTests.cs new file mode 100644 index 00000000..ec9bd698 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeFileSystemBrowserRendererTests.cs @@ -0,0 +1,231 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeFileSystemBrowserRendererTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly ThemeFileSystemBrowserRenderer _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new(); + private readonly ThemeFileSystemBrowserConfigurationDtoFixture _themeFileSystemBrowserConfigurationDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeFileSystemBrowserRendererTests() + { + _mockApiHttpClient = Substitute.For(); + _mockHttpContextAccessor = Substitute.For(); + _mockStringLocalizer = CreateLocalizer(); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + ThemeService themeService = new(_mockApiHttpClient); + ThemeFileSystemBrowserBuilder builder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor); + _sut = new ThemeFileSystemBrowserRenderer(themeService, new ThemeTemplateEngine(), builder); + } + + [Fact] + public async Task RenderAsync_WhenShellTemplateRendered_ShouldReturnThemedContentWithSubTemplatesAndInitScript() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); + SetupRenderDocuments(theme, + shellTemplate: "
    {{assetBase}}|{{iconBaseUrl}}|{{fileIconsUrl}}|{{strings.cancel}}
    ", + treeNodeTemplate: "
    {{name}}
    ", + explorerItemTemplate: "
    {{name}}
    ", + pathSegmentTemplate: "
  • {{path}}
  • "); + ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large"); + + // Act + Result result = await _sut.RenderAsync(configuration, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Contains("/theme-assets/editorial/assets", result.Value); + Assert.Contains("/theme-assets/editorial/assets/images/icons", result.Value); + Assert.Contains("data-path=\"{{path}}\"", result.Value); + Assert.Contains("initFileSystemBrowser(", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenSubTemplateIsMissing_ShouldRenderEmptySubTemplate() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); + SetupRenderDocuments(theme, + shellTemplate: "", + treeNodeTemplate: "not-returned", + explorerItemTemplate: "not-returned", + pathSegmentTemplate: "not-returned"); + StubSubTemplateFailure(theme.ThemeId, "shared/file-system-browser/tree-node"); + ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(); + + // Act + Result result = await _sut.RenderAsync(configuration, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Contains("", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenShellDocumentCannotBeLoaded_ShouldReturnTemplateUnavailableError() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(Task.FromException(new HttpRequestException("The theme API is unavailable."))); + ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(); + + // Act + Result result = await _sut.RenderAsync(configuration, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code); + } + + [Fact] + public async Task RenderAsync_WhenShellTemplateIsInvalid_ShouldReturnTemplateUnavailableError() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); + SetupRenderDocuments(theme, + shellTemplate: "{{#unclosed}}", + treeNodeTemplate: string.Empty, + explorerItemTemplate: string.Empty, + pathSegmentTemplate: string.Empty); + ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(); + + // Act + Result result = await _sut.RenderAsync(configuration, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task RenderAsync_WhenCalled_ShouldFetchShellAndAllSubTemplatesFromActiveTheme() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); + SetupRenderDocuments(theme, "shell", "tree", "item", "segment"); + ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(); + + // Act + await _sut.RenderAsync(configuration, CancellationToken.None); + + // Assert + string[] pageKeys = + [ + "shared/file-system-browser", + "shared/file-system-browser/tree-node", + "shared/file-system-browser/explorer-item", + "shared/file-system-browser/path-segment" + ]; + foreach (string pageKey in pageKeys) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "editorial") + .Replace("{*pageKey}", pageKey); + await _mockApiHttpClient.Received(1).GetAsync(endpoint, Arg.Any()); + } + } + + [Fact] + public async Task RenderAsync_WhenCalled_ShouldEscapeInitialPathInInitializationScript() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); + SetupRenderDocuments(theme, "shell", "tree", "item", "segment"); + ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large"); + + // Act + Result result = await _sut.RenderAsync(configuration, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Contains(@"C:\\Users\\", result.Value); + } + + /// + /// Creates a substitute string localizer that returns a string prefixed with "Localized-". + /// + /// The created substitute string localizer. + private static IStringLocalizer CreateLocalizer() + { + IStringLocalizer localizer = Substitute.For(); + localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + return localizer; + } + + /// + /// Stubs the API responses that return the component shell and sub templates of the given theme, together with the current theme. + /// + /// The theme whose templates are stubbed. + /// The template returned for the component shell document. + /// The template returned for the tree node document. + /// The template returned for the explorer item document. + /// The template returned for the path segment document. + private void SetupRenderDocuments(ThemeResponseDto theme, string shellTemplate, string treeNodeTemplate, string explorerItemTemplate, string pathSegmentTemplate) + { + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(theme); + StubTemplateResponse(theme.ThemeId, "shared/file-system-browser", shellTemplate); + StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/tree-node", treeNodeTemplate); + StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/explorer-item", explorerItemTemplate); + StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/path-segment", pathSegmentTemplate); + } + + /// + /// Stubs the API response that returns a single theme template document. + /// + /// The manifest id of the theme. + /// The page key of the template. + /// The template returned for the document. + private void StubTemplateResponse(string themeId, string pageKey, string template) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", themeId) + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(endpoint, Arg.Any()) + .Returns(_themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: template)); + } + + /// + /// Stubs the API response of a theme template document to fail, as when the theme does not provide the template. + /// + /// The manifest id of the theme. + /// The page key of the template. + private void StubSubTemplateFailure(string themeId, string pageKey) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", themeId) + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(endpoint, Arg.Any()) + .Returns(Task.FromException(new HttpRequestException("The sub template is unavailable."))); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs index f802258d..d824e70f 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs @@ -23,6 +23,7 @@ public class ThemeTemplateEngineTests private readonly ThemeNavMenuDtoFixture _themeNavMenuDtoFixture = new(); private readonly ThemeNavSectionDtoFixture _themeNavSectionDtoFixture = new(); private readonly ThemeNavEntryDtoFixture _themeNavEntryDtoFixture = new(); + private readonly ThemeFileSystemBrowserDtoFixture _themeFileSystemBrowserDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -158,6 +159,24 @@ public class ThemeTemplateEngineTests Assert.Equal("Tools:[Language]English,Francais,Settings", result.Value.Content); } + [Fact] + public void RenderPage_WhenFileSystemBrowserModelUsed_ShouldResolveStringsAndInlineRawSubTemplates() + { + // Arrange + ThemeFileSystemBrowserDto model = _themeFileSystemBrowserDtoFixture.Create( + assetBase: "/theme-assets/editorial/assets", + treeNodeTemplate: "
    {{name}}
    ", + strings: new Dictionary { ["cancel"] = "Annuler" }); + string template = "{{assetBase}}|{{strings.cancel}}|"; + + // Act + Result result = _sut.RenderPage(template, model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("/theme-assets/editorial/assets|Annuler|", result.Value.Content); + } + [Fact] public void RenderPage_WhenSectionIsTruthy_ShouldRenderChildren() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/ViewComponents/FileSystemBrowserViewComponentTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/ViewComponents/FileSystemBrowserViewComponentTests.cs new file mode 100644 index 00000000..b893a721 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/ViewComponents/FileSystemBrowserViewComponentTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Core.ViewComponents; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ViewComponents; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.ViewComponents; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemBrowserViewComponentTests +{ + private readonly ThemeFileSystemBrowserRenderer _mockRenderer; + private readonly FileSystemBrowserViewComponent _sut; + + /// + /// Initializes a new instance of the class. + /// + public FileSystemBrowserViewComponentTests() + { + ThemeService themeService = new(Substitute.For()); + ThemeFileSystemBrowserBuilder builder = new(Substitute.For(), Substitute.For()); + _mockRenderer = Substitute.For(themeService, new ThemeTemplateEngine(), builder); + _sut = new FileSystemBrowserViewComponent(_mockRenderer); + } + + [Fact] + public async Task InvokeAsync_WhenThemedRenderSucceeds_ShouldReturnContentWithRenderedHtml() + { + // Arrange + _mockRenderer.RenderAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From("themed-html")); + + // Act + IViewComponentResult result = await _sut.InvokeAsync(); + + // Assert + ViewViewComponentResult viewResult = Assert.IsType(result); + Assert.Equal("Themed", viewResult.ViewName); + Assert.Equal("themed-html", viewResult.ViewData.Model); + } + + [Fact] + public async Task InvokeAsync_WhenThemedRenderFails_ShouldReturnFallbackView() + { + // Arrange + _mockRenderer.RenderAsync(Arg.Any(), Arg.Any()) + .Returns(Error.NotFound("Theme.Template.Unavailable", "The file system browser theme template could not be loaded.")); + + // Act + IViewComponentResult result = await _sut.InvokeAsync(); + + // Assert + ViewViewComponentResult viewResult = Assert.IsType(result); + Assert.NotNull(viewResult.ViewData); + Assert.NotNull(viewResult.ViewData!.Model); + dynamic model = viewResult.ViewData!.Model!; + string expectedPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? @"/" : @"C:\Users\"; + Assert.Equal(expectedPath, (string)model.Path); + Assert.Equal("list", (string)model.ViewMode); + Assert.Equal("large", (string)model.IconSize); + } + + [Fact] + public async Task InvokeAsync_WhenCalled_ShouldPassConfigurationToRenderer() + { + // Arrange + _mockRenderer.RenderAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From("themed-html")); + + // Act + await _sut.InvokeAsync(); + + // Assert + await _mockRenderer.Received(1).RenderAsync( + Arg.Is(configuration => + configuration.ClientBasePath == "http://localhost:5012/" && + configuration.ViewMode == "list" && + configuration.IconSize == "large"), + Arg.Any()); + } +}