Adds the server-side theme repository and reworks the web theme engine onto it

This commit is contained in:
BinaryAlley committed 2026-08-19 22:50:07 -07:00
1 parent 85928f7c3c
commit bf8faba24d
136 files changed
+6942 -1197

No files matched your search

@@ -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; }
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
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>
{
/// <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,103 @@
#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 a value indicating whether theme templates may contain script elements and theme assets may include script files.
/// </summary>
bool AllowThemeScripts { get; }
/// <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>
/// 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,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Contracts.Requests.Themes;
using System.IO;
#endregion
namespace Lumina.Application.Common.Mapping.Themes;
/// <summary>
/// Extension methods for converting <see cref="InstallThemeRequest"/>.
/// </summary>
public static class InstallThemeRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="InstallThemeCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="archive">The ZIP archive stream of the theme pack.</param>
/// <param name="fileName">The file name of the uploaded archive.</param>
/// <returns>The converted command.</returns>
public static InstallThemeCommand ToCommand(this InstallThemeRequest request, Stream? archive, string? fileName)
{
return new InstallThemeCommand(archive, fileName);
}
}
@@ -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,32 @@
#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);
}
}
@@ -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,129 @@
#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);
}
theme.IsDeleted = true;
theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
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,148 @@
#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,
IsDeleted = existingTheme.IsDeleted,
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.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.AllowThemeScripts, _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,54 @@
#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;
return Result.From<IReadOnlyList<ThemeResponse>>([.. getThemesResult.Value
.Where(theme => !theme.IsDeleted)
.OrderByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled)
.ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)
.Select(theme => theme.ToResponse())]);
}
}
@@ -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,12 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Themes;
/// <summary>
/// Represents a request to install a theme pack, sent as a multipart form whose single file field contains the theme archive.
/// </summary>
[DebuggerDisplay("InstallThemeRequest")]
public record InstallThemeRequest;
@@ -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
);
@@ -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,34 @@
#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>
[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
);
@@ -0,0 +1,19 @@
#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="AllowThemeScripts">Whether theme templates may contain script elements and theme assets may include script files.</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,
bool AllowThemeScripts,
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
);
@@ -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);
}
}
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");
}
}
}
@@ -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")
@@ -0,0 +1,97 @@
#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.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>
/// 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,25 @@
#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 ThemeArchiveNotReadable => Error.Failure(description: nameof(ThemeArchiveNotReadable));
public static Error ThemeFilesUnreadable => Error.Failure(description: nameof(ThemeFilesUnreadable));
public static Error ThemeNotAvailable => Error.Failure(description: nameof(ThemeNotAvailable));
}
}
@@ -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,22 @@ 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.
/// Gets or sets a value indicating whether script elements in theme templates and script files in theme assets are allowed to be served.
/// </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,105 @@
#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
HashSet<string> knownThemeIds = [.. getThemesResult.Value.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;
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);
}
await unitOfWork.SaveChangesAsync(stoppingToken);
}
}
@@ -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,787 @@
#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.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);
// strips every script element from a template, both the inline content and the src attribute variants,
// so that no script bundled in a theme is executed in any client when scripts are disabled
private static readonly Regex s_scriptElementPattern = new(
"<script\\b[^>]*>[\\s\\S]*?</script\\s*>",
RegexOptions.Compiled | RegexOptions.IgnoreCase | 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;
private readonly SemaphoreSlim _mutationGate = new(1, 1);
/// <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);
}
/// <summary>
/// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files.
/// </summary>
public bool AllowThemeScripts => _options.AllowThemeScripts;
/// <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>
/// 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);
if (Directory.Exists(destination))
Directory.Delete(destination, recursive: true);
Directory.Move(extractionPath, destination);
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;
if (!manifest.Templates.TryGetValue(pageKey, out string? templatePath))
templatePath = manifest.Templates["default"]; // the manifest validation guarantees a default template
Result<string> fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), templatePath);
if (fullPathResult.IsFailure)
return fullPathResult.Errors;
if (!File.Exists(fullPathResult.Value))
return Errors.Themes.ThemeFilesUnreadable;
string template = await File.ReadAllTextAsync(fullPathResult.Value, cancellationToken);
if (!AllowThemeScripts)
template = StripScriptElements(template);
return template;
}
/// <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.");
// scripts in theme assets are gated globally: when disabled, script files are not served at all
if (!AllowThemeScripts && string.Equals(Path.GetExtension(normalizedPath), ".js", StringComparison.OrdinalIgnoreCase))
return Errors.Themes.ThemeFilesUnreadable;
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.");
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;
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>
/// Removes every script element from a theme template, so that no script bundled in the theme runs when scripts are disabled.
/// </summary>
/// <param name="template">The template content to strip script elements from.</param>
/// <returns>The template content without script elements.</returns>
private static string StripScriptElements(string template)
{
return s_scriptElementPattern.Replace(template, string.Empty);
}
/// <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>
/// 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,15 @@
"PluginsSettings": {
"Directory": "plugins"
},
"CommonSettings": {
"Theme": "LuminaDark"
"ThemeEngine": {
"StoragePath": "themes",
"BundledThemesPath": "themes/bundled",
"DefaultThemeId": "lumina-default",
"MaxArchiveBytes": 8388608,
"MaxExpandedBytes": 25165824,
"MaxSingleFileBytes": 6291456,
"MaxEntries": 250,
"AllowThemeScripts": false
},
"ConnectionStrings": {
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"
@@ -0,0 +1,20 @@
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 DELETE_THEME = "/themes/{themeId}";
}
}
@@ -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,56 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using Lumina.Contracts.Requests.Themes;
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.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<InstallThemeRequest, 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(InstallThemeRequest request, CancellationToken cancellationToken)
{
IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault();
Result<ThemeResponse> result = await _installThemeCommandHandler.HandleAsync(request.ToCommand(archive?.OpenReadStream(), archive?.FileName), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,125 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Themes;
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, InstallThemeRequest>
{
/// <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
));
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,54 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using Lumina.Contracts.Requests.Themes;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.SetCurrentTheme;
/// <summary>
/// API endpoint for the <c>/themes/current</c> route.
/// </summary>
public class SetCurrentThemeEndpoint : BaseEndpoint<SetCurrentThemeRequest, IResult>
{
private readonly ICommandHandler<SetCurrentThemeCommand, Result<ThemeResponse>> _setCurrentThemeCommandHandler;
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpoint"/> class.
/// </summary>
/// <param name="setCurrentThemeCommandHandler">Injected service for handling set current theme commands.</param>
public SetCurrentThemeEndpoint(ICommandHandler<SetCurrentThemeCommand, Result<ThemeResponse>> setCurrentThemeCommandHandler)
{
_setCurrentThemeCommandHandler = setCurrentThemeCommandHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(FastEndpoints.Http.PUT);
Routes(ApiRoutes.Themes.SET_CURRENT_THEME);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Sets the theme stored in <paramref name="request"/> as the currently active theme.
/// </summary>
/// <param name="request">The request containing the theme to activate.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SetCurrentThemeRequest request, CancellationToken cancellationToken)
{
Result<ThemeResponse> result = await _setCurrentThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,122 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Themes;
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.SetCurrentTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetCurrentThemeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetCurrentThemeEndpointSummary : Summary<SetCurrentThemeEndpoint, SetCurrentThemeRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeEndpointSummary"/> class.
/// </summary>
public SetCurrentThemeEndpointSummary()
{
Summary = "Sets the currently active theme.";
Description = "Sets the theme identified by the request as the currently active theme.";
ExampleRequest = new SetCurrentThemeRequest(
ThemeId: "lumina-default"
);
RequestParam(r => r.ThemeId, "The manifest id of the theme to activate. Required.");
Response(200, "The theme was successfully activated.",
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.Bundled,
IsCurrent: true,
InstalledAtUtc: DateTime.UtcNow
));
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/current"
},
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/current"
},
new
{
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
status = 401,
title = "Unauthorized",
detail = "The token is invalid",
instance = "/api/v1/themes/current"
}
}
);
Response(403, "The request failed because the user is not an Admin.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/themes/current",
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/current",
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/current",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"ThemeIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetCurrentTheme;
/// <summary>
/// API endpoint for the <c>/themes/current</c> route.
/// </summary>
public class GetCurrentThemeEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetCurrentThemeQuery, Result<ThemeResponse>> _getCurrentThemeQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeEndpoint"/> class.
/// </summary>
/// <param name="getCurrentThemeQueryHandler">Injected service for handling get current theme queries.</param>
public GetCurrentThemeEndpoint(IQueryHandler<GetCurrentThemeQuery, Result<ThemeResponse>> getCurrentThemeQueryHandler)
{
_getCurrentThemeQueryHandler = getCurrentThemeQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Themes.GET_CURRENT_THEME);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the currently active theme.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
Result<ThemeResponse> result = await _getCurrentThemeQueryHandler.HandleAsync(new GetCurrentThemeQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetCurrentTheme;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetCurrentThemeEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetCurrentThemeEndpointSummary : Summary<GetCurrentThemeEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeEndpointSummary"/> class.
/// </summary>
public GetCurrentThemeEndpointSummary()
{
Summary = "Retrieves the currently active theme.";
Description = "Retrieves the metadata of the theme that is currently active.";
Response(200, "The currently active theme is returned.",
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.Bundled,
IsCurrent: true,
InstalledAtUtc: DateTime.UtcNow
));
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using Lumina.Contracts.Requests.Themes;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeArchive;
/// <summary>
/// API endpoint for the <c>/themes/{themeId}/archive</c> route.
/// </summary>
public class GetThemeArchiveEndpoint : BaseEndpoint<GetThemeArchiveRequest, IResult>
{
private readonly IQueryHandler<GetThemeArchiveQuery, Result<ThemeArchiveResponse>> _getThemeArchiveQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveEndpoint"/> class.
/// </summary>
/// <param name="getThemeArchiveQueryHandler">Injected service for handling get theme archive queries.</param>
public GetThemeArchiveEndpoint(IQueryHandler<GetThemeArchiveQuery, Result<ThemeArchiveResponse>> getThemeArchiveQueryHandler)
{
_getThemeArchiveQueryHandler = getThemeArchiveQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Themes.GET_THEME_ARCHIVE);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the downloadable archive of the theme identified by <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme to archive.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThemeArchiveRequest request, CancellationToken cancellationToken)
{
Result<ThemeArchiveResponse> result = await _getThemeArchiveQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.File(success.Bytes, success.ContentType, fileDownloadName: success.FileName), Problem);
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeArchive;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThemeArchiveEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeArchiveEndpointSummary : Summary<GetThemeArchiveEndpoint, GetThemeArchiveRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveEndpointSummary"/> class.
/// </summary>
public GetThemeArchiveEndpointSummary()
{
Summary = "Retrieves the archive of a theme.";
Description = "Retrieves the downloadable ZIP archive of an installed theme.";
ExampleRequest = new GetThemeArchiveRequest(
ThemeId: "lumina-default"
);
RequestParam(r => r.ThemeId, "The manifest id of the theme. Required.");
Response(200, "The ZIP archive of the theme is returned.", "application/zip",
example: new ThemeArchiveResponse(
Bytes: [],
FileName: "lumina-default.zip",
ContentType: "application/zip"
));
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}/archive"
},
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}/archive"
},
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}/archive"
}
}
);
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}/archive",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"ThemeIdCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-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}/archive",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using Lumina.Contracts.Requests.Themes;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeAsset;
/// <summary>
/// API endpoint for the <c>/themes/{themeId}/assets/{assetPath}</c> route.
/// </summary>
public class GetThemeAssetEndpoint : BaseEndpoint<GetThemeAssetRequest, IResult>
{
private readonly IQueryHandler<GetThemeAssetQuery, Result<ThemeAssetResponse>> _getThemeAssetQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetEndpoint"/> class.
/// </summary>
/// <param name="getThemeAssetQueryHandler">Injected service for handling get theme asset queries.</param>
public GetThemeAssetEndpoint(IQueryHandler<GetThemeAssetQuery, Result<ThemeAssetResponse>> getThemeAssetQueryHandler)
{
_getThemeAssetQueryHandler = getThemeAssetQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Themes.GET_THEME_ASSET);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the asset of the theme stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme and the path of the asset to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThemeAssetRequest request, CancellationToken cancellationToken)
{
Result<ThemeAssetResponse> result = await _getThemeAssetQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.File(success.Bytes, success.ContentType), Problem);
}
}
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Themes;
using Lumina.Contracts.Responses.Themes;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeAsset;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThemeAssetEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeAssetEndpointSummary : Summary<GetThemeAssetEndpoint, GetThemeAssetRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetEndpointSummary"/> class.
/// </summary>
public GetThemeAssetEndpointSummary()
{
Summary = "Retrieves an asset file of a theme.";
Description = "Retrieves the binary content of an asset file of a theme, with its MIME content type.";
ExampleRequest = new GetThemeAssetRequest(
ThemeId: "lumina-default",
AssetPath: "assets/style.css"
);
RequestParam(r => r.ThemeId, "The manifest id of the theme. Required.");
RequestParam(r => r.AssetPath, "The asset path relative to the theme pack root. Required.");
Response(200, "The asset file of the theme is returned.", "application/octet-stream");
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}/assets/{assetPath}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"ThemeIdCannotBeEmpty",
"ThemeAssetPathCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
Response(403, "The request failed because the stored files of the theme are not readable.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "ThemeFilesUnreadable",
instance = "/api/v1/themes/{themeId}/assets/{assetPath}",
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}/assets/{assetPath}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeSettings;
/// <summary>
/// API endpoint for the <c>/themes/settings</c> route.
/// </summary>
public class GetThemeSettingsEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetThemeSettingsQuery, Result<ThemeSettingsResponse>> _getThemeSettingsQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsEndpoint"/> class.
/// </summary>
/// <param name="getThemeSettingsQueryHandler">Injected service for handling get theme settings queries.</param>
public GetThemeSettingsEndpoint(IQueryHandler<GetThemeSettingsQuery, Result<ThemeSettingsResponse>> getThemeSettingsQueryHandler)
{
_getThemeSettingsQueryHandler = getThemeSettingsQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Themes.GET_THEME_SETTINGS);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the theme engine settings.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
Result<ThemeSettingsResponse> result = await _getThemeSettingsQueryHandler.HandleAsync(new GetThemeSettingsQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeSettings;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThemeSettingsEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeSettingsEndpointSummary : Summary<GetThemeSettingsEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsEndpointSummary"/> class.
/// </summary>
public GetThemeSettingsEndpointSummary()
{
Summary = "Retrieves the theme engine settings.";
Description = "Retrieves the settings of the theme engine, including whether theme scripts are allowed and the maximum archive size.";
Response(200, "The theme engine settings are returned.",
example: new ThemeSettingsResponse(
MaxArchiveBytes: 8388608,
AllowThemeScripts: false,
DefaultThemeId: "lumina-default"
));
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using Lumina.Contracts.Requests.Themes;
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.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate;
/// <summary>
/// API endpoint for the <c>/themes/{themeId}/templates/{pageKey}</c> route.
/// </summary>
public class GetThemeTemplateEndpoint : BaseEndpoint<GetThemeTemplateRequest, IResult>
{
private readonly IQueryHandler<GetThemeTemplateQuery, Result<ThemeTemplateResponse>> _getThemeTemplateQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateEndpoint"/> class.
/// </summary>
/// <param name="getThemeTemplateQueryHandler">Injected service for handling get theme template queries.</param>
public GetThemeTemplateEndpoint(IQueryHandler<GetThemeTemplateQuery, Result<ThemeTemplateResponse>> getThemeTemplateQueryHandler)
{
_getThemeTemplateQueryHandler = getThemeTemplateQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Themes.GET_THEME_TEMPLATE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the template of the theme selected by the page key stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the theme and the page key of the template to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThemeTemplateRequest request, CancellationToken cancellationToken)
{
Result<ThemeTemplateResponse> result = await _getThemeTemplateQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,98 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Themes;
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.Queries.GetThemeTemplate;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThemeTemplateEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemeTemplateEndpointSummary : Summary<GetThemeTemplateEndpoint, GetThemeTemplateRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateEndpointSummary"/> class.
/// </summary>
public GetThemeTemplateEndpointSummary()
{
Summary = "Retrieves the template of a theme.";
Description = "Retrieves the raw template of a theme selected by a page key, after applying the theme engine sanitization.";
ExampleRequest = new GetThemeTemplateRequest(
ThemeId: "lumina-default",
PageKey: "index"
);
RequestParam(r => r.ThemeId, "The manifest id of the theme. Required.");
RequestParam(r => r.PageKey, "The page key that selects the template. Required.");
Response(200, "The template of the theme is returned.",
example: new ThemeTemplateResponse(
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.Bundled,
IsCurrent: true,
InstalledAtUtc: DateTime.UtcNow
),
"<html><body><div class=\"content\">{{content}}</div></body></html>"
));
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}/templates/{pageKey}",
errors = new Dictionary<string, string[]>
{
{
"General.Validation", new[]
{
"ThemeIdCannotBeEmpty",
"PageKeyCannotBeEmpty"
}
}
},
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
}
);
Response(403, "The request failed because the stored files of the theme are not readable.", "application/problem+json",
example: new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "ThemeNotAvailable",
instance = "/api/v1/themes/{themeId}/templates/{pageKey}",
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}/templates/{pageKey}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
}
}
@@ -0,0 +1,53 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Themes.Management.Queries.GetThemes;
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.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemes;
/// <summary>
/// API endpoint for the <c>/themes</c> route.
/// </summary>
public class GetThemesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetThemesQuery, Result<IReadOnlyList<ThemeResponse>>> _getThemesQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpoint"/> class.
/// </summary>
/// <param name="getThemesQueryHandler">Injected service for handling get themes queries.</param>
public GetThemesEndpoint(IQueryHandler<GetThemesQuery, Result<IReadOnlyList<ThemeResponse>>> getThemesQueryHandler)
{
_getThemesQueryHandler = getThemesQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Themes.GET_THEMES);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the list of all the installed themes.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
Result<IReadOnlyList<ThemeResponse>> result = await _getThemesQueryHandler.HandleAsync(new GetThemesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,83 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemes;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThemesEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetThemesEndpointSummary : Summary<GetThemesEndpoint, EmptyRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesEndpointSummary"/> class.
/// </summary>
public GetThemesEndpointSummary()
{
Summary = "Retrieves the installed themes.";
Description = "Retrieves the list of all installed themes.";
Response(200, "The list of installed themes is returned.",
example: new ThemeResponse[] {
new (
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.Bundled,
IsCurrent: true,
InstalledAtUtc: DateTime.UtcNow
),
new (
Id: Guid.NewGuid(),
ThemeId: "neon-grid",
Name: "Neon Grid",
Description: "A dark theme with a neon grid background.",
Author: "Lumina Team",
Version: "0.9.3",
PreviewPath: "preview.jpg",
InstallSource: ThemeInstallSource.Uploaded,
IsCurrent: null,
InstalledAtUtc: DateTime.UtcNow
)
});
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"
}
}
);
}
}
@@ -192,6 +192,34 @@ public class ApiHttpClient : IApiHttpClient
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends a POST request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="fileStream">The stream of the file to upload.</param>
/// <param name="fileName">The name of the file to upload.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
public async Task<TResponse> PostMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default)
{
// the file is streamed as a generic binary part, since the exact content type of the uploaded file is not known
using MultipartFormDataContent form = [];
using StreamContent fileContent = new(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, fieldName, fileName);
using HttpRequestMessage request = new(HttpMethod.Post, endpoint)
{
Content = form
};
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
if (authenticationHeader is not null)
request.Headers.Authorization = authenticationHeader;
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sends an HTTP request and deserializes the response into the specified type if the request is successful.
/// If the request fails, it attempts to deserialize the response content into a <see cref="ProblemDetailsDto"/> and throws an <see cref="ApiException"/>.
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -56,6 +57,18 @@ public interface IApiHttpClient
/// <returns>The deserialized response containing the result of the PUT request.</returns>
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request with a multipart form containing a single file to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
/// <param name="fileStream">The stream of the file to upload.</param>
/// <param name="fileName">The name of the file to upload.</param>
/// <param name="fieldName">The name of the form field carrying the file.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized response containing the result of the POST request.</returns>
Task<TResponse> PostMultipartAsync<TResponse>(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default);
/// <summary>
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
/// </summary>
@@ -1,18 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for an installed theme.
/// </summary>
/// <param name="Manifest">The validated theme manifest.</param>
/// <param name="Info">The display metadata of the theme.</param>
/// <param name="RootPath">The absolute path of the installed theme directory.</param>
[DebuggerDisplay("Manifest name: {Manifest.Name}")]
public sealed record InstalledThemeDto(
ThemeManifestDto Manifest,
ThemeInfoDto Info,
string RootPath
);
@@ -1,17 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the settings persisted for the theme engine.
/// </summary>
[DebuggerDisplay("CurrentThemeId: {CurrentThemeId}")]
public sealed class PersistedThemeSettingsDto
{
/// <summary>
/// Gets or sets the unique identifier of the currently selected theme.
/// </summary>
public string CurrentThemeId { get; set; } = string.Empty;
}
@@ -1,24 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Themes;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the metadata persisted alongside an installed theme.
/// </summary>
[DebuggerDisplay("Source: {Source}")]
public sealed class ThemeInstallationMetadataDto
{
/// <summary>
/// Gets or sets the source the theme was installed from.
/// </summary>
public ThemeInstallSource Source { get; set; }
/// <summary>
/// Gets or sets the UTC timestamp at which the theme was installed.
/// </summary>
public DateTimeOffset InstalledAtUtc { get; set; }
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Themes;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for a theme returned by the remote API.
/// </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>
[DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")]
public sealed record ThemeResponseDto(
Guid Id,
string ThemeId,
string Name,
string Description,
string Author,
string Version,
string? PreviewPath,
ThemeInstallSource InstallSource,
bool? IsCurrent,
DateTime InstalledAtUtc
);
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the theme engine settings returned by the remote API.
/// </summary>
/// <param name="MaxArchiveBytes">The maximum allowed size of a theme archive, in bytes.</param>
/// <param name="AllowThemeScripts">Whether theme templates may contain script elements and theme assets may include script files.</param>
/// <param name="DefaultThemeId">The identifier of the theme selected when no valid current theme is available.</param>
[DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")]
public sealed record ThemeSettingsResponseDto(
long MaxArchiveBytes,
bool AllowThemeScripts,
string DefaultThemeId
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the template of a theme returned by the remote API.
/// </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 sealed record ThemeTemplateResponseDto(
ThemeResponseDto Theme,
string Template
);
@@ -36,11 +36,6 @@ internal static class PresentationWebLayerConfiguration
.ValidateFluently()
.ValidateOnStart();
serviceCollection.AddOptions<ThemeEngineOptionsDto>()
.Bind(configuration.GetRequiredSection(ThemeEngineOptionsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return serviceCollection;
}
}
@@ -301,7 +301,6 @@ public static class PresentationWebLayerServices
services.AddHttpContextAccessor();
services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024);
services.AddSingleton<ThemeSettingsStore>();
services.AddSingleton<ThemeService>();
services.AddSingleton<ThemeTemplateEngine>();
services.AddSingleton<ThemePageRenderer>();
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Themes;
/// <summary>
/// Represents a request to delete a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to delete.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record DeleteThemeRequest(
string? ThemeId
);
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more