Merge pull request #158 from BinaryAlley/feature/theme-management

Feature/theme management
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-21 12:13:11 -07:00
commit 743d3f4599
386 files changed
+27262 -1842

No files matched your search

+2
View File
@@ -57,6 +57,8 @@ $RECYCLE.BIN/
# Archives
*.zip
# bundled themes should be tracked
!src/Lumina.Presentation.Api/Core/Themes/Bundled/*.zip
*.tar.gz
*.rar
+334
View File
@@ -0,0 +1,334 @@
# Lumina Theming
The web client of Lumina is a themed shell: every page is rendered inside the templates of an active theme. A theme is a self contained ZIP archive with a manifest, HTML templates and static assets. This document explains how themes are structured, how the template engine works, and how to create, install and manage a theme.
- [Lumina Theming](#lumina-theming)
- [Overview](#overview)
- [Theme Pack Structure](#theme-pack-structure)
- [The Manifest (theme.json)](#the-manifest-themejson)
- [Pack Validation Rules](#pack-validation-rules)
- [Templates](#templates)
- [Template Syntax](#template-syntax)
- [Expressions](#expressions)
- [Safety Limits](#safety-limits)
- [Template Resolution](#template-resolution)
- [The Layout Template (shared/layout)](#the-layout-template-sharedlayout)
- [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu)
- [Page Templates](#page-templates)
- [The Scripts Section](#the-scripts-section)
- [Assets](#assets)
- [Configuration Options](#configuration-options)
- [Creating a Theme](#creating-a-theme)
- [Installing a Theme](#installing-a-theme)
- [Bundled Themes](#bundled-themes)
- [Selecting the Current Theme](#selecting-the-current-theme)
- [Managing Themes from the Administration Page](#managing-themes-from-the-administration-page)
- [Security Notes](#security-notes)
## Overview
The application stores installed themes on the API server and serves their templates and assets. The web client fetches the templates of the active theme and renders them locally with a small, non-executable Mustache-style template engine. Theme templates can interpolate values, iterate collections and test truthiness, but they cannot run code.
Because the templates are HTML, a theme can restyle the whole application, rearrange the layout and navigation, and provide custom pages for the built-in routes. A theme cannot extend the functionality of the application: it only shapes how the existing pages look and are structured.
## Theme Pack Structure
A theme pack is a directory that is shipped as a ZIP archive with `theme.json` at its root:
```
my-theme/
theme.json
assets/
preview.svg
theme.css
templates/
index.html
shared/
layout.html
nav-menu.html
not-found.html
library/
written-content-library/
book-library/
books/
index.html
```
Only three locations may exist inside a pack:
- `theme.json`, the manifest, at the root of the archive.
- `templates/`, holding the HTML templates.
- `assets/`, holding any static file served to the browser (stylesheets, images, fonts, scripts).
The bundled reference theme `editorial-paper` follows exactly this layout and is the best starting point when authoring a new theme.
## The Manifest (theme.json)
The manifest is a JSON object describing the theme. The example below is the manifest of the bundled `editorial-paper` theme:
```json
{
"schemaVersion": 1,
"id": "editorial-paper",
"name": "Editorial Paper",
"description": "A clean, readable proof of concept theme.",
"author": "Lumina",
"version": "1.4.0",
"preview": "assets/preview.svg",
"templates": {
"default": "templates/index.html"
}
}
```
| Field | Required | Rule |
| --- | --- | --- |
| `schemaVersion` | yes | Must be `1`. |
| `id` | yes | A lowercase kebab-case value, up to 64 characters, used to reference the theme. For example `editorial-paper` or `my-dark-theme`. |
| `name` | yes | Display name, up to 80 characters. |
| `description` | yes | Description of the theme, up to 300 characters. |
| `author` | yes | Author of the theme, up to 80 characters. |
| `version` | yes | Semantic version form, for example `1.0.0`. Up to 40 characters. |
| `preview` | no | Path to a preview image, relative to the pack root and under `assets/`. Shown on the administration page. |
| `templates` | yes | A mapping from template key to a file under `templates/`, with 1 to 32 entries. Must include the `default` key. |
All text fields must be non-empty and must not contain control characters. Template keys follow the same lowercase kebab-case rule as the theme id and are at most 40 characters. Template paths are normalized and must point to an existing file under `templates/`.
## Pack Validation Rules
A theme archive is validated on install:
- `theme.json` must exist at the root of the archive and be at most 64 KB.
- Only `theme.json`, files under `templates/` and files under `assets/` are allowed. Anything else makes the archive invalid.
- Paths are normalized and any path that would escape the pack is rejected.
- `theme.json` must contain a valid manifest object that satisfies the rules in the previous section.
Installing a theme is an atomic operation: an invalid pack is rejected entirely and nothing is left behind.
## Templates
Templates are rendered with the built-in template engine. The engine is intentionally small and safe: it parses Mustache-style tags and renders them against a model. It never executes arbitrary code.
### Template Syntax
| Syntax | Meaning |
| --- | --- |
| `{{name}}` | Outputs the value of `name`, HTML-escaped. |
| `{{{name}}}` | Outputs the value of `name` without escaping. |
| `{{&name}}` | Outputs the value of `name` without escaping. |
| `{{!comment}}` | A comment, produces no output. |
| `{{#name}}...{{/name}}` | A section. Renders its children when the value is truthy. When the value is a collection, the children are rendered once per item. |
| `{{^name}}...{{/name}}` | An inverted section. Renders its children when the value is falsy. |
### Expressions
Expressions resolve against the model and support:
- Dotted property paths, for example `{{user.name}}`. Dictionary keys and public properties are matched case-insensitively.
- Parent traversal, for example `{{../title}}`, to reach values outside the current section scope.
- The current value, for example `{{.}}`.
- `{{#count}}` on a collection, where `Count` is exposed for collections.
Values that do not exist resolve to an empty string for variables, or to falsy for sections. Truthiness follows these rules: `null`, `false`, empty strings and empty collections are falsy; everything else is truthy.
### Safety Limits
The template engine enforces hard limits so a single theme cannot exhaust the server:
| Limit | Value |
| --- | --- |
| Maximum section nesting depth | 32 levels |
| Maximum expression length | 120 characters |
| Maximum rendered output | 4 MB per page |
A template that exceeds any of these limits is rejected with a template error and the page falls back to the application layout.
### Template Resolution
Every themed page is identified by a page key that mirrors the path of the corresponding Razor view. When a page is rendered, its template is selected in this order:
1. An explicit mapping in `templates` when the manifest declares the page key.
2. A mirrored template file at `templates/{pageKey}.html`, walking up the scope of the path when the exact mirror does not exist.
3. The `default` template from the manifest.
For example, the books index page has the page key `library/written-content-library/book-library/books/index`. The engine tries, in order: the explicit `templates` entry for that key, `templates/library/written-content-library/book-library/books/index.html`, then the parent scopes such as `templates/library/written-content-library/book-library/books.html`, and finally the `default` template.
Known page keys:
| Page key | Purpose |
| --- | --- |
| `shared/layout` | The layout that wraps the shell of every page. |
| `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. |
### The Layout Template (shared/layout)
Every page is rendered inside the layout template. The layout receives a model with the following fields:
| Field | Content |
| --- | --- |
| `title` | The title of the page. |
| `assetBase` | The base URL of the theme assets, for example `/theme-assets/editorial-paper/assets`. |
| `appHead` | The head links of the application, such as its global stylesheets. |
| `nav` | The fully rendered navigation menu HTML. |
| `content` | The fully rendered content section of the page. |
| `audioPlayer` | The rendered audio player when the user is authenticated, empty otherwise. |
| `appScripts` | The global scripts of the application. |
| `scripts` | The rendered script section of the page. |
| `mainStyle` | An inline style for the main content area, `bottom: 0px;` when the user is not authenticated and empty otherwise. |
The layout template of the bundled theme shows the intended shape:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}} - Lumina</title>
{{&appHead}}
<link rel="stylesheet" href="{{assetBase}}/theme.css">
</head>
<body>
<div id="page">
<header>
{{&nav}}
</header>
<main role="main" style="{{mainStyle}}">
<article class="h-100">
{{&content}}
<div id="modal-background-article"></div>
<div class="dialog-container"></div>
</article>
</main>
{{#audioPlayer}}
{{&audioPlayer}}
{{/audioPlayer}}
</div>
<div id="modal-background-menu"></div>
{{&appScripts}}
<div data-section="scripts">
{{&scripts}}
</div>
</body>
</html>
```
The rendered page content, navigation and scripts are inserted unescaped with `{{&...}}`, because they are trusted application HTML. The layout is best effort: when the theme cannot be loaded or rendered, the application falls back to its built-in layout, so a broken theme never takes the whole site down.
### The Navigation Template (shared/nav-menu)
The navigation template renders the menu of the active theme. Its model contains the site name and two menu structures, one for the mobile menu and one for the desktop menu bar:
- `siteName` is the site name.
- `mobileSections` and `menubarSections` are lists of sections.
- A section has a `label` and a list of `items`.
- An item has a `label`, an optional `url`, an optional `cssClass` and a list of `children`. Items with children are submenus, items without children are plain links.
The navigation template is also best effort: when its template cannot be rendered, the application menu is used instead.
### 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.
Page templates are rendered into a content section that the layout wraps. A page template can also declare a reserved top-level `scripts` section, whose content is rendered separately and passed to the layout, mirroring the `Scripts` section of a Razor view:
```html
{{#title}}
<h1 class="page-title">{{title}}</h1>
{{/title}}
{{^title}}
<p>No title available.</p>
{{/title}}
{{#sections}}
<div class="section">
<h2>{{label}}</h2>
</div>
{{/sections}}
{{#scripts}}
<script>
window.pageConfiguration = {{&configurationJson}};
</script>
{{/scripts}}
```
### The Scripts Section
JavaScript is always allowed in themes: script elements in templates are served and rendered as-is, and script files under `assets/` are served normally. A theme relies on scripts for the client side navigation of the application, because pages are swapped in place by the global AJAX navigator, so themes are expected to ship their own JavaScript. Because JavaScript is enabled, *themes can execute malicious code*, so, be aware about the source of your installed themes! Themes bundled with the application are reviewed and safe.
## Assets
Static files under `assets/` are served to the browser. The asset base URL is available to the layout and page templates as `assetBase`, so a stylesheet is referenced as `{{assetBase}}/theme.css`. Assets are served only from within the pack, and paths that would escape the pack are rejected.
The `preview` field of the manifest points at an asset that is shown as the theme thumbnail on the administration page.
## Configuration Options
The theme engine is configured through the `ThemeEngine` section of the API configuration (`appsettings.shared.json`):
| Option | Default | Meaning |
| --- | --- | --- |
| `StoragePath` | `themes` | Directory where installed theme packs are stored, relative to the API base directory when not rooted. |
| `BundledThemesPath` | `themes/bundled` | Directory where the theme archives shipped with the application are located. |
| `DefaultThemeId` | `lumina-default` | Identifier of the theme selected when no valid current theme is persisted. |
| `MaxArchiveBytes` | `8388608` | Maximum size of an uploaded theme archive, in bytes (8 MB). |
| `MaxExpandedBytes` | `25165824` | Maximum total size of an extracted theme pack, in bytes (24 MB). |
| `MaxSingleFileBytes` | `6291456` | Maximum size of a single file within a theme pack, in bytes (6 MB). |
| `MaxEntries` | `250` | Maximum number of entries in a theme pack archive. |
## Creating a Theme
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 and the `default` template.
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.
## Installing a Theme
A theme is installed by uploading its ZIP archive:
- From the administration themes page, using the upload control.
- Directly against the API with a `multipart/form-data` POST to `POST /api/v1/themes`, sending the archive in a form field named `archive`.
The archive is validated against the pack rules and stored on the server under `themes/{id}`. Installing a theme with an id that already exists replaces the files of the existing theme. A newly installed theme is not active until it is selected as the current theme.
Validation failures are returned as problem details, for example when the archive is unreadable, the manifest is invalid, or a template references a missing file.
## Bundled Themes
The archives shipped with the application live in the API under `Core/Themes/Bundled` and are installed automatically at startup by the theme detection job. `editorial-paper` is the bundled reference theme.
A bundled theme whose files go missing or are corrupted is restored automatically from its shipped archive on the next startup, unless the user explicitly deleted the theme from the Administrator - Themes page. This means bundled themes always come back unless the user removes them. The last available theme cannot be deleted.
## Selecting the Current Theme
The current theme is the one whose templates are used for page rendering. At startup, when no theme is current, the application activates one automatically, preferring the configured default theme id. The active theme is exposed at `GET /api/v1/themes/current` and can be changed from the administration page, which calls `PUT /api/v1/themes/current`.
## Managing Themes from the Administration Page
The administration themes page lists every installed theme and provides:
- A preview thumbnail for each theme, taken from the `preview` field of the manifest.
- The source of the theme, either bundled with the application or provided by a user.
- The ability to set the current theme, download a theme as a ZIP archive and install a new theme.
- The ability to delete a theme, subject to these rules:
- Only administrators can delete themes.
- The last remaining bundled theme cannot be deleted, so the application never ends up without a theme.
- When the active theme is deleted, another available theme is activated automatically, preferring the configured default.
- Bundled themes are soft deleted (the theme files are deleted, but the theme zip archive is kept), so they can be restored; user themes are removed entirely, because their files are not shipped with the application.
## Security Notes
Theme packs are treated as untrusted input:
- Values rendered with `{{name}}` are HTML-encoded, so a theme cannot inject markup through a model value.
- Themes can contain javascript, which means, they can run malicious code. Only install themes from sources you trust, or review the code of the theme files.
- Paths are normalized and validated so that templates and assets cannot escape the theme pack or the storage directory.
- The template engine has no access to the application and cannot execute code, only render values against the model.
- Size and count limits prevent an archive from exhausting server memory or disk.
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Themes;
/// <summary>
/// Repository entity for a theme.
/// </summary>
[DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")]
public class ThemeEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the theme.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the unique identifier of the theme, taken from its manifest and used by clients to reference it.
/// </summary>
public required string ThemeId { get; set; }
/// <summary>
/// Gets or sets the display name of the theme.
/// </summary>
public required string Name { get; set; }
/// <summary>
/// Gets or sets the description of the theme.
/// </summary>
public required string Description { get; set; }
/// <summary>
/// Gets or sets the author of the theme.
/// </summary>
public required string Author { get; set; }
/// <summary>
/// Gets or sets the version of the theme, using semantic version form.
/// </summary>
public required string Version { get; set; }
/// <summary>
/// Gets or sets the path of the theme preview image, relative to the theme pack root, or <see langword="null"/> when the theme has no preview.
/// </summary>
public string? PreviewPath { get; set; }
/// <summary>
/// Gets or sets the source the theme was installed from.
/// </summary>
public required ThemeInstallSource InstallSource { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this is the currently active theme. At most one theme can be current.
/// </summary>
public bool? IsCurrent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the theme was soft deleted, so it is not shown and not reinstalled automatically.
/// </summary>
public bool IsDeleted { get; set; }
/// <summary>
/// Gets or sets the UTC timestamp at which the theme was installed.
/// </summary>
public required DateTime InstalledAtUtc { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -37,6 +37,11 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity
/// </summary>
public bool IgnoreThePrefixForAlphaPicker { get; set; }
/// <summary>
/// Gets or sets whether the theme data served to this user is cached, or not.
/// </summary>
public bool IsThemeCachingEnabled { get; set; } = true;
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Domain.Common.Primitives;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Themes;
/// <summary>
/// Interface for the repository for themes.
/// </summary>
public interface IThemeRepository : IRepository<ThemeEntity>,
IGetAllRepositoryAction<ThemeEntity>,
IInsertRepositoryAction<ThemeEntity>,
IUpdateRepositoryAction<ThemeEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets a theme identified by its manifest <paramref name="themeId"/> from the storage medium.
/// </summary>
/// <param name="themeId">The manifest id of the theme to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ThemeEntity"/> identified by <paramref name="themeId"/>, or an error.</returns>
Task<Result<ThemeEntity?>> GetByThemeIdAsync(string themeId, CancellationToken cancellationToken);
/// <summary>
/// Gets the currently active theme from the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the active <see cref="ThemeEntity"/>, or an error.</returns>
Task<Result<ThemeEntity?>> GetCurrentAsync(CancellationToken cancellationToken);
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using System.Threading;
using System.Threading.Tasks;
@@ -75,6 +76,11 @@ public interface IUnitOfWork
/// </summary>
IPluginRepository PluginRepository { get; }
/// <summary>
/// Gets the theme repository.
/// </summary>
IThemeRepository ThemeRepository { get; }
/// <summary>
/// Gets the user repository.
/// </summary>
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
/// <summary>
/// Data transfer object for a downloadable archive of a theme pack.
/// </summary>
/// <param name="Bytes">The bytes of the ZIP archive.</param>
/// <param name="FileName">The file name to expose when downloading the archive.</param>
/// <param name="ContentType">The MIME content type of the archive.</param>
[DebuggerDisplay("FileName: {FileName}")]
public sealed record ThemeArchiveDto(
byte[] Bytes,
string FileName,
string ContentType
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
/// <summary>
/// Data transfer object for a theme asset file served by the theme service.
/// </summary>
/// <param name="Bytes">The bytes of the asset file.</param>
/// <param name="ContentType">The MIME content type of the asset file.</param>
[DebuggerDisplay("ContentType: {ContentType}")]
public sealed record ThemeAssetDto(
byte[] Bytes,
string ContentType
);
@@ -4,10 +4,10 @@ using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
namespace Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
/// <summary>
/// Data transfer object for the theme.json manifest of a theme package.
/// Data transfer object for the theme.json manifest of a theme pack.
/// </summary>
[DebuggerDisplay("Id: {Id}, Name: {Name}")]
public sealed class ThemeManifestDto
@@ -18,7 +18,7 @@ public sealed class ThemeManifestDto
public int SchemaVersion { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the theme, a lowercase kebab-case value.
/// Gets or sets the unique identifier of the theme, a lowercase kebab-case value used by clients to reference it.
/// </summary>
public string Id { get; set; } = string.Empty;
@@ -43,12 +43,12 @@ public sealed class ThemeManifestDto
public string Version { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the preview image path relative to the theme package root, or <see langword="null"/> when the theme has no preview.
/// Gets or sets the preview image path relative to the theme pack root, or <see langword="null"/> when the theme has no preview.
/// </summary>
public string? Preview { get; set; }
/// <summary>
/// Gets or sets the template mappings from template key to an HTML file path under templates/.
/// Gets or sets the template mappings from template key to a file path under templates/.
/// </summary>
public Dictionary<string, string> Templates { get; set; } = new(StringComparer.OrdinalIgnoreCase);
}
@@ -0,0 +1,105 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Infrastructure.Themes;
/// <summary>
/// Service for the storage and serving of theme packs.
/// </summary>
public interface IThemeService
{
/// <summary>
/// Gets the maximum allowed size of a theme archive, in bytes.
/// </summary>
long MaxArchiveBytes { get; }
/// <summary>
/// Gets the identifier of the theme selected when no valid current theme is available.
/// </summary>
string DefaultThemeId { get; }
/// <summary>
/// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id.
/// </summary>
/// <param name="archive">The ZIP archive stream of the theme pack.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest of the installed theme, or an error.</returns>
Task<Result<ThemeManifestDto>> InstallAsync(Stream archive, CancellationToken cancellationToken);
/// <summary>
/// Reads the manifest of a theme pack archive without installing it.
/// </summary>
/// <param name="archivePath">The path of the theme pack ZIP archive.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
Task<Result<ThemeManifestDto>> ReadManifestFromArchiveAsync(string archivePath, CancellationToken cancellationToken);
/// <summary>
/// Deletes the stored files of a theme pack.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> DeleteAsync(string themeId, CancellationToken cancellationToken);
/// <summary>
/// Loads the manifest of an installed theme pack from its storage location.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
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.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key that selects the template.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the template content, or an error.</returns>
Task<Result<string>> GetTemplateAsync(string themeId, string pageKey, CancellationToken cancellationToken);
/// <summary>
/// Gets a theme asset file.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="assetPath">The asset path relative to the theme pack root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the asset, or an error.</returns>
Task<Result<ThemeAssetDto>> GetAssetAsync(string themeId, string assetPath, CancellationToken cancellationToken);
/// <summary>
/// Builds a downloadable ZIP archive of an installed theme pack.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the archive, or an error.</returns>
Task<Result<ThemeArchiveDto>> BuildArchiveAsync(string themeId, CancellationToken cancellationToken);
/// <summary>
/// Restores the files of a bundled theme from its shipped archive, used when the stored files were removed externally.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken);
/// <summary>
/// Checks whether the stored pack files of a theme still exist.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <returns><see langword="true"/> when the theme pack files exist, <see langword="false"/> otherwise.</returns>
bool HasThemePack(string themeId);
/// <summary>
/// Gets the paths of the theme pack archives shipped with the application.
/// </summary>
/// <returns>The list of bundled theme archive paths.</returns>
IReadOnlyList<string> GetBundledThemeArchivePaths();
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Contracts.Requests.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="DeleteThemeRequest"/>.
/// </summary>
public static class DeleteThemeRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="DeleteThemeCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static DeleteThemeCommand ToCommand(this DeleteThemeRequest request)
{
return new DeleteThemeCommand(request.ThemeId);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Contracts.Requests.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="GetThemeArchiveRequest"/>.
/// </summary>
public static class GetThemeArchiveRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetThemeArchiveQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetThemeArchiveQuery ToQuery(this GetThemeArchiveRequest request)
{
return new GetThemeArchiveQuery(request.ThemeId);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Contracts.Requests.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="GetThemeAssetRequest"/>.
/// </summary>
public static class GetThemeAssetRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetThemeAssetQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetThemeAssetQuery ToQuery(this GetThemeAssetRequest request)
{
return new GetThemeAssetQuery(request.ThemeId, request.AssetPath);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Contracts.Requests.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="GetThemeTemplateRequest"/>.
/// </summary>
public static class GetThemeTemplateRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetThemeTemplateQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetThemeTemplateQuery ToQuery(this GetThemeTemplateRequest request)
{
return new GetThemeTemplateQuery(request.ThemeId, request.PageKey);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Contracts.Requests.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="RestoreThemeRequest"/>.
/// </summary>
public static class RestoreThemeRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="RestoreThemeCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static RestoreThemeCommand ToCommand(this RestoreThemeRequest request)
{
return new RestoreThemeCommand(request.ThemeId);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Contracts.Requests.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="SetCurrentThemeRequest"/>.
/// </summary>
public static class SetCurrentThemeRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="SetCurrentThemeCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static SetCurrentThemeCommand ToCommand(this SetCurrentThemeRequest request)
{
return new SetCurrentThemeCommand(request.ThemeId);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Contracts.Responses.Themes;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="ThemeEntity"/>.
/// </summary>
public static class ThemeEntityMapping
{
/// <summary>
/// Converts <paramref name="theme"/> to <see cref="ThemeResponse"/>.
/// </summary>
/// <param name="theme">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static ThemeResponse ToResponse(this ThemeEntity theme)
{
return new ThemeResponse(
theme.Id,
theme.ThemeId,
theme.Name,
theme.Description,
theme.Author,
theme.Version,
theme.PreviewPath,
theme.InstallSource,
theme.IsCurrent,
theme.InstalledAtUtc,
theme.IsDeleted);
}
}
@@ -20,6 +20,7 @@ public static class UpdateUserSettingsRequestMapping
return new UpdateUserSettingsCommand(
request.IsPaginationEnabled,
request.ItemsPerPage,
request.IgnoreThePrefixForAlphaPicker);
request.IgnoreThePrefixForAlphaPicker,
request.IsThemeCachingEnabled);
}
}
@@ -28,7 +28,8 @@ public static class UserSettingsEntityMapping
UserId.Create(repositoryEntity.UserId),
repositoryEntity.IsPaginationEnabled,
repositoryEntity.ItemsPerPage,
repositoryEntity.IgnoreThePrefixForAlphaPicker);
repositoryEntity.IgnoreThePrefixForAlphaPicker,
repositoryEntity.IsThemeCachingEnabled);
}
/// <summary>
@@ -42,6 +43,7 @@ public static class UserSettingsEntityMapping
repositoryEntity.UserId,
repositoryEntity.IsPaginationEnabled,
repositoryEntity.ItemsPerPage,
repositoryEntity.IgnoreThePrefixForAlphaPicker);
repositoryEntity.IgnoreThePrefixForAlphaPicker,
repositoryEntity.IsThemeCachingEnabled);
}
}
@@ -24,7 +24,8 @@ public static class UserSettingsMapping
UserId = domainEntity.UserId.Value,
IsPaginationEnabled = domainEntity.IsPaginationEnabled,
ItemsPerPage = domainEntity.ItemsPerPage,
IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker
IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker,
IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled
};
}
@@ -39,6 +40,7 @@ public static class UserSettingsMapping
domainEntity.UserId.Value,
domainEntity.IsPaginationEnabled,
domainEntity.ItemsPerPage,
domainEntity.IgnoreThePrefixForAlphaPicker);
domainEntity.IgnoreThePrefixForAlphaPicker,
domainEntity.IsThemeCachingEnabled);
}
}
@@ -39,6 +39,33 @@ public static class ValidatorUtilities
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the long property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, long> GreaterThan<TRequest>(this IRuleBuilder<TRequest, long> ruleBuilder, long valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable long property is greater than the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, long?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, long?> ruleBuilder, long valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the decimal property is greater than the specified value.
/// </summary>
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Command for deleting a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to delete.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record DeleteThemeCommand(
string? ThemeId
) : ICommand;
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Handler for the command to delete a theme.
/// </summary>
public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<DeleteThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeCommandHandler"/> class.
/// </summary>
/// <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="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteThemeCommandHandler(
IUnitOfWork unitOfWork,
IThemeService themeService,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<DeleteThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a theme.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async Task<Result<Success>> HandleAsync(DeleteThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can delete themes
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<IEnumerable<ThemeEntity>> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getAllResult.IsFailure)
return getAllResult.Errors;
List<ThemeEntity> availableThemes = getAllResult.Value.Where(availableTheme => !availableTheme.IsDeleted).ToList();
// at least one bundled theme must always remain available, so the application never ends up without any theme
if (theme.InstallSource == ThemeInstallSource.Bundled)
{
int availableBundledThemes = availableThemes.Count(availableTheme => availableTheme.InstallSource == ThemeInstallSource.Bundled);
if (availableBundledThemes <= 1)
return DomainErrors.Themes.LastBundledThemeCannotBeDeleted;
}
// if the deleted theme was the active one, switch to another available theme, preferring the configured default
if (theme.IsCurrent == true)
{
ThemeEntity? replacementTheme = availableThemes
.Where(availableTheme => availableTheme.Id != theme.Id)
.OrderBy(availableTheme => string.Equals(availableTheme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(availableTheme => availableTheme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (replacementTheme is null)
return DomainErrors.Themes.ThemeCannotBeDeleted;
replacementTheme.IsCurrent = true;
await _unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken).ConfigureAwait(false);
}
if (theme.InstallSource == ThemeInstallSource.Bundled)
{
// bundled themes are soft deleted, so they can be restored automatically later, as long as the user did not delete them
theme.IsDeleted = true;
theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
}
else
{
// user themes are removed entirely, because their files are not shipped with the application and could never be restored
Result<Deleted> deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> deleteFilesResult = await _themeService.DeleteAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (deleteFilesResult.IsFailure)
return deleteFilesResult.Errors;
return Result.Success;
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteThemeCommand"/>.
/// </summary>
public class DeleteThemeCommandValidator : AbstractValidator<DeleteThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeCommandValidator"/> class.
/// </summary>
public DeleteThemeCommandValidator()
{
RuleFor(command => command.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Command for installing a theme pack, replacing the files of an existing theme with the same manifest id.
/// </summary>
/// <param name="Archive">The ZIP archive stream of the theme pack.</param>
/// <param name="FileName">The file name of the uploaded archive.</param>
[DebuggerDisplay("FileName: {FileName}")]
public record InstallThemeCommand(
Stream? Archive,
string? FileName
) : ICommand;
@@ -0,0 +1,149 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Handler for the command to install a theme pack.
/// </summary>
public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, Result<ThemeResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<InstallThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeCommandHandler"/> class.
/// </summary>
/// <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="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public InstallThemeCommandHandler(
IUnitOfWork unitOfWork,
IThemeService themeService,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<InstallThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to install a theme pack.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully installed <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<ThemeResponse>> HandleAsync(InstallThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can install themes
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// store the theme pack files on the server, replacing the files of an existing theme with the same manifest id
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false);
if (installResult.IsFailure)
return installResult.Errors;
ThemeManifestDto manifest = installResult.Value;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity themeEntity;
if (getThemeResult.Value is not null)
{
ThemeEntity existingTheme = getThemeResult.Value;
themeEntity = new ThemeEntity
{
Id = existingTheme.Id,
ThemeId = manifest.Id,
Name = manifest.Name,
Description = manifest.Description,
Author = manifest.Author,
Version = manifest.Version,
PreviewPath = manifest.Preview,
InstallSource = existingTheme.InstallSource,
IsCurrent = existingTheme.IsCurrent,
// reinstalling a theme must bring it back even if it was soft deleted before, so the uploaded pack becomes visible again
IsDeleted = false,
InstalledAtUtc = DateTime.UtcNow,
CreatedOnUtc = existingTheme.CreatedOnUtc,
CreatedBy = existingTheme.CreatedBy,
UpdatedOnUtc = DateTime.UtcNow,
UpdatedBy = userId
};
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
}
else
{
themeEntity = new ThemeEntity
{
Id = Guid.NewGuid(),
ThemeId = manifest.Id,
Name = manifest.Name,
Description = manifest.Description,
Author = manifest.Author,
Version = manifest.Version,
PreviewPath = manifest.Preview,
InstallSource = ThemeInstallSource.Uploaded,
InstalledAtUtc = DateTime.UtcNow,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = userId
};
Result<Created> insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
{
// roll back the stored files so a failed install leaves no orphaned theme pack behind
await _themeService.DeleteAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
return insertResult.Errors;
}
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return themeEntity.ToResponse();
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="InstallThemeCommand"/>.
/// </summary>
public class InstallThemeCommandValidator : AbstractValidator<InstallThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeCommandValidator"/> class.
/// </summary>
public InstallThemeCommandValidator()
{
RuleFor(command => command.Archive)
.NotNull()
.WithError(DomainErrors.Themes.ThemeArchiveCannotBeNull);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
/// <summary>
/// Command for restoring a soft deleted bundled theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to restore.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record RestoreThemeCommand(
string? ThemeId
) : ICommand;
@@ -0,0 +1,106 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
/// <summary>
/// Handler for the command to restore a soft deleted bundled theme.
/// </summary>
public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<RestoreThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreThemeCommandHandler"/> class.
/// </summary>
/// <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="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public RestoreThemeCommandHandler(
IUnitOfWork unitOfWork,
IThemeService themeService,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<RestoreThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to restore a soft deleted bundled theme.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async Task<Result<Success>> HandleAsync(RestoreThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can restore themes
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null)
return DomainErrors.Themes.ThemeNotFound;
// only bundled themes are soft deleted, so only a soft deleted bundled theme can be restored
if (!theme.IsDeleted || theme.InstallSource != ThemeInstallSource.Bundled)
return DomainErrors.Themes.ThemeCannotBeRestored;
// restore the pack files from the shipped archive before reactivating the theme
Result<Success> restoreFilesResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (restoreFilesResult.IsFailure)
return restoreFilesResult.Errors;
theme.IsDeleted = false;
theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return Result.Success;
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="RestoreThemeCommand"/>.
/// </summary>
public class RestoreThemeCommandValidator : AbstractValidator<RestoreThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="RestoreThemeCommandValidator"/> class.
/// </summary>
public RestoreThemeCommandValidator()
{
RuleFor(command => command.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Command for setting the currently active theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to activate.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record SetCurrentThemeCommand(
string? ThemeId
) : ICommand;
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Handler for the command to set the currently active theme.
/// </summary>
public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeCommand, Result<ThemeResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<SetCurrentThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public SetCurrentThemeCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<SetCurrentThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to set the currently active theme.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the newly active <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<ThemeResponse>> HandleAsync(SetCurrentThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can change the active theme
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
if (theme.IsCurrent == true)
return theme.ToResponse();
Result<ThemeEntity?> getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false);
if (getCurrentResult.IsFailure)
return getCurrentResult.Errors;
ThemeEntity? currentTheme = getCurrentResult.Value;
if (currentTheme is not null && currentTheme.Id != theme.Id)
{
currentTheme.IsCurrent = null;
await _unitOfWork.ThemeRepository.UpdateAsync(currentTheme, cancellationToken).ConfigureAwait(false);
}
theme.IsCurrent = true;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return theme.ToResponse();
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="SetCurrentThemeCommand"/>.
/// </summary>
public class SetCurrentThemeCommandValidator : AbstractValidator<SetCurrentThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeCommandValidator"/> class.
/// </summary>
public SetCurrentThemeCommandValidator()
{
RuleFor(command => command.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
/// <summary>
/// Query for retrieving the currently active theme.
/// </summary>
[DebuggerDisplay("GetCurrentThemeQuery")]
public record GetCurrentThemeQuery : IQuery;
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
/// <summary>
/// Handler for the query to get the currently active theme.
/// </summary>
public class GetCurrentThemeQueryHandler : IQueryHandler<GetCurrentThemeQuery, Result<ThemeResponse>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetCurrentThemeQueryHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get the currently active theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the active <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<ThemeResponse>> HandleAsync(GetCurrentThemeQuery query, CancellationToken cancellationToken)
{
Result<ThemeEntity?> getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false);
if (getCurrentResult.IsFailure)
return getCurrentResult.Errors;
if (getCurrentResult.Value is null)
return DomainErrors.Themes.ThemeNotFound;
return getCurrentResult.Value.ToResponse();
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Query for retrieving the downloadable archive of a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record GetThemeArchiveQuery(
string? ThemeId
) : IQuery;
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Handler for the query to get the downloadable archive of a theme.
/// </summary>
public class GetThemeArchiveQueryHandler : IQueryHandler<GetThemeArchiveQuery, Result<ThemeArchiveResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeArchiveQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveQueryHandler"/> class.
/// </summary>
/// <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 GetThemeArchiveQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeArchiveQuery> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the downloadable archive of a theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the archive of the theme, or an error.
/// </returns>
public async Task<Result<ThemeArchiveResponse>> HandleAsync(GetThemeArchiveQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<ThemeArchiveDto> archiveResult = await _themeService.BuildArchiveAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (archiveResult.IsFailure)
return archiveResult.Errors;
return new ThemeArchiveResponse(archiveResult.Value.Bytes, archiveResult.Value.FileName, archiveResult.Value.ContentType);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Validates the needed validation rules for <see cref="GetThemeArchiveQuery"/>.
/// </summary>
public class GetThemeArchiveQueryValidator : AbstractValidator<GetThemeArchiveQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveQueryValidator"/> class.
/// </summary>
public GetThemeArchiveQueryValidator()
{
RuleFor(query => query.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Query for retrieving an asset file of a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme.</param>
/// <param name="AssetPath">The asset path relative to the theme pack root.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, AssetPath: {AssetPath}")]
public record GetThemeAssetQuery(
string? ThemeId,
string? AssetPath
) : IQuery;
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Handler for the query to get an asset file of a theme.
/// </summary>
public class GetThemeAssetQueryHandler : IQueryHandler<GetThemeAssetQuery, Result<ThemeAssetResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeAssetQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetQueryHandler"/> class.
/// </summary>
/// <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 GetThemeAssetQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeAssetQuery> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
}
/// <summary>
/// Handles the query to get an asset file of a theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the asset of the theme, or an error.
/// </returns>
public async Task<Result<ThemeAssetResponse>> HandleAsync(GetThemeAssetQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<ThemeAssetDto> assetResult = await _themeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, cancellationToken).ConfigureAwait(false);
if (assetResult.IsFailure)
{
// the stored files of a bundled theme removed externally are restored, so its assets keep being served
if (theme.InstallSource == ThemeInstallSource.Bundled)
{
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (restoreResult.IsFailure)
return restoreResult.Errors;
assetResult = await _themeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, cancellationToken).ConfigureAwait(false);
}
if (assetResult.IsFailure)
return assetResult.Errors;
}
return new ThemeAssetResponse(assetResult.Value.Bytes, assetResult.Value.ContentType);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Validates the needed validation rules for <see cref="GetThemeAssetQuery"/>.
/// </summary>
public class GetThemeAssetQueryValidator : AbstractValidator<GetThemeAssetQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetQueryValidator"/> class.
/// </summary>
public GetThemeAssetQueryValidator()
{
RuleFor(query => query.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
RuleFor(query => query.AssetPath)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeAssetPathCannotBeEmpty);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
/// <summary>
/// Query for retrieving the theme engine settings.
/// </summary>
[DebuggerDisplay("GetThemeSettingsQuery")]
public record GetThemeSettingsQuery : IQuery;
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
/// <summary>
/// Handler for the query to get the theme engine settings.
/// </summary>
public class GetThemeSettingsQueryHandler : IQueryHandler<GetThemeSettingsQuery, Result<ThemeSettingsResponse>>
{
private readonly IThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsQueryHandler"/> class.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
public GetThemeSettingsQueryHandler(IThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Handles the query to get the theme engine settings.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing the theme engine settings, or an error.
/// </returns>
public Task<Result<ThemeSettingsResponse>> HandleAsync(GetThemeSettingsQuery query, CancellationToken cancellationToken)
{
ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.DefaultThemeId);
return Task.FromResult(Result.From(response));
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Query for retrieving the template of a theme selected by a page key.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme.</param>
/// <param name="PageKey">The page key that selects the template.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, PageKey: {PageKey}")]
public record GetThemeTemplateQuery(
string? ThemeId,
string? PageKey
) : IQuery;
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Handler for the query to get the template of a theme.
/// </summary>
public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery, Result<ThemeTemplateResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeTemplateQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateQueryHandler"/> class.
/// </summary>
/// <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)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the template of a theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the template of the theme, or an error.
/// </returns>
public async Task<Result<ThemeTemplateResponse>> HandleAsync(GetThemeTemplateQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<string> templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false);
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))
templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false);
if (templateResult.IsFailure)
return templateResult.Errors;
}
return new ThemeTemplateResponse(theme.ToResponse(), templateResult.Value);
}
/// <summary>
/// Restores the files of a bundled theme whose stored files were removed externally, and switches the active theme to the configured default when the broken theme was the active one.
/// </summary>
/// <param name="theme">The bundled theme to restore.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <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)
{
Result<ThemeEntity?> getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false);
if (getDefaultResult.IsFailure)
return true;
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);
defaultTheme.IsCurrent = true;
await _unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
}
return true;
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Validates the needed validation rules for <see cref="GetThemeTemplateQuery"/>.
/// </summary>
public class GetThemeTemplateQueryValidator : AbstractValidator<GetThemeTemplateQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateQueryValidator"/> class.
/// </summary>
public GetThemeTemplateQueryValidator()
{
RuleFor(query => query.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
RuleFor(query => query.PageKey)
.NotEmpty()
.WithError(DomainErrors.Themes.PageKeyCannotBeEmpty);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemes;
/// <summary>
/// Query for retrieving all installed themes.
/// </summary>
[DebuggerDisplay("GetThemesQuery")]
public record GetThemesQuery : IQuery;
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemes;
/// <summary>
/// Handler for the query to get all installed themes.
/// </summary>
public class GetThemesQueryHandler : IQueryHandler<GetThemesQuery, Result<IReadOnlyList<ThemeResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetThemesQueryHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get all installed themes.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<IReadOnlyList<ThemeResponse>>> HandleAsync(GetThemesQuery query, CancellationToken cancellationToken)
{
Result<IEnumerable<ThemeEntity>> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
return getThemesResult.Errors;
// deleted bundled themes are returned as well, so the administration page can offer to restore them
return Result.From<IReadOnlyList<ThemeResponse>>([.. getThemesResult.Value
.OrderBy(theme => theme.IsDeleted)
// the shipped bundled themes are listed before the user themes, so the defaults stay the most visible
.ThenByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled)
.ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)
.Select(theme => theme.ToResponse())]);
}
}
@@ -10,8 +10,10 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
public record UpdateUserSettingsCommand(
bool IsPaginationEnabled,
int ItemsPerPage,
bool IgnoreThePrefixForAlphaPicker
bool IgnoreThePrefixForAlphaPicker,
bool IsThemeCachingEnabled
) : ICommand;
@@ -72,7 +72,8 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
UserId.Create(userId),
command.IsPaginationEnabled,
command.ItemsPerPage,
command.IgnoreThePrefixForAlphaPicker);
command.IgnoreThePrefixForAlphaPicker,
command.IsThemeCachingEnabled);
if (createSettingsResult.IsFailure)
return createSettingsResult.Errors;
@@ -90,7 +91,8 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
Result<Updated> updateSettingsResult = toDomainEntityResult.Value.UpdateSettings(
command.IsPaginationEnabled,
command.ItemsPerPage,
command.IgnoreThePrefixForAlphaPicker);
command.IgnoreThePrefixForAlphaPicker,
command.IsThemeCachingEnabled);
if (updateSettingsResult.IsFailure)
return updateSettingsResult.Errors;
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to delete a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to delete. Required.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record DeleteThemeRequest(
string? ThemeId
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to download the archive of a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme. Required.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record GetThemeArchiveRequest(
string? ThemeId
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to get an asset file of a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme. Required.</param>
/// <param name="AssetPath">The asset path relative to the theme pack root. Required.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, AssetPath: {AssetPath}")]
public record GetThemeAssetRequest(
string? ThemeId,
string? AssetPath
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to get the template of a theme selected by a page key.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme. Required.</param>
/// <param name="PageKey">The page key that selects the template. Required.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, PageKey: {PageKey}")]
public record GetThemeTemplateRequest(
string? ThemeId,
string? PageKey
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to restore a soft deleted bundled theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to restore. Required.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record RestoreThemeRequest(
string? ThemeId
);
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to set the currently active theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to activate. Required.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record SetCurrentThemeRequest(
string? ThemeId
);
@@ -10,9 +10,11 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings;
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not. Required.</param>
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled. Required.</param>
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required.</param>
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not. Required.</param>
[DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")]
public sealed record UpdateUserSettingsRequest(
bool IsPaginationEnabled,
int ItemsPerPage,
bool IgnoreThePrefixForAlphaPicker
bool IgnoreThePrefixForAlphaPicker,
bool IsThemeCachingEnabled
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Themes;
/// <summary>
/// Represents a theme archive response.
/// </summary>
/// <param name="Bytes">The bytes of the ZIP archive.</param>
/// <param name="FileName">The file name to expose when downloading the archive.</param>
/// <param name="ContentType">The MIME content type of the archive.</param>
[DebuggerDisplay("FileName: {FileName}")]
public record ThemeArchiveResponse(
byte[] Bytes,
string FileName,
string ContentType
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Themes;
/// <summary>
/// Represents a theme asset response.
/// </summary>
/// <param name="Bytes">The bytes of the asset file.</param>
/// <param name="ContentType">The MIME content type of the asset file.</param>
[DebuggerDisplay("ContentType: {ContentType}")]
public record ThemeAssetResponse(
byte[] Bytes,
string ContentType
);
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Themes;
/// <summary>
/// Represents a theme response.
/// </summary>
/// <param name="Id">The unique identifier of the theme.</param>
/// <param name="ThemeId">The manifest id of the theme, used by clients to reference it.</param>
/// <param name="Name">The display name of the theme.</param>
/// <param name="Description">The description of the theme.</param>
/// <param name="Author">The author of the theme.</param>
/// <param name="Version">The version of the theme, using semantic version form.</param>
/// <param name="PreviewPath">The path of the theme preview image, relative to the theme pack root, or <see langword="null"/> when the theme has no preview.</param>
/// <param name="InstallSource">The source the theme was installed from.</param>
/// <param name="IsCurrent">Whether the theme is the currently active one.</param>
/// <param name="InstalledAtUtc">The UTC timestamp at which the theme was installed.</param>
/// <param name="IsDeleted">Whether the theme was deleted by the user, which is only possible for bundled themes.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")]
public record ThemeResponse(
Guid Id,
string ThemeId,
string Name,
string Description,
string Author,
string Version,
string? PreviewPath,
ThemeInstallSource InstallSource,
bool? IsCurrent,
DateTime InstalledAtUtc,
bool IsDeleted
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Themes;
/// <summary>
/// Represents a theme settings response.
/// </summary>
/// <param name="MaxArchiveBytes">The maximum allowed size of a theme archive, in bytes.</param>
/// <param name="DefaultThemeId">The identifier of the theme selected when no valid current theme is available.</param>
[DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")]
public record ThemeSettingsResponse(
long MaxArchiveBytes,
string DefaultThemeId
);
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Themes;
/// <summary>
/// Represents a theme template response.
/// </summary>
/// <param name="Theme">The theme the template belongs to.</param>
/// <param name="Template">The sanitized content of the template.</param>
[DebuggerDisplay("ThemeId: {Theme.ThemeId}")]
public record ThemeTemplateResponse(
ThemeResponse Theme,
string Template
);
@@ -12,10 +12,12 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings;
/// <param name="IsPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
/// <param name="ItemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
/// <param name="IgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
[DebuggerDisplay("UserId: {UserId}")]
public sealed record UserSettingsResponse(
Guid UserId,
bool IsPaginationEnabled,
int ItemsPerPage,
bool IgnoreThePrefixForAlphaPicker
bool IgnoreThePrefixForAlphaPicker,
bool IsThemeCachingEnabled
);
@@ -0,0 +1,100 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="ThemeEntity"/> entity.
/// </summary>
public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
{
/// <summary>
/// Configures the <see cref="ThemeEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<ThemeEntity> builder)
{
builder.ToTable("Themes");
builder.HasKey(theme => theme.Id);
builder.Property(theme => theme.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the install, we need to tell EF not to generate it
.HasColumnOrder(0);
// the manifest id is the business key used by the clients, so it must be unique
builder.HasIndex(theme => theme.ThemeId)
.IsUnique();
builder.Property(theme => theme.ThemeId)
.IsRequired()
.HasMaxLength(64)
.HasColumnOrder(1);
builder.Property(theme => theme.Name)
.IsRequired()
.HasMaxLength(80)
.HasColumnOrder(2);
builder.Property(theme => theme.Description)
.IsRequired()
.HasMaxLength(300)
.HasColumnOrder(3);
builder.Property(theme => theme.Author)
.IsRequired()
.HasMaxLength(80)
.HasColumnOrder(4);
builder.Property(theme => theme.Version)
.IsRequired()
.HasMaxLength(40)
.HasColumnOrder(5);
builder.Property(theme => theme.PreviewPath)
.HasMaxLength(240)
.HasDefaultValue(null)
.HasColumnOrder(6);
builder.Property(theme => theme.InstallSource)
.IsRequired()
.HasConversion<string>()
.HasColumnOrder(7);
// at most one theme can be current: the filtered unique index guarantees it at the database level, since every row that is not current has a null value here, and nulls are allowed to repeat
builder.HasIndex(theme => theme.IsCurrent)
.IsUnique()
.HasFilter("IsCurrent = 1");
builder.Property(theme => theme.IsCurrent)
.HasDefaultValue(null)
.HasColumnOrder(8);
builder.Property(theme => theme.IsDeleted)
.HasDefaultValue(false)
.HasColumnOrder(9);
builder.Property(theme => theme.InstalledAtUtc)
.IsRequired()
.HasColumnOrder(10);
// audit
builder.Property(theme => theme.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(11);
builder.Property(theme => theme.CreatedBy)
.IsRequired()
.HasColumnOrder(12);
builder.Property(theme => theme.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(13);
builder.Property(theme => theme.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(14);
}
}
@@ -47,6 +47,10 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
.IsRequired()
.HasColumnOrder(4);
builder.Property(settings => settings.IsThemeCachingEnabled)
.IsRequired()
.HasColumnOrder(9);
// audit
builder.Property(settings => settings.CreatedOnUtc)
.IsRequired()
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,60 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsThemesTable : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Themes",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
ThemeId = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 80, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 300, nullable: false),
Author = table.Column<string>(type: "TEXT", maxLength: 80, nullable: false),
Version = table.Column<string>(type: "TEXT", maxLength: 40, nullable: false),
PreviewPath = table.Column<string>(type: "TEXT", maxLength: 240, nullable: true),
InstallSource = table.Column<string>(type: "TEXT", nullable: false),
IsCurrent = table.Column<bool>(type: "INTEGER", nullable: true),
IsDeleted = table.Column<bool>(type: "INTEGER", nullable: false, defaultValue: false),
InstalledAtUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Themes", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Themes_IsCurrent",
table: "Themes",
column: "IsCurrent",
unique: true,
filter: "IsCurrent = 1");
migrationBuilder.CreateIndex(
name: "IX_Themes_ThemeId",
table: "Themes",
column: "ThemeId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Themes");
}
}
}
@@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsIsThemeCachingEnabledToUserSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsThemeCachingEnabled",
table: "UserSettings",
type: "INTEGER",
nullable: false,
defaultValue: true)
.Annotation("Relational:ColumnOrder", 9);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsThemeCachingEnabled",
table: "UserSettings");
}
}
}
@@ -15,7 +15,7 @@ namespace Lumina.DataAccess.Common.Migrations
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.HasAnnotation("ProductVersion", "10.0.11");
modelBuilder.Entity("BookGenres", b =>
{
@@ -809,6 +809,94 @@ namespace Lumina.DataAccess.Common.Migrations
b.ToTable("Plugins", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<string>("Author")
.IsRequired()
.HasMaxLength(80)
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(300)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.Property<string>("InstallSource")
.IsRequired()
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<DateTime>("InstalledAtUtc")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<bool?>("IsCurrent")
.HasColumnType("INTEGER")
.HasColumnOrder(8);
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(false)
.HasColumnOrder(9);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(80)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<string>("PreviewPath")
.HasMaxLength(240)
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<string>("ThemeId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(14);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(13);
b.Property<string>("Version")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.HasKey("Id");
b.HasIndex("IsCurrent")
.IsUnique()
.HasFilter("IsCurrent = 1");
b.HasIndex("ThemeId")
.IsUnique();
b.ToTable("Themes", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
{
b.Property<Guid>("Id")
@@ -884,6 +972,10 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("INTEGER")
.HasColumnOrder(2);
b.Property<bool>("IsThemeCachingEnabled")
.HasColumnType("INTEGER")
.HasColumnOrder(9);
b.Property<int>("ItemsPerPage")
.HasColumnType("INTEGER")
.HasColumnOrder(3);
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Themes;
/// <summary>
/// Repository for themes.
/// </summary>
internal sealed class ThemeRepository : IThemeRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public ThemeRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new theme.
/// </summary>
/// <param name="theme">The theme to add.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Created>> InsertAsync(ThemeEntity theme, CancellationToken cancellationToken)
{
bool themeExists = await _luminaDbContext.Themes.AnyAsync(repositoryTheme => repositoryTheme.Id == theme.Id, cancellationToken).ConfigureAwait(false);
if (themeExists)
return Errors.Themes.ThemeNotFound;
_luminaDbContext.Themes.Add(theme);
return Result.Created;
}
/// <summary>
/// Updates a theme.
/// </summary>
/// <param name="data">The theme to update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Updated>> UpdateAsync(ThemeEntity data, CancellationToken cancellationToken)
{
ThemeEntity? foundTheme = await _luminaDbContext.Themes
.FirstOrDefaultAsync(theme => theme.Id == data.Id, cancellationToken).ConfigureAwait(false);
if (foundTheme is null)
return Errors.Themes.ThemeNotFound;
_luminaDbContext.Entry(foundTheme).CurrentValues.SetValues(data);
return Result.Updated;
}
/// <summary>
/// Gets all themes from the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="ThemeEntity"/>, or an error.</returns>
public async Task<Result<IEnumerable<ThemeEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Themes.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a theme identified by its manifest <paramref name="themeId"/> from the storage medium.
/// </summary>
/// <param name="themeId">The manifest id of the theme to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="ThemeEntity"/> identified by <paramref name="themeId"/>, or an error.</returns>
public async Task<Result<ThemeEntity?>> GetByThemeIdAsync(string themeId, CancellationToken cancellationToken)
{
return await _luminaDbContext.Themes
.FirstOrDefaultAsync(theme => theme.ThemeId == themeId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a theme identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the theme to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
ThemeEntity? foundTheme = await _luminaDbContext.Themes
.FirstOrDefaultAsync(theme => theme.Id == id, cancellationToken).ConfigureAwait(false);
if (foundTheme is null)
return Errors.Themes.ThemeNotFound;
_luminaDbContext.Themes.Remove(foundTheme);
return Result.Deleted;
}
/// <summary>
/// Gets the currently active theme from the storage medium.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the active <see cref="ThemeEntity"/>, or an error.</returns>
public async Task<Result<ThemeEntity?>> GetCurrentAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Themes
.FirstOrDefaultAsync(theme => theme.IsCurrent == true, cancellationToken).ConfigureAwait(false);
}
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Microsoft.EntityFrameworkCore;
#endregion
@@ -32,6 +33,7 @@ public class LuminaDbContext : DbContext
public virtual DbSet<RolePermissionEntity> RolePermissions { get; set; } = null!;
public virtual DbSet<PluginEntity> Plugins { get; set; } = null!;
public virtual DbSet<LibraryMetadataProviderConfigurationEntity> LibraryMetadataProviderConfigurations { get; set; } = null!;
public virtual DbSet<ThemeEntity> Themes { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -3,12 +3,14 @@ using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.DataAccess.Core.Repositories.Authorization;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.Repositories.Themes;
using Lumina.DataAccess.Core.Repositories.Users;
using Microsoft.EntityFrameworkCore.Storage;
using System;
@@ -38,6 +40,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository;
private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository;
private IPluginRepository? _pluginRepository;
private IThemeRepository? _themeRepository;
private IUserRepository? _userRepository;
private IUserSettingsRepository? _userSettingsRepository;
@@ -185,6 +188,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the theme repository.
/// </summary>
public IThemeRepository ThemeRepository
{
get
{
_themeRepository ??= new ThemeRepository(_luminaDbContext);
return _themeRepository;
}
}
/// <summary>
/// Gets the user repository.
/// </summary>
@@ -0,0 +1,17 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Themes;
/// <summary>
/// Enumeration for the source a theme was installed from.
/// </summary>
public enum ThemeInstallSource
{
/// <summary>
/// The theme was uploaded by a user.
/// </summary>
Uploaded,
/// <summary>
/// The theme is bundled with the application.
/// </summary>
Bundled
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Domain.Common.Errors;
/// <summary>
/// Theme error types.
/// </summary>
public static partial class Errors
{
public static class Themes
{
public static Error ThemeNotFound => Error.NotFound(description: nameof(ThemeNotFound));
public static Error ThemeIdCannotBeEmpty => Error.Validation(description: nameof(ThemeIdCannotBeEmpty));
public static Error PageKeyCannotBeEmpty => Error.Validation(description: nameof(PageKeyCannotBeEmpty));
public static Error ThemeAssetPathCannotBeEmpty => Error.Validation(description: nameof(ThemeAssetPathCannotBeEmpty));
public static Error ThemeArchiveCannotBeNull => Error.Validation(description: nameof(ThemeArchiveCannotBeNull));
public static Error LastBundledThemeCannotBeDeleted => Error.Forbidden(description: nameof(LastBundledThemeCannotBeDeleted));
public static Error ThemeCannotBeDeleted => Error.Forbidden(description: nameof(ThemeCannotBeDeleted));
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 ThemeNotAvailable => Error.Failure(description: nameof(ThemeNotAvailable));
}
}
@@ -19,6 +19,7 @@ public class UserSettings : AggregateRoot<UserSettingsId>
private const bool DEFAULT_IS_PAGINATION_ENABLED = true;
private const int DEFAULT_ITEMS_PER_PAGE = 48;
private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false;
private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true;
/// <summary>
/// Gets the object representing the unique identifier of the user that owns these settings.
@@ -40,6 +41,11 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// </summary>
public bool IgnoreThePrefixForAlphaPicker { get; private set; }
/// <summary>
/// Gets whether the theme data served to this user is cached, or not.
/// </summary>
public bool IsThemeCachingEnabled { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="UserSettings"/> class.
/// </summary>
@@ -48,17 +54,20 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
private UserSettings(
UserSettingsId id,
UserId userId,
bool isPaginationEnabled,
int itemsPerPage,
bool ignoreThePrefixForAlphaPicker) : base(id)
bool ignoreThePrefixForAlphaPicker,
bool isThemeCachingEnabled) : base(id)
{
UserId = userId;
IsPaginationEnabled = isPaginationEnabled;
ItemsPerPage = itemsPerPage;
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
IsThemeCachingEnabled = isThemeCachingEnabled;
}
/// <summary>
@@ -69,7 +78,7 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// </returns>
public static Result<UserSettings> Create()
{
return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER);
return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED);
}
/// <summary>
@@ -81,7 +90,7 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// </returns>
public static Result<UserSettings> Create(UserId userId)
{
return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER);
return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED);
}
/// <summary>
@@ -91,6 +100,7 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
/// </returns>
@@ -98,7 +108,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
UserId userId,
bool isPaginationEnabled,
int itemsPerPage,
bool ignoreThePrefixForAlphaPicker)
bool ignoreThePrefixForAlphaPicker,
bool isThemeCachingEnabled)
{
if (itemsPerPage <= 0)
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
@@ -108,7 +119,8 @@ public class UserSettings : AggregateRoot<UserSettingsId>
userId,
isPaginationEnabled,
itemsPerPage,
ignoreThePrefixForAlphaPicker);
ignoreThePrefixForAlphaPicker,
isThemeCachingEnabled);
}
/// <summary>
@@ -119,6 +131,7 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="UserSettings"/>, or an error message.
/// </returns>
@@ -127,12 +140,13 @@ public class UserSettings : AggregateRoot<UserSettingsId>
UserId userId,
bool isPaginationEnabled,
int itemsPerPage,
bool ignoreThePrefixForAlphaPicker)
bool ignoreThePrefixForAlphaPicker,
bool isThemeCachingEnabled)
{
if (itemsPerPage <= 0)
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker);
return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker, isThemeCachingEnabled);
}
/// <summary>
@@ -141,11 +155,13 @@ public class UserSettings : AggregateRoot<UserSettingsId>
/// <param name="isPaginationEnabled">Whether pagination is enabled for the user, or not.</param>
/// <param name="itemsPerPage">The number of library items displayed per page when pagination is enabled.</param>
/// <param name="ignoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
/// <param name="isThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
public Result<Updated> UpdateSettings(
bool isPaginationEnabled,
int itemsPerPage,
bool ignoreThePrefixForAlphaPicker)
bool ignoreThePrefixForAlphaPicker,
bool isThemeCachingEnabled)
{
if (itemsPerPage <= 0)
return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero;
@@ -153,6 +169,7 @@ public class UserSettings : AggregateRoot<UserSettingsId>
IsPaginationEnabled = isPaginationEnabled;
ItemsPerPage = itemsPerPage;
IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker;
IsThemeCachingEnabled = isThemeCachingEnabled;
return Result.Updated;
}
}
@@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
@@ -29,6 +30,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Themes;
using Lumina.Infrastructure.Core.Time;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.Configuration;
@@ -113,6 +115,10 @@ public static class InfrastructureLayerServices
serviceProvider.GetRequiredService<ILogger<PluginDetectionSyncJob>>()));
services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService<PluginDetectionSyncJob>());
// themes: the theme service stores and serves theme packs, and the detection job seeds the bundled themes at startup
services.AddSingleton<IThemeService, ThemeService>();
services.AddHostedService<ThemeDetectionSyncJob>();
return services;
}
}
@@ -35,11 +35,6 @@ public static class SharedConfiguration
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the appsettings sections
services.AddOptions<CommonSettingsDto>()
.Bind(configuration.GetRequiredSection(CommonSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<DatabaseSettingsDto>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME))
.ValidateFluently()
@@ -70,6 +65,11 @@ public static class SharedConfiguration
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<ThemeEngineOptionsDto>()
.Bind(configuration.GetRequiredSection(ThemeEngineOptionsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return services;
}
}
@@ -11,7 +11,6 @@ public static partial class Errors
{
public static class Configuration
{
public static Error ApplicationThemeCannotBeEmpty => Error.Validation(description: nameof(ApplicationThemeCannotBeEmpty));
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty));
public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty));
public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty));
@@ -25,5 +24,12 @@ public static partial class Errors
public static Error CorsOriginsCannotBeEmpty => Error.Validation(description: nameof(CorsOriginsCannotBeEmpty));
public static Error CorsOriginIsInvalid => Error.Validation(description: nameof(CorsOriginIsInvalid));
public static Error PluginsDirectoryCannotBeEmpty => Error.Validation(description: nameof(PluginsDirectoryCannotBeEmpty));
public static Error ThemeStoragePathCannotBeEmpty => Error.Validation(description: nameof(ThemeStoragePathCannotBeEmpty));
public static Error ThemeBundledThemesPathCannotBeEmpty => Error.Validation(description: nameof(ThemeBundledThemesPathCannotBeEmpty));
public static Error ThemeDefaultThemeIdCannotBeEmpty => Error.Validation(description: nameof(ThemeDefaultThemeIdCannotBeEmpty));
public static Error ThemeMaxArchiveBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxArchiveBytesMustBePositive));
public static Error ThemeMaxExpandedBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxExpandedBytesMustBePositive));
public static Error ThemeMaxSingleFileBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxSingleFileBytesMustBePositive));
public static Error ThemeMaxEntriesMustBePositive => Error.Validation(description: nameof(ThemeMaxEntriesMustBePositive));
}
}
@@ -1,19 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.Configuration;
/// <summary>
/// Data transfer object for deserializing shared application configuration settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class CommonSettingsDto
{
public const string SECTION_NAME = "CommonSettings";
/// <summary>
/// Gets or sets the theme of the application.
/// </summary>
public required string Theme { get; init; }
}
@@ -2,7 +2,7 @@
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Configuration;
namespace Lumina.Infrastructure.Common.Models.DTO.Configuration;
/// <summary>
/// Data transfer object for deserializing theme engine settings.
@@ -13,14 +13,14 @@ public sealed class ThemeEngineOptionsDto
public const string SECTION_NAME = "ThemeEngine";
/// <summary>
/// Gets or sets the directory where installed theme packages are stored.
/// Gets or sets the directory where installed theme packs are stored, relative to the API base directory when not rooted.
/// </summary>
public string StoragePath { get; set; } = "Themes";
public string StoragePath { get; set; } = "themes";
/// <summary>
/// Gets or sets the file name of the persisted theme settings.
/// Gets or sets the directory where the theme pack archives shipped with the application are located, relative to the API base directory when not rooted.
/// </summary>
public string SettingsPath { get; set; } = "theme-settings.json";
public string BundledThemesPath { get; set; } = "themes/bundled";
/// <summary>
/// Gets or sets the identifier of the theme selected when no valid current theme is persisted.
@@ -33,22 +33,17 @@ public sealed class ThemeEngineOptionsDto
public long MaxArchiveBytes { get; set; } = 8 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum allowed total size of an extracted theme archive, in bytes.
/// Gets or sets the maximum allowed total size of an extracted theme pack, in bytes.
/// </summary>
public long MaxExpandedBytes { get; set; } = 24 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum allowed size of a single file within a theme archive, in bytes.
/// Gets or sets the maximum allowed size of a single file within a theme pack, in bytes.
/// </summary>
public long MaxSingleFileBytes { get; set; } = 6 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum allowed number of entries in a theme archive.
/// Gets or sets the maximum allowed number of entries in a theme pack archive.
/// </summary>
public int MaxEntries { get; set; } = 250;
/// <summary>
/// Gets or sets a value indicating whether theme templates may load script files.
/// </summary>
public bool AllowThemeScripts { get; set; }
}
@@ -1,23 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the CommonSettings application configuration settings section.
/// </summary>
public class CommonSettingsDtoValidator : AbstractValidator<CommonSettingsDto>
{
/// <summary>
/// Initializes a new instance of the <see cref="CommonSettingsDtoValidator"/> class.
/// </summary>
public CommonSettingsDtoValidator()
{
RuleFor(settings => settings.Theme)
.NotEmpty()
.WithError(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty);
}
}
@@ -1,11 +1,10 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Utilities;
using Lumina.Presentation.Web.Common.Validation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the ThemeEngine application configuration settings section.
@@ -19,30 +18,30 @@ public class ThemeEngineOptionsDtoValidator : AbstractValidator<ThemeEngineOptio
{
RuleFor(themeEngineOptions => themeEngineOptions.StoragePath)
.NotEmpty()
.WithError(Error.Validation(description: "Theme storage path cannot be empty!"));
.WithError(Errors.Errors.Configuration.ThemeStoragePathCannotBeEmpty);
RuleFor(themeEngineOptions => themeEngineOptions.SettingsPath)
RuleFor(themeEngineOptions => themeEngineOptions.BundledThemesPath)
.NotEmpty()
.WithError(Error.Validation(description: "Theme settings path cannot be empty!"));
.WithError(Errors.Errors.Configuration.ThemeBundledThemesPathCannotBeEmpty);
RuleFor(themeEngineOptions => themeEngineOptions.DefaultThemeId)
.NotEmpty()
.WithError(Error.Validation(description: "Default theme Id cannot be empty!"));
.WithError(Errors.Errors.Configuration.ThemeDefaultThemeIdCannotBeEmpty);
RuleFor(themeEngineOptions => themeEngineOptions.MaxArchiveBytes)
.GreaterThan(0)
.WithError(Error.Validation(description: "Maximum archive size must be greater than 0!"));
.WithError(Errors.Errors.Configuration.ThemeMaxArchiveBytesMustBePositive);
RuleFor(themeEngineOptions => themeEngineOptions.MaxExpandedBytes)
.GreaterThan(0)
.WithError(Error.Validation(description: "Maximum expanded size must be greater than 0!"));
.WithError(Errors.Errors.Configuration.ThemeMaxExpandedBytesMustBePositive);
RuleFor(themeEngineOptions => themeEngineOptions.MaxSingleFileBytes)
.GreaterThan(0)
.WithError(Error.Validation(description: "Maximum single file size must be greater than 0!"));
.WithError(Errors.Errors.Configuration.ThemeMaxSingleFileBytesMustBePositive);
RuleFor(themeEngineOptions => themeEngineOptions.MaxEntries)
.GreaterThan(0)
.WithError(Error.Validation(description: "Maximum entries count must be greater than 0!"));
.WithError(Errors.Errors.Configuration.ThemeMaxEntriesMustBePositive);
}
}
@@ -0,0 +1,197 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Themes;
/// <summary>
/// Background job that installs the bundled themes into the storage medium and the theme storage at startup.
/// </summary>
internal sealed class ThemeDetectionSyncJob : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IThemeService _themeService;
private readonly ILogger<ThemeDetectionSyncJob> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeDetectionSyncJob"/> class.
/// </summary>
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which services are requested.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="logger">Injected logger used for logging.</param>
public ThemeDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IThemeService themeService, ILogger<ThemeDetectionSyncJob> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_themeService = themeService;
_logger = logger;
}
/// <summary>
/// Method called when the background service starts.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService<IUnitOfWork>();
Result<IEnumerable<ThemeEntity>> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(stoppingToken);
if (getThemesResult.IsFailure)
{
_logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description);
return;
}
// themes that were soft deleted by the user must not be reinstalled automatically
List<ThemeEntity> themes = [.. getThemesResult.Value];
HashSet<string> knownThemeIds = [.. themes.Select(theme => theme.ThemeId)];
foreach (string archivePath in _themeService.GetBundledThemeArchivePaths())
{
Result<ThemeManifestDto> manifestResult = await _themeService.ReadManifestFromArchiveAsync(archivePath, stoppingToken);
if (manifestResult.IsFailure)
{
_logger.LogWarning("Skipping bundled theme archive {ArchivePath}: {Error}", archivePath, manifestResult.FirstError.Description);
continue;
}
if (knownThemeIds.Contains(manifestResult.Value.Id))
continue;
// installing a bundled theme at startup is best effort: a file system failure here must never crash the host,
// because the default BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and
// disposes its service provider, making every later request fail
try
{
await using FileStream archive = File.OpenRead(archivePath);
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(archive, stoppingToken);
if (installResult.IsFailure)
{
_logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description);
continue;
}
ThemeEntity themeEntity = new()
{
Id = Guid.NewGuid(),
ThemeId = manifestResult.Value.Id,
Name = manifestResult.Value.Name,
Description = manifestResult.Value.Description,
Author = manifestResult.Value.Author,
Version = manifestResult.Value.Version,
PreviewPath = manifestResult.Value.Preview,
InstallSource = ThemeInstallSource.Bundled,
InstalledAtUtc = DateTime.UtcNow,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
};
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken);
if (insertResult.IsFailure)
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
else
themes.Add(themeEntity);
}
catch (IOException exception)
{
_logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id);
}
catch (UnauthorizedAccessException exception)
{
_logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id);
}
}
await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken);
await EnsureCurrentThemeExistsAsync(unitOfWork, themes, stoppingToken);
await unitOfWork.SaveChangesAsync(stoppingToken);
}
/// <summary>
/// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered.
/// </summary>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
// a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored
// automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed
// externally, and is the only case where the files are restored
IReadOnlyList<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
if (brokenThemes.Count is 0)
return;
foreach (ThemeEntity brokenTheme in brokenThemes)
{
if (brokenTheme.InstallSource == ThemeInstallSource.Bundled)
{
// 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);
// 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);
}
}
}
/// <summary>
/// Activates the configured default theme when no theme is currently active, so the application always has an active theme.
/// </summary>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return;
ThemeEntity? defaultTheme = themes
.Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId))
.OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (defaultTheme is null)
return;
defaultTheme.IsCurrent = true;
defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
defaultTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken);
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.IO;
#endregion
namespace Lumina.Infrastructure.Core.Themes;
/// <summary>
/// Resolves the MIME content type of theme files based on their file extension.
/// </summary>
internal static class ThemeMimeTypes
{
private static readonly Dictionary<string, string> s_mimeByExtension = new(StringComparer.OrdinalIgnoreCase)
{
[".htm"] = "text/html",
[".html"] = "text/html",
[".css"] = "text/css",
[".js"] = "application/javascript",
[".json"] = "application/json",
[".png"] = "image/png",
[".jpg"] = "image/jpeg",
[".jpeg"] = "image/jpeg",
[".gif"] = "image/gif",
[".webp"] = "image/webp",
[".svg"] = "image/svg+xml",
[".ico"] = "image/x-icon",
[".woff"] = "font/woff",
[".woff2"] = "font/woff2",
[".ttf"] = "font/ttf",
[".txt"] = "text/plain"
};
/// <summary>
/// Gets the MIME content type of a file based on its extension.
/// </summary>
/// <param name="filePath">The path of the file to get the content type of.</param>
/// <returns>The MIME content type, or <c>application/octet-stream</c> when the extension is unknown.</returns>
public static string GetMimeType(string filePath)
{
return s_mimeByExtension.TryGetValue(Path.GetExtension(filePath), out string? mimeType) ? mimeType : "application/octet-stream";
}
}
@@ -0,0 +1,842 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.Themes;
/// <summary>
/// Stores and serves theme packs on the server, validating the pack envelope at install time and sanitizing served content.
/// </summary>
public sealed class ThemeService : IThemeService
{
private const string MANIFEST_FILE_NAME = "theme.json";
private const long MAX_MANIFEST_BYTES = 64 * 1024;
private static readonly Regex s_themeIdPattern = new(
"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex s_templateKeyPattern = new(
"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex s_versionPattern = new(
"^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex s_pathSegmentPattern = new(
"^[A-Za-z0-9][A-Za-z0-9._ -]*$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
MaxDepth = 16
};
private readonly ThemeEngineOptionsDto _options;
private readonly ILogger<ThemeService> _logger;
private readonly string _storageRoot;
private readonly string _stagingRoot;
private readonly string _bundledRoot;
// serializes theme pack mutations, so concurrent installs and deletes cannot race on the same files; the gate is
// shared by every instance that writes to the same storage root, because several hosts can run against the same
// storage directory at once (for example the parallel in-memory hosts started by the test factories). A per-instance
// gate is NOT enough: concurrent hosts raced on the shared staging cleanup and one host's directory move failed with
// an access denied exception, which crashed that host and disposed its service provider. Keep the gate keyed on the
// resolved storage root.
private static readonly ConcurrentDictionary<string, SemaphoreSlim> s_storageGates = new(StringComparer.Ordinal);
private readonly SemaphoreSlim _mutationGate;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeService"/> class.
/// </summary>
/// <param name="options">The theme engine configuration options.</param>
/// <param name="logger">The logger for this service.</param>
public ThemeService(IOptions<ThemeEngineOptionsDto> options, ILogger<ThemeService> logger)
{
_options = options.Value;
_logger = logger;
string basePath = AppContext.BaseDirectory;
_storageRoot = ResolvePath(basePath, _options.StoragePath);
_stagingRoot = Path.Combine(_storageRoot, ".staging");
_bundledRoot = ResolvePath(basePath, _options.BundledThemesPath);
_mutationGate = s_storageGates.GetOrAdd(_storageRoot, static _ => new SemaphoreSlim(1, 1));
}
/// <summary>
/// Gets the maximum allowed size of a theme archive, in bytes.
/// </summary>
public long MaxArchiveBytes => _options.MaxArchiveBytes;
/// <summary>
/// Gets the identifier of the theme selected when no valid current theme is available.
/// </summary>
public string DefaultThemeId => _options.DefaultThemeId;
/// <summary>
/// Gets the paths of the theme pack archives shipped with the application.
/// </summary>
/// <returns>The list of bundled theme archive paths.</returns>
public IReadOnlyList<string> GetBundledThemeArchivePaths()
{
if (!Directory.Exists(_bundledRoot))
return [];
return [.. Directory.EnumerateFiles(_bundledRoot, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Checks whether the stored pack files of a theme still exist.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <returns><see langword="true"/> when the theme pack files exist, <see langword="false"/> otherwise.</returns>
public bool HasThemePack(string themeId)
{
string themePath = ResolveThemePath(themeId);
return Directory.Exists(themePath) && File.Exists(Path.Combine(themePath, MANIFEST_FILE_NAME));
}
/// <summary>
/// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id.
/// </summary>
/// <param name="archive">The ZIP archive stream of the theme pack.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest of the installed theme, or an error.</returns>
public async Task<Result<ThemeManifestDto>> InstallAsync(Stream archive, CancellationToken cancellationToken)
{
await _mutationGate.WaitAsync(cancellationToken);
try
{
Directory.CreateDirectory(_storageRoot);
Directory.CreateDirectory(_stagingRoot);
CleanStagingDirectory();
string workId = Guid.NewGuid().ToString("N");
string temporaryArchivePath = Path.Combine(_stagingRoot, $"{workId}.zip");
string extractionPath = Path.Combine(_stagingRoot, workId);
try
{
Result<Success> copyResult = await CopyArchiveWithLimitAsync(archive, temporaryArchivePath, cancellationToken);
if (copyResult.IsFailure)
return copyResult.Errors;
Directory.CreateDirectory(extractionPath);
Result<Success> extractResult = await ExtractArchiveAsync(temporaryArchivePath, extractionPath, cancellationToken);
if (extractResult.IsFailure)
return extractResult.Errors;
Result<ThemeManifestDto> manifestResult = LoadManifestFromDirectory(extractionPath);
if (manifestResult.IsFailure)
return manifestResult.Errors;
// install means replace: the files of an existing theme with the same manifest id are swapped with the new pack
string destination = Path.Combine(_storageRoot, manifestResult.Value.Id);
await SwapIntoDestinationAsync(extractionPath, destination, cancellationToken);
return manifestResult.Value;
}
catch (InvalidDataException exception)
{
_logger.LogWarning(exception, "An uploaded theme archive could not be read.");
return Errors.Themes.ThemeArchiveNotReadable;
}
finally
{
if (File.Exists(temporaryArchivePath))
File.Delete(temporaryArchivePath);
if (Directory.Exists(extractionPath))
Directory.Delete(extractionPath, recursive: true);
}
}
finally
{
_mutationGate.Release();
}
}
/// <summary>
/// Reads the manifest of a theme pack archive without installing it.
/// </summary>
/// <param name="archivePath">The path of the theme pack ZIP archive.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
public async Task<Result<ThemeManifestDto>> ReadManifestFromArchiveAsync(string archivePath, CancellationToken cancellationToken)
{
try
{
using ZipArchive archive = ZipFile.OpenRead(archivePath);
ZipArchiveEntry? manifestEntry = archive.GetEntry(MANIFEST_FILE_NAME);
if (manifestEntry is null)
return PackageInvalid("The theme is missing theme.json.");
await using Stream manifestStream = manifestEntry.Open();
using StreamReader reader = new(manifestStream);
string json = await reader.ReadToEndAsync(cancellationToken);
return DeserializeManifest(json);
}
catch (InvalidDataException)
{
return Errors.Themes.ThemeArchiveNotReadable;
}
catch (IOException)
{
return Errors.Themes.ThemeFilesUnreadable;
}
}
/// <summary>
/// Deletes the stored files of a theme pack.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> DeleteAsync(string themeId, CancellationToken cancellationToken)
{
await _mutationGate.WaitAsync(cancellationToken);
try
{
string themePath = ResolveThemePath(themeId);
if (Directory.Exists(themePath))
Directory.Delete(themePath, recursive: true);
return Result.Success;
}
finally
{
_mutationGate.Release();
}
}
/// <summary>
/// Loads the manifest of an installed theme pack from its storage location.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
public async Task<Result<ThemeManifestDto>> LoadManifestAsync(string themeId, CancellationToken cancellationToken)
{
string themePath = ResolveThemePath(themeId);
if (!Directory.Exists(themePath))
return Errors.Themes.ThemeFilesUnreadable;
return await Task.FromResult(LoadManifestFromDirectory(themePath));
}
/// <summary>
/// Gets the sanitized content of the template selected by a page key, falling back to the default template when the key is missing.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key that selects the template.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the template content, or an error.</returns>
public async Task<Result<string>> GetTemplateAsync(string themeId, string pageKey, CancellationToken cancellationToken)
{
Result<ThemeManifestDto> manifestResult = await LoadManifestAsync(themeId, cancellationToken);
if (manifestResult.IsFailure)
return manifestResult.Errors;
ThemeManifestDto manifest = manifestResult.Value;
string themePath = ResolveThemePath(themeId);
string? templatePath = manifest.Templates.TryGetValue(pageKey, out string? explicitPath)
? explicitPath
: ResolveMirroredTemplatePath(themePath, pageKey);
templatePath ??= manifest.Templates["default"]; // the manifest validation guarantees a default template
Result<string> fullPathResult = ResolveContainedPath(themePath, templatePath);
if (fullPathResult.IsFailure)
return fullPathResult.Errors;
if (!File.Exists(fullPathResult.Value))
return Errors.Themes.ThemeFilesUnreadable;
string template = await File.ReadAllTextAsync(fullPathResult.Value, cancellationToken);
return template;
}
/// <summary>
/// Resolves the mirrored template path of a page key, walking up the scopes of the path when the exact mirror does not exist.
/// </summary>
/// <param name="themePath">The absolute path of the theme pack directory.</param>
/// <param name="pageKey">The page key that selects the template.</param>
/// <returns>The mirrored template path, or <see langword="null"/> when no mirrored template exists.</returns>
private static string? ResolveMirroredTemplatePath(string themePath, string pageKey)
{
string? candidate = pageKey;
while (candidate is not null)
{
// normalize the mirrored candidate so that malicious page keys cannot escape the theme pack
Result<string> normalizedResult = NormalizeRelativePath($"templates/{candidate}.html");
if (normalizedResult.IsSuccess)
{
Result<string> fullPathResult = ResolveContainedPath(themePath, normalizedResult.Value);
if (fullPathResult.IsSuccess && File.Exists(fullPathResult.Value))
return normalizedResult.Value;
}
int lastSlash = candidate.LastIndexOf('/');
candidate = lastSlash < 0 ? null : candidate[..lastSlash];
}
return null;
}
/// <summary>
/// Gets a theme asset file.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="assetPath">The asset path relative to the theme pack root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the asset, or an error.</returns>
public async Task<Result<ThemeAssetDto>> GetAssetAsync(string themeId, string assetPath, CancellationToken cancellationToken)
{
Result<string> normalizedResult = NormalizeRelativePath(assetPath);
if (normalizedResult.IsFailure)
return normalizedResult.Errors;
string normalizedPath = normalizedResult.Value;
if (!normalizedPath.StartsWith("assets/", StringComparison.Ordinal))
return PackageInvalid("The requested asset is not located under the assets directory.");
Result<string> fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), normalizedPath);
if (fullPathResult.IsFailure)
return fullPathResult.Errors;
if (!File.Exists(fullPathResult.Value))
return Errors.Themes.ThemeFilesUnreadable;
byte[] bytes = await File.ReadAllBytesAsync(fullPathResult.Value, cancellationToken);
return new ThemeAssetDto(bytes, ThemeMimeTypes.GetMimeType(fullPathResult.Value));
}
/// <summary>
/// Builds a downloadable ZIP archive of an installed theme pack.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the archive, or an error.</returns>
public async Task<Result<ThemeArchiveDto>> BuildArchiveAsync(string themeId, CancellationToken cancellationToken)
{
string themePath = ResolveThemePath(themeId);
if (!Directory.Exists(themePath))
return Errors.Themes.ThemeFilesUnreadable;
using MemoryStream output = new();
using (ZipArchive archive = new(output, ZipArchiveMode.Create, leaveOpen: true))
{
foreach (string filePath in Directory.EnumerateFiles(themePath, "*", SearchOption.AllDirectories).OrderBy(path => path, StringComparer.Ordinal))
{
string relativePath = Path.GetRelativePath(themePath, filePath).Replace(Path.DirectorySeparatorChar, '/');
ZipArchiveEntry entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal);
await using FileStream input = File.OpenRead(filePath);
await using Stream outputStream = entry.Open();
await input.CopyToAsync(outputStream, cancellationToken);
}
}
return new ThemeArchiveDto(output.ToArray(), $"{themeId}.zip", "application/zip");
}
/// <summary>
/// Restores the files of a bundled theme from its shipped archive, used when the stored files were removed externally.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken)
{
foreach (string archivePath in GetBundledThemeArchivePaths())
{
Result<ThemeManifestDto> manifestResult = await ReadManifestFromArchiveAsync(archivePath, cancellationToken);
if (manifestResult.IsFailure)
continue;
if (!string.Equals(manifestResult.Value.Id, themeId, StringComparison.OrdinalIgnoreCase))
continue;
await using FileStream archive = File.OpenRead(archivePath);
Result<ThemeManifestDto> installResult = await InstallAsync(archive, cancellationToken);
if (installResult.IsFailure)
return installResult.Errors;
return Result.Success;
}
return Errors.Themes.ThemeFilesUnreadable;
}
/// <summary>
/// Copies the source archive to the staging directory while enforcing the maximum archive size.
/// </summary>
/// <param name="source">The archive stream to copy.</param>
/// <param name="destinationPath">The temporary file to copy the archive into.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> CopyArchiveWithLimitAsync(Stream source, string destinationPath, CancellationToken cancellationToken)
{
await using FileStream destination = new(destinationPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 64 * 1024, useAsync: true);
byte[] buffer = new byte[64 * 1024];
long totalBytes = 0;
while (true)
{
int read = await source.ReadAsync(buffer.AsMemory(), cancellationToken);
if (read == 0)
break;
totalBytes += read;
if (totalBytes > _options.MaxArchiveBytes)
return Error.Validation(code: "Theme.Archive.TooLarge", description: $"The theme archive exceeds the {_options.MaxArchiveBytes / 1024 / 1024} MB limit.");
await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
}
if (totalBytes == 0)
return PackageInvalid("The uploaded theme archive is empty.");
return Result.Success;
}
/// <summary>
/// Extracts a staged theme archive into the staging extraction directory after validating its entries.
/// </summary>
/// <param name="archivePath">The path of the staged ZIP archive.</param>
/// <param name="extractionPath">The directory the archive is extracted into.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private async Task<Result<Success>> ExtractArchiveAsync(string archivePath, string extractionPath, CancellationToken cancellationToken)
{
using ZipArchive archive = ZipFile.OpenRead(archivePath);
if (archive.Entries.Count == 0)
return PackageInvalid("The theme archive contains no files.");
if (archive.Entries.Count > _options.MaxEntries)
return Error.Validation(code: "Theme.Archive.TooManyEntries", description: $"The theme archive contains more than {_options.MaxEntries} entries.");
HashSet<string> seenPaths = new(StringComparer.OrdinalIgnoreCase);
long expandedBytes = 0;
foreach (ZipArchiveEntry entry in archive.Entries)
{
cancellationToken.ThrowIfCancellationRequested();
int unixFileType = (entry.ExternalAttributes >> 16) & 0xF000;
if (unixFileType == 0xA000)
return PackageInvalid("Symbolic links are not allowed in theme archives.");
Result<string> normalizedPathResult = NormalizeRelativePath(entry.FullName, allowTrailingSlash: true);
if (normalizedPathResult.IsFailure)
return normalizedPathResult.Errors;
string normalizedPath = normalizedPathResult.Value;
if (!seenPaths.Add(normalizedPath))
return PackageInvalid($"The archive contains a duplicate path: {normalizedPath}");
bool isDirectory = entry.FullName.EndsWith('/') || string.IsNullOrEmpty(entry.Name);
if (isDirectory)
{
Result<Success> directoryValidationResult = ValidatePackageDirectory(normalizedPath);
if (directoryValidationResult.IsFailure)
return directoryValidationResult.Errors;
Result<string> directoryPathResult = ResolveContainedPath(extractionPath, normalizedPath);
if (directoryPathResult.IsFailure)
return directoryPathResult.Errors;
Directory.CreateDirectory(directoryPathResult.Value);
continue;
}
Result<Success> fileValidationResult = ValidatePackageFile(normalizedPath);
if (fileValidationResult.IsFailure)
return fileValidationResult.Errors;
if (entry.Length > _options.MaxSingleFileBytes)
return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large.");
// guard the total decompressed size, so a tiny archive cannot expand into a decompression bomb
expandedBytes += entry.Length;
if (expandedBytes > _options.MaxExpandedBytes)
return Error.Validation(code: "Theme.Archive.ExpandedTooLarge", description: "The expanded theme archive is too large.");
Result<string> outputPathResult = ResolveContainedPath(extractionPath, normalizedPath);
if (outputPathResult.IsFailure)
return outputPathResult.Errors;
string outputPath = outputPathResult.Value;
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
await using Stream input = entry.Open();
await using FileStream output = new(outputPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 64 * 1024, useAsync: true);
byte[] buffer = new byte[64 * 1024];
long entryBytes = 0;
while (true)
{
int read = await input.ReadAsync(buffer.AsMemory(), cancellationToken);
if (read == 0)
break;
// enforce the per-file limit while streaming, because the declared entry size is not trustworthy
entryBytes += read;
if (entryBytes > _options.MaxSingleFileBytes)
return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large.");
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
}
}
if (!File.Exists(Path.Combine(extractionPath, MANIFEST_FILE_NAME)))
return PackageInvalid("The archive must contain theme.json at its root.");
return Result.Success;
}
/// <summary>
/// Loads and validates the manifest of a theme pack from its directory.
/// </summary>
/// <param name="themeRoot">The absolute path of the theme pack directory.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
private static Result<ThemeManifestDto> LoadManifestFromDirectory(string themeRoot)
{
string manifestPath = Path.Combine(themeRoot, MANIFEST_FILE_NAME);
if (!File.Exists(manifestPath))
return PackageInvalid("The theme is missing theme.json.");
if (new FileInfo(manifestPath).Length > MAX_MANIFEST_BYTES)
return Error.Validation(code: "Theme.Manifest.TooLarge", description: "theme.json exceeds the 64 KB limit.");
string json;
ThemeManifestDto? manifest;
try
{
json = File.ReadAllText(manifestPath);
manifest = JsonSerializer.Deserialize<ThemeManifestDto>(json, s_manifestJsonOptions);
}
catch (JsonException)
{
return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json is not valid JSON.");
}
catch (IOException)
{
return Errors.Themes.ThemeFilesUnreadable;
}
if (manifest is null)
return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json contains no manifest object.");
Result<Success> validationResult = ValidateManifest(themeRoot, manifest);
if (validationResult.IsFailure)
return validationResult.Errors;
return manifest;
}
/// <summary>
/// Deserializes a theme pack manifest from its JSON content.
/// </summary>
/// <param name="json">The JSON content of the manifest.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the parsed manifest, or an error.</returns>
private static Result<ThemeManifestDto> DeserializeManifest(string json)
{
ThemeManifestDto? manifest;
try
{
manifest = JsonSerializer.Deserialize<ThemeManifestDto>(json, s_manifestJsonOptions);
}
catch (JsonException)
{
return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json is not valid JSON.");
}
if (manifest is null)
return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json contains no manifest object.");
return manifest;
}
/// <summary>
/// Validates the manifest fields and template mappings, normalizing the referenced paths.
/// </summary>
/// <param name="themeRoot">The absolute path of the theme pack directory.</param>
/// <param name="manifest">The manifest to validate.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private static Result<Success> ValidateManifest(string themeRoot, ThemeManifestDto manifest)
{
if (manifest.SchemaVersion != 1)
return PackageInvalid("Only theme schemaVersion 1 is supported.");
if (string.IsNullOrWhiteSpace(manifest.Id) || !s_themeIdPattern.IsMatch(manifest.Id) || manifest.Id.Length > 64)
return PackageInvalid("Theme id must be a lowercase kebab-case value up to 64 characters.");
Result<Success> nameResult = ValidateText(manifest.Name, "name", 80);
if (nameResult.IsFailure)
return nameResult;
Result<Success> descriptionResult = ValidateText(manifest.Description, "description", 300);
if (descriptionResult.IsFailure)
return descriptionResult;
Result<Success> authorResult = ValidateText(manifest.Author, "author", 80);
if (authorResult.IsFailure)
return authorResult;
Result<Success> versionResult = ValidateText(manifest.Version, "version", 40);
if (versionResult.IsFailure)
return versionResult;
if (!s_versionPattern.IsMatch(manifest.Version))
return PackageInvalid("Theme version must use semantic version form, for example 1.0.0.");
if (manifest.Templates is null || manifest.Templates.Count == 0 || manifest.Templates.Count > 32)
return PackageInvalid("A theme must declare between 1 and 32 templates.");
Dictionary<string, string> normalizedTemplates = new(StringComparer.OrdinalIgnoreCase);
foreach ((string key, string path) in manifest.Templates)
{
if (!s_templateKeyPattern.IsMatch(key) || key.Length > 40)
return PackageInvalid($"Template key '{key}' is invalid.");
Result<string> normalizedPathResult = NormalizeRelativePath(path);
if (normalizedPathResult.IsFailure)
return normalizedPathResult.Errors;
string normalizedPath = normalizedPathResult.Value;
if (!normalizedPath.StartsWith("templates/", StringComparison.Ordinal))
return PackageInvalid($"Template '{key}' must point to a file under templates/.");
Result<string> fullTemplatePathResult = ResolveContainedPath(themeRoot, normalizedPath);
if (fullTemplatePathResult.IsFailure)
return fullTemplatePathResult.Errors;
if (!File.Exists(fullTemplatePathResult.Value))
return PackageInvalid($"Template '{key}' points to missing file '{normalizedPath}'.");
normalizedTemplates[key] = normalizedPath;
}
if (!normalizedTemplates.ContainsKey("default"))
return PackageInvalid("The manifest must define a 'default' template fallback.");
manifest.Templates = normalizedTemplates;
if (!string.IsNullOrWhiteSpace(manifest.Preview))
{
Result<string> previewPathResult = NormalizeRelativePath(manifest.Preview);
if (previewPathResult.IsFailure)
return previewPathResult.Errors;
string previewPath = previewPathResult.Value;
Result<string> fullPreviewPathResult = ResolveContainedPath(themeRoot, previewPath);
if (fullPreviewPathResult.IsFailure)
return fullPreviewPathResult.Errors;
if (!previewPath.StartsWith("assets/", StringComparison.Ordinal) || !File.Exists(fullPreviewPathResult.Value))
return PackageInvalid("The preview must reference an existing asset file.");
manifest.Preview = previewPath;
}
return Result.Success;
}
/// <summary>
/// Validates that a package file resides in the manifest, template or asset locations.
/// </summary>
/// <param name="normalizedPath">The normalized package-relative path of the file.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private static Result<Success> ValidatePackageFile(string normalizedPath)
{
if (string.Equals(normalizedPath, MANIFEST_FILE_NAME, StringComparison.Ordinal))
return Result.Success;
if (normalizedPath.StartsWith("templates/", StringComparison.Ordinal))
return Result.Success;
if (normalizedPath.StartsWith("assets/", StringComparison.Ordinal))
return Result.Success;
return PackageInvalid($"Theme file '{normalizedPath}' is outside the allowed manifest, template, or asset locations.");
}
/// <summary>
/// Validates that a package directory resides under the templates or assets locations.
/// </summary>
/// <param name="normalizedPath">The normalized package-relative path of the directory.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private static Result<Success> ValidatePackageDirectory(string normalizedPath)
{
if (normalizedPath.Equals("templates", StringComparison.Ordinal) ||
normalizedPath.StartsWith("templates/", StringComparison.Ordinal) ||
normalizedPath.Equals("assets", StringComparison.Ordinal) ||
normalizedPath.StartsWith("assets/", StringComparison.Ordinal))
return Result.Success;
return PackageInvalid($"Theme directory '{normalizedPath}' is not allowed.");
}
/// <summary>
/// Normalizes a package-relative path, rejecting paths that escape the package or violate the path rules.
/// </summary>
/// <param name="path">The package-relative path to normalize.</param>
/// <param name="allowTrailingSlash">Whether a trailing slash, used for directory entries, is permitted.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the normalized path, or an error.</returns>
private static Result<string> NormalizeRelativePath(string path, bool allowTrailingSlash = false)
{
if (string.IsNullOrWhiteSpace(path) || path.Length > 240 || path.Contains('\\') || path.Contains('\0') || path.StartsWith('/') || path.Contains("//"))
return PackageInvalid("The theme contains an invalid path.");
string candidate = allowTrailingSlash ? path.TrimEnd('/') : path;
if (string.IsNullOrWhiteSpace(candidate))
return PackageInvalid("The theme contains an invalid path.");
string[] segments = candidate.Split('/');
if (segments.Length > 12)
return PackageInvalid("A theme path is nested too deeply.");
foreach (string segment in segments)
if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.') || !s_pathSegmentPattern.IsMatch(segment))
return PackageInvalid($"Theme path segment '{segment}' is invalid.");
return string.Join('/', segments);
}
/// <summary>
/// Resolves a package-relative path against a package root, rejecting paths that escape the root.
/// </summary>
/// <param name="root">The absolute path of the package root.</param>
/// <param name="relativePath">The package-relative path to resolve.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the absolute path, or an error.</returns>
private static Result<string> ResolveContainedPath(string root, string relativePath)
{
string normalized = relativePath.Replace('/', Path.DirectorySeparatorChar);
string rootPath = Path.GetFullPath(root);
string candidate = Path.GetFullPath(Path.Combine(rootPath, normalized));
string rootWithSeparator = rootPath.EndsWith(Path.DirectorySeparatorChar) ? rootPath : rootPath + Path.DirectorySeparatorChar;
StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
if (!candidate.StartsWith(rootWithSeparator, comparison))
return PackageInvalid("A theme path escapes its package root.");
return candidate;
}
/// <summary>
/// Validates a manifest text field: required, within the maximum length and without control characters.
/// </summary>
/// <param name="value">The field value to validate.</param>
/// <param name="fieldName">The name of the manifest field, used in error messages.</param>
/// <param name="maxLength">The maximum allowed length of the field.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
private static Result<Success> ValidateText(string value, string fieldName, int maxLength)
{
if (string.IsNullOrWhiteSpace(value) || value.Length > maxLength || value.Any(char.IsControl))
return PackageInvalid($"Theme manifest field '{fieldName}' is required and must be at most {maxLength} characters.");
return Result.Success;
}
/// <summary>
/// Creates a validation error for an invalid theme pack.
/// </summary>
/// <param name="description">The human-readable description of the package error.</param>
/// <returns>The validation error describing the invalid theme pack.</returns>
private static Error PackageInvalid(string description)
{
return Error.Validation(code: "Theme.Package.Invalid", description: description);
}
/// <summary>
/// Resolves the storage path of a theme pack directory for a theme identifier.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <returns>The absolute path of the theme pack directory.</returns>
private string ResolveThemePath(string themeId)
{
return Path.Combine(_storageRoot, themeId);
}
/// <summary>
/// Removes stale files and directories left over in the staging directory.
/// </summary>
private void CleanStagingDirectory()
{
foreach (string path in Directory.EnumerateFileSystemEntries(_stagingRoot))
{
try
{
if (Directory.Exists(path))
Directory.Delete(path, recursive: true);
else
File.Delete(path);
}
catch (IOException exception)
{
_logger.LogDebug(exception, "Could not remove stale theme staging path {StagingPath}.", path);
}
}
}
/// <summary>
/// Moves an extracted theme pack into the storage directory, replacing an existing pack with the same manifest id.
/// </summary>
/// <remarks>
/// The move is retried on transient file system errors, because a concurrent process may briefly hold a file of the
/// destination directory open (for example another host serving a template while this installation replaces the pack).
/// Without the retry, that transient contention aborts the install and, when triggered by the startup job, crashes the
/// whole host.
/// </remarks>
/// <param name="extractionPath">The directory of the extracted theme pack in the staging area.</param>
/// <param name="destination">The storage directory the theme pack is moved to.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private static async Task SwapIntoDestinationAsync(string extractionPath, string destination, CancellationToken cancellationToken)
{
const int maxAttempts = 10;
for (int attempt = 1; ; attempt++)
{
try
{
if (Directory.Exists(destination))
Directory.Delete(destination, recursive: true);
Directory.Move(extractionPath, destination);
return;
}
catch (IOException) when (attempt < maxAttempts)
{
await Task.Delay(100 * attempt, cancellationToken);
}
}
}
/// <summary>
/// Resolves a configured path to an absolute path, rooted against the base directory when relative.
/// </summary>
/// <param name="basePath">The base directory the path is rooted against when relative.</param>
/// <param name="configuredPath">The path from the configuration.</param>
/// <returns>The absolute path.</returns>
private static string ResolvePath(string basePath, string configuredPath)
{
return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(basePath, configuredPath));
}
}
@@ -6,8 +6,14 @@
"PluginsSettings": {
"Directory": "plugins"
},
"CommonSettings": {
"Theme": "LuminaDark"
"ThemeEngine": {
"StoragePath": "themes",
"BundledThemesPath": "themes/bundled",
"DefaultThemeId": "lumina-default",
"MaxArchiveBytes": 8388608,
"MaxExpandedBytes": 25165824,
"MaxSingleFileBytes": 6291456,
"MaxEntries": 250
},
"ConnectionStrings": {
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"
@@ -0,0 +1,21 @@
namespace Lumina.Presentation.Api.Common.Routes.Themes;
/// <summary>
/// Class for the collection of the theme routes of the API.
/// </summary>
public static partial class ApiRoutes
{
public static class Themes
{
public const string GET_THEMES = "/themes";
public const string INSTALL_THEME = "/themes";
public const string GET_THEME_SETTINGS = "/themes/settings";
public const string GET_CURRENT_THEME = "/themes/current";
public const string SET_CURRENT_THEME = "/themes/current";
public const string GET_THEME_TEMPLATE = "/themes/{themeId}/templates/{*pageKey}";
public const string GET_THEME_ASSET = "/themes/{themeId}/assets/{*assetPath}";
public const string GET_THEME_ARCHIVE = "/themes/{themeId}/archive";
public const string RESTORE_THEME = "/themes/{themeId}/restore";
public const string DELETE_THEME = "/themes/{themeId}";
}
}
@@ -2,7 +2,6 @@
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -12,7 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.Get
/// Class used for providing a textual description for the <see cref="GetDrivesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDrivesEndpointSummary : Summary<GetDrivesEndpoint>
public class GetDrivesEndpointSummary : Summary<GetDrivesEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesEndpointSummary"/> class.
@@ -11,7 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem
/// Class used for providing a textual description for the <see cref="GetTypeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTypeEndpointSummary : Summary<GetTypeEndpoint, FileSystemTypeResponse>
public class GetTypeEndpointSummary : Summary<GetTypeEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTypeEndpointSummary"/> class.
@@ -10,7 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa
/// Class used for providing a textual description for the <see cref="GetPathSeparatorEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPathSeparatorEndpointSummary : Summary<GetPathSeparatorEndpoint>
public class GetPathSeparatorEndpointSummary : Summary<GetPathSeparatorEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointSummary"/> class.
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using System;
using System.Collections.Generic;
@@ -12,7 +13,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary;
/// Class used for providing a textual description for the <see cref="ScanLibraryEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, EmptyRequest>
public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, ScanLibraryRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryEndpointSummary"/> class.
@@ -22,6 +23,12 @@ public class ScanLibraryEndpointSummary : Summary<ScanLibraryEndpoint, EmptyRequ
Summary = "Triggers the scan of a media library.";
Description = "Starts the scanning process of a media library of a user.";
ExampleRequest = new ScanLibraryRequest(
Id: Guid.NewGuid()
);
RequestParam(r => r.Id, "The unique identifier of the media library to be scanned. Required.");
Response(200, "The media library scan was successfully started.",
example: new MediaLibraryScanResponse(
ScanId: Guid.NewGuid(),
@@ -3,9 +3,11 @@ using FastEndpoints;
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -17,7 +19,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B
/// Class used for providing a textual description for the <see cref="GetBooksEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
public class GetBooksEndpointSummary : Summary<GetBooksEndpoint, GetBooksRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointSummary"/> class.
@@ -27,6 +29,21 @@ public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
Summary = "Retrieves the list of books.";
Description = "Returns the entire list of books.";
ExampleRequest = new GetBooksRequest(
LibraryId: Guid.NewGuid(),
CurrentPage: 1,
PerPage: 48,
SearchTerm: "fellowship",
SortBy: "title",
SortOrder: SortOrder.Ascending
);
RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required.");
RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional.");
RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional.");
RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional.");
RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional.");
RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional.");
Response(200, "The paginated list of books is returned.",
example: new PaginatedResponse<BookResponse>
@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -13,7 +15,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B
/// Class used for providing a textual description for the <see cref="GetBooksLiteEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint>
public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint, GetBooksLiteRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksLiteEndpointSummary"/> class.
@@ -23,6 +25,26 @@ public class GetBooksLiteEndpointSummary : Summary<GetBooksLiteEndpoint>
Summary = "Retrieves the lightweight details of the list of books.";
Description = "Returns a paginated list of the lightweight details of the books of the media library, suitable for card-style navigation.";
ExampleRequest = new GetBooksLiteRequest(
LibraryId: Guid.NewGuid(),
CurrentPage: 1,
PerPage: 48,
SearchTerm: "fellowship",
FilterAlphaKey: "f",
IgnoreThePrefixForAlphaPicker: true,
SortBy: "title",
SortOrder: SortOrder.Ascending
);
RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required.");
RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional.");
RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional.");
RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional.");
RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional.");
RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required.");
RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional.");
RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional.");
Response(200, "The paginated list of lightweight book details is returned.",
example: new PaginatedResponse<BookLiteResponse>
{
@@ -10,7 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint>
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpointSummary"/> class.
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using Lumina.Contracts.Requests.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.DeleteTheme;
/// <summary>
/// API endpoint for the <c>/themes/{themeId}</c> route.
/// </summary>
public class DeleteThemeEndpoint : BaseEndpoint<DeleteThemeRequest, IResult>
{
private readonly ICommandHandler<DeleteThemeCommand, Result<Success>> _deleteThemeCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeEndpoint"/> class.
/// </summary>
/// <param name="deleteThemeCommandHandler">Injected service for handling delete theme commands.</param>
public DeleteThemeEndpoint(ICommandHandler<DeleteThemeCommand, Result<Success>> deleteThemeCommandHandler)
{
_deleteThemeCommandHandler = deleteThemeCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.DELETE);
Routes(ApiRoutes.Themes.DELETE_THEME);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Deletes the theme identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(DeleteThemeRequest request, CancellationToken cancellationToken)
{
Result<Success> result = await _deleteThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Themes;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.DeleteTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="DeleteThemeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteThemeEndpointSummary : Summary<DeleteThemeEndpoint, DeleteThemeRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeEndpointSummary"/> class.
/// </summary>
public DeleteThemeEndpointSummary()
{
Summary = "Deletes a theme.";
Description = "Deletes the theme identified by the request, switching to another available theme when the deleted theme was the active one.";
ExampleRequest = new DeleteThemeRequest(
ThemeId: "neon-grid"
);
RequestParam(r => r.ThemeId, "The manifest id of the theme to delete. Required.");
Response(204, "The theme was successfully deleted.");
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/themes/{themeId}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/themes/{themeId}"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/themes/{themeId}"
}
}
);
Response(403, "The request failed because the user is not an Admin, the theme is the last bundled theme, or the active theme cannot be replaced.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/themes/{themeId}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "LastBundledThemeCannotBeDeleted",
instance = "/api/v1/themes/{themeId}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "ThemeCannotBeDeleted",
instance = "/api/v1/themes/{themeId}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(404, "The request failed because the provided theme does not exist.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
title = "General.NotFound",
status = 404,
detail = "ThemeNotFound",
instance = "/api/v1/themes/{themeId}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/themes/{themeId}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"ThemeIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme;
/// <summary>
/// API endpoint for the <c>/themes</c> route.
/// </summary>
public class InstallThemeEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
private readonly ICommandHandler<InstallThemeCommand, Result<ThemeResponse>> _installThemeCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeEndpoint"/> class.
/// </summary>
/// <param name="installThemeCommandHandler">Injected service for handling install theme commands.</param>
public InstallThemeEndpoint(ICommandHandler<InstallThemeCommand, Result<ThemeResponse>> installThemeCommandHandler)
{
_installThemeCommandHandler = installThemeCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.POST);
Routes(ApiRoutes.Themes.INSTALL_THEME);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Installs the theme pack uploaded in the multipart form of the request.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// a multipart body without any part cannot be parsed as a form, so a malformed upload is treated as a missing archive
IFormFile? archive = null;
if (HttpContext.Request.HasFormContentType)
{
try
{
archive = HttpContext.Request.Form.Files.FirstOrDefault();
}
catch (InvalidDataException)
{
archive = null;
}
}
InstallThemeCommand command = new(archive?.OpenReadStream(), archive?.FileName);
Result<ThemeResponse> result = await _installThemeCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,125 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="InstallThemeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class InstallThemeEndpointSummary : Summary<InstallThemeEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeEndpointSummary"/> class.
/// </summary>
public InstallThemeEndpointSummary()
{
Summary = "Installs a theme pack.";
Description = "Installs the theme pack uploaded in the multipart form of the request, replacing the files of an existing theme with the same manifest id.";
Response(200, "The theme was successfully installed.",
example: new ThemeResponse(
Id: Guid.NewGuid(),
ThemeId: "lumina-default",
Name: "Lumina Default",
Description: "A clean, readable theme.",
Author: "Lumina Team",
Version: "1.2.0",
PreviewPath: "preview.png",
InstallSource: ThemeInstallSource.Uploaded,
IsCurrent: null,
InstalledAtUtc: DateTime.UtcNow,
IsDeleted: false
));
Response(401, "Authentication required.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "You are not authorized",
instance = "/api/v1/themes"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "Invalid token: The token expired at '01/01/2024 01:00:00'",
instance = "/api/v1/themes"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/themes"
}
}
);
Response(403, "The request failed because the user is not an Admin, or the uploaded theme pack is not readable.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/themes",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "ThemeArchiveNotReadable",
instance = "/api/v1/themes",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "ThemeFilesUnreadable",
instance = "/api/v1/themes",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/themes",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"ThemeArchiveCannotBeNull"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme;
using Lumina.Contracts.Requests.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Common.Routes.Themes;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme;
/// <summary>
/// API endpoint for the <c>/themes/{themeId}/restore</c> route.
/// </summary>
public class RestoreThemeEndpoint : BaseEndpoint<RestoreThemeRequest, IResult>
{
private readonly ICommandHandler<RestoreThemeCommand, Result<Success>> _restoreThemeCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreThemeEndpoint"/> class.
/// </summary>
/// <param name="restoreThemeCommandHandler">Injected service for handling restore theme commands.</param>
public RestoreThemeEndpoint(ICommandHandler<RestoreThemeCommand, Result<Success>> restoreThemeCommandHandler)
{
_restoreThemeCommandHandler = restoreThemeCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.POST);
Routes(ApiRoutes.Themes.RESTORE_THEME);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Restores the soft deleted bundled theme identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme to restore.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RestoreThemeRequest request, CancellationToken cancellationToken)
{
Result<Success> result = await _restoreThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.NoContent(), Problem);
}
}
Loaded 100 of 386 files, more files were not shown because too many files have changed in this diff. Show more