From bf8faba24dbd2068aad8c0a9203a6c930ccd4b39 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 19 Aug 2026 22:50:07 -0700 Subject: [PATCH 01/31] Adds the server-side theme repository and reworks the web theme engine onto it --- .../DataAccess/Entities/Themes/ThemeEntity.cs | 90 ++ .../Repositories/Themes/IThemeRepository.cs | 34 + .../Common/DataAccess/UoW/IUnitOfWork.cs | 6 + .../Models/DTO/Themes/ThemeArchiveDto.cs | 19 + .../Models/DTO/Themes/ThemeAssetDto.cs | 17 + .../Models}/DTO/Themes/ThemeManifestDto.cs | 10 +- .../Infrastructure/Themes/IThemeService.cs | 103 ++ .../Themes/DeleteThemeRequestMapping.cs | 22 + .../Themes/GetThemeArchiveRequestMapping.cs | 22 + .../Themes/GetThemeAssetRequestMapping.cs | 22 + .../Themes/GetThemeTemplateRequestMapping.cs | 22 + .../Themes/InstallThemeRequestMapping.cs | 25 + .../Themes/SetCurrentThemeRequestMapping.cs | 22 + .../Mapping/Themes/ThemeEntityMapping.cs | 32 + .../Common/Utilities/ValidatorUtilities.cs | 27 + .../DeleteTheme/DeleteThemeCommand.cs | 16 + .../DeleteTheme/DeleteThemeCommandHandler.cs | 129 ++ .../DeleteThemeCommandValidator.cs | 24 + .../InstallTheme/InstallThemeCommand.cs | 19 + .../InstallThemeCommandHandler.cs | 148 ++ .../InstallThemeCommandValidator.cs | 25 + .../SetCurrentTheme/SetCurrentThemeCommand.cs | 16 + .../SetCurrentThemeCommandHandler.cs | 103 ++ .../SetCurrentThemeCommandValidator.cs | 24 + .../GetCurrentTheme/GetCurrentThemeQuery.cs | 13 + .../GetCurrentThemeQueryHandler.cs | 50 + .../GetThemeArchive/GetThemeArchiveQuery.cs | 16 + .../GetThemeArchiveQueryHandler.cs | 68 + .../GetThemeArchiveQueryValidator.cs | 24 + .../GetThemeAsset/GetThemeAssetQuery.cs | 18 + .../GetThemeAssetQueryHandler.cs | 82 ++ .../GetThemeAssetQueryValidator.cs | 28 + .../GetThemeSettings/GetThemeSettingsQuery.cs | 13 + .../GetThemeSettingsQueryHandler.cs | 41 + .../GetThemeTemplate/GetThemeTemplateQuery.cs | 18 + .../GetThemeTemplateQueryHandler.cs | 113 ++ .../GetThemeTemplateQueryValidator.cs | 28 + .../Queries/GetThemes/GetThemesQuery.cs | 13 + .../GetThemes/GetThemesQueryHandler.cs | 54 + .../Requests/Themes/DeleteThemeRequest.cs | 15 + .../Requests/Themes/GetThemeArchiveRequest.cs | 15 + .../Requests/Themes/GetThemeAssetRequest.cs | 17 + .../Themes/GetThemeTemplateRequest.cs | 17 + .../Requests/Themes/InstallThemeRequest.cs | 12 + .../Requests/Themes/SetCurrentThemeRequest.cs | 15 + .../Responses/Themes/ThemeArchiveResponse.cs | 19 + .../Responses/Themes/ThemeAssetResponse.cs | 17 + .../Responses/Themes/ThemeResponse.cs | 34 + .../Responses/Themes/ThemeSettingsResponse.cs | 19 + .../Responses/Themes/ThemeTemplateResponse.cs | 17 + .../Configuration/ThemeConfiguration.cs | 100 ++ ...20260819181057_AddsThemesTable.Designer.cs | 1302 +++++++++++++++++ .../20260819181057_AddsThemesTable.cs | 60 + .../LuminaDbContextModelSnapshot.cs | 90 +- .../Repositories/Themes/ThemeRepository.cs | 97 ++ .../Core/UoW/LuminaDbContext.cs | 2 + src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 15 + .../Common/Enums/Themes/ThemeInstallSource.cs | 17 + .../Common/Errors/Errors.Themes.cs | 25 + .../InfrastructureLayerServices.cs | 6 + .../SharedConfiguration.cs | 10 +- .../Common/Errors/Errors.Configuration.cs | 8 +- .../DTO/Configuration/CommonSettingsDto.cs | 19 - .../Configuration/ThemeEngineOptionsDto.cs | 18 +- .../Validators/CommonSettingsDtoValidator.cs | 23 - .../ThemeEngineOptionsDtoValidator.cs | 25 +- .../Core/Themes/ThemeDetectionSyncJob.cs | 105 ++ .../Core/Themes/ThemeMimeTypes.cs | 43 + .../Core/Themes/ThemeService.cs | 787 ++++++++++ .../appsettings.shared.json | 11 +- .../Common/Routes/Themes/ApiRoutes.Themes.cs | 20 + .../DeleteTheme/DeleteThemeEndpoint.cs | 53 + .../DeleteTheme/DeleteThemeEndpointSummary.cs | 129 ++ .../InstallTheme/InstallThemeEndpoint.cs | 56 + .../InstallThemeEndpointSummary.cs | 125 ++ .../SetCurrentThemeEndpoint.cs | 54 + .../SetCurrentThemeEndpointSummary.cs | 122 ++ .../GetCurrentThemeEndpoint.cs | 53 + .../GetCurrentThemeEndpointSummary.cs | 39 + .../GetThemeArchiveEndpoint.cs | 55 + .../GetThemeArchiveEndpointSummary.cs | 102 ++ .../GetThemeAsset/GetThemeAssetEndpoint.cs | 56 + .../GetThemeAssetEndpointSummary.cs | 82 ++ .../GetThemeSettingsEndpoint.cs | 53 + .../GetThemeSettingsEndpointSummary.cs | 31 + .../GetThemeTemplateEndpoint.cs | 56 + .../GetThemeTemplateEndpointSummary.cs | 98 ++ .../Queries/GetThemes/GetThemesEndpoint.cs | 53 + .../GetThemes/GetThemesEndpointSummary.cs | 83 ++ .../Common/Api/ApiHttpClient.cs | 28 + .../Common/Api/IApiHttpClient.cs | 13 + .../Common/DTO/Themes/InstalledThemeDto.cs | 18 - .../DTO/Themes/PersistedThemeSettingsDto.cs | 17 - .../Themes/ThemeInstallationMetadataDto.cs | 24 - .../Common/DTO/Themes/ThemeResponseDto.cs | 34 + .../DTO/Themes/ThemeSettingsResponseDto.cs | 19 + .../DTO/Themes/ThemeTemplateResponseDto.cs | 16 + .../PresentationWebLayerConfiguration.cs | 5 - .../PresentationWebLayerServices.cs | 1 - .../Requests/Themes/DeleteThemeRequest.cs | 14 + .../Requests/Themes/GetThemeArchiveRequest.cs | 14 + .../Requests/Themes/GetThemeAssetRequest.cs | 16 + .../Requests/Themes/SetCurrentThemeRequest.cs | 14 + .../Common/Routes/ApiRoutes.Themes.cs | 23 + .../Common/Routes/WebRoutes.Themes.cs | 20 + .../Themes/DeleteTheme/DeleteThemeEndpoint.cs | 59 + .../DeleteTheme/DeleteThemeEndpointSummary.cs | 29 + .../DownloadTheme/DownloadThemeEndpoint.cs | 59 + .../DownloadThemeEndpointSummary.cs | 28 + .../Themes/GetThemes/GetThemesEndpoint.cs | 66 + .../GetThemes/GetThemesEndpointSummary.cs | 27 + .../InstallTheme/InstallThemeEndpoint.cs | 63 + .../InstallThemeEndpointSummary.cs | 27 + .../SetCurrentThemeEndpoint.cs | 59 + .../SetCurrentThemeEndpointSummary.cs | 29 + .../Themes/ThemeAssets/ThemeAssetsEndpoint.cs | 58 + .../ThemeAssets/ThemeAssetsEndpointSummary.cs | 29 + .../ExceptionHandlingMiddleware.de-DE.resx | 30 + .../ExceptionHandlingMiddleware.en-US.resx | 30 + .../ExceptionHandlingMiddleware.es-ES.resx | 30 + .../ExceptionHandlingMiddleware.fr-FR.resx | 30 + .../ExceptionHandlingMiddleware.it-IT.resx | 30 + .../ExceptionHandlingMiddleware.ja-JP.resx | 30 + .../ExceptionHandlingMiddleware.resx | 30 + .../ExceptionHandlingMiddleware.ro-RO.resx | 30 + .../ExceptionHandlingMiddleware.ru-RU.resx | 30 + .../ExceptionHandlingMiddleware.zh-CN.resx | 30 + .../Core/Themes/ThemePageRenderer.cs | 6 +- .../Core/Themes/ThemeService.cs | 878 +---------- .../Core/Themes/ThemeSettingsStore.cs | 115 -- .../Core/Themes/ThemeTemplateEngine.cs | 26 +- src/Lumina.Presentation.Web/appsettings.json | 10 - .../Common/Api/StubApiHttpClient.cs | 19 + .../CommonSettingsDtoValidatorTests.cs | 61 - .../DatabaseSettingsDtoValidatorTests.cs | 4 +- .../ThemeEngineOptionsDtoValidatorTests.cs | 75 +- 136 files changed, 6942 insertions(+), 1197 deletions(-) create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/Themes/ThemeEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDto.cs create mode 100644 src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDto.cs rename src/{Lumina.Presentation.Web/Common => Lumina.Application/Common/Infrastructure/Models}/DTO/Themes/ThemeManifestDto.cs (87%) create mode 100644 src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/DeleteThemeRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/GetThemeArchiveRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/GetThemeAssetRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/GetThemeTemplateRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/SetCurrentThemeRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommand.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommand.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommand.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQuery.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQuery.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidator.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQuery.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidator.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQuery.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQuery.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidator.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQuery.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/DeleteThemeRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/GetThemeArchiveRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/GetThemeAssetRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/GetThemeTemplateRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/SetCurrentThemeRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Themes/ThemeArchiveResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Themes/ThemeAssetResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Themes/ThemeTemplateResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/ThemeConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Themes/ThemeInstallSource.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.Themes.cs delete mode 100644 src/Lumina.Infrastructure/Common/Models/DTO/Configuration/CommonSettingsDto.cs rename src/{Lumina.Presentation.Web/Common => Lumina.Infrastructure/Common/Models}/DTO/Configuration/ThemeEngineOptionsDto.cs (68%) delete mode 100644 src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs rename src/{Lumina.Presentation.Web => Lumina.Infrastructure}/Common/Validators/ThemeEngineOptionsDtoValidator.cs (54%) create mode 100644 src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs create mode 100644 src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs create mode 100644 src/Lumina.Infrastructure/Core/Themes/ThemeService.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs delete mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs delete mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs delete mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateResponseDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs create mode 100644 src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs delete mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs delete mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs rename tests/UnitTests/{Lumina.Presentation.Web.UnitTests => Lumina.Infrastructure.UnitTests}/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs (56%) diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Themes/ThemeEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Themes/ThemeEntity.cs new file mode 100644 index 00000000..4b698c47 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Themes/ThemeEntity.cs @@ -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; + +/// +/// Repository entity for a theme. +/// +[DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")] +public class ThemeEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the theme. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the unique identifier of the theme, taken from its manifest and used by clients to reference it. + /// + public required string ThemeId { get; set; } + + /// + /// Gets or sets the display name of the theme. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the description of the theme. + /// + public required string Description { get; set; } + + /// + /// Gets or sets the author of the theme. + /// + public required string Author { get; set; } + + /// + /// Gets or sets the version of the theme, using semantic version form. + /// + public required string Version { get; set; } + + /// + /// Gets or sets the path of the theme preview image, relative to the theme pack root, or when the theme has no preview. + /// + public string? PreviewPath { get; set; } + + /// + /// Gets or sets the source the theme was installed from. + /// + public required ThemeInstallSource InstallSource { get; set; } + + /// + /// Gets or sets a value indicating whether this is the currently active theme. At most one theme can be current. + /// + public bool? IsCurrent { get; set; } + + /// + /// Gets or sets a value indicating whether the theme was soft deleted, so it is not shown and not reinstalled automatically. + /// + public bool IsDeleted { get; set; } + + /// + /// Gets or sets the UTC timestamp at which the theme was installed. + /// + public required DateTime InstalledAtUtc { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs new file mode 100644 index 00000000..db094c7a --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs @@ -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; + +/// +/// Interface for the repository for themes. +/// +public interface IThemeRepository : IRepository, + IGetAllRepositoryAction, + IInsertRepositoryAction, + IUpdateRepositoryAction +{ + /// + /// Gets a theme identified by its manifest from the storage medium. + /// + /// The manifest id of the theme to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + Task> GetByThemeIdAsync(string themeId, CancellationToken cancellationToken); + + /// + /// Gets the currently active theme from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either the active , or an error. + Task> GetCurrentAsync(CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index f8717656..dc49b1f4 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -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 /// IPluginRepository PluginRepository { get; } + /// + /// Gets the theme repository. + /// + IThemeRepository ThemeRepository { get; } + /// /// Gets the user repository. /// diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDto.cs new file mode 100644 index 00000000..58b3d228 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Data transfer object for a downloadable archive of a theme pack. +/// +/// The bytes of the ZIP archive. +/// The file name to expose when downloading the archive. +/// The MIME content type of the archive. +[DebuggerDisplay("FileName: {FileName}")] +public sealed record ThemeArchiveDto( + byte[] Bytes, + string FileName, + string ContentType +); diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDto.cs new file mode 100644 index 00000000..307392cf --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Data transfer object for a theme asset file served by the theme service. +/// +/// The bytes of the asset file. +/// The MIME content type of the asset file. +[DebuggerDisplay("ContentType: {ContentType}")] +public sealed record ThemeAssetDto( + byte[] Bytes, + string ContentType +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeManifestDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDto.cs similarity index 87% rename from src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeManifestDto.cs rename to src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDto.cs index 1e2f2b48..1888eda3 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeManifestDto.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDto.cs @@ -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; /// -/// Data transfer object for the theme.json manifest of a theme package. +/// Data transfer object for the theme.json manifest of a theme pack. /// [DebuggerDisplay("Id: {Id}, Name: {Name}")] public sealed class ThemeManifestDto @@ -18,7 +18,7 @@ public sealed class ThemeManifestDto public int SchemaVersion { get; set; } /// - /// 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. /// public string Id { get; set; } = string.Empty; @@ -43,12 +43,12 @@ public sealed class ThemeManifestDto public string Version { get; set; } = string.Empty; /// - /// Gets or sets the preview image path relative to the theme package root, or when the theme has no preview. + /// Gets or sets the preview image path relative to the theme pack root, or when the theme has no preview. /// public string? Preview { get; set; } /// - /// 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/. /// public Dictionary Templates { get; set; } = new(StringComparer.OrdinalIgnoreCase); } diff --git a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs new file mode 100644 index 00000000..f9e00778 --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs @@ -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; + +/// +/// Service for the storage and serving of theme packs. +/// +public interface IThemeService +{ + /// + /// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files. + /// + bool AllowThemeScripts { get; } + + /// + /// Gets the maximum allowed size of a theme archive, in bytes. + /// + long MaxArchiveBytes { get; } + + /// + /// Gets the identifier of the theme selected when no valid current theme is available. + /// + string DefaultThemeId { get; } + + /// + /// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id. + /// + /// The ZIP archive stream of the theme pack. + /// Cancellation token that can be used to stop the execution. + /// An containing either the parsed manifest of the installed theme, or an error. + Task> InstallAsync(Stream archive, CancellationToken cancellationToken); + + /// + /// Reads the manifest of a theme pack archive without installing it. + /// + /// The path of the theme pack ZIP archive. + /// Cancellation token that can be used to stop the execution. + /// An containing either the parsed manifest, or an error. + Task> ReadManifestFromArchiveAsync(string archivePath, CancellationToken cancellationToken); + + /// + /// Deletes the stored files of a theme pack. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteAsync(string themeId, CancellationToken cancellationToken); + + /// + /// Loads the manifest of an installed theme pack from its storage location. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An containing either the parsed manifest, or an error. + Task> LoadManifestAsync(string themeId, CancellationToken cancellationToken); + + /// + /// Gets the sanitized content of the template selected by a page key, falling back to the default template when the key is missing. + /// + /// The manifest id of the theme. + /// The page key that selects the template. + /// Cancellation token that can be used to stop the execution. + /// An containing either the template content, or an error. + Task> GetTemplateAsync(string themeId, string pageKey, CancellationToken cancellationToken); + + /// + /// Gets a theme asset file. + /// + /// The manifest id of the theme. + /// The asset path relative to the theme pack root. + /// Cancellation token that can be used to stop the execution. + /// An containing either the asset, or an error. + Task> GetAssetAsync(string themeId, string assetPath, CancellationToken cancellationToken); + + /// + /// Builds a downloadable ZIP archive of an installed theme pack. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An containing either the archive, or an error. + Task> BuildArchiveAsync(string themeId, CancellationToken cancellationToken); + + /// + /// Restores the files of a bundled theme from its shipped archive, used when the stored files were removed externally. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken); + + /// + /// Gets the paths of the theme pack archives shipped with the application. + /// + /// The list of bundled theme archive paths. + IReadOnlyList GetBundledThemeArchivePaths(); +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/DeleteThemeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/DeleteThemeRequestMapping.cs new file mode 100644 index 00000000..144c8493 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/DeleteThemeRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class DeleteThemeRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static DeleteThemeCommand ToCommand(this DeleteThemeRequest request) + { + return new DeleteThemeCommand(request.ThemeId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/GetThemeArchiveRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/GetThemeArchiveRequestMapping.cs new file mode 100644 index 00000000..11a4b707 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/GetThemeArchiveRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetThemeArchiveRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetThemeArchiveQuery ToQuery(this GetThemeArchiveRequest request) + { + return new GetThemeArchiveQuery(request.ThemeId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/GetThemeAssetRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/GetThemeAssetRequestMapping.cs new file mode 100644 index 00000000..c2f718d3 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/GetThemeAssetRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetThemeAssetRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetThemeAssetQuery ToQuery(this GetThemeAssetRequest request) + { + return new GetThemeAssetQuery(request.ThemeId, request.AssetPath); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/GetThemeTemplateRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/GetThemeTemplateRequestMapping.cs new file mode 100644 index 00000000..647c8db8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/GetThemeTemplateRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class GetThemeTemplateRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetThemeTemplateQuery ToQuery(this GetThemeTemplateRequest request) + { + return new GetThemeTemplateQuery(request.ThemeId, request.PageKey); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs new file mode 100644 index 00000000..9e17d55b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class InstallThemeRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The ZIP archive stream of the theme pack. + /// The file name of the uploaded archive. + /// The converted command. + public static InstallThemeCommand ToCommand(this InstallThemeRequest request, Stream? archive, string? fileName) + { + return new InstallThemeCommand(archive, fileName); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/SetCurrentThemeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/SetCurrentThemeRequestMapping.cs new file mode 100644 index 00000000..035b69e1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/SetCurrentThemeRequestMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class SetCurrentThemeRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetCurrentThemeCommand ToCommand(this SetCurrentThemeRequest request) + { + return new SetCurrentThemeCommand(request.ThemeId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs new file mode 100644 index 00000000..c6818b85 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs @@ -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; + +/// +/// Extension methods for converting . +/// +public static class ThemeEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response. + 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); + } +} diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs index 86912552..2e14e2f2 100644 --- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -39,6 +39,33 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); } + /// + /// Defines a validation rule that ensures the long property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, long valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable long property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, long valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + /// /// Defines a validation rule that ensures the decimal property is greater than the specified value. /// diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommand.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommand.cs new file mode 100644 index 00000000..38666b55 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommand.cs @@ -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; + +/// +/// Command for deleting a theme. +/// +/// The manifest id of the theme to delete. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record DeleteThemeCommand( + string? ThemeId +) : ICommand; diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs new file mode 100644 index 00000000..e329555e --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs @@ -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; + +/// +/// Handler for the command to delete a theme. +/// +public class DeleteThemeCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public DeleteThemeCommandHandler( + IUnitOfWork unitOfWork, + IThemeService themeService, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to delete a theme. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(DeleteThemeCommand command, CancellationToken cancellationToken) + { + List 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 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> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getAllResult.IsFailure) + return getAllResult.Errors; + + List 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 deleteFilesResult = await _themeService.DeleteAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); + if (deleteFilesResult.IsFailure) + return deleteFilesResult.Errors; + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidator.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidator.cs new file mode 100644 index 00000000..752eb358 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteThemeCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeCommandValidator() + { + RuleFor(command => command.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommand.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommand.cs new file mode 100644 index 00000000..488d3442 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommand.cs @@ -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; + +/// +/// Command for installing a theme pack, replacing the files of an existing theme with the same manifest id. +/// +/// The ZIP archive stream of the theme pack. +/// The file name of the uploaded archive. +[DebuggerDisplay("FileName: {FileName}")] +public record InstallThemeCommand( + Stream? Archive, + string? FileName +) : ICommand; diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs new file mode 100644 index 00000000..c804d7d1 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs @@ -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; + +/// +/// Handler for the command to install a theme pack. +/// +public class InstallThemeCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public InstallThemeCommandHandler( + IUnitOfWork unitOfWork, + IThemeService themeService, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to install a theme pack. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully installed , or an error. + /// + public async Task> HandleAsync(InstallThemeCommand command, CancellationToken cancellationToken) + { + List 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 installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false); + if (installResult.IsFailure) + return installResult.Errors; + + ThemeManifestDto manifest = installResult.Value; + Result 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 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 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(); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidator.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidator.cs new file mode 100644 index 00000000..11c9698a --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class InstallThemeCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public InstallThemeCommandValidator() + { + RuleFor(command => command.Archive) + .NotNull() + .WithError(DomainErrors.Themes.ThemeArchiveCannotBeNull); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommand.cs b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommand.cs new file mode 100644 index 00000000..37bc72be --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommand.cs @@ -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; + +/// +/// Command for setting the currently active theme. +/// +/// The manifest id of the theme to activate. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record SetCurrentThemeCommand( + string? ThemeId +) : ICommand; diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs new file mode 100644 index 00000000..3269b174 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs @@ -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; + +/// +/// Handler for the command to set the currently active theme. +/// +public class SetCurrentThemeCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public SetCurrentThemeCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to set the currently active theme. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the newly active , or an error. + /// + public async Task> HandleAsync(SetCurrentThemeCommand command, CancellationToken cancellationToken) + { + List 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 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 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(); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidator.cs b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidator.cs new file mode 100644 index 00000000..29ab5055 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class SetCurrentThemeCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeCommandValidator() + { + RuleFor(command => command.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQuery.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQuery.cs new file mode 100644 index 00000000..510ccf83 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQuery.cs @@ -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; + +/// +/// Query for retrieving the currently active theme. +/// +[DebuggerDisplay("GetCurrentThemeQuery")] +public record GetCurrentThemeQuery : IQuery; diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandler.cs new file mode 100644 index 00000000..3014a68e --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the currently active theme. +/// +public class GetCurrentThemeQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public GetCurrentThemeQueryHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get the currently active theme. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the active , or an error. + /// + public async Task> HandleAsync(GetCurrentThemeQuery query, CancellationToken cancellationToken) + { + Result 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(); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQuery.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQuery.cs new file mode 100644 index 00000000..c5163a09 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQuery.cs @@ -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; + +/// +/// Query for retrieving the downloadable archive of a theme. +/// +/// The manifest id of the theme. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record GetThemeArchiveQuery( + string? ThemeId +) : IQuery; diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandler.cs new file mode 100644 index 00000000..5d9012bb --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the downloadable archive of a theme. +/// +public class GetThemeArchiveQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected validator for application validation rules. + public GetThemeArchiveQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _validator = validator; + } + + /// + /// Handles the query to get the downloadable archive of a theme. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the archive of the theme, or an error. + /// + public async Task> HandleAsync(GetThemeArchiveQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + Result 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 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); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidator.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidator.cs new file mode 100644 index 00000000..073e83ac --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetThemeArchiveQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetThemeArchiveQueryValidator() + { + RuleFor(query => query.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQuery.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQuery.cs new file mode 100644 index 00000000..a576fafa --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQuery.cs @@ -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; + +/// +/// Query for retrieving an asset file of a theme. +/// +/// The manifest id of the theme. +/// The asset path relative to the theme pack root. +[DebuggerDisplay("ThemeId: {ThemeId}, AssetPath: {AssetPath}")] +public record GetThemeAssetQuery( + string? ThemeId, + string? AssetPath +) : IQuery; diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandler.cs new file mode 100644 index 00000000..9f69ce6a --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get an asset file of a theme. +/// +public class GetThemeAssetQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected validator for application validation rules. + public GetThemeAssetQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _validator = validator; + } + + /// + /// Handles the query to get an asset file of a theme. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the asset of the theme, or an error. + /// + public async Task> HandleAsync(GetThemeAssetQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + Result 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 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 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); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidator.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidator.cs new file mode 100644 index 00000000..2600048d --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetThemeAssetQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetThemeAssetQueryValidator() + { + RuleFor(query => query.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + + RuleFor(query => query.AssetPath) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeAssetPathCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQuery.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQuery.cs new file mode 100644 index 00000000..f56b71ae --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQuery.cs @@ -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; + +/// +/// Query for retrieving the theme engine settings. +/// +[DebuggerDisplay("GetThemeSettingsQuery")] +public record GetThemeSettingsQuery : IQuery; diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs new file mode 100644 index 00000000..595c53b5 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the theme engine settings. +/// +public class GetThemeSettingsQueryHandler : IQueryHandler> +{ + private readonly IThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for the server-side storage and serving of theme packs. + public GetThemeSettingsQueryHandler(IThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Handles the query to get the theme engine settings. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing the theme engine settings, or an error. + /// + public Task> HandleAsync(GetThemeSettingsQuery query, CancellationToken cancellationToken) + { + ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.AllowThemeScripts, _themeService.DefaultThemeId); + return Task.FromResult(Result.From(response)); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQuery.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQuery.cs new file mode 100644 index 00000000..fbab092e --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQuery.cs @@ -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; + +/// +/// Query for retrieving the template of a theme selected by a page key. +/// +/// The manifest id of the theme. +/// The page key that selects the template. +[DebuggerDisplay("ThemeId: {ThemeId}, PageKey: {PageKey}")] +public record GetThemeTemplateQuery( + string? ThemeId, + string? PageKey +) : IQuery; diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs new file mode 100644 index 00000000..e547d303 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get the template of a theme. +/// +public class GetThemeTemplateQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected validator for application validation rules. + public GetThemeTemplateQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _validator = validator; + } + + /// + /// Handles the query to get the template of a theme. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the template of the theme, or an error. + /// + public async Task> HandleAsync(GetThemeTemplateQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + Result 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 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); + } + + /// + /// 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. + /// + /// The bundled theme to restore. + /// Cancellation token that can be used to stop the execution. + /// when the theme was restored; otherwise. + private async Task TryRestoreBundledThemeAsync(ThemeEntity theme, CancellationToken cancellationToken) + { + Result restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); + if (restoreResult.IsFailure) + return false; + + if (theme.IsCurrent == true) + { + Result 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; + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidator.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidator.cs new file mode 100644 index 00000000..1818dbe4 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for . +/// +public class GetThemeTemplateQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetThemeTemplateQueryValidator() + { + RuleFor(query => query.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + + RuleFor(query => query.PageKey) + .NotEmpty() + .WithError(DomainErrors.Themes.PageKeyCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQuery.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQuery.cs new file mode 100644 index 00000000..05dd246d --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQuery.cs @@ -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; + +/// +/// Query for retrieving all installed themes. +/// +[DebuggerDisplay("GetThemesQuery")] +public record GetThemesQuery : IQuery; diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs new file mode 100644 index 00000000..d3ceca64 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs @@ -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; + +/// +/// Handler for the query to get all installed themes. +/// +public class GetThemesQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + public GetThemesQueryHandler(IUnitOfWork unitOfWork) + { + _unitOfWork = unitOfWork; + } + + /// + /// Handles the query to get all installed themes. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetThemesQuery query, CancellationToken cancellationToken) + { + Result> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getThemesResult.IsFailure) + return getThemesResult.Errors; + + return Result.From>([.. getThemesResult.Value + .Where(theme => !theme.IsDeleted) + .OrderByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) + .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase) + .Select(theme => theme.ToResponse())]); + } +} diff --git a/src/Lumina.Contracts/Requests/Themes/DeleteThemeRequest.cs b/src/Lumina.Contracts/Requests/Themes/DeleteThemeRequest.cs new file mode 100644 index 00000000..1b7de807 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/DeleteThemeRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to delete a theme. +/// +/// The manifest id of the theme to delete. Required. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record DeleteThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Contracts/Requests/Themes/GetThemeArchiveRequest.cs b/src/Lumina.Contracts/Requests/Themes/GetThemeArchiveRequest.cs new file mode 100644 index 00000000..0d356b69 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/GetThemeArchiveRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to download the archive of a theme. +/// +/// The manifest id of the theme. Required. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record GetThemeArchiveRequest( + string? ThemeId +); diff --git a/src/Lumina.Contracts/Requests/Themes/GetThemeAssetRequest.cs b/src/Lumina.Contracts/Requests/Themes/GetThemeAssetRequest.cs new file mode 100644 index 00000000..24c01a97 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/GetThemeAssetRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to get an asset file of a theme. +/// +/// The manifest id of the theme. Required. +/// The asset path relative to the theme pack root. Required. +[DebuggerDisplay("ThemeId: {ThemeId}, AssetPath: {AssetPath}")] +public record GetThemeAssetRequest( + string? ThemeId, + string? AssetPath +); diff --git a/src/Lumina.Contracts/Requests/Themes/GetThemeTemplateRequest.cs b/src/Lumina.Contracts/Requests/Themes/GetThemeTemplateRequest.cs new file mode 100644 index 00000000..47e047a8 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/GetThemeTemplateRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to get the template of a theme selected by a page key. +/// +/// The manifest id of the theme. Required. +/// The page key that selects the template. Required. +[DebuggerDisplay("ThemeId: {ThemeId}, PageKey: {PageKey}")] +public record GetThemeTemplateRequest( + string? ThemeId, + string? PageKey +); diff --git a/src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs b/src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs new file mode 100644 index 00000000..d000c42b --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to install a theme pack, sent as a multipart form whose single file field contains the theme archive. +/// +[DebuggerDisplay("InstallThemeRequest")] +public record InstallThemeRequest; diff --git a/src/Lumina.Contracts/Requests/Themes/SetCurrentThemeRequest.cs b/src/Lumina.Contracts/Requests/Themes/SetCurrentThemeRequest.cs new file mode 100644 index 00000000..9e171853 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/SetCurrentThemeRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to set the currently active theme. +/// +/// The manifest id of the theme to activate. Required. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record SetCurrentThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeArchiveResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeArchiveResponse.cs new file mode 100644 index 00000000..841c8bc8 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Themes/ThemeArchiveResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Themes; + +/// +/// Represents a theme archive response. +/// +/// The bytes of the ZIP archive. +/// The file name to expose when downloading the archive. +/// The MIME content type of the archive. +[DebuggerDisplay("FileName: {FileName}")] +public record ThemeArchiveResponse( + byte[] Bytes, + string FileName, + string ContentType +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeAssetResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeAssetResponse.cs new file mode 100644 index 00000000..f7c3d7b5 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Themes/ThemeAssetResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Themes; + +/// +/// Represents a theme asset response. +/// +/// The bytes of the asset file. +/// The MIME content type of the asset file. +[DebuggerDisplay("ContentType: {ContentType}")] +public record ThemeAssetResponse( + byte[] Bytes, + string ContentType +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs new file mode 100644 index 00000000..adda0c8c --- /dev/null +++ b/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Themes; + +/// +/// Represents a theme response. +/// +/// The unique identifier of the theme. +/// The manifest id of the theme, used by clients to reference it. +/// The display name of the theme. +/// The description of the theme. +/// The author of the theme. +/// The version of the theme, using semantic version form. +/// The path of the theme preview image, relative to the theme pack root, or when the theme has no preview. +/// The source the theme was installed from. +/// Whether the theme is the currently active one. +/// The UTC timestamp at which the theme was installed. +[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 +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs new file mode 100644 index 00000000..c21851cc --- /dev/null +++ b/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Themes; + +/// +/// Represents a theme settings response. +/// +/// The maximum allowed size of a theme archive, in bytes. +/// Whether theme templates may contain script elements and theme assets may include script files. +/// The identifier of the theme selected when no valid current theme is available. +[DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")] +public record ThemeSettingsResponse( + long MaxArchiveBytes, + bool AllowThemeScripts, + string DefaultThemeId +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeTemplateResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeTemplateResponse.cs new file mode 100644 index 00000000..7e14fc5d --- /dev/null +++ b/src/Lumina.Contracts/Responses/Themes/ThemeTemplateResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Themes; + +/// +/// Represents a theme template response. +/// +/// The theme the template belongs to. +/// The sanitized content of the template. +[DebuggerDisplay("ThemeId: {Theme.ThemeId}")] +public record ThemeTemplateResponse( + ThemeResponse Theme, + string Template +); diff --git a/src/Lumina.DataAccess/Common/Configuration/ThemeConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ThemeConfiguration.cs new file mode 100644 index 00000000..5f36830f --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/ThemeConfiguration.cs @@ -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; + +/// +/// Configures the entity mapping for the entity. +/// +public class ThemeConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder 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() + .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); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.Designer.cs new file mode 100644 index 00000000..d63afd4c --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.Designer.cs @@ -0,0 +1,1302 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260819181057_AddsThemesTable")] + partial class AddsThemesTable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("DownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.cs b/src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.cs new file mode 100644 index 00000000..6db67314 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260819181057_AddsThemesTable.cs @@ -0,0 +1,60 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsThemesTable : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Themes", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ThemeId = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Name = table.Column(type: "TEXT", maxLength: 80, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 300, nullable: false), + Author = table.Column(type: "TEXT", maxLength: 80, nullable: false), + Version = table.Column(type: "TEXT", maxLength: 40, nullable: false), + PreviewPath = table.Column(type: "TEXT", maxLength: 240, nullable: true), + InstallSource = table.Column(type: "TEXT", nullable: false), + IsCurrent = table.Column(type: "INTEGER", nullable: true), + IsDeleted = table.Column(type: "INTEGER", nullable: false, defaultValue: false), + InstalledAtUtc = table.Column(type: "TEXT", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(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); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Themes"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index fc0c29c7..d21b069d 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("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("Id") diff --git a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs new file mode 100644 index 00000000..2dbc7def --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs @@ -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; + +/// +/// Repository for themes. +/// +internal sealed class ThemeRepository : IThemeRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ThemeRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new theme. + /// + /// The theme to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + + /// + /// Updates a theme. + /// + /// The theme to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + + /// + /// Gets all themes from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetAllAsync(CancellationToken cancellationToken) + { + return await _luminaDbContext.Themes.ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets a theme identified by its manifest from the storage medium. + /// + /// The manifest id of the theme to get. + /// Cancellation token that can be used to stop the execution. + /// An containing either a identified by , or an error. + public async Task> GetByThemeIdAsync(string themeId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Themes + .FirstOrDefaultAsync(theme => theme.ThemeId == themeId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the currently active theme from the storage medium. + /// + /// Cancellation token that can be used to stop the execution. + /// An containing either the active , or an error. + public async Task> GetCurrentAsync(CancellationToken cancellationToken) + { + return await _luminaDbContext.Themes + .FirstOrDefaultAsync(theme => theme.IsCurrent == true, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 1de516e3..909e7e1d 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -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 RolePermissions { get; set; } = null!; public virtual DbSet Plugins { get; set; } = null!; public virtual DbSet LibraryMetadataProviderConfigurations { get; set; } = null!; + public virtual DbSet Themes { get; set; } = null!; /// /// Initializes a new instance of the class. diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 4fd25021..0a23313a 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -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 } } + /// + /// Gets the theme repository. + /// + public IThemeRepository ThemeRepository + { + get + { + _themeRepository ??= new ThemeRepository(_luminaDbContext); + return _themeRepository; + } + } + /// /// Gets the user repository. /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Themes/ThemeInstallSource.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Themes/ThemeInstallSource.cs new file mode 100644 index 00000000..69a2353d --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Themes/ThemeInstallSource.cs @@ -0,0 +1,17 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Themes; + +/// +/// Enumeration for the source a theme was installed from. +/// +public enum ThemeInstallSource +{ + /// + /// The theme was uploaded by a user. + /// + Uploaded, + + /// + /// The theme is bundled with the application. + /// + Bundled +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs new file mode 100644 index 00000000..81affa2e --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Theme error types. +/// +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)); + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 971452d7..2f7ed608 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -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>())); services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); + // themes: the theme service stores and serves theme packs, and the detection job seeds the bundled themes at startup + services.AddSingleton(); + services.AddHostedService(); + return services; } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index c7a2a772..afd1c2c7 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -35,11 +35,6 @@ public static class SharedConfiguration configuration.AddEnvironmentVariables(); // environment variables should override the configuration files // bind the appsettings sections - services.AddOptions() - .Bind(configuration.GetRequiredSection(CommonSettingsDto.SECTION_NAME)) - .ValidateFluently() - .ValidateOnStart(); - services.AddOptions() .Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME)) .ValidateFluently() @@ -70,6 +65,11 @@ public static class SharedConfiguration .ValidateFluently() .ValidateOnStart(); + services.AddOptions() + .Bind(configuration.GetRequiredSection(ThemeEngineOptionsDto.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return services; } } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index a2625302..1c41488f 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -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)); } } diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/CommonSettingsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/CommonSettingsDto.cs deleted file mode 100644 index 3c355a73..00000000 --- a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/CommonSettingsDto.cs +++ /dev/null @@ -1,19 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Infrastructure.Common.Models.DTO.Configuration; - -/// -/// Data transfer object for deserializing shared application configuration settings. -/// -[DebuggerDisplay("{SECTION_NAME}")] -public class CommonSettingsDto -{ - public const string SECTION_NAME = "CommonSettings"; - - /// - /// Gets or sets the theme of the application. - /// - public required string Theme { get; init; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Configuration/ThemeEngineOptionsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs similarity index 68% rename from src/Lumina.Presentation.Web/Common/DTO/Configuration/ThemeEngineOptionsDto.cs rename to src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs index 4d32856f..1d2623b6 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Configuration/ThemeEngineOptionsDto.cs +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Presentation.Web.Common.DTO.Configuration; +namespace Lumina.Infrastructure.Common.Models.DTO.Configuration; /// /// Data transfer object for deserializing theme engine settings. @@ -13,14 +13,14 @@ public sealed class ThemeEngineOptionsDto public const string SECTION_NAME = "ThemeEngine"; /// - /// 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. /// - public string StoragePath { get; set; } = "Themes"; + public string StoragePath { get; set; } = "themes"; /// - /// 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. /// - public string SettingsPath { get; set; } = "theme-settings.json"; + public string BundledThemesPath { get; set; } = "themes/bundled"; /// /// 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; /// - /// 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. /// public long MaxExpandedBytes { get; set; } = 24 * 1024 * 1024; /// - /// 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. /// public long MaxSingleFileBytes { get; set; } = 6 * 1024 * 1024; /// - /// 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. /// public int MaxEntries { get; set; } = 250; /// - /// 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. /// public bool AllowThemeScripts { get; set; } } diff --git a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs deleted file mode 100644 index 3d3db812..00000000 --- a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsDtoValidator.cs +++ /dev/null @@ -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; - -/// -/// Validates the needed validation rules for the CommonSettings application configuration settings section. -/// -public class CommonSettingsDtoValidator : AbstractValidator -{ - /// - /// Initializes a new instance of the class. - /// - public CommonSettingsDtoValidator() - { - RuleFor(settings => settings.Theme) - .NotEmpty() - .WithError(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty); - } -} diff --git a/src/Lumina.Presentation.Web/Common/Validators/ThemeEngineOptionsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/ThemeEngineOptionsDtoValidator.cs similarity index 54% rename from src/Lumina.Presentation.Web/Common/Validators/ThemeEngineOptionsDtoValidator.cs rename to src/Lumina.Infrastructure/Common/Validators/ThemeEngineOptionsDtoValidator.cs index 5d1b8274..d5eca7d3 100644 --- a/src/Lumina.Presentation.Web/Common/Validators/ThemeEngineOptionsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/ThemeEngineOptionsDtoValidator.cs @@ -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; /// /// Validates the needed validation rules for the ThemeEngine application configuration settings section. @@ -19,30 +18,30 @@ public class ThemeEngineOptionsDtoValidator : AbstractValidator 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); } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs new file mode 100644 index 00000000..c13ef49a --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -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; + +/// +/// Background job that installs the bundled themes into the storage medium and the theme storage at startup. +/// +internal sealed class ThemeDetectionSyncJob : BackgroundService +{ + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IThemeService _themeService; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Injected factory for creating scopes in which services are requested. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected logger used for logging. + public ThemeDetectionSyncJob(IServiceScopeFactory serviceScopeFactory, IThemeService themeService, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _themeService = themeService; + _logger = logger; + } + + /// + /// Method called when the background service starts. + /// + /// Cancellation token that can be used to stop the execution. + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope(); + IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetRequiredService(); + + Result> 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 knownThemeIds = [.. getThemesResult.Value.Select(theme => theme.ThemeId)]; + + foreach (string archivePath in _themeService.GetBundledThemeArchivePaths()) + { + Result 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 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 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); + } +} diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs new file mode 100644 index 00000000..12b00303 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeMimeTypes.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.Core.Themes; + +/// +/// Resolves the MIME content type of theme files based on their file extension. +/// +internal static class ThemeMimeTypes +{ + private static readonly Dictionary 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" + }; + + /// + /// Gets the MIME content type of a file based on its extension. + /// + /// The path of the file to get the content type of. + /// The MIME content type, or application/octet-stream when the extension is unknown. + public static string GetMimeType(string filePath) + { + return s_mimeByExtension.TryGetValue(Path.GetExtension(filePath), out string? mimeType) ? mimeType : "application/octet-stream"; + } +} diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs new file mode 100644 index 00000000..a2ad40b6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -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; + +/// +/// Stores and serves theme packs on the server, validating the pack envelope at install time and sanitizing served content. +/// +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( + "]*>[\\s\\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 _logger; + private readonly string _storageRoot; + private readonly string _stagingRoot; + private readonly string _bundledRoot; + private readonly SemaphoreSlim _mutationGate = new(1, 1); + + /// + /// Initializes a new instance of the class. + /// + /// The theme engine configuration options. + /// The logger for this service. + public ThemeService(IOptions options, ILogger 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); + } + + /// + /// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files. + /// + public bool AllowThemeScripts => _options.AllowThemeScripts; + + /// + /// Gets the maximum allowed size of a theme archive, in bytes. + /// + public long MaxArchiveBytes => _options.MaxArchiveBytes; + + /// + /// Gets the identifier of the theme selected when no valid current theme is available. + /// + public string DefaultThemeId => _options.DefaultThemeId; + + /// + /// Gets the paths of the theme pack archives shipped with the application. + /// + /// The list of bundled theme archive paths. + public IReadOnlyList GetBundledThemeArchivePaths() + { + if (!Directory.Exists(_bundledRoot)) + return []; + + return [.. Directory.EnumerateFiles(_bundledRoot, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id. + /// + /// The ZIP archive stream of the theme pack. + /// Cancellation token that can be used to stop the execution. + /// An containing either the parsed manifest of the installed theme, or an error. + public async Task> 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 copyResult = await CopyArchiveWithLimitAsync(archive, temporaryArchivePath, cancellationToken); + if (copyResult.IsFailure) + return copyResult.Errors; + + Directory.CreateDirectory(extractionPath); + Result extractResult = await ExtractArchiveAsync(temporaryArchivePath, extractionPath, cancellationToken); + if (extractResult.IsFailure) + return extractResult.Errors; + + Result 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(); + } + } + + /// + /// Reads the manifest of a theme pack archive without installing it. + /// + /// The path of the theme pack ZIP archive. + /// Cancellation token that can be used to stop the execution. + /// An containing either the parsed manifest, or an error. + public async Task> 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; + } + } + + /// + /// Deletes the stored files of a theme pack. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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(); + } + } + + /// + /// Loads the manifest of an installed theme pack from its storage location. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An containing either the parsed manifest, or an error. + public async Task> LoadManifestAsync(string themeId, CancellationToken cancellationToken) + { + string themePath = ResolveThemePath(themeId); + if (!Directory.Exists(themePath)) + return Errors.Themes.ThemeFilesUnreadable; + + return await Task.FromResult(LoadManifestFromDirectory(themePath)); + } + + /// + /// Gets the sanitized content of the template selected by a page key, falling back to the default template when the key is missing. + /// + /// The manifest id of the theme. + /// The page key that selects the template. + /// Cancellation token that can be used to stop the execution. + /// An containing either the template content, or an error. + public async Task> GetTemplateAsync(string themeId, string pageKey, CancellationToken cancellationToken) + { + Result 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 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; + } + + /// + /// Gets a theme asset file. + /// + /// The manifest id of the theme. + /// The asset path relative to the theme pack root. + /// Cancellation token that can be used to stop the execution. + /// An containing either the asset, or an error. + public async Task> GetAssetAsync(string themeId, string assetPath, CancellationToken cancellationToken) + { + Result 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 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)); + } + + /// + /// Builds a downloadable ZIP archive of an installed theme pack. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An containing either the archive, or an error. + public async Task> 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"); + } + + /// + /// Restores the files of a bundled theme from its shipped archive, used when the stored files were removed externally. + /// + /// The manifest id of the theme. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken) + { + foreach (string archivePath in GetBundledThemeArchivePaths()) + { + Result 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 installResult = await InstallAsync(archive, cancellationToken); + if (installResult.IsFailure) + return installResult.Errors; + + return Result.Success; + } + + return Errors.Themes.ThemeFilesUnreadable; + } + + /// + /// Copies the source archive to the staging directory while enforcing the maximum archive size. + /// + /// The archive stream to copy. + /// The temporary file to copy the archive into. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> 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; + } + + /// + /// Extracts a staged theme archive into the staging extraction directory after validating its entries. + /// + /// The path of the staged ZIP archive. + /// The directory the archive is extracted into. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> 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 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 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 directoryValidationResult = ValidatePackageDirectory(normalizedPath); + if (directoryValidationResult.IsFailure) + return directoryValidationResult.Errors; + + Result directoryPathResult = ResolveContainedPath(extractionPath, normalizedPath); + if (directoryPathResult.IsFailure) + return directoryPathResult.Errors; + + Directory.CreateDirectory(directoryPathResult.Value); + continue; + } + + Result 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 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; + } + + /// + /// Loads and validates the manifest of a theme pack from its directory. + /// + /// The absolute path of the theme pack directory. + /// An containing either the parsed manifest, or an error. + private static Result 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(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 validationResult = ValidateManifest(themeRoot, manifest); + if (validationResult.IsFailure) + return validationResult.Errors; + + return manifest; + } + + /// + /// Deserializes a theme pack manifest from its JSON content. + /// + /// The JSON content of the manifest. + /// An containing either the parsed manifest, or an error. + private static Result DeserializeManifest(string json) + { + ThemeManifestDto? manifest; + try + { + manifest = JsonSerializer.Deserialize(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; + } + + /// + /// Validates the manifest fields and template mappings, normalizing the referenced paths. + /// + /// The absolute path of the theme pack directory. + /// The manifest to validate. + /// An representing either a successful operation, or an error. + private static Result 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 nameResult = ValidateText(manifest.Name, "name", 80); + if (nameResult.IsFailure) + return nameResult; + + Result descriptionResult = ValidateText(manifest.Description, "description", 300); + if (descriptionResult.IsFailure) + return descriptionResult; + + Result authorResult = ValidateText(manifest.Author, "author", 80); + if (authorResult.IsFailure) + return authorResult; + + Result 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 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 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 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 previewPathResult = NormalizeRelativePath(manifest.Preview); + if (previewPathResult.IsFailure) + return previewPathResult.Errors; + + string previewPath = previewPathResult.Value; + Result 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; + } + + /// + /// Validates that a package file resides in the manifest, template or asset locations. + /// + /// The normalized package-relative path of the file. + /// An representing either a successful operation, or an error. + private static Result 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."); + } + + /// + /// Validates that a package directory resides under the templates or assets locations. + /// + /// The normalized package-relative path of the directory. + /// An representing either a successful operation, or an error. + private static Result 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."); + } + + /// + /// Normalizes a package-relative path, rejecting paths that escape the package or violate the path rules. + /// + /// The package-relative path to normalize. + /// Whether a trailing slash, used for directory entries, is permitted. + /// An containing either the normalized path, or an error. + private static Result 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); + } + + /// + /// Resolves a package-relative path against a package root, rejecting paths that escape the root. + /// + /// The absolute path of the package root. + /// The package-relative path to resolve. + /// An containing either the absolute path, or an error. + private static Result 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; + } + + /// + /// Validates a manifest text field: required, within the maximum length and without control characters. + /// + /// The field value to validate. + /// The name of the manifest field, used in error messages. + /// The maximum allowed length of the field. + /// An representing either a successful operation, or an error. + private static Result 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; + } + + /// + /// Creates a validation error for an invalid theme pack. + /// + /// The human-readable description of the package error. + /// The validation error describing the invalid theme pack. + private static Error PackageInvalid(string description) + { + return Error.Validation(code: "Theme.Package.Invalid", description: description); + } + + /// + /// Removes every script element from a theme template, so that no script bundled in the theme runs when scripts are disabled. + /// + /// The template content to strip script elements from. + /// The template content without script elements. + private static string StripScriptElements(string template) + { + return s_scriptElementPattern.Replace(template, string.Empty); + } + + /// + /// Resolves the storage path of a theme pack directory for a theme identifier. + /// + /// The manifest id of the theme. + /// The absolute path of the theme pack directory. + private string ResolveThemePath(string themeId) + { + return Path.Combine(_storageRoot, themeId); + } + + /// + /// Removes stale files and directories left over in the staging directory. + /// + 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); + } + } + } + + /// + /// Resolves a configured path to an absolute path, rooted against the base directory when relative. + /// + /// The base directory the path is rooted against when relative. + /// The path from the configuration. + /// The absolute path. + private static string ResolvePath(string basePath, string configuredPath) + { + return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(basePath, configuredPath)); + } +} diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index af9eda89..43b33ac7 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -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=;Database=;User Id=;Password=;" diff --git a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs new file mode 100644 index 00000000..ed0b0169 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Api.Common.Routes.Themes; + +/// +/// Class for the collection of the theme routes of the API. +/// +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}"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpoint.cs new file mode 100644 index 00000000..b995549c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/{themeId} route. +/// +public class DeleteThemeEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteThemeCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete theme commands. + public DeleteThemeEndpoint(ICommandHandler> deleteThemeCommandHandler) + { + _deleteThemeCommandHandler = deleteThemeCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Themes.DELETE_THEME); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes the theme identified by . + /// + /// The request containing the theme to delete. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteThemeRequest request, CancellationToken cancellationToken) + { + Result result = await _deleteThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointSummary.cs new file mode 100644 index 00000000..b6baa1fd --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "General.Validation", new[] + { + "ThemeIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs new file mode 100644 index 00000000..25a9a914 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes route. +/// +public class InstallThemeEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _installThemeCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling install theme commands. + public InstallThemeEndpoint(ICommandHandler> installThemeCommandHandler) + { + _installThemeCommandHandler = installThemeCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Themes.INSTALL_THEME); + Version(1); + DontCatchExceptions(); + } + + /// + /// Installs the theme pack uploaded in the multipart form of the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(InstallThemeRequest request, CancellationToken cancellationToken) + { + IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault(); + Result result = await _installThemeCommandHandler.HandleAsync(request.ToCommand(archive?.OpenReadStream(), archive?.FileName), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs new file mode 100644 index 00000000..298ed743 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "General.Validation", new[] + { + "ThemeArchiveCannotBeNull" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpoint.cs new file mode 100644 index 00000000..b949d246 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/current route. +/// +public class SetCurrentThemeEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _setCurrentThemeCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling set current theme commands. + public SetCurrentThemeEndpoint(ICommandHandler> setCurrentThemeCommandHandler) + { + _setCurrentThemeCommandHandler = setCurrentThemeCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Themes.SET_CURRENT_THEME); + Version(1); + DontCatchExceptions(); + } + + /// + /// Sets the theme stored in as the currently active theme. + /// + /// The request containing the theme to activate. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetCurrentThemeRequest request, CancellationToken cancellationToken) + { + Result result = await _setCurrentThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs new file mode 100644 index 00000000..a26d0331 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "General.Validation", new[] + { + "ThemeIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs new file mode 100644 index 00000000..7191b7b0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/current route. +/// +public class GetCurrentThemeEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getCurrentThemeQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get current theme queries. + public GetCurrentThemeEndpoint(IQueryHandler> getCurrentThemeQueryHandler) + { + _getCurrentThemeQueryHandler = getCurrentThemeQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Themes.GET_CURRENT_THEME); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the currently active theme. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + Result result = await _getCurrentThemeQueryHandler.HandleAsync(new GetCurrentThemeQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointSummary.cs new file mode 100644 index 00000000..1a584f12 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + )); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpoint.cs new file mode 100644 index 00000000..fdc7c39d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/{themeId}/archive route. +/// +public class GetThemeArchiveEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getThemeArchiveQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get theme archive queries. + public GetThemeArchiveEndpoint(IQueryHandler> getThemeArchiveQueryHandler) + { + _getThemeArchiveQueryHandler = getThemeArchiveQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Themes.GET_THEME_ARCHIVE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the downloadable archive of the theme identified by . + /// + /// The request containing the theme to archive. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThemeArchiveRequest request, CancellationToken cancellationToken) + { + Result result = await _getThemeArchiveQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.File(success.Bytes, success.ContentType, fileDownloadName: success.FileName), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointSummary.cs new file mode 100644 index 00000000..6f4a78c9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "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" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs new file mode 100644 index 00000000..1fefad91 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/{themeId}/assets/{assetPath} route. +/// +public class GetThemeAssetEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getThemeAssetQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get theme asset queries. + public GetThemeAssetEndpoint(IQueryHandler> getThemeAssetQueryHandler) + { + _getThemeAssetQueryHandler = getThemeAssetQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Themes.GET_THEME_ASSET); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the asset of the theme stored in . + /// + /// The request containing the theme and the path of the asset to get. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThemeAssetRequest request, CancellationToken cancellationToken) + { + Result result = await _getThemeAssetQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.File(success.Bytes, success.ContentType), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointSummary.cs new file mode 100644 index 00000000..0c3e7fb7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + { + { + "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" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs new file mode 100644 index 00000000..ba384018 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/settings route. +/// +public class GetThemeSettingsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getThemeSettingsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get theme settings queries. + public GetThemeSettingsEndpoint(IQueryHandler> getThemeSettingsQueryHandler) + { + _getThemeSettingsQueryHandler = getThemeSettingsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Themes.GET_THEME_SETTINGS); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the theme engine settings. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + Result result = await _getThemeSettingsQueryHandler.HandleAsync(new GetThemeSettingsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs new file mode 100644 index 00000000..791d45f6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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" + )); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs new file mode 100644 index 00000000..b6b10f9e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes/{themeId}/templates/{pageKey} route. +/// +public class GetThemeTemplateEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getThemeTemplateQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get theme template queries. + public GetThemeTemplateEndpoint(IQueryHandler> getThemeTemplateQueryHandler) + { + _getThemeTemplateQueryHandler = getThemeTemplateQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Themes.GET_THEME_TEMPLATE); + Version(1); + AllowAnonymous(); + DontCatchExceptions(); + } + + /// + /// Gets the template of the theme selected by the page key stored in . + /// + /// The request containing the theme and the page key of the template to get. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThemeTemplateRequest request, CancellationToken cancellationToken) + { + Result result = await _getThemeTemplateQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs new file mode 100644 index 00000000..6980380f --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 + ), + "
{{content}}
" + )); + + 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 + { + { + "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" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpoint.cs new file mode 100644 index 00000000..d6f0282d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpoint.cs @@ -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; + +/// +/// API endpoint for the /themes route. +/// +public class GetThemesEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getThemesQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get themes queries. + public GetThemesEndpoint(IQueryHandler>> getThemesQueryHandler) + { + _getThemesQueryHandler = getThemesQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Themes.GET_THEMES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of all the installed themes. + /// + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) + { + Result> result = await _getThemesQueryHandler.HandleAsync(new GetThemesQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs new file mode 100644 index 00000000..f4d20771 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs @@ -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; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs index f0651b05..84bdaf0c 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiHttpClient.cs @@ -192,6 +192,34 @@ public class ApiHttpClient : IApiHttpClient return await SendRequestAsync(request, cancellationToken).ConfigureAwait(false); } + /// + /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + public async Task PostMultipartAsync(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(request, cancellationToken).ConfigureAwait(false); + } + /// /// 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 and throws an . diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index cfbb30ad..fa208872 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -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 /// The deserialized response containing the result of the PUT request. Task PutAsync(string endpoint, TModel data, CancellationToken cancellationToken = default); + /// + /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default); + /// /// Sends a POST request to the specified as an asynchronous operation and returns the result. /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs deleted file mode 100644 index 257f3ff9..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/InstalledThemeDto.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for an installed theme. -/// -/// The validated theme manifest. -/// The display metadata of the theme. -/// The absolute path of the installed theme directory. -[DebuggerDisplay("Manifest name: {Manifest.Name}")] -public sealed record InstalledThemeDto( - ThemeManifestDto Manifest, - ThemeInfoDto Info, - string RootPath -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs deleted file mode 100644 index d9d84f2d..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/PersistedThemeSettingsDto.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for the settings persisted for the theme engine. -/// -[DebuggerDisplay("CurrentThemeId: {CurrentThemeId}")] -public sealed class PersistedThemeSettingsDto -{ - /// - /// Gets or sets the unique identifier of the currently selected theme. - /// - public string CurrentThemeId { get; set; } = string.Empty; -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs deleted file mode 100644 index 22338ad5..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInstallationMetadataDto.cs +++ /dev/null @@ -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; - -/// -/// Data transfer object for the metadata persisted alongside an installed theme. -/// -[DebuggerDisplay("Source: {Source}")] -public sealed class ThemeInstallationMetadataDto -{ - /// - /// Gets or sets the source the theme was installed from. - /// - public ThemeInstallSource Source { get; set; } - - /// - /// Gets or sets the UTC timestamp at which the theme was installed. - /// - public DateTimeOffset InstalledAtUtc { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs new file mode 100644 index 00000000..632cac46 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs @@ -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; + +/// +/// Data transfer object for a theme returned by the remote API. +/// +/// The unique identifier of the theme. +/// The manifest id of the theme, used by clients to reference it. +/// The display name of the theme. +/// The description of the theme. +/// The author of the theme. +/// The version of the theme, using semantic version form. +/// The path of the theme preview image, relative to the theme pack root, or when the theme has no preview. +/// The source the theme was installed from. +/// Whether the theme is the currently active one. +/// The UTC timestamp at which the theme was installed. +[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 +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs new file mode 100644 index 00000000..636830db --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the theme engine settings returned by the remote API. +/// +/// The maximum allowed size of a theme archive, in bytes. +/// Whether theme templates may contain script elements and theme assets may include script files. +/// The identifier of the theme selected when no valid current theme is available. +[DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")] +public sealed record ThemeSettingsResponseDto( + long MaxArchiveBytes, + bool AllowThemeScripts, + string DefaultThemeId +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateResponseDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateResponseDto.cs new file mode 100644 index 00000000..f3a8d1e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeTemplateResponseDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the template of a theme returned by the remote API. +/// +/// The theme the template belongs to. +/// The sanitized content of the template. +[DebuggerDisplay("ThemeId: {Theme.ThemeId}")] +public sealed record ThemeTemplateResponseDto( + ThemeResponseDto Theme, + string Template +); diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs index bd397d21..8bea5b86 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerConfiguration.cs @@ -36,11 +36,6 @@ internal static class PresentationWebLayerConfiguration .ValidateFluently() .ValidateOnStart(); - serviceCollection.AddOptions() - .Bind(configuration.GetRequiredSection(ThemeEngineOptionsDto.SECTION_NAME)) - .ValidateFluently() - .ValidateOnStart(); - return serviceCollection; } } diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 4a5a04a5..23efe7b7 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -301,7 +301,6 @@ public static class PresentationWebLayerServices services.AddHttpContextAccessor(); services.Configure(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs new file mode 100644 index 00000000..60f6fb80 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/DeleteThemeRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Themes; + +/// +/// Represents a request to delete a theme. +/// +/// The manifest id of the theme to delete. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record DeleteThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs new file mode 100644 index 00000000..56705036 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeArchiveRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Themes; + +/// +/// Represents a request to download the archive of a theme. +/// +/// The manifest id of the theme to download. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record GetThemeArchiveRequest( + string? ThemeId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs new file mode 100644 index 00000000..6d3f040b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/GetThemeAssetRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Themes; + +/// +/// Represents a request to get an asset file of a theme. +/// +/// The manifest id of the theme. +/// The asset path relative to the theme pack root. +[DebuggerDisplay("ThemeId: {ThemeId}, Path: {Path}")] +public record GetThemeAssetRequest( + string? ThemeId, + string? Path +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs new file mode 100644 index 00000000..81c7c2ac --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/SetCurrentThemeRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Themes; + +/// +/// Represents a request to set the currently active theme. +/// +/// The manifest id of the theme to activate. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record SetCurrentThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs new file mode 100644 index 00000000..8c8bc704 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs @@ -0,0 +1,23 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the themes endpoints of the remote API. + /// + 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}"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs new file mode 100644 index 00000000..3ff06780 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the themes pages. + /// + public static class Themes + { + public const string GET_THEMES = "{culture}/admin/themes/api-get-themes"; + public const string INSTALL_THEME = "{culture}/admin/themes/api-install-theme"; + public const string SET_CURRENT_THEME = "{culture}/admin/themes/api-set-current-theme"; + public const string DELETE_THEME = "{culture}/admin/themes/api-delete-theme/{themeId}"; + public const string DOWNLOAD_THEME = "{culture}/admin/themes/api-download-theme/{themeId}"; + public const string THEME_ASSETS = "theme-assets/{themeId}/{*path}"; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpoint.cs new file mode 100644 index 00000000..48ef5220 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// API endpoint for the /{culture}/admin/themes/api-delete-theme/{themeId} route. +/// +public class DeleteThemeEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public DeleteThemeEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Themes.DELETE_THEME); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Deletes the theme identified by . + /// + /// The request containing the theme to delete. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteThemeRequest request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.ThemeId)) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty."); + + await _themeService.DeleteThemeAsync(request.ThemeId, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs new file mode 100644 index 00000000..1c69055e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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."; + + RequestParam(r => r.ThemeId, "The manifest id of the theme to delete."); + + Response(200, "The theme was successfully deleted.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpoint.cs new file mode 100644 index 00000000..434c9fce --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// API endpoint for the /{culture}/admin/themes/api-download-theme/{themeId} route. +/// +public class DownloadThemeEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public DownloadThemeEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Themes.DOWNLOAD_THEME); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Downloads the archive of the theme identified by . + /// + /// The request containing the theme to download. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThemeArchiveRequest request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.ThemeId)) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty."); + + ThemeArchiveDto archive = await _themeService.BuildArchiveAsync(request.ThemeId, cancellationToken).ConfigureAwait(false); + return Results.File(archive.Content, "application/zip", archive.FileName); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs new file mode 100644 index 00000000..112f6b51 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DownloadThemeEndpointSummary() + { + Summary = "Downloads the archive of a theme."; + Description = "Downloads the ZIP archive of the installed theme identified by the request."; + + RequestParam(r => r.ThemeId, "The manifest id of the theme to download."); + + Response(200, "The ZIP archive of the theme is returned.", "application/zip"); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs new file mode 100644 index 00000000..d1fd73ee --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; + +/// +/// API endpoint for the /{culture}/admin/themes/api-get-themes route. +/// +public class GetThemesEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public GetThemesEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Themes.GET_THEMES); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Gets the installed themes together with the current theme and the theme engine settings. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + IReadOnlyList themes = await _themeService.GetThemesAsync(cancellationToken).ConfigureAwait(false); + ThemeInfoDto currentTheme = await _themeService.GetCurrentThemeAsync(cancellationToken).ConfigureAwait(false); + ThemeSettingsResponseDto settings = await _themeService.GetThemeSettingsAsync(cancellationToken).ConfigureAwait(false); + + ThemeAdminDto themeAdmin = new() + { + Themes = themes, + CurrentThemeId = currentTheme.Id, + AllowThemeScripts = settings.AllowThemeScripts, + MaxArchiveBytes = settings.MaxArchiveBytes + }; + return JsonSuccess(themeAdmin); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointSummary.cs new file mode 100644 index 00000000..057749e4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetThemesEndpointSummary() + { + Summary = "Retrieves the theme administration data."; + Description = "Retrieves the installed themes, together with the current theme and the theme engine settings."; + + Response(200, "The theme administration data is returned.", example: new SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpoint.cs new file mode 100644 index 00000000..5eb56544 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; + +/// +/// API endpoint for the /{culture}/admin/themes/api-install-theme route. +/// +public class InstallThemeEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public InstallThemeEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Themes.INSTALL_THEME); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Installs the theme pack uploaded in the multipart form of the request. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault(); + if (archive is null) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The uploaded theme archive is missing."); + + await using Stream archiveStream = archive.OpenReadStream(); + ThemeInfoDto theme = await _themeService.InstallAsync(archiveStream, archive.FileName, cancellationToken).ConfigureAwait(false); + return JsonSuccess(theme); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointSummary.cs new file mode 100644 index 00000000..81000bf8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointSummary.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + 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 SuccessResponse(true, default)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpoint.cs new file mode 100644 index 00000000..cd169032 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; + +/// +/// API endpoint for the /{culture}/admin/themes/api-set-current-theme route. +/// +public class SetCurrentThemeEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public SetCurrentThemeEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Themes.SET_CURRENT_THEME); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Sets the theme identified by as the currently active theme. + /// + /// The request containing the theme to activate. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetCurrentThemeRequest request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.ThemeId)) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty."); + + await _themeService.SetCurrentThemeAsync(request.ThemeId, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs new file mode 100644 index 00000000..e7811d5d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Requests.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeEndpointSummary() + { + Summary = "Sets the currently active theme."; + Description = "Sets the theme identified by the request as the currently active theme."; + + RequestParam(r => r.ThemeId, "The manifest id of the theme to activate."); + + Response(200, "The theme was successfully activated.", example: new SuccessResponse(true)); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs new file mode 100644 index 00000000..2abfe226 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; + +/// +/// API endpoint for the /theme-assets/{themeId}/{path} route. +/// +public class ThemeAssetsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public ThemeAssetsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Themes.THEME_ASSETS); + AllowAnonymous(); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + } + + /// + /// Serves the asset of the theme stored in , fetched from the remote API. + /// + /// The request containing the theme and the path of the asset. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetThemeAssetRequest request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.ThemeId) || string.IsNullOrWhiteSpace(request.Path)) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id and the asset path are required."); + + BlobDataDto blob = await _apiHttpClient.GetBlobAsync( + ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{assetPath}", request.Path), cancellationToken).ConfigureAwait(false); + return Results.File(blob.Data, blob.ContentType); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs new file mode 100644 index 00000000..96cbb9e4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ThemeAssetsEndpointSummary() + { + Summary = "Retrieves an asset file of a theme."; + Description = "Serves the binary content of an asset file of a theme, fetched from the remote API."; + + RequestParam(r => r.ThemeId, "The manifest id of the theme."); + RequestParam(r => r.Path, "The asset path relative to the theme pack root."); + + Response(200, "The asset file of the theme is returned.", "application/octet-stream"); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index c5328293..f5e0a0ce 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -321,6 +321,9 @@ Eigenname der Sprache darf maximal 50 Zeichen lang sein! + + Das letzte mitgelieferte Theme kann nicht gelöscht werden! + Bibliothek existiert bereits! @@ -378,6 +381,9 @@ Seitenzahl muss größer als null sein! + + Der Seiten-Schlüssel darf nicht leer sein! + Übergeordneter Knoten darf nicht null sein! @@ -489,6 +495,30 @@ Das Buch ist nicht in der Serie! + + Das Theme-Archiv darf nicht null sein! + + + Das Theme-Archiv konnte nicht gelesen werden! + + + Der Theme-Asset-Pfad darf nicht leer sein! + + + Das Theme kann nicht gelöscht werden! + + + Die Theme-Dateien konnten nicht gelesen werden! + + + Die Theme-ID darf nicht leer sein! + + + Das Theme ist nicht verfügbar! + + + Das angegebene Theme wurde nicht gefunden! + Titel darf nicht leer sein! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 53a1ee57..2796fff9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -321,6 +321,9 @@ Language native name must be maximum 50 characters long! + + The last bundled theme cannot be deleted! + Library already exists! @@ -378,6 +381,9 @@ Page count must be greater than zero! + + Page key cannot be empty! + Parent node cannot be null! @@ -489,6 +495,30 @@ The book is not in the series! + + Theme archive cannot be null! + + + The theme archive could not be read! + + + Theme asset path cannot be empty! + + + The theme cannot be deleted! + + + The theme files could not be read! + + + Theme id cannot be empty! + + + The theme is not available! + + + The specified theme was not found! + Title cannot be empty! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index 5b86070e..ece0e07f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -321,6 +321,9 @@ ¡El nombre nativo del idioma debe tener máximo 50 caracteres! + + ¡El último tema incluido no se puede eliminar! + ¡La biblioteca ya existe! @@ -378,6 +381,9 @@ ¡El número de páginas debe ser mayor que cero! + + ¡La clave de página no puede estar vacía! + ¡El nodo padre no puede ser nulo! @@ -489,6 +495,30 @@ ¡El libro no está en la serie! + + ¡El archivo del tema no puede ser nulo! + + + ¡No se pudo leer el archivo del tema! + + + ¡La ruta del recurso del tema no puede estar vacía! + + + ¡El tema no se puede eliminar! + + + ¡No se pudieron leer los archivos del tema! + + + ¡El id del tema no puede estar vacío! + + + ¡El tema no está disponible! + + + ¡El tema especificado no fue encontrado! + ¡El título no puede estar vacío! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index b100f70c..9c616507 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -321,6 +321,9 @@ Le nom natif de la langue ne doit pas dépasser 50 caractères ! + + Le dernier thème inclus ne peut pas être supprimé ! + La bibliothèque existe déjà ! @@ -378,6 +381,9 @@ Le nombre de pages doit être supérieur à zéro ! + + La clé de page ne peut pas être vide ! + Le nœud parent ne peut pas être nul! @@ -489,6 +495,30 @@ Le livre n'est pas dans la série ! + + L'archive du thème ne peut pas être nulle ! + + + L'archive du thème n'a pas pu être lue ! + + + Le chemin de la ressource du thème ne peut pas être vide ! + + + Le thème ne peut pas être supprimé ! + + + Les fichiers du thème n'ont pas pu être lus ! + + + L'identifiant du thème ne peut pas être vide ! + + + Le thème n'est pas disponible ! + + + Le thème spécifié est introuvable ! + Le titre ne peut pas être vide ! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index 16584872..7236cc2f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -321,6 +321,9 @@ Il nome nativo della lingua deve essere lungo al massimo 50 caratteri! + + L'ultimo tema incluso non può essere eliminato! + La libreria esiste già! @@ -378,6 +381,9 @@ Il numero di pagine deve essere maggiore di zero! + + La chiave di pagina non può essere vuota! + Il nodo padre non può essere nullo! @@ -489,6 +495,30 @@ Il libro non è presente nella serie! + + L'archivio del tema non può essere nullo! + + + L'archivio del tema non può essere letto! + + + Il percorso della risorsa del tema non può essere vuoto! + + + Il tema non può essere eliminato! + + + I file del tema non possono essere letti! + + + L'id del tema non può essere vuoto! + + + Il tema non è disponibile! + + + Il tema specificato non è stato trovato! + Il titolo non può essere vuoto! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 5f1e06e0..7a3c3c38 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -321,6 +321,9 @@ 言語の固有名は最大50文字までです! + + 最後の同梱テーマは削除できません! + ライブラリはすでに存在します! @@ -378,6 +381,9 @@ ページ数は0より大きくなければなりません! + + ページキーは空にできません! + 親ノードをnullにすることはできません! @@ -489,6 +495,30 @@ この本はシリーズに含まれていません! + + テーマアーカイブは null にできません! + + + テーマアーカイブを読み取れませんでした! + + + テーマアセットのパスは空にできません! + + + テーマは削除できません! + + + テーマのファイルを読み取れませんでした! + + + テーマ ID は空にできません! + + + テーマを利用できません! + + + 指定されたテーマが見つかりませんでした! + タイトルを空にすることはできません! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 1c28604f..2101b9ae 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -321,6 +321,9 @@ Language native name must be maximum 50 characters long! + + The last bundled theme cannot be deleted! + Library already exists! @@ -378,6 +381,9 @@ Page count must be greater than zero! + + Page key cannot be empty! + Parent node cannot be null! @@ -489,6 +495,30 @@ The book is not in the series! + + Theme archive cannot be null! + + + The theme archive could not be read! + + + Theme asset path cannot be empty! + + + The theme cannot be deleted! + + + The theme files could not be read! + + + Theme id cannot be empty! + + + The theme is not available! + + + The specified theme was not found! + Title cannot be empty! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index c526acfc..e6c30e94 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -321,6 +321,9 @@ Numele nativ al limbii trebuie să aibă maximum 50 caractere! + + Ultima temă inclusă nu poate fi ștearsă! + Biblioteca există deja! @@ -378,6 +381,9 @@ Numărul de pagini trebuie să fie mai mare decât zero! + + Cheia de pagină nu poate fi goală! + Nodul părinte nu poate fi nul! @@ -489,6 +495,30 @@ Cartea nu este în serie! + + Arhiva temei nu poate fi nulă! + + + Arhiva temei nu a putut fi citită! + + + Calea resursei temei nu poate fi goală! + + + Tema nu poate fi ștearsă! + + + Fișierele temei nu au putut fi citite! + + + Id-ul temei nu poate fi gol! + + + Tema nu este disponibilă! + + + Tema specificată nu a fost găsită! + Titlul nu poate fi gol! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index 0b91bfb2..f2f287bf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -321,6 +321,9 @@ Исходное название языка не должно превышать 50 символов! + + Последнюю встроенную тему нельзя удалить! + Библиотека уже существует! @@ -378,6 +381,9 @@ Количество страниц должно быть больше нуля! + + Ключ страницы не может быть пустым! + Родительский узел не может быть пустым! @@ -489,6 +495,30 @@ Книга не входит в серию! + + Архив темы не может быть пустым! + + + Не удалось прочитать архив темы! + + + Путь к ресурсу темы не может быть пустым! + + + Тему нельзя удалить! + + + Не удалось прочитать файлы темы! + + + Идентификатор темы не может быть пустым! + + + Тема недоступна! + + + Указанная тема не найдена! + Название не может быть пустым! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index bfc9dadc..37905256 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -321,6 +321,9 @@ 语言本地名称最多只能有50个字符! + + 不能删除最后一个内置主题! + 库已存在! @@ -378,6 +381,9 @@ 页数必须大于零! + + 页面键不能为空! + 父节点不能为空! @@ -489,6 +495,30 @@ 该图书不在系列中! + + 主题存档不能为空! + + + 无法读取主题存档! + + + 主题资源路径不能为空! + + + 主题不能删除! + + + 无法读取主题文件! + + + 主题 ID 不能为空! + + + 主题不可用! + + + 未找到指定的主题! + 标题不能为空! diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs index a9031382..660d0c91 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs @@ -36,11 +36,7 @@ public sealed class ThemePageRenderer /// An containing either the rendered HTML, or an error. public async Task> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default) { - Result documentResult = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken); - if (documentResult.IsFailure) - return Result.Failure(documentResult.Errors); - - ThemeRenderDocumentDto document = documentResult.Value; + ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken); model.ThemeId = document.Theme.Id; model.ThemeName = document.Theme.Name; diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs index 76578d42..f9807e5d 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -1,20 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Enums.Themes; -using Lumina.Presentation.Web.Common.Primitives; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Concurrent; +using Lumina.Presentation.Web.Common.Routes; 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 @@ -22,185 +14,51 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Themes; /// -/// Manages the installed theme packages: installation, selection, rendering documents and archives. +/// Facade over the theme endpoints of the remote API, which stores and serves the theme packs, while the rendering logic stays in this project. /// public sealed class ThemeService { - private const string MANIFEST_FILE_NAME = "theme.json"; - private const string INSTALLATION_FILE_NAME = ".theme-install.json"; - private const long MAX_MANIFEST_BYTES = 64 * 1024; - - private static readonly Regex s_themeIdPattern = new( - "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - - private static readonly Regex s_templateKeyPattern = new( - "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - - private static readonly Regex s_versionPattern = new( - "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - - private static readonly Regex s_pathSegmentPattern = new( - "^[A-Za-z0-9][A-Za-z0-9._ -]*$", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - - private static readonly HashSet s_assetExtensions = new(StringComparer.OrdinalIgnoreCase) - { - ".css", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", - ".woff", ".woff2", ".ttf" - }; - - private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web) - { - PropertyNameCaseInsensitive = true, - MaxDepth = 16 - }; - - private static readonly JsonSerializerOptions s_metadataJsonOptions = new(JsonSerializerDefaults.Web) - { - WriteIndented = true - }; - - private readonly ThemeEngineOptionsDto _options; - private readonly ThemeSettingsStore _settingsStore; - private readonly ThemeTemplateEngine _templateEngine; - private readonly ILogger _logger; - private readonly string _contentRoot; - private readonly string _storageRoot; - private readonly string _stagingRoot; - private readonly ConcurrentDictionary _themes = new(StringComparer.OrdinalIgnoreCase); - private readonly SemaphoreSlim _mutationGate = new(1, 1); - private bool _initialized; + private readonly IApiHttpClient _apiHttpClient; /// /// Initializes a new instance of the class. /// - /// The web host environment, used to resolve the content root. - /// The theme engine configuration options. - /// The store that persists the current theme selection. - /// The template engine used to validate installed templates. - /// The logger for this service. - public ThemeService( - IWebHostEnvironment environment, - IOptions options, - ThemeSettingsStore settingsStore, - ThemeTemplateEngine templateEngine, - ILogger logger) + /// Injected service for interactions with the API. + public ThemeService(IApiHttpClient apiHttpClient) { - _contentRoot = environment.ContentRootPath; - _options = options.Value; - _settingsStore = settingsStore; - _templateEngine = templateEngine; - _logger = logger; - _storageRoot = ResolvePath(_contentRoot, _options.StoragePath); - _stagingRoot = Path.Combine(_storageRoot, ".staging"); - } - - /// - /// Gets a value indicating whether theme templates may load script files. - /// - public bool AllowThemeScripts => _options.AllowThemeScripts; - - /// - /// Gets the maximum allowed size of a theme archive, in bytes. - /// - public long MaxArchiveBytes => _options.MaxArchiveBytes; - - /// - /// Loads the bundled and previously installed themes into memory and selects a valid current theme. - /// - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> InitializeAsync(CancellationToken cancellationToken = default) - { - await _mutationGate.WaitAsync(cancellationToken); - try - { - if (_initialized) - return Result.Success; - - Directory.CreateDirectory(_storageRoot); - Directory.CreateDirectory(_stagingRoot); - CleanStagingDirectory(); - - string sampleThemeDirectory = Path.Combine(_contentRoot, "SampleThemes"); - if (Directory.Exists(sampleThemeDirectory)) - { - foreach (string? archivePath in Directory.EnumerateFiles(sampleThemeDirectory, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)) - { - await using FileStream archive = File.OpenRead(archivePath); - Result installResult = await InstallCoreAsync(archive, skipIfInstalled: true, source: ThemeInstallSource.Bundled, cancellationToken); - if (installResult.IsFailure) - return Result.Failure(installResult.Errors); - } - } - - foreach (string themeDirectory in Directory.EnumerateDirectories(_storageRoot)) - { - if (Path.GetFileName(themeDirectory).StartsWith('.')) - continue; - - Result loadResult = await LoadInstalledThemeAsync(themeDirectory, cancellationToken); - if (loadResult.IsFailure) - { - _logger.LogWarning("Skipping invalid installed theme directory {ThemeDirectory}. {Error}", themeDirectory, loadResult.FirstError.Description); - continue; - } - - _themes[loadResult.Value.Manifest.Id] = loadResult.Value; - } - - if (_themes.IsEmpty) - return Error.Failure(code: "Theme.NoInstalledThemes", description: "No valid themes are installed. Ensure the SampleThemes archives are present."); - - string? currentThemeId = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken); - if (currentThemeId is null || !_themes.ContainsKey(currentThemeId)) - await EnsureValidCurrentThemeAsync(cancellationToken); - _initialized = true; - return Result.Success; - } - finally - { - _mutationGate.Release(); - } + _apiHttpClient = apiHttpClient; } /// /// Gets the display metadata of all installed themes. /// - /// The list of installed theme metadata. - public IReadOnlyList GetThemes() + /// Cancellation token that can be used to stop the execution. + /// The list of installed themes. + public async Task> GetThemesAsync(CancellationToken cancellationToken = default) { - return [.. _themes.Values - .Select(theme => theme.Info) - .OrderByDescending(theme => theme.IsBundled) - .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)]; + ThemeResponseDto[] themes = await _apiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, cancellationToken).ConfigureAwait(false); + return [.. themes.Select(ToThemeInfo)]; } /// - /// Determines whether a theme with the specified identifier is installed. - /// - /// The theme identifier to look up. - /// true when the theme is installed; otherwise, false. - public bool IsInstalled(string themeId) - { - return !string.IsNullOrWhiteSpace(themeId) && _themes.ContainsKey(themeId); - } - - /// - /// Gets the identifier of the currently selected theme, resolving a valid selection when needed. + /// Gets the display metadata of the currently active theme. /// /// Cancellation token that can be used to stop the execution. - /// The identifier of the current theme. - public async Task GetCurrentThemeIdAsync(CancellationToken cancellationToken = default) + /// The current theme. + public async Task GetCurrentThemeAsync(CancellationToken cancellationToken = default) { - string? current = await _settingsStore.GetCurrentThemeIdAsync(cancellationToken); - if (current is not null && _themes.ContainsKey(current)) - return current; + ThemeResponseDto theme = await _apiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, cancellationToken).ConfigureAwait(false); + return ToThemeInfo(theme); + } - return await EnsureValidCurrentThemeAsync(cancellationToken); + /// + /// Gets the theme engine settings used by the administration interface. + /// + /// Cancellation token that can be used to stop the execution. + /// The theme engine settings. + public async Task GetThemeSettingsAsync(CancellationToken cancellationToken = default) + { + return await _apiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, cancellationToken).ConfigureAwait(false); } /// @@ -208,37 +66,32 @@ public sealed class ThemeService /// /// The identifier of the theme to select. /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - public async Task> SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default) + public async Task SetCurrentThemeAsync(string themeId, CancellationToken cancellationToken = default) { - if (string.IsNullOrWhiteSpace(themeId) || !_themes.ContainsKey(themeId)) - return ThemeNotFound(themeId); - - await _settingsStore.SetCurrentThemeIdAsync(themeId, cancellationToken); - return Result.Success; + await _apiHttpClient.PutAsync(ApiRoutes.Themes.SET_CURRENT_THEME, new { ThemeId = themeId }, cancellationToken).ConfigureAwait(false); } /// - /// Installs a theme from the provided archive. + /// Installs a theme from the provided archive, replacing the files of an existing theme with the same manifest id. /// - /// The ZIP archive stream of the theme package. + /// The ZIP archive stream of the theme pack. + /// The file name of the uploaded archive. /// Cancellation token that can be used to stop the execution. - /// An containing either the installed theme metadata, or an error. - public async Task> InstallAsync(Stream archive, CancellationToken cancellationToken = default) + /// The installed theme metadata. + public async Task InstallAsync(Stream archive, string fileName, CancellationToken cancellationToken = default) { - await _mutationGate.WaitAsync(cancellationToken); - try - { - Result installedResult = await InstallCoreAsync(archive, skipIfInstalled: false, source: ThemeInstallSource.Uploaded, cancellationToken); - if (installedResult.IsFailure) - return Result.Failure(installedResult.Errors); + ThemeResponseDto theme = await _apiHttpClient.PostMultipartAsync(ApiRoutes.Themes.INSTALL_THEME, archive, fileName, "archive", cancellationToken).ConfigureAwait(false); + return ToThemeInfo(theme); + } - return installedResult.Value.Info; - } - finally - { - _mutationGate.Release(); - } + /// + /// Deletes a theme. + /// + /// The identifier of the theme to delete. + /// Cancellation token that can be used to stop the execution. + public async Task DeleteThemeAsync(string themeId, CancellationToken cancellationToken = default) + { + await _apiHttpClient.DeleteAsync(ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false); } /// @@ -247,68 +100,18 @@ public sealed class ThemeService /// The page key that selects the template to render. /// The optional theme to render with, falling back to the current theme when null. /// Cancellation token that can be used to stop the execution. - /// An containing either the render document, or an error. - public async Task> GetRenderDocumentAsync(string pageKey, string? requestedThemeId, CancellationToken cancellationToken = default) + /// The render document. + public async Task GetRenderDocumentAsync(string pageKey, string? requestedThemeId, CancellationToken cancellationToken = default) { - InstalledThemeDto installedTheme; - if (!string.IsNullOrWhiteSpace(requestedThemeId)) - { - if (!_themes.TryGetValue(requestedThemeId, out InstalledThemeDto? requestedTheme)) - return ThemeNotFound(requestedThemeId); - - installedTheme = requestedTheme; - } + string themeId; + if (string.IsNullOrWhiteSpace(requestedThemeId)) + themeId = (await GetCurrentThemeAsync(cancellationToken).ConfigureAwait(false)).Id; else - { - string currentThemeId = await GetCurrentThemeIdAsync(cancellationToken); - installedTheme = _themes[currentThemeId]; - } + themeId = requestedThemeId; - if (!installedTheme.Manifest.Templates.TryGetValue(pageKey, out string? templatePath)) - templatePath = installedTheme.Manifest.Templates["default"]; - - Result fullTemplatePathResult = ResolveContainedPath(installedTheme.RootPath, templatePath); - if (fullTemplatePathResult.IsFailure) - return Result.Failure(fullTemplatePathResult.Errors); - - string template = await File.ReadAllTextAsync(fullTemplatePathResult.Value, cancellationToken); - return new ThemeRenderDocumentDto(installedTheme.Info, template); - } - - /// - /// Resolves the absolute path of an allowed theme asset, when it exists. - /// - /// The theme identifier. - /// The asset path relative to the theme package root. - /// The resolved absolute path of the asset, empty when not resolved. - /// true when the asset was resolved; otherwise, false. - public bool TryResolveAsset(string themeId, string assetPath, out string fullPath) - { - fullPath = string.Empty; - if (!_themes.TryGetValue(themeId, out InstalledThemeDto? installedTheme)) - return false; - - Result normalizedPathResult = NormalizeRelativePath(assetPath); - if (normalizedPathResult.IsFailure) - return false; - - string normalizedPath = normalizedPathResult.Value; - if (!normalizedPath.StartsWith("assets/", StringComparison.Ordinal)) - return false; - - string extension = Path.GetExtension(normalizedPath); - if (!IsAllowedAssetExtension(extension)) - return false; - - Result candidateResult = ResolveContainedPath(installedTheme.RootPath, normalizedPath); - if (candidateResult.IsFailure) - return false; - - if (!File.Exists(candidateResult.Value)) - return false; - - fullPath = candidateResult.Value; - return true; + ThemeTemplateResponseDto response = await _apiHttpClient.GetAsync( + ApiRoutes.Themes.GET_THEME_TEMPLATE.Replace("{themeId}", themeId).Replace("{pageKey}", pageKey), cancellationToken).ConfigureAwait(false); + return new ThemeRenderDocumentDto(ToThemeInfo(response.Theme), response.Template); } /// @@ -316,574 +119,21 @@ public sealed class ThemeService /// /// The identifier of the theme to archive. /// Cancellation token that can be used to stop the execution. - /// An containing either the theme archive, or an error. - public async Task> BuildArchiveAsync(string themeId, CancellationToken cancellationToken = default) + /// The theme archive. + public async Task BuildArchiveAsync(string themeId, CancellationToken cancellationToken = default) { - if (!_themes.TryGetValue(themeId, out InstalledThemeDto? installedTheme)) - return ThemeNotFound(themeId); - - MemoryStream output = new(); - using (ZipArchive archive = new(output, ZipArchiveMode.Create, leaveOpen: true)) - { - foreach (string? filePath in Directory.EnumerateFiles(installedTheme.RootPath, "*", SearchOption.AllDirectories) - .Where(path => !string.Equals(Path.GetFileName(path), INSTALLATION_FILE_NAME, StringComparison.Ordinal)) - .OrderBy(path => path, StringComparer.Ordinal)) - { - string relativePath = Path.GetRelativePath(installedTheme.RootPath, 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); - } - } - - output.Position = 0; - string safeVersion = installedTheme.Manifest.Version.Replace('+', '-'); - return new ThemeArchiveDto($"{installedTheme.Manifest.Id}-{safeVersion}.zip", output); + BlobDataDto blob = await _apiHttpClient.GetBlobAsync(ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false); + return new ThemeArchiveDto($"{themeId}.zip", new MemoryStream(blob.Data)); } /// - /// Installs a theme package from an archive stream into the storage root. + /// Converts a theme response from the remote API to the display metadata of the theme. /// - /// The ZIP archive stream of the theme package. - /// Whether an already installed theme with the same id is accepted without reinstalling. - /// The source the theme is installed from. - /// Cancellation token that can be used to stop the execution. - /// An containing either the installed theme, or an error. - private async Task> InstallCoreAsync(Stream sourceArchive, bool skipIfInstalled, ThemeInstallSource source, CancellationToken cancellationToken) + /// The theme response to convert. + /// The converted theme display metadata. + private static ThemeInfoDto ToThemeInfo(ThemeResponseDto theme) { - string workId = Guid.NewGuid().ToString("N"); - string temporaryArchivePath = Path.Combine(_stagingRoot, $"{workId}.zip"); - string extractionPath = Path.Combine(_stagingRoot, workId); - - try - { - Result copyResult = await CopyArchiveWithLimitAsync(sourceArchive, temporaryArchivePath, cancellationToken); - if (copyResult.IsFailure) - return Result.Failure(copyResult.Errors); - - Directory.CreateDirectory(extractionPath); - Result extractResult = await ExtractArchiveAsync(temporaryArchivePath, extractionPath, cancellationToken); - if (extractResult.IsFailure) - return Result.Failure(extractResult.Errors); - - Result stagedResult = await LoadInstalledThemeAsync(extractionPath, cancellationToken, sourceOverride: source); - if (stagedResult.IsFailure) - return Result.Failure(stagedResult.Errors); - - InstalledThemeDto stagedTheme = stagedResult.Value; - string destination = Path.Combine(_storageRoot, stagedTheme.Manifest.Id); - - if (Directory.Exists(destination)) - { - if (!skipIfInstalled) - return Error.Conflict(code: "Theme.AlreadyInstalled", description: $"A theme with id '{stagedTheme.Manifest.Id}' is already installed."); - - Result existingResult = await LoadInstalledThemeAsync(destination, cancellationToken); - if (existingResult.IsFailure) - return Result.Failure(existingResult.Errors); - - _themes[existingResult.Value.Manifest.Id] = existingResult.Value; - return existingResult.Value; - } - - ThemeInstallationMetadataDto metadata = new() - { - Source = source, - InstalledAtUtc = DateTimeOffset.UtcNow - }; - string metadataJson = JsonSerializer.Serialize(metadata, s_metadataJsonOptions); - await File.WriteAllTextAsync(Path.Combine(extractionPath, INSTALLATION_FILE_NAME), metadataJson, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken); - - Directory.Move(extractionPath, destination); - Result installedResult = await LoadInstalledThemeAsync(destination, cancellationToken); - if (installedResult.IsFailure) - return Result.Failure(installedResult.Errors); - - _themes[installedResult.Value.Manifest.Id] = installedResult.Value; - return installedResult.Value; - } - catch (InvalidDataException exception) - { - _logger.LogWarning(exception, "An uploaded theme archive could not be read."); - return Error.Failure(code: "Theme.Archive.ReadFailed", description: "The uploaded file is not a readable ZIP archive."); - } - finally - { - if (File.Exists(temporaryArchivePath)) - File.Delete(temporaryArchivePath); - - if (Directory.Exists(extractionPath)) - Directory.Delete(extractionPath, recursive: true); - } - } - - /// - /// Copies the source archive to the staging directory while enforcing the maximum archive size. - /// - /// The archive stream to copy. - /// The temporary file to copy the archive into. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> 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 Error.Validation(code: "Theme.Archive.Empty", description: "The uploaded theme archive is empty."); - - return Result.Success; - } - - /// - /// Extracts a staged theme archive into the staging extraction directory after validating its entries. - /// - /// The path of the staged ZIP archive. - /// The directory the archive is extracted into. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> ExtractArchiveAsync(string archivePath, string extractionPath, CancellationToken cancellationToken) - { - using ZipArchive archive = ZipFile.OpenRead(archivePath); - if (archive.Entries.Count == 0) - return Error.Validation(code: "Theme.Archive.Empty", description: "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 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 normalizedPathResult = NormalizeRelativePath(entry.FullName, allowTrailingSlash: true); - if (normalizedPathResult.IsFailure) - return Result.Failure(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 directoryValidationResult = ValidatePackageDirectory(normalizedPath); - if (directoryValidationResult.IsFailure) - return Result.Failure(directoryValidationResult.Errors); - - Result directoryPathResult = ResolveContainedPath(extractionPath, normalizedPath); - if (directoryPathResult.IsFailure) - return Result.Failure(directoryPathResult.Errors); - - Directory.CreateDirectory(directoryPathResult.Value); - continue; - } - - Result fileValidationResult = ValidatePackageFile(normalizedPath); - if (fileValidationResult.IsFailure) - return Result.Failure(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 outputPathResult = ResolveContainedPath(extractionPath, normalizedPath); - if (outputPathResult.IsFailure) - return Result.Failure(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; - } - - /// - /// Loads and validates the manifest, templates and metadata of an installed theme directory. - /// - /// The absolute path of the installed theme directory. - /// Cancellation token that can be used to stop the execution. - /// The install source to report, overriding the persisted metadata when provided. - /// An containing either the installed theme, or an error. - private async Task> LoadInstalledThemeAsync(string themeRoot, CancellationToken cancellationToken, ThemeInstallSource? sourceOverride = null) - { - 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 = await File.ReadAllTextAsync(manifestPath, cancellationToken); - manifest = JsonSerializer.Deserialize(json, s_manifestJsonOptions); - } - catch (JsonException) - { - return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json is not valid JSON."); - } - catch (IOException) - { - return Error.Failure(code: "Theme.Files.Unreadable", description: "The theme files could not be read."); - } - - if (manifest is null) - return Error.Validation(code: "Theme.Manifest.InvalidJson", description: "theme.json contains no manifest object."); - - Result manifestValidationResult = ValidateManifest(themeRoot, manifest); - if (manifestValidationResult.IsFailure) - return Result.Failure(manifestValidationResult.Errors); - - foreach (string templatePath in manifest.Templates.Values.Distinct(StringComparer.Ordinal)) - { - Result fullTemplatePathResult = ResolveContainedPath(themeRoot, templatePath); - if (fullTemplatePathResult.IsFailure) - return Result.Failure(fullTemplatePathResult.Errors); - - try - { - string template = await File.ReadAllTextAsync(fullTemplatePathResult.Value, cancellationToken); - Result templateValidationResult = _templateEngine.Validate(template); - if (templateValidationResult.IsFailure) - return Result.Failure(templateValidationResult.Errors); - } - catch (IOException) - { - return Error.Failure(code: "Theme.Files.Unreadable", description: "The theme files could not be read."); - } - } - - ThemeInstallSource source = sourceOverride ?? await ReadInstallSourceAsync(themeRoot, cancellationToken); - string previewUrl = string.IsNullOrWhiteSpace(manifest.Preview) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{manifest.Id}/{manifest.Preview}"; - ThemeInfoDto info = new(manifest.Id, manifest.Name, manifest.Description, manifest.Author, manifest.Version, previewUrl, source == ThemeInstallSource.Bundled); - - return new InstalledThemeDto(manifest, info, Path.GetFullPath(themeRoot)); - } - - /// - /// Validates the manifest fields and template mappings, normalizing the referenced paths. - /// - /// The absolute path of the theme package root. - /// The manifest to validate. - /// An representing either a successful operation, or an error. - private Result ValidateManifest(string themeRoot, ThemeManifestDto manifest) - { - if (manifest.SchemaVersion != 1) - return PackageInvalid("Only theme schemaVersion 1 is supported."); - - if (manifest.Id is null || !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 nameResult = ValidateText(manifest.Name, "name", 80); - if (nameResult.IsFailure) - return nameResult; - - Result descriptionResult = ValidateText(manifest.Description, "description", 300); - if (descriptionResult.IsFailure) - return descriptionResult; - - Result authorResult = ValidateText(manifest.Author, "author", 80); - if (authorResult.IsFailure) - return authorResult; - - Result 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 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 normalizedPathResult = NormalizeRelativePath(path); - if (normalizedPathResult.IsFailure) - return Result.Failure(normalizedPathResult.Errors); - - string normalizedPath = normalizedPathResult.Value; - if (!normalizedPath.StartsWith("templates/", StringComparison.Ordinal) || !string.Equals(Path.GetExtension(normalizedPath), ".html", StringComparison.OrdinalIgnoreCase)) - return PackageInvalid($"Template '{key}' must point to an HTML file under templates/."); - - Result fullTemplatePathResult = ResolveContainedPath(themeRoot, normalizedPath); - if (fullTemplatePathResult.IsFailure) - return Result.Failure(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 previewPathResult = NormalizeRelativePath(manifest.Preview); - if (previewPathResult.IsFailure) - return Result.Failure(previewPathResult.Errors); - - string previewPath = previewPathResult.Value; - Result fullPreviewPathResult = ResolveContainedPath(themeRoot, previewPath); - if (fullPreviewPathResult.IsFailure) - return Result.Failure(fullPreviewPathResult.Errors); - - if (!previewPath.StartsWith("assets/", StringComparison.Ordinal) || !IsAllowedAssetExtension(Path.GetExtension(previewPath)) || !File.Exists(fullPreviewPathResult.Value)) - return PackageInvalid("The preview must reference an existing asset file."); - - manifest.Preview = previewPath; - } - - return Result.Success; - } - - /// - /// Reads the persisted install source of a theme directory, defaulting to Uploaded when absent or invalid. - /// - /// The absolute path of the installed theme directory. - /// Cancellation token that can be used to stop the execution. - /// The install source of the theme. - private static async Task ReadInstallSourceAsync(string themeRoot, CancellationToken cancellationToken) - { - string metadataPath = Path.Combine(themeRoot, INSTALLATION_FILE_NAME); - if (!File.Exists(metadataPath)) - return ThemeInstallSource.Uploaded; - - try - { - string json = await File.ReadAllTextAsync(metadataPath, cancellationToken); - return JsonSerializer.Deserialize(json, s_metadataJsonOptions)?.Source ?? ThemeInstallSource.Uploaded; - } - catch (JsonException) - { - return ThemeInstallSource.Uploaded; - } - } - - /// - /// Selects and persists a valid current theme, preferring the configured default theme. - /// - /// Cancellation token that can be used to stop the execution. - /// The identifier of the selected theme. - private async Task EnsureValidCurrentThemeAsync(CancellationToken cancellationToken) - { - string preferred = _options.DefaultThemeId; - string selected = _themes.ContainsKey(preferred) ? preferred : _themes.Values.OrderBy(theme => theme.Info.Name, StringComparer.OrdinalIgnoreCase).First().Manifest.Id; - await _settingsStore.SetCurrentThemeIdAsync(selected, cancellationToken); - return selected; - } - - /// - /// Validates that a package file resides in the manifest, template or asset locations. - /// - /// The normalized package-relative path of the file. - /// An representing either a successful operation, or an error. - private Result ValidatePackageFile(string normalizedPath) - { - if (string.Equals(normalizedPath, MANIFEST_FILE_NAME, StringComparison.Ordinal)) - return Result.Success; - - if (normalizedPath.StartsWith("templates/", StringComparison.Ordinal) && string.Equals(Path.GetExtension(normalizedPath), ".html", StringComparison.OrdinalIgnoreCase)) - return Result.Success; - - if (normalizedPath.StartsWith("assets/", StringComparison.Ordinal) && IsAllowedAssetExtension(Path.GetExtension(normalizedPath))) - return Result.Success; - - return PackageInvalid($"Theme file '{normalizedPath}' is outside the allowed manifest, template, or asset locations."); - } - - /// - /// Validates that a package directory resides under the templates or assets locations. - /// - /// The normalized package-relative path of the directory. - /// An representing either a successful operation, or an error. - private static Result 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."); - } - - /// - /// Determines whether the file extension is an allowed theme asset extension. - /// - /// The file extension, including the leading dot. - /// true when the extension is allowed; otherwise, false. - private bool IsAllowedAssetExtension(string extension) - { - return s_assetExtensions.Contains(extension) || (_options.AllowThemeScripts && string.Equals(extension, ".js", StringComparison.OrdinalIgnoreCase)); - } - - /// - /// Normalizes a package-relative path, rejecting paths that escape the package or violate the path rules. - /// - /// The package-relative path to normalize. - /// Whether a trailing slash, used for directory entries, is permitted. - /// An containing either the normalized path, or an error. - private static Result 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); - } - - /// - /// Resolves a package-relative path against a package root, rejecting paths that escape the root. - /// - /// The absolute path of the package root. - /// The package-relative path to resolve. - /// An containing either the absolute path, or an error. - private static Result 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; - } - - /// - /// Validates a manifest text field: required, within the maximum length and without control characters. - /// - /// The field value to validate. - /// The name of the manifest field, used in error messages. - /// The maximum allowed length of the field. - /// An representing either a successful operation, or an error. - private static Result 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; - } - - /// - /// Creates a validation error for an invalid theme package. - /// - /// The human-readable description of the package error. - /// The validation error describing the invalid theme package. - private static Error PackageInvalid(string description) - { - return Error.Validation(code: "Theme.Package.Invalid", description: description); - } - - /// - /// Creates a not found error for a theme identifier that is not installed. - /// - /// The missing theme identifier. - /// The not found error describing the missing theme. - private static Error ThemeNotFound(string themeId) - { - return Error.NotFound(code: "Theme.NotFound", description: $"The theme '{themeId}' is not installed."); - } - - /// - /// Removes stale files and directories left over in the staging directory. - /// - 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); - } - } - } - - /// - /// Resolves a configured path to an absolute path, rooted against the content root when relative. - /// - /// The content root of the application. - /// The path from the configuration. - /// The absolute path. - private static string ResolvePath(string contentRoot, string configuredPath) - { - return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(contentRoot, configuredPath)); + string previewUrl = string.IsNullOrWhiteSpace(theme.PreviewPath) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{theme.ThemeId}/{theme.PreviewPath}"; + return new ThemeInfoDto(theme.ThemeId, theme.Name, theme.Description, theme.Author, theme.Version, previewUrl, theme.InstallSource == ThemeInstallSource.Bundled); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs deleted file mode 100644 index ab5bf1c1..00000000 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeSettingsStore.cs +++ /dev/null @@ -1,115 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Configuration; -using Lumina.Presentation.Web.Common.DTO.Themes; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.IO; -using System.Text; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Themes; - -/// -/// Persists and reads the theme settings file that stores the current theme selection. -/// -public sealed class ThemeSettingsStore -{ - private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web) - { - WriteIndented = true - }; - - private readonly string _settingsPath; - private readonly ILogger _logger; - private readonly SemaphoreSlim _gate = new(1, 1); - - /// - /// Initializes a new instance of the class. - /// - /// The web host environment, used to resolve the content root. - /// The theme engine configuration options. - /// The logger for this store. - public ThemeSettingsStore(IWebHostEnvironment webHostEnvironment, IOptions themeEngineOptions, ILogger logger) - { - _logger = logger; - _settingsPath = ResolvePath(webHostEnvironment.ContentRootPath, themeEngineOptions.Value.SettingsPath); - } - - /// - /// Reads the unique identifier of the currently selected theme. - /// - /// Cancellation token that can be used to stop the execution. - /// The current theme identifier, or when no selection is persisted. - public async Task GetCurrentThemeIdAsync(CancellationToken cancellationToken = default) - { - await _gate.WaitAsync(cancellationToken); - try - { - if (!File.Exists(_settingsPath)) - return null; - - try - { - string json = await File.ReadAllTextAsync(_settingsPath, cancellationToken); - return JsonSerializer.Deserialize(json, s_jsonOptions)?.CurrentThemeId; - } - catch (JsonException exception) - { - _logger.LogWarning(exception, "Ignoring an invalid theme settings file at {SettingsPath}.", _settingsPath); - return null; - } - } - finally - { - _gate.Release(); - } - } - - /// - /// Persists the unique identifier of the currently selected theme. - /// - /// The theme unique identifier to persist. - /// Cancellation token that can be used to stop the execution. - public async Task SetCurrentThemeIdAsync(string themeId, CancellationToken cancellationToken = default) - { - await _gate.WaitAsync(cancellationToken); - try - { - string? directory = Path.GetDirectoryName(_settingsPath) ?? throw new InvalidOperationException("The theme settings path has no parent directory."); - Directory.CreateDirectory(directory); - - string temporaryPath = Path.Combine(directory, $".theme-settings-{Guid.NewGuid():N}.tmp"); - try - { - string json = JsonSerializer.Serialize(new PersistedThemeSettingsDto { CurrentThemeId = themeId }, s_jsonOptions); - await File.WriteAllTextAsync(temporaryPath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), cancellationToken); - File.Move(temporaryPath, _settingsPath, overwrite: true); - } - finally - { - if (File.Exists(temporaryPath)) - File.Delete(temporaryPath); - } - } - finally - { - _gate.Release(); - } - } - - /// - /// Resolves a configured path to an absolute path, rooted against the content root when relative. - /// - /// The content root of the application. - /// The path from the configuration. - /// The absolute path. - private static string ResolvePath(string contentRoot, string configuredPath) - { - return Path.GetFullPath(Path.IsPathRooted(configuredPath) ? configuredPath : Path.Combine(contentRoot, configuredPath)); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs index a2aae9ce..e00d65f1 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs @@ -36,7 +36,7 @@ public sealed class ThemeTemplateEngine int cursor = 0; Result> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0); if (parseResult.IsFailure) - return Result.Failure(parseResult.Errors); + return parseResult.Errors; return Result.Success; } @@ -55,12 +55,12 @@ public sealed class ThemeTemplateEngine int cursor = 0; Result> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0); if (parseResult.IsFailure) - return Result.Failure(parseResult.Errors); + return parseResult.Errors; StringBuilder output = new(Math.Min(template.Length * 2, 256 * 1024)); Result renderResult = RenderNodes(parseResult.Value, new ThemeRenderScopeDto(model, Parent: null), output); if (renderResult.IsFailure) - return Result.Failure(renderResult.Errors); + return renderResult.Errors; return output.ToString(); } @@ -103,7 +103,7 @@ public sealed class ThemeTemplateEngine string expression = template[(opening + 3)..closing].Trim(); Result expressionResult = ValidateExpression(expression); if (expressionResult.IsFailure) - return Result>.Failure(expressionResult.Errors); + return expressionResult.Errors; nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false)); cursor = closing + 3; @@ -129,11 +129,11 @@ public sealed class ThemeTemplateEngine string expression = tag[1..].Trim(); Result sectionExpressionResult = ValidateExpression(expression); if (sectionExpressionResult.IsFailure) - return Result>.Failure(sectionExpressionResult.Errors); + return sectionExpressionResult.Errors; Result> childrenResult = ParseNodes(template, ref cursor, expression, depth + 1); if (childrenResult.IsFailure) - return Result>.Failure(childrenResult.Errors); + return childrenResult.Errors; nodes.Add(new ThemeSectionNodeDto(expression, Inverted: tag[0] == '^', Children: childrenResult.Value)); break; @@ -143,7 +143,7 @@ public sealed class ThemeTemplateEngine string closingName = tag[1..].Trim(); Result closingNameResult = ValidateExpression(closingName); if (closingNameResult.IsFailure) - return Result>.Failure(closingNameResult.Errors); + return closingNameResult.Errors; if (expectedClosingName is null) return TemplateInvalid($"Closing section '{closingName}' has no matching opening section."); @@ -158,7 +158,7 @@ public sealed class ThemeTemplateEngine string expression = tag[1..].Trim(); Result unescapedExpressionResult = ValidateExpression(expression); if (unescapedExpressionResult.IsFailure) - return Result>.Failure(unescapedExpressionResult.Errors); + return unescapedExpressionResult.Errors; nodes.Add(new ThemeVariableNodeDto(expression, ShouldBeEscaped: false)); break; @@ -167,7 +167,7 @@ public sealed class ThemeTemplateEngine { Result variableResult = ValidateExpression(tag); if (variableResult.IsFailure) - return Result>.Failure(variableResult.Errors); + return variableResult.Errors; nodes.Add(new ThemeVariableNodeDto(tag, ShouldBeEscaped: true)); break; @@ -198,7 +198,7 @@ public sealed class ThemeTemplateEngine { Result textResult = AppendChecked(output, text.Value); if (textResult.IsFailure) - return Result.Failure(textResult.Errors); + return textResult.Errors; break; } @@ -208,7 +208,7 @@ public sealed class ThemeTemplateEngine string value = ConvertToString(resolved); Result variableResult = AppendChecked(output, variable.ShouldBeEscaped ? HtmlEncoder.Default.Encode(value) : value); if (variableResult.IsFailure) - return Result.Failure(variableResult.Errors); + return variableResult.Errors; break; } @@ -216,7 +216,7 @@ public sealed class ThemeTemplateEngine { Result sectionResult = RenderSection(section, scope, output); if (sectionResult.IsFailure) - return Result.Failure(sectionResult.Errors); + return sectionResult.Errors; break; } @@ -257,7 +257,7 @@ public sealed class ThemeTemplateEngine { Result itemResult = RenderNodes(section.Children, new ThemeRenderScopeDto(item, scope), output); if (itemResult.IsFailure) - return Result.Failure(itemResult.Errors); + return itemResult.Errors; } return Result.Success; diff --git a/src/Lumina.Presentation.Web/appsettings.json b/src/Lumina.Presentation.Web/appsettings.json index b83e511e..73c0a7f4 100644 --- a/src/Lumina.Presentation.Web/appsettings.json +++ b/src/Lumina.Presentation.Web/appsettings.json @@ -2,16 +2,6 @@ "EncryptionSettings": { "SecretKey": "" // base64 string }, - "ThemeEngine": { - "StoragePath": "Themes", - "SettingsPath": "theme-settings.json", - "DefaultThemeId": "editorial-paper", - "MaxArchiveBytes": 8388608, - "MaxExpandedBytes": 25165824, - "MaxSingleFileBytes": 6291456, - "MaxEntries": 250, - "AllowThemeScripts": false - }, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": { diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs index 93a80e81..c21b41f9 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -9,6 +9,7 @@ using Lumina.Presentation.Web.Common.Routes; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; @@ -234,6 +235,24 @@ public class StubApiHttpClient : IApiHttpClient throw new InvalidOperationException($"No PUT response is registered for the endpoint '{endpoint}'."); } + /// + /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. + /// + /// The expected type of the response content. + /// The API endpoint where the request is being sent. + /// The stream of the file to upload. + /// The name of the file to upload. + /// The name of the form field carrying the file. + /// Cancellation token that can be used to stop the execution. + /// The deserialized response containing the result of the POST request. + public Task PostMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) + { + PostRequests.Add((endpoint, fileName)); + if (_postResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) + return Task.FromResult((TResponse)responseFactory(fileName)); + throw new InvalidOperationException($"No POST response is registered for the endpoint '{endpoint}'."); + } + /// /// Sends a POST request to the specified as an asynchronous operation and returns the result. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs deleted file mode 100644 index 650670ef..00000000 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CommonSettingsDtoValidatorTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using AutoFixture; -using AutoFixture.AutoNSubstitute; -using Lumina.Domain.Common.Primitives; -using Lumina.Infrastructure.Common.Errors; -using Lumina.Infrastructure.Common.Models.DTO.Configuration; -using Lumina.Infrastructure.Common.Validators; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Infrastructure.UnitTests.Common.Validators; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class CommonSettingsDtoValidatorTests -{ - private readonly CommonSettingsDtoValidator _validator = new(); - private readonly IFixture _fixture; - - /// - /// Initializes a new instance of the class. - /// - public CommonSettingsDtoValidatorTests() - { - _fixture = new Fixture().Customize(new AutoNSubstituteCustomization()); - } - - [Fact] - public void Validate_WhenThemeProvided_ShouldNotHaveValidationError() - { - // Arrange - CommonSettingsDto model = _fixture.Build() - .With(x => x.Theme, "Dark") - .Create(); - - // Act - List result = _validator.Validate(model); - - // Assert - Assert.Empty(result); - } - - [Fact] - public void Validate_WhenThemeNotProvided_ShouldNotHaveValidationError() - { - // Arrange - CommonSettingsDto model = _fixture.Build() - .With(x => x.Theme, string.Empty) - .Create(); - - // Act - List result = _validator.Validate(model); - - // Assert - Assert.Single(result); - Assert.Equal(Errors.Configuration.ApplicationThemeCannotBeEmpty.Description, result[0].Description); - } -} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs index f89b4fc7..c8e436ad 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/DatabaseSettingsDtoValidatorTests.cs @@ -12,7 +12,7 @@ using System.Diagnostics.CodeAnalysis; namespace Lumina.Infrastructure.UnitTests.Common.Validators; /// -/// Contains unit tests for the class. +/// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class DatabaseSettingsDtoValidatorTests @@ -21,7 +21,7 @@ public class DatabaseSettingsDtoValidatorTests private readonly IFixture _fixture; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// public DatabaseSettingsDtoValidatorTests() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs similarity index 56% rename from tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs rename to tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs index bb0e17ff..05e9cc01 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Configuration; -using Lumina.Presentation.Web.Common.Primitives; -using Lumina.Presentation.Web.Common.Validators; -using Lumina.Presentation.Web.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Common.Validators; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion -namespace Lumina.Presentation.Web.UnitTests.Common.Validators; +namespace Lumina.Infrastructure.UnitTests.Common.Validators; /// /// Contains unit tests for the class. @@ -17,6 +17,19 @@ public class ThemeEngineOptionsDtoValidatorTests { private readonly ThemeEngineOptionsDtoValidator _validator = new(); + [Fact] + public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError() + { + // Arrange + ThemeEngineOptionsDto options = new(); + + // Act + List result = _validator.Validate(options); + + // Assert + Assert.Empty(result); + } + [Fact] public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError() { @@ -24,23 +37,25 @@ public class ThemeEngineOptionsDtoValidatorTests ThemeEngineOptionsDto options = new() { StoragePath = string.Empty }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Theme storage path cannot be empty!")); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeStoragePathCannotBeEmpty.Description, result[0].Description); } [Fact] - public void Validate_WhenSettingsPathIsEmpty_ShouldHaveValidationError() + public void Validate_WhenBundledThemesPathIsEmpty_ShouldHaveValidationError() { // Arrange - ThemeEngineOptionsDto options = new() { SettingsPath = string.Empty }; + ThemeEngineOptionsDto options = new() { BundledThemesPath = string.Empty }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Theme settings path cannot be empty!")); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeBundledThemesPathCannotBeEmpty.Description, result[0].Description); } [Fact] @@ -50,10 +65,11 @@ public class ThemeEngineOptionsDtoValidatorTests ThemeEngineOptionsDto options = new() { DefaultThemeId = string.Empty }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Default theme Id cannot be empty!")); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeDefaultThemeIdCannotBeEmpty.Description, result[0].Description); } [Theory] @@ -65,10 +81,11 @@ public class ThemeEngineOptionsDtoValidatorTests ThemeEngineOptionsDto options = new() { MaxArchiveBytes = maxArchiveBytes }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Maximum archive size must be greater than 0!")); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeMaxArchiveBytesMustBePositive.Description, result[0].Description); } [Theory] @@ -80,10 +97,11 @@ public class ThemeEngineOptionsDtoValidatorTests ThemeEngineOptionsDto options = new() { MaxExpandedBytes = maxExpandedBytes }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Maximum expanded size must be greater than 0!")); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeMaxExpandedBytesMustBePositive.Description, result[0].Description); } [Theory] @@ -95,10 +113,11 @@ public class ThemeEngineOptionsDtoValidatorTests ThemeEngineOptionsDto options = new() { MaxSingleFileBytes = maxSingleFileBytes }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Maximum single file size must be greater than 0!")); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeMaxSingleFileBytesMustBePositive.Description, result[0].Description); } [Theory] @@ -110,22 +129,10 @@ public class ThemeEngineOptionsDtoValidatorTests ThemeEngineOptionsDto options = new() { MaxEntries = maxEntries }; // Act - List result = _validator.TestValidate(options); + List result = _validator.Validate(options); // Assert - result.ShouldHaveValidationError(Error.Validation(description: "Maximum entries count must be greater than 0!")); - } - - [Fact] - public void Validate_WhenOptionsAreValid_ShouldNotHaveAnyValidationErrors() - { - // Arrange - ThemeEngineOptionsDto options = new(); - - // Act - List result = _validator.TestValidate(options); - - // Assert - result.ShouldNotHaveAnyValidationErrors(); + Assert.Single(result); + Assert.Equal(Errors.Configuration.ThemeMaxEntriesMustBePositive.Description, result[0].Description); } } From 45dc3f5706301174cf5b7da297bddda4f6ab5552 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 00:16:58 -0700 Subject: [PATCH 02/31] Hard deletes user themes, restores damaged bundled themes and fixes the web theme service DI lifetime --- .../Repositories/Themes/IThemeRepository.cs | 6 +- .../Infrastructure/Themes/IThemeService.cs | 7 ++ .../DeleteTheme/DeleteThemeCommandHandler.cs | 21 ++++-- .../Repositories/Themes/ThemeRepository.cs | 18 +++++ .../Core/Themes/ThemeDetectionSyncJob.cs | 69 ++++++++++++++++++- .../Core/Themes/ThemeService.cs | 11 +++ .../PresentationWebLayerServices.cs | 4 +- 7 files changed, 126 insertions(+), 10 deletions(-) diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs index db094c7a..ae0d994b 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs @@ -1,8 +1,9 @@ #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 Lumina.Domain.Common.Primitives; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -15,7 +16,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Themes; public interface IThemeRepository : IRepository, IGetAllRepositoryAction, IInsertRepositoryAction, - IUpdateRepositoryAction + IUpdateRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets a theme identified by its manifest from the storage medium. diff --git a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs index f9e00778..4ac5fae5 100644 --- a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs @@ -95,6 +95,13 @@ public interface IThemeService /// An representing either a successful operation, or an error. Task> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken); + /// + /// Checks whether the stored pack files of a theme still exist. + /// + /// The manifest id of the theme. + /// when the theme pack files exist, otherwise. + bool HasThemePack(string themeId); + /// /// Gets the paths of the theme pack archives shipped with the application. /// diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs index e329555e..ec859146 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs @@ -112,11 +112,22 @@ public class DeleteThemeCommandHandler : ICommandHandler deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + } await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs index 2dbc7def..330b06ce 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -84,6 +85,23 @@ internal sealed class ThemeRepository : IThemeRepository .FirstOrDefaultAsync(theme => theme.ThemeId == themeId, cancellationToken).ConfigureAwait(false); } + /// + /// Deletes a theme identified by from the storage medium. + /// + /// The id of the theme to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + ThemeEntity? foundTheme = await _luminaDbContext.Themes + .FirstOrDefaultAsync(theme => theme.Id == id, cancellationToken).ConfigureAwait(false); + if (foundTheme is null) + return Errors.Themes.ThemeNotFound; + + _luminaDbContext.Themes.Remove(foundTheme); + return Result.Deleted; + } + /// /// Gets the currently active theme from the storage medium. /// diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index c13ef49a..910d4112 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -57,7 +57,8 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService } // themes that were soft deleted by the user must not be reinstalled automatically - HashSet knownThemeIds = [.. getThemesResult.Value.Select(theme => theme.ThemeId)]; + List themes = [.. getThemesResult.Value]; + HashSet knownThemeIds = [.. themes.Select(theme => theme.ThemeId)]; foreach (string archivePath in _themeService.GetBundledThemeArchivePaths()) { @@ -100,6 +101,72 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); } + await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken); + await unitOfWork.SaveChangesAsync(stoppingToken); } + + /// + /// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered. + /// + /// The unit of work for interacting with the theme repository. + /// The installed themes read from the storage medium. + /// Cancellation token that can be used to stop the execution. + private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List themes, CancellationToken cancellationToken) + { + // a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored + // automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed + // externally, and is the only case where the files are restored + List brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; + if (brokenThemes.Count is 0) + return; + + foreach (ThemeEntity brokenTheme in brokenThemes) + { + if (brokenTheme.InstallSource == ThemeInstallSource.Bundled) + { + // the files of a bundled theme that was not deleted by the user are restored from its shipped archive + Result restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken); + if (restoreResult.IsSuccess) + continue; + + _logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); + + // a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later + brokenTheme.IsDeleted = true; + brokenTheme.IsCurrent = null; + brokenTheme.UpdatedOnUtc = DateTime.UtcNow; + brokenTheme.UpdatedBy = default; + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken); + if (updateResult.IsFailure) + _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); + } + else + { + // a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely + _logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); + brokenTheme.IsCurrent = null; + Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken); + if (deleteResult.IsFailure) + _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); + } + } + + // if the deleted theme was the active one, switch to another available theme, preferring the configured default + if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) + return; + + ThemeEntity? replacementTheme = themes + .Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId)) + .OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(); + if (replacementTheme is null) + return; + + replacementTheme.IsCurrent = true; + replacementTheme.UpdatedOnUtc = DateTime.UtcNow; + replacementTheme.UpdatedBy = default; + await unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken); + } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index a2ad40b6..d9e64869 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -105,6 +105,17 @@ public sealed class ThemeService : IThemeService return [.. Directory.EnumerateFiles(_bundledRoot, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)]; } + /// + /// Checks whether the stored pack files of a theme still exist. + /// + /// The manifest id of the theme. + /// when the theme pack files exist, otherwise. + public bool HasThemePack(string themeId) + { + string themePath = ResolveThemePath(themeId); + return Directory.Exists(themePath) && File.Exists(Path.Combine(themePath, MANIFEST_FILE_NAME)); + } + /// /// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id. /// diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 23efe7b7..176cedab 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -301,9 +301,9 @@ public static class PresentationWebLayerServices services.AddHttpContextAccessor(); services.Configure(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024); - services.AddSingleton(); + services.AddScoped(); services.AddSingleton(); - services.AddSingleton(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); From f17e6852395906e77aaaaf5f4f91ae6afcbcffc9 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 06:50:04 -0700 Subject: [PATCH 03/31] Tracks the bundled theme archives --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 898b006a..ca957e19 100644 --- a/.gitignore +++ b/.gitignore @@ -57,6 +57,7 @@ $RECYCLE.BIN/ # Archives *.zip +!src/Lumina.Presentation.Api/Themes/Bundled/*.zip # bundled themes should be tracked *.tar.gz *.rar From e37bb3ecc66d57559960aa58b3c6c554b8e6380f Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 06:50:17 -0700 Subject: [PATCH 04/31] Renders themed pages as swappable sections with path-mirrored template scopes and a Razor fallback --- .../Core/Themes/ThemeDetectionSyncJob.cs | 29 +++++--- .../Core/Themes/ThemeService.cs | 36 +++++++++- .../appsettings.shared.json | 2 +- .../Common/Routes/Themes/ApiRoutes.Themes.cs | 2 +- .../GetThemeTemplateEndpoint.cs | 2 +- .../GetThemeTemplateEndpointSummary.cs | 6 +- .../Lumina.Presentation.Api.csproj | 8 +++ .../Common/DTO/Themes/ContentItemDto.cs | 28 -------- .../Common/DTO/Themes/NavigationItemDto.cs | 20 ------ .../Common/DTO/Themes/StatItemDto.cs | 18 ----- .../Common/DTO/Themes/ThemePageDto.cs | 66 ++---------------- .../DTO/Themes/ThemePageRenderResultDto.cs | 16 +++++ .../Common/DTO/Themes/ThemeViewDto.cs | 18 +++++ .../Common/Routes/ApiRoutes.Themes.cs | 2 +- .../Books/Index/BooksIndexViewEndpoint.cs | 44 +++++++++++- .../Themes/ThemeAssets/ThemeAssetsEndpoint.cs | 2 +- .../Core/Themes/ThemePageDataFactory.cs | 26 +++++++ .../Core/Themes/ThemePageRenderer.cs | 16 ++--- .../Core/Themes/ThemeService.cs | 2 +- .../Core/Themes/ThemeTemplateEngine.cs | 58 +++++++++------- .../Core/Views/Shared/_Layout.cshtml | 1 + .../Core/Views/Shared/_ThemedView.cshtml | 14 ++++ .../Index/BooksIndexViewEndpointTests.cs | 55 +++++++++++++-- .../ThemeAssets/ThemeAssetsEndpointTests.cs | 67 +++++++++++++++++++ 24 files changed, 351 insertions(+), 187 deletions(-) delete mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs delete mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs delete mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index 910d4112..9bdd21e5 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -99,9 +99,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService Result insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken); if (insertResult.IsFailure) _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); + else + themes.Add(themeEntity); } await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken); + await EnsureCurrentThemeExistsAsync(unitOfWork, themes, stoppingToken); await unitOfWork.SaveChangesAsync(stoppingToken); } @@ -112,12 +115,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. /// Cancellation token that can be used to stop the execution. - private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List themes, CancellationToken cancellationToken) + private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) { // a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored // automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed // externally, and is the only case where the files are restored - List brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; + IReadOnlyList brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; if (brokenThemes.Count is 0) return; @@ -151,22 +154,30 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); } } + } - // if the deleted theme was the active one, switch to another available theme, preferring the configured default + /// + /// Activates the configured default theme when no theme is currently active, so the application always has an active theme. + /// + /// The unit of work for interacting with the theme repository. + /// The installed themes read from the storage medium. + /// Cancellation token that can be used to stop the execution. + private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) + { if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) return; - ThemeEntity? replacementTheme = themes + ThemeEntity? defaultTheme = themes .Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId)) .OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) .ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(); - if (replacementTheme is null) + if (defaultTheme is null) return; - replacementTheme.IsCurrent = true; - replacementTheme.UpdatedOnUtc = DateTime.UtcNow; - replacementTheme.UpdatedBy = default; - await unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken); + defaultTheme.IsCurrent = true; + defaultTheme.UpdatedOnUtc = DateTime.UtcNow; + defaultTheme.UpdatedBy = default; + await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken); } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index d9e64869..b8948db1 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -260,10 +260,13 @@ public sealed class ThemeService : IThemeService return manifestResult.Errors; ThemeManifestDto manifest = manifestResult.Value; - if (!manifest.Templates.TryGetValue(pageKey, out string? templatePath)) - templatePath = manifest.Templates["default"]; // the manifest validation guarantees a default template + string themePath = ResolveThemePath(themeId); + string? templatePath = manifest.Templates.TryGetValue(pageKey, out string? explicitPath) + ? explicitPath + : ResolveMirroredTemplatePath(themePath, pageKey); + templatePath ??= manifest.Templates["default"]; // the manifest validation guarantees a default template - Result fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), templatePath); + Result fullPathResult = ResolveContainedPath(themePath, templatePath); if (fullPathResult.IsFailure) return fullPathResult.Errors; @@ -277,6 +280,33 @@ public sealed class ThemeService : IThemeService return template; } + /// + /// Resolves the mirrored template path of a page key, walking up the scopes of the path when the exact mirror does not exist. + /// + /// The absolute path of the theme pack directory. + /// The page key that selects the template. + /// The mirrored template path, or when no mirrored template exists. + private static string? ResolveMirroredTemplatePath(string themePath, string pageKey) + { + string? candidate = pageKey; + while (candidate is not null) + { + // normalize the mirrored candidate so that malicious page keys cannot escape the theme pack + Result normalizedResult = NormalizeRelativePath($"templates/{candidate}.html"); + if (normalizedResult.IsSuccess) + { + Result fullPathResult = ResolveContainedPath(themePath, normalizedResult.Value); + if (fullPathResult.IsSuccess && File.Exists(fullPathResult.Value)) + return normalizedResult.Value; + } + + int lastSlash = candidate.LastIndexOf('/'); + candidate = lastSlash < 0 ? null : candidate[..lastSlash]; + } + + return null; + } + /// /// Gets a theme asset file. /// diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 43b33ac7..6ccc0db4 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -14,7 +14,7 @@ "MaxExpandedBytes": 25165824, "MaxSingleFileBytes": 6291456, "MaxEntries": 250, - "AllowThemeScripts": false + "AllowThemeScripts": true }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;User Id=;Password=;" diff --git a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs index ed0b0169..f9e366ce 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs @@ -12,7 +12,7 @@ public static partial class ApiRoutes 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_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}"; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs index b6b10f9e..439b27f4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate; /// -/// API endpoint for the /themes/{themeId}/templates/{pageKey} route. +/// API endpoint for the /themes/{themeId}/templates/{*pageKey} route. /// public class GetThemeTemplateEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs index 6980380f..545cd57f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs @@ -56,7 +56,7 @@ public class GetThemeTemplateEndpointSummary : Summary { { @@ -78,7 +78,7 @@ public class GetThemeTemplateEndpointSummary : Summary + + + PreserveNewest + PreserveNewest + themes\bundled\%(Filename)%(Extension) + + + diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs deleted file mode 100644 index 01bbaab2..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for a content entry rendered by a theme. -/// -/// The ordering number of the content entry. -/// The title of the content entry. -/// The description of the content entry. -/// The metadata line of the content entry. -/// The badge text of the content entry. -/// The accent color of the content entry. -/// The glyph or icon of the content entry. -/// The URL the content entry links to. -[DebuggerDisplay("Number: {Number}, Title: {Title}")] -public sealed record ContentItemDto( - string Number, - string Title, - string Description, - string Meta, - string Badge, - string Accent, - string Glyph, - string Url -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs deleted file mode 100644 index fef38268..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs +++ /dev/null @@ -1,20 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for a navigation entry rendered by a theme. -/// -/// The unique key of the navigation entry. -/// The display label of the navigation entry. -/// The URL the navigation entry links to. -/// Whether the navigation entry represents the currently displayed page. -[DebuggerDisplay("Key: {Key}, Label: {Label}")] -public sealed record NavigationItemDto( - string Key, - string Label, - string Url, - bool IsCurrent -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs deleted file mode 100644 index 380039a6..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for a statistic rendered by a theme. -/// -/// The numeric or textual value of the statistic. -/// The label of the statistic. -/// The additional detail of the statistic. -[DebuggerDisplay("Value: {Value}, Label: {Label}")] -public sealed record StatItemDto( - string Value, - string Label, - string Detail -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs index 6c3d3113..27968900 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs @@ -6,7 +6,7 @@ using System.Diagnostics; namespace Lumina.Presentation.Web.Common.DTO.Themes; /// -/// Data transfer object for the full model available to a theme template while rendering a page. +/// Data transfer object for the model available to a theme template while rendering a page. /// [DebuggerDisplay("Title: {Title}")] public sealed class ThemePageDto @@ -16,11 +16,6 @@ public sealed class ThemePageDto /// public required string PageKey { get; init; } - /// - /// Gets or sets the name of the site displayed by the theme. - /// - public required string SiteName { get; init; } - /// /// Gets or sets the title of the page. /// @@ -32,72 +27,23 @@ public sealed class ThemePageDto public required string Description { get; init; } /// - /// Gets or sets the eyebrow text shown above the page title. + /// Gets or sets the resolved values exposed to the theme template and its scripts. Each page populates the entries its + /// template needs, such as resolved URLs, identifiers and server paths, and the localized strings of the page under the strings key. /// - public required string Eyebrow { get; init; } + public required IReadOnlyDictionary PageData { get; init; } = new Dictionary(); /// - /// Gets or sets the label of the primary call to action. + /// Gets or sets the identifier of the script section of the page. Populated immediately before rendering. /// - public required string PrimaryActionLabel { get; init; } - - /// - /// Gets or sets the URL of the primary call to action. - /// - public required string PrimaryActionUrl { get; init; } - - /// - /// Gets or sets the label of the secondary call to action. - /// - public required string SecondaryActionLabel { get; init; } - - /// - /// Gets or sets the URL of the secondary call to action. - /// - public required string SecondaryActionUrl { get; init; } - - /// - /// Gets or sets the navigation entries rendered by the theme. - /// - public required IReadOnlyList Navigation { get; init; } - - /// - /// Gets or sets the content entries rendered by the theme. - /// - public required IReadOnlyList Items { get; init; } - - /// - /// Gets or sets the statistics rendered by the theme. - /// - public required IReadOnlyList Stats { get; init; } - - /// - /// Gets or sets a value indicating whether the page is a theme preview. - /// - public bool IsPreview { get; init; } + public string ScriptId { get; set; } = string.Empty; /// /// Gets or sets the identifier of the theme rendering the page. Populated immediately before rendering. /// public string ThemeId { get; set; } = string.Empty; - /// - /// Gets or sets the name of the theme rendering the page. Populated immediately before rendering. - /// - public string ThemeName { get; set; } = string.Empty; - - /// - /// Gets or sets the version of the theme rendering the page. Populated immediately before rendering. - /// - public string ThemeVersion { get; set; } = string.Empty; - /// /// Gets or sets the base URL of the theme assets. Populated immediately before rendering. /// public string AssetBase { get; set; } = string.Empty; - - /// - /// Gets or sets the current year. Populated immediately before rendering. - /// - public int CurrentYear { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs new file mode 100644 index 00000000..0e1bacf7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the rendered content and script of a themed page section. +/// +/// The rendered HTML content of the page section. +/// The rendered script element of the page section, when the template defines one. +[DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")] +public sealed record ThemePageRenderResultDto( + string Content, + string Script +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs new file mode 100644 index 00000000..2ec915c8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the rendered sections of a themed page, served through the shared themed view. +/// +/// The rendered HTML content of the page section. +/// The rendered script element of the page section, when the template defines one. +/// The base URL of the theme assets, used to load the theme stylesheet of the page. +[DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")] +public sealed record ThemeViewDto( + string Content, + string Script, + string AssetBase +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs index 8c8bc704..c7f14c91 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs @@ -15,7 +15,7 @@ public static partial class ApiRoutes 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_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}"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 51c5a6b1..0d281a23 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -2,12 +2,17 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -19,18 +24,32 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.B /// public class BooksIndexViewEndpoint : BaseEndpoint { + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it + // with the configured ResourcesPath, so "Lumina.Presentation.Web.Views.X" resolves to the embedded + // "Lumina.Presentation.Web.Core.Resources.Views.X" resource; including "Core" here would insert it twice + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.WrittenContentLibrary.BookLibrary.Books.Index"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // the page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope + private const string VIEW_PAGE_KEY = "library/written-content-library/book-library/books/index"; + private readonly IApiHttpClient _apiHttpClient; private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IStringLocalizer _localizer; /// /// Initializes a new instance of the class. /// /// Injected service for interactions with the API. /// Injected service for generating URLs from action and controller names, with localization. - public BooksIndexViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService) + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + public BooksIndexViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory) { _apiHttpClient = apiHttpClient; _urlService = urlService; + _themePageRenderer = themePageRenderer; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); } /// @@ -46,7 +65,7 @@ public class BooksIndexViewEndpoint : BaseEndpoint } /// - /// Displays the books browsing view. + /// Displays the books browsing view, rendered by the active theme with a fallback to the Razor view. /// /// The request containing the Id of the media library whose books are browsed. /// Cancellation token that can be used to stop the execution. @@ -55,6 +74,25 @@ public class BooksIndexViewEndpoint : BaseEndpoint if (request.LibraryId is null) return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); LibraryDto library = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false); - return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = library.Title ?? string.Empty, + Description = string.Empty, + PageData = new Dictionary + { + ["libraryId"] = library.Id?.ToString() ?? request.LibraryId.Value.ToString(), + ["itemsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS) ?? string.Empty, + ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result renderResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (renderResult.IsFailure) + return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(renderResult.Value.Content, renderResult.Value.Script, pageModel.AssetBase)); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs index 2abfe226..77476bde 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs @@ -52,7 +52,7 @@ public class ThemeAssetsEndpoint : BaseEndpoint return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id and the asset path are required."); BlobDataDto blob = await _apiHttpClient.GetBlobAsync( - ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{assetPath}", request.Path), cancellationToken).ConfigureAwait(false); + ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{*assetPath}", request.Path), cancellationToken).ConfigureAwait(false); return Results.File(blob.Data, blob.ContentType); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs new file mode 100644 index 00000000..85f1c29c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the page data entries that the themed endpoints expose to their templates. +/// +public static class ThemePageDataFactory +{ + /// + /// Creates the localized strings of a page from the provided localizer, keyed by their resource names. + /// + /// The localizer of the page resources. + /// The localized strings keyed by their resource names. + public static Dictionary CreateLocalizedStrings(IStringLocalizer localizer) + { + Dictionary strings = []; + foreach (LocalizedString localizedString in localizer.GetAllStrings(includeParentCultures: true)) + strings[localizedString.Name] = localizedString.Value; + + return strings; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs index 660d0c91..1e7ceda8 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Primitives; -using System; +using Lumina.Presentation.Web.Common.Services; using System.Threading; using System.Threading.Tasks; #endregion @@ -11,7 +11,7 @@ namespace Lumina.Presentation.Web.Core.Themes; /// /// Renders a theme template against a page model, populating the theme metadata before rendering. /// -public sealed class ThemePageRenderer +public class ThemePageRenderer { private readonly ThemeService _themeService; private readonly ThemeTemplateEngine _templateEngine; @@ -28,22 +28,20 @@ public sealed class ThemePageRenderer } /// - /// Renders the page model with the theme selected for the requested theme identifier. + /// Renders the page model with the theme selected for the requested theme identifier, producing the content and script sections of the page. /// /// The page model to render. /// The optional unique identifier of the theme to render with, falling back to the current theme when . /// Cancellation token that can be used to stop the execution. - /// An containing either the rendered HTML, or an error. - public async Task> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default) + /// An containing either the rendered page, or an error. + public virtual async Task> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default) { ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken); model.ThemeId = document.Theme.Id; - model.ThemeName = document.Theme.Name; - model.ThemeVersion = document.Theme.Version; model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets"; - model.CurrentYear = DateTime.UtcNow.Year; + model.ScriptId = ScriptIdentifierHelper.GenerateScriptId(); - return _templateEngine.Render(document.Template, model); + return _templateEngine.RenderPage(document.Template, model); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs index f9807e5d..ebb5b27a 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -110,7 +110,7 @@ public sealed class ThemeService themeId = requestedThemeId; ThemeTemplateResponseDto response = await _apiHttpClient.GetAsync( - ApiRoutes.Themes.GET_THEME_TEMPLATE.Replace("{themeId}", themeId).Replace("{pageKey}", pageKey), cancellationToken).ConfigureAwait(false); + ApiRoutes.Themes.GET_THEME_TEMPLATE.Replace("{themeId}", themeId).Replace("{*pageKey}", pageKey), cancellationToken).ConfigureAwait(false); return new ThemeRenderDocumentDto(ToThemeInfo(response.Theme), response.Template); } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs index e00d65f1..3a838b82 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs @@ -26,28 +26,12 @@ public sealed class ThemeTemplateEngine RegexOptions.Compiled | RegexOptions.CultureInvariant); /// - /// Validates the structure and expressions of a theme template. - /// - /// The template source to validate. - /// An representing either a successful operation, or an error. - public Result Validate(string template) - { - ArgumentNullException.ThrowIfNull(template); - int cursor = 0; - Result> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0); - if (parseResult.IsFailure) - return parseResult.Errors; - - return Result.Success; - } - - /// - /// Renders a theme template against the provided model. + /// Renders a theme template against the provided model, splitting the reserved top-level scripts section from the page content. /// /// The template source to render. /// The model the template expressions resolve against. - /// An containing either the rendered output, or an error. - public Result Render(string template, object model) + /// An containing either the rendered page, or an error. + public Result RenderPage(string template, object model) { ArgumentNullException.ThrowIfNull(template); ArgumentNullException.ThrowIfNull(model); @@ -57,12 +41,38 @@ public sealed class ThemeTemplateEngine if (parseResult.IsFailure) return parseResult.Errors; - StringBuilder output = new(Math.Min(template.Length * 2, 256 * 1024)); - Result renderResult = RenderNodes(parseResult.Value, new ThemeRenderScopeDto(model, Parent: null), output); - if (renderResult.IsFailure) - return renderResult.Errors; + // the reserved top-level 'scripts' section holds the script of the page and is rendered separately, mirroring the + // 'Scripts' section of a Razor view, so that the layout can host it in the scripts container of the navigator; + // every other top-level node is the content of the page section + List contentNodes = []; + ThemeSectionNodeDto? scriptsSection = null; + foreach (ThemeTemplateNodeDto node in parseResult.Value) + { + if (node is ThemeSectionNodeDto { Inverted: false } section + && scriptsSection is null + && string.Equals(section.Expression, "scripts", StringComparison.OrdinalIgnoreCase)) + { + scriptsSection = section; + continue; + } - return output.ToString(); + contentNodes.Add(node); + } + + StringBuilder contentOutput = new(Math.Min(template.Length * 2, 256 * 1024)); + Result contentResult = RenderNodes(contentNodes, new ThemeRenderScopeDto(model, Parent: null), contentOutput); + if (contentResult.IsFailure) + return contentResult.Errors; + + StringBuilder scriptOutput = new(64 * 1024); + if (scriptsSection is not null) + { + Result scriptResult = RenderNodes(scriptsSection.Children, new ThemeRenderScopeDto(model, Parent: null), scriptOutput); + if (scriptResult.IsFailure) + return scriptResult.Errors; + } + + return new ThemePageRenderResultDto(contentOutput.ToString(), scriptOutput.ToString()); } /// diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index 2b8187f2..d7251b2c 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -22,6 +22,7 @@ + @await RenderSectionAsync("Head", required: false)
diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml new file mode 100644 index 00000000..770fbdad --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml @@ -0,0 +1,14 @@ +@model Lumina.Presentation.Web.Common.DTO.Themes.ThemeViewDto + +@section Head { + @if (!string.IsNullOrEmpty(Model.AssetBase)) + { + + } +} + +@Html.Raw(Model.Content) + +@section Scripts { + @Html.Raw(Model.Script) +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index bc80d5b6..a0d00dc3 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -2,17 +2,22 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +using Lumina.Presentation.Web.Core.Themes; using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.Extensions.Localization; using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -28,6 +33,9 @@ public class BooksIndexViewEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly IUrlService _mockUrlService; + private readonly ThemePageRenderer _mockThemePageRenderer; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; private readonly BooksIndexViewEndpoint _sut; private readonly LibraryDtoFixture _libraryDtoFixture = new(); @@ -38,7 +46,12 @@ public class BooksIndexViewEndpointTests { _mockApiHttpClient = Substitute.For(); _mockUrlService = Substitute.For(); - _sut = Factory.Create(_mockApiHttpClient, _mockUrlService); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns(new LocalizedString[] { new("Search", "Search") }); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory); TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); _sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books"; } @@ -56,22 +69,56 @@ public class BooksIndexViewEndpointTests RedirectHttpResult redirectResult = Assert.IsType(result); Assert.Equal("http://localhost/en-us", redirectResult.Url); await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] - public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldReturnRazorViewResultWithLibraryModel() + public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldRenderThemedPageThroughTheSharedView() { // Arrange LibraryDto expectedLibrary = _libraryDtoFixture.Create(); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(expectedLibrary); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings"); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(new ThemePageRenderResultDto("
content
", ""))); // Act IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); // Assert Assert.IsType(result); - string expectedEndpoint = ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id!.Value.ToString()); - await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => + page.PageKey == "library/written-content-library/book-library/books/index" && + page.Title == expectedLibrary.Title && + page.PageData.ContainsKey("libraryId") && + page.PageData.ContainsKey("settingsUrl") && + page.PageData.ContainsKey("strings") && + string.Equals( + page.PageData["itemsUrl"] as string, + "http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items", + StringComparison.Ordinal)), + Arg.Is(requestedThemeId => requestedThemeId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView() + { + // Arrange + LibraryDto expectedLibrary = _libraryDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedLibrary); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); + + // Act + IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); + + // Assert + Assert.IsType(result); + await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs new file mode 100644 index 00000000..182c9993 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Themes.ThemeAssets; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemeAssetsEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeAssetsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenAssetPathProvided_ShouldFetchAssetWithTheResolvedPath() + { + // Arrange + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(new BlobDataDto { Data = [1, 2, 3], ContentType = "text/css" }); + + // Act + IResult result = await _sut.ExecuteAsync(new GetThemeAssetRequest(ThemeId: "editorial-paper", Path: "assets/style.css"), CancellationToken.None); + + // Assert + FileContentHttpResult fileResult = Assert.IsType(result); + Assert.Equal("text/css", fileResult.ContentType); + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ASSET + .Replace("{themeId}", "editorial-paper") + .Replace("{*assetPath}", "assets/style.css"); + await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAssetPathMissing_ShouldReturnProblem() + { + // Act + IResult result = await _sut.ExecuteAsync(new GetThemeAssetRequest(ThemeId: "editorial-paper", Path: null), CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().GetBlobAsync(Arg.Any(), Arg.Any()); + } +} From 4ef8570854c8cd59d8b0a83f81104450dc035a18 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 10:21:05 -0700 Subject: [PATCH 05/31] Renders every page through the themed shell with a themed navigation menu --- .../Common/DTO/Themes/ThemeLayoutModelDto.cs | 30 +++ .../Common/DTO/Themes/ThemeLayoutPageDto.cs | 18 ++ .../Common/DTO/Themes/ThemeNavEntryDto.cs | 21 ++ .../Common/DTO/Themes/ThemeNavMenuDto.cs | 19 ++ .../Common/DTO/Themes/ThemeNavSectionDto.cs | 17 ++ .../Common/DTO/Themes/ThemeViewDto.cs | 4 +- .../PresentationWebLayerServices.cs | 3 + .../Home/HomeNotFoundViewEndpoint.cs | 49 +++- .../Books/Index/BooksIndexViewEndpoint.cs | 9 +- .../Core/Themes/RazorViewToStringRenderer.cs | 64 +++++ .../Core/Themes/ThemeLayoutRenderer.cs | 95 +++++++ .../Core/Themes/ThemeNavBuilder.cs | 251 ++++++++++++++++++ .../Views/Library/Management/Index.cshtml | 3 +- .../Core/Views/Shared/_AudioPlayer.cshtml | 17 ++ .../Core/Views/Shared/_Layout.cshtml | 152 +++++------ .../Core/Views/Shared/_NavMenu.cshtml | 4 +- .../Core/Views/Shared/_ThemeLayoutHead.cshtml | 11 + .../Views/Shared/_ThemeLayoutScripts.cshtml | 37 +++ .../Core/Views/Shared/_ThemedView.cshtml | 7 - 19 files changed, 707 insertions(+), 104 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs new file mode 100644 index 00000000..b361e203 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed layout template while rendering the shell of a page. +/// +/// The title of the page, rendered by the theme. +/// The base URL of the theme assets. +/// The application head links, such as its global stylesheets. +/// The rendered navigation menu of the page. +/// The rendered content section of the page. +/// The rendered audio player, when the current user is authenticated. +/// The application global scripts, such as its client libraries and configuration. +/// The rendered script section of the page. +/// The inline style of the main content area, used to fill the viewport when the user is not authenticated. +[DebuggerDisplay("Title: {Title}")] +public sealed record ThemeLayoutModelDto( + string Title, + string AssetBase, + string AppHead, + string Nav, + string Content, + string AudioPlayer, + string AppScripts, + string Scripts, + string MainStyle +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs new file mode 100644 index 00000000..5c674c47 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the page content handed to the layout renderer, which wraps it in the themed shell. +/// +/// The title of the page, displayed by the themed shell. +/// The rendered HTML content of the page section. +/// The rendered script element of the page section, when the template defines one. +[DebuggerDisplay("Title: {Title}")] +public sealed record ThemeLayoutPageDto( + string Title, + string Content, + string Script +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs new file mode 100644 index 00000000..3cab20a2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a menu entry of the themed navigation menu, either a link or a submenu. +/// +/// The localized label of the menu entry. +/// The URL of the link, or for a submenu. +/// The CSS classes of the link, such as nav-link for AJAX navigation. +/// The child links of a submenu, empty for a plain link. +[DebuggerDisplay("Label: {Label}")] +public sealed record ThemeNavEntryDto( + string Label, + string? Url, + string? CssClass, + IReadOnlyList Children +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs new file mode 100644 index 00000000..978f3337 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed navigation menu template. +/// +/// The name of the site displayed by the navigation menu. +/// The menu sections of the mobile navigation menu. +/// The menu sections of the desktop navigation menu bar. +[DebuggerDisplay("SiteName: {SiteName}")] +public sealed record ThemeNavMenuDto( + string SiteName, + IReadOnlyList MobileSections, + IReadOnlyList MenubarSections +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs new file mode 100644 index 00000000..cd016274 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a menu section of the themed navigation menu. +/// +/// The localized label of the menu section. +/// The menu entries of the section, visible to the current user. +[DebuggerDisplay("Label: {Label}")] +public sealed record ThemeNavSectionDto( + string Label, + IReadOnlyList Items +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs index 2ec915c8..d3fd5350 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs @@ -9,10 +9,8 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; ///
/// The rendered HTML content of the page section. /// The rendered script element of the page section, when the template defines one. -/// The base URL of the theme assets, used to load the theme stylesheet of the page. [DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")] public sealed record ThemeViewDto( string Content, - string Script, - string AssetBase + string Script ); diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 176cedab..757dc241 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -304,6 +304,9 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddSingleton(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs index 25e9853a..6e5c239e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs @@ -1,9 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion @@ -15,6 +20,26 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Home; ///
public class HomeNotFoundViewEndpoint : BaseEndpoint { + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared.NotFound"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // the page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope + private const string VIEW_PAGE_KEY = "shared/not-found"; + + private readonly ThemePageRenderer _themePageRenderer; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + public HomeNotFoundViewEndpoint(ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory) + { + _themePageRenderer = themePageRenderer; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + /// /// Configures the endpoint. /// @@ -28,12 +53,30 @@ public class HomeNotFoundViewEndpoint : BaseEndpoint } /// - /// Displays the not-found page. + /// Displays the not-found page, rendered by the active theme with a fallback to the Razor view. /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Shared/NotFound.cshtml")); + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = _localizer["PageNotFound"].Value, + Description = _localizer["ThereIsNoPage"].Value, + PageData = new Dictionary + { + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Shared/NotFound.cshtml"); + + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = pageModel.Title }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 0d281a23..d384431e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -89,10 +89,13 @@ public class BooksIndexViewEndpoint : BaseEndpoint } }; - Result renderResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); - if (renderResult.IsFailure) + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library); - return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(renderResult.Value.Content, renderResult.Value.Script, pageModel.AssetBase)); + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = pageModel.Title }); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs new file mode 100644 index 00000000..834fd809 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders a Razor partial to a string, so that the application chrome can be reused by the themed layout renderer. +/// +public sealed class RazorViewToStringRenderer +{ + private readonly ICompositeViewEngine _viewEngine; + private readonly ITempDataProvider _tempDataProvider; + private readonly IServiceProvider _serviceProvider; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// Injected engine used to resolve the partial to render. + /// Injected provider used to create the temp data dictionary of the view context. + /// Injected service provider used to resolve the model metadata provider. + /// Injected accessor for the current HTTP context. + public RazorViewToStringRenderer(ICompositeViewEngine viewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor) + { + _viewEngine = viewEngine; + _tempDataProvider = tempDataProvider; + _serviceProvider = serviceProvider; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Renders the partial with the specified name to a string. + /// + /// The name of the partial to render. + /// Cancellation token that can be used to stop the execution. + /// The rendered HTML of the partial. + public async Task RenderPartialAsync(string partialName, CancellationToken cancellationToken = default) + { + HttpContext httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("The current HTTP context is unavailable."); + ActionContext actionContext = new(httpContext, httpContext.GetRouteData() ?? new RouteData(), new ActionDescriptor()); + IView view = _viewEngine.FindView(actionContext, partialName, isMainPage: false).View + ?? throw new InvalidOperationException($"The partial '{partialName}' could not be found."); + + IModelMetadataProvider metadataProvider = _serviceProvider.GetRequiredService(); + ViewDataDictionary viewData = new(metadataProvider, new ModelStateDictionary()); + using StringWriter writer = new(); + ViewContext viewContext = new(actionContext, view, viewData, new TempDataDictionary(httpContext, _tempDataProvider), writer, new HtmlHelperOptions()); + await view.RenderAsync(viewContext).ConfigureAwait(false); + return writer.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs new file mode 100644 index 00000000..65a7ca79 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders the themed shell of a page, wrapping the page section in the layout and navigation templates of the active theme. +/// +public class ThemeLayoutRenderer +{ + // the page keys mirror the paths of the corresponding Razor views under Core/Views, so that theme templates can override them at the page, section or default scope + private const string LAYOUT_PAGE_KEY = "shared/layout"; + private const string NAV_PAGE_KEY = "shared/nav-menu"; + + private readonly ThemeService _themeService; + private readonly ThemeTemplateEngine _templateEngine; + private readonly RazorViewToStringRenderer _viewRenderer; + private readonly ThemeNavBuilder _navBuilder; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// The service that resolves the render documents. + /// The template engine used to render the documents. + /// The renderer used to produce the application chrome fragments. + /// The builder used to produce the navigation menu model. + /// Injected accessor for the current HTTP context. + public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, IHttpContextAccessor httpContextAccessor) + { + _themeService = themeService; + _templateEngine = templateEngine; + _viewRenderer = viewRenderer; + _navBuilder = navBuilder; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Renders the themed shell of the page, wrapping the page section in the layout template of the active theme. + /// + /// The rendered page section to wrap. + /// The optional unique identifier of the theme to render with, falling back to the current theme when . + /// Cancellation token that can be used to stop the execution. + /// An containing either the full page HTML, or an error. + public virtual async Task> RenderAsync(ThemeLayoutPageDto page, string? requestedThemeId = null, CancellationToken cancellationToken = default) + { + ThemeRenderDocumentDto layoutDocument = await _themeService.GetRenderDocumentAsync(LAYOUT_PAGE_KEY, requestedThemeId, cancellationToken); + string themeId = layoutDocument.Theme.Id; + bool isAuthenticated = _httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated == true; + + string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken); + string nav = await RenderNavAsync(themeId, cancellationToken); + string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty; + string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken); + + ThemeLayoutModelDto layoutModel = new( + page.Title, + $"/theme-assets/{themeId}/assets", + appHead, + nav, + page.Content, + audioPlayer, + appScripts, + page.Script, + isAuthenticated ? string.Empty : "bottom: 0px;"); + + Result renderResult = _templateEngine.RenderPage(layoutDocument.Template, layoutModel); + if (renderResult.IsFailure) + return renderResult.Errors; + + return renderResult.Value.Content; + } + + /// + /// Renders the navigation menu of the active theme, falling back to the application Razor menu when the theme template cannot be rendered. + /// + /// The manifest id of the active theme. + /// Cancellation token that can be used to stop the execution. + /// The rendered navigation menu HTML. + private async Task RenderNavAsync(string themeId, CancellationToken cancellationToken) + { + ThemeNavMenuDto navModel = await _navBuilder.BuildAsync(cancellationToken); + ThemeRenderDocumentDto navDocument = await _themeService.GetRenderDocumentAsync(NAV_PAGE_KEY, themeId, cancellationToken); + Result navRenderResult = _templateEngine.RenderPage(navDocument.Template, navModel); + if (navRenderResult.IsSuccess) + return navRenderResult.Value.Content; + + return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs new file mode 100644 index 00000000..7dd6b983 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs @@ -0,0 +1,251 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the navigation menu model for the themed navigation template, resolving the authorization conditions and localized labels server side. +/// +public sealed class ThemeNavBuilder +{ + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared._NavMenu"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + + private readonly IUrlService _urlService; + private readonly IStringLocalizerFactory _stringLocalizerFactory; + private readonly IAuthorizationService _authorizationService; + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected factory used to create the localizer of the navigation resources. + /// Injected service used to resolve the roles and permissions of the current user. + /// Injected accessor for the current HTTP context. + public ThemeNavBuilder(IUrlService urlService, IStringLocalizerFactory stringLocalizerFactory, IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor) + { + _urlService = urlService; + _stringLocalizerFactory = stringLocalizerFactory; + _authorizationService = authorizationService; + _httpContextAccessor = httpContextAccessor; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Builds the navigation menu model for the current user and request. + /// + /// Cancellation token that can be used to stop the execution. + /// The navigation menu model, with the sections visible to the current user. + public async Task BuildAsync(CancellationToken cancellationToken) + { + ClaimsPrincipal user = _httpContextAccessor.HttpContext?.User ?? new ClaimsPrincipal(); + bool isAuthenticated = user.Identity?.IsAuthenticated == true; + bool isAdmin = isAuthenticated && await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false); + bool canCreateLibraries = isAuthenticated && (isAdmin || await _authorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)); + string returnUrl = Uri.EscapeDataString(GetCurrentRequestUrl()); + ThemeNavEntryDto[] languages = CreateLanguageEntries(returnUrl); + + List mobileSections = []; + mobileSections.Add(CreateSiteSection()); + mobileSections.Add(CreateAccountSection(isAuthenticated)); + if (isAdmin) + mobileSections.Add(CreateAdministratorSection()); + if (isAuthenticated) + mobileSections.Add(CreateLibrarySection(canCreateLibraries)); + mobileSections.Add(new ThemeNavSectionDto(Localize("Language"), languages)); + if (isAuthenticated) + mobileSections.Add(CreateToolsSection(isAuthenticated, languages: [])); + mobileSections.Add(CreateHelpSection()); + + List menubarSections = []; + menubarSections.Add(CreateSiteSection()); + menubarSections.Add(CreateAccountSection(isAuthenticated)); + if (isAdmin) + menubarSections.Add(CreateAdministratorSection()); + if (isAuthenticated) + menubarSections.Add(CreateLibrarySection(canCreateLibraries)); + menubarSections.Add(CreateToolsSection(isAuthenticated, languages)); + menubarSections.Add(CreateHelpSection()); + + return new ThemeNavMenuDto("Lumina", mobileSections, menubarSections); + } + + /// + /// Creates the site section, which links to the home page. + /// + /// The site section of the navigation menu. + private ThemeNavSectionDto CreateSiteSection() + { + return new ThemeNavSectionDto( + "Lumina", + [new ThemeNavEntryDto(Localize("Home"), _urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED), "nav-link", [])]); + } + + /// + /// Creates the account section, whose entries depend on the authentication state of the user. + /// + /// Whether the current user is authenticated. + /// The account section of the navigation menu. + private ThemeNavSectionDto CreateAccountSection(bool isAuthenticated) + { + List items = []; + if (isAuthenticated) + { + items.Add(new ThemeNavEntryDto(Localize("Logout"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT), CssClass: null, Children: [])); + items.Add(new ThemeNavEntryDto(Localize("Register"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("ChangePassword"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("Profile"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW), "nav-link", [])); + } + else + { + items.Add(new ThemeNavEntryDto(Localize("Login"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW), CssClass: null, Children: [])); + items.Add(new ThemeNavEntryDto(Localize("RecoverPassword"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW), CssClass: null, Children: [])); + } + + return new ThemeNavSectionDto(Localize("Account"), items); + } + + /// + /// Creates the administrator section, shown only to administrators. + /// + /// The administrator section of the navigation menu. + private ThemeNavSectionDto CreateAdministratorSection() + { + return new ThemeNavSectionDto( + Localize("Administrator"), + [ + new ThemeNavEntryDto(Localize("ManageRoles"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES), "nav-link", []), + new ThemeNavEntryDto(Localize("ManagePermissions"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS), "nav-link", []), + new ThemeNavEntryDto(Localize("Plugins"), _urlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX), "nav-link", []) + ]); + } + + /// + /// Creates the library section, shown only to authenticated users. + /// + /// Whether the current user can create media libraries. + /// The library section of the navigation menu. + private ThemeNavSectionDto CreateLibrarySection(bool canCreateLibraries) + { + List items = + [ + new ThemeNavEntryDto(Localize("ManageLibraries"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX), "nav-link", []) + ]; + if (canCreateLibraries) + items.Add(new ThemeNavEntryDto(Localize("AddNewLibrary"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("WrittenContent"), Url: null, CssClass: null, + [ + new ThemeNavEntryDto(Localize("Books"), "library/written-content-library/books-library/books", "nav-link", []), + new ThemeNavEntryDto(Localize("Magazines"), "library/written-content/magazines", "nav-link", []) + ])); + items.Add(new ThemeNavEntryDto(Localize("Audio"), Url: null, CssClass: null, + [ + new ThemeNavEntryDto(Localize("Music"), "library/audio/music", "nav-link", []), + new ThemeNavEntryDto(Localize("Interviews"), "library/audio/interviews", "nav-link", []) + ])); + items.Add(new ThemeNavEntryDto(Localize("Video"), Url: null, CssClass: null, + [ + new ThemeNavEntryDto(Localize("Movies"), "library/video/movies", "nav-link", []), + new ThemeNavEntryDto(Localize("TvShows"), "library/video/tvshows", "nav-link", []) + ])); + + return new ThemeNavSectionDto(Localize("Library"), items); + } + + /// + /// Creates the tools section, with the language submenu and the settings entry. + /// + /// Whether the current user is authenticated. + /// The language entries of the submenu. + /// The tools section of the navigation menu. + private ThemeNavSectionDto CreateToolsSection(bool isAuthenticated, IReadOnlyList languages) + { + List items = []; + if (languages.Count > 0) + items.Add(new ThemeNavEntryDto(Localize("Language"), Url: null, CssClass: null, Children: languages)); + if (isAuthenticated) + items.Add(new ThemeNavEntryDto(Localize("Settings"), _urlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX), "nav-link", [])); + + return new ThemeNavSectionDto(Localize("Tools"), items); + } + + /// + /// Creates the help section. + /// + /// The help section of the navigation menu. + private ThemeNavSectionDto CreateHelpSection() + { + return new ThemeNavSectionDto( + Localize("Help"), + [ + new ThemeNavEntryDto(Localize("Documentation"), "help/documentation", "nav-link", []), + new ThemeNavEntryDto(Localize("About"), "help/about", "nav-link", []) + ]); + } + + /// + /// Creates the language entries of the navigation menu, each keeping the current request URL as the return URL. + /// + /// The encoded current request URL used as the return URL. + /// The language entries of the navigation menu. + private ThemeNavEntryDto[] CreateLanguageEntries(string returnUrl) + { + string baseUrl = _urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE) ?? string.Empty; + (string Culture, string DisplayName)[] cultures = + [ + ("zh-cn", "简体中文"), + ("de-de", "Deutsch"), + ("en-us", "English"), + ("es-es", "Español"), + ("fr-fr", "Français"), + ("it-it", "Italiano"), + ("ja-jp", "日本語"), + ("ro-ro", "Română"), + ("ru-ru", "Русский") + ]; + + ThemeNavEntryDto[] entries = new ThemeNavEntryDto[cultures.Length]; + for (int index = 0; index < cultures.Length; index++) + { + (string culture, string displayName) = cultures[index]; + entries[index] = new ThemeNavEntryDto(displayName, $"{baseUrl}?newCulture={culture}&returnUrl={returnUrl}", "lang-set", []); + } + + return entries; + } + + /// + /// Gets the path and query string of the current request. + /// + /// The path and query string of the current request. + private string GetCurrentRequestUrl() + { + HttpRequest request = _httpContextAccessor.HttpContext?.Request ?? throw new InvalidOperationException("The current HTTP context is unavailable."); + return $"{request.Path}{request.QueryString}"; + } + + /// + /// Resolves a localized navigation label. + /// + /// The resource key of the label. + /// The localized label. + private string Localize(string key) + { + return _localizer[key].Value; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index 8cca8518..1d7bcd51 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -259,7 +259,7 @@
@_localizer[ - + @_localizer[ @_localizer[ @@ -269,6 +269,7 @@ `; }).join(''); + bindNavigationLinks(); // bind the dynamically created edit links, so that editing keeps the persistent chrome running } else { btnScanAllLibraries.style.display = 'none'; table.style.display = 'none'; diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml new file mode 100644 index 00000000..65f7ceaa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -0,0 +1,17 @@ +@using Microsoft.Extensions.Localization + +@inject IStringLocalizerFactory _stringLocalizerFactory + +@{ + IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); +} + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index d7251b2c..8bb2c584 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -1,89 +1,71 @@ -@using Lumina.Presentation.Web.Common.DTO.Configuration -@using Microsoft.AspNetCore.Mvc.Localization -@using Microsoft.Extensions.Options +@using Lumina.Presentation.Web.Common.DTO.Themes +@using Lumina.Presentation.Web.Common.Primitives +@using Lumina.Presentation.Web.Core.Themes +@using Microsoft.AspNetCore.Html +@using System.IO +@using System.Text.Encodings.Web -@inject IViewLocalizer _localizer -@inject IOptions _serverConfigurationModel +@inject ThemeLayoutRenderer _themeLayoutRenderer - - - - - - @ViewData["Title"] - Lumina - - - - - - - - - - - - @await RenderSectionAsync("Head", required: false) - - -
-
- @await Html.PartialAsync("_NavMenu") -
-
-
- @RenderBody() -
-
-
-
- @if (User?.Identity?.IsAuthenticated == true) - { - - - } -
- - +@{ + string bodyHtml; + using (StringWriter bodyWriter = new()) + { + IHtmlContent bodyContent = RenderBody(); + bodyContent.WriteTo(bodyWriter, HtmlEncoder.Default); + bodyHtml = bodyWriter.ToString(); + } - - - - - -
- @await RenderSectionAsync("Scripts", required: false) -
- - + string title = ViewData["Title"]?.ToString() ?? string.Empty; + Result themedResult = await _themeLayoutRenderer.RenderAsync(new ThemeLayoutPageDto(title, bodyHtml, scriptsHtml), cancellationToken: ViewContext.HttpContext.RequestAborted); +} + +@if (themedResult.IsSuccess) +{ + @Html.Raw(themedResult.Value) +} +else +{ + + + + + + @ViewData["Title"] - Lumina + @await Html.PartialAsync("_ThemeLayoutHead") + + +
+
+ @await Html.PartialAsync("_NavMenu") +
+
+
+ @Html.Raw(bodyHtml) +
+
+
+
+ @if (User?.Identity?.IsAuthenticated == true) + { + @await Html.PartialAsync("_AudioPlayer") + } +
+ + @await Html.PartialAsync("_ThemeLayoutScripts") +
+ @Html.Raw(scriptsHtml) +
+ + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml index a1f51376..cd8b1705 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml @@ -19,7 +19,7 @@ Lumina
@_localizer["Account"] @@ -124,7 +124,7 @@
  • diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml new file mode 100644 index 00000000..abe3dcc8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml new file mode 100644 index 00000000..68f3d5a5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -0,0 +1,37 @@ +@using Lumina.Presentation.Web.Common.DTO.Configuration +@using Microsoft.Extensions.Localization +@using Microsoft.Extensions.Options + +@inject IStringLocalizerFactory _stringLocalizerFactory +@inject IOptions _serverConfigurationModel + +@{ + IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); +} + + + + + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml index 770fbdad..ed431a82 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml @@ -1,12 +1,5 @@ @model Lumina.Presentation.Web.Common.DTO.Themes.ThemeViewDto -@section Head { - @if (!string.IsNullOrEmpty(Model.AssetBase)) - { - - } -} - @Html.Raw(Model.Content) @section Scripts { From fd64cbd6baff448abf4d7022578e1f9f3b715ff7 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 23:38:50 -0700 Subject: [PATCH 06/31] Adds comments. --- .../Management/Queries/GetThemes/GetThemesQueryHandler.cs | 1 + src/Lumina.Infrastructure/Core/Themes/ThemeService.cs | 3 +++ .../Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs | 1 + .../Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs | 1 + .../Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs | 1 + .../Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs | 1 + .../Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs | 1 + .../Core/Themes/RazorViewToStringRenderer.cs | 1 + src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs | 2 ++ .../Core/Themes/ThemePageDataFactory.cs | 1 + src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs | 1 + src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs | 1 + src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml | 2 ++ 13 files changed, 17 insertions(+) diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs index d3ceca64..90202b57 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs @@ -47,6 +47,7 @@ public class GetThemesQueryHandler : IQueryHandler>([.. getThemesResult.Value .Where(theme => !theme.IsDeleted) + // the shipped bundled themes are listed before the user themes, so the defaults stay the most visible .OrderByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase) .Select(theme => theme.ToResponse())]); diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index b8948db1..7af797f9 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -61,6 +61,7 @@ public sealed class ThemeService : IThemeService private readonly string _storageRoot; private readonly string _stagingRoot; private readonly string _bundledRoot; + // serializes theme pack mutations, so concurrent installs and deletes cannot race on the same files private readonly SemaphoreSlim _mutationGate = new(1, 1); /// @@ -484,6 +485,7 @@ public sealed class ThemeService : IThemeService if (entry.Length > _options.MaxSingleFileBytes) return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large."); + // guard the total decompressed size, so a tiny archive cannot expand into a decompression bomb expandedBytes += entry.Length; if (expandedBytes > _options.MaxExpandedBytes) return Error.Validation(code: "Theme.Archive.ExpandedTooLarge", description: "The expanded theme archive is too large."); @@ -506,6 +508,7 @@ public sealed class ThemeService : IThemeService if (read == 0) break; + // enforce the per-file limit while streaming, because the declared entry size is not trustworthy entryBytes += read; if (entryBytes > _options.MaxSingleFileBytes) return Error.Validation(code: "Theme.File.TooLarge", description: $"Theme file '{normalizedPath}' is too large."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs index 7191b7b0..0c981623 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpoint.cs @@ -37,6 +37,7 @@ public class GetCurrentThemeEndpoint : BaseEndpoint Verbs(Http.GET); Routes(ApiRoutes.Themes.GET_CURRENT_THEME); Version(1); + // theme content is public, since the web renders themed pages for anonymous visitors too (i.e.: login page); only install and manage operations are admin-gated AllowAnonymous(); DontCatchExceptions(); } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs index 1fefad91..81bf2e62 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpoint.cs @@ -39,6 +39,7 @@ public class GetThemeAssetEndpoint : BaseEndpoint Verbs(Http.GET); Routes(ApiRoutes.Themes.GET_THEME_ASSET); Version(1); + // theme content is public, since the web renders themed pages for anonymous visitors too (i.e.: login page); only install and manage operations are admin-gated AllowAnonymous(); DontCatchExceptions(); } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs index ba384018..fd6c177d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpoint.cs @@ -37,6 +37,7 @@ public class GetThemeSettingsEndpoint : BaseEndpoint Verbs(Http.GET); Routes(ApiRoutes.Themes.GET_THEME_SETTINGS); Version(1); + // theme content is public, since the web renders themed pages for anonymous visitors too (i.e.: login page); only install and manage operations are admin-gated AllowAnonymous(); DontCatchExceptions(); } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs index 439b27f4..10cae257 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs @@ -39,6 +39,7 @@ public class GetThemeTemplateEndpoint : BaseEndpoint if (string.IsNullOrWhiteSpace(request.ThemeId) || string.IsNullOrWhiteSpace(request.Path)) return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id and the asset path are required."); + // the API route token is a catch-all ("{*assetPath}"), so the replace target must include the star to match it BlobDataDto blob = await _apiHttpClient.GetBlobAsync( ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{*assetPath}", request.Path), cancellationToken).ConfigureAwait(false); return Results.File(blob.Data, blob.ContentType); diff --git a/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs index 834fd809..7961f07f 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs @@ -49,6 +49,7 @@ public sealed class RazorViewToStringRenderer /// The rendered HTML of the partial. public async Task RenderPartialAsync(string partialName, CancellationToken cancellationToken = default) { + // the theme shell reuses the application's Razor chrome as strings, so the same markup stays in one place HttpContext httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("The current HTTP context is unavailable."); ActionContext actionContext = new(httpContext, httpContext.GetRouteData() ?? new RouteData(), new ActionDescriptor()); IView view = _viewEngine.FindView(actionContext, partialName, isMainPage: false).View diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs index 7dd6b983..eed43d75 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs @@ -60,6 +60,8 @@ public sealed class ThemeNavBuilder string returnUrl = Uri.EscapeDataString(GetCurrentRequestUrl()); ThemeNavEntryDto[] languages = CreateLanguageEntries(returnUrl); + // the mobile and desktop menus arrange the same sections differently, notably the language switcher, which is + // its own mobile heading but a submenu under Tools on the desktop, so each menu gets its own section list List mobileSections = []; mobileSections.Add(CreateSiteSection()); mobileSections.Add(CreateAccountSection(isAuthenticated)); diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs index 85f1c29c..25f752fc 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs @@ -17,6 +17,7 @@ public static class ThemePageDataFactory /// The localized strings keyed by their resource names. public static Dictionary CreateLocalizedStrings(IStringLocalizer localizer) { + // expose the page's full resource set, so templates can pull any localized string without the page enumerating keys Dictionary strings = []; foreach (LocalizedString localizedString in localizer.GetAllStrings(includeParentCultures: true)) strings[localizedString.Name] = localizedString.Value; diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs index 1e7ceda8..bbcc3f8b 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs @@ -40,6 +40,7 @@ public class ThemePageRenderer model.ThemeId = document.Theme.Id; model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets"; + // a fresh script id per render lets the AJAX navigator unload this view's script when navigating away model.ScriptId = ScriptIdentifierHelper.GenerateScriptId(); return _templateEngine.RenderPage(document.Template, model); diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs index 3a838b82..a535de9c 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs @@ -18,6 +18,7 @@ namespace Lumina.Presentation.Web.Core.Themes; /// public sealed class ThemeTemplateEngine { + // bound template nesting and rendered output, so a single theme cannot exhaust the server memory private const int MAX_NESTING_DEPTH = 32; private const int MAX_RENDERED_CHARACTERS = 4 * 1024 * 1024; diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index 8bb2c584..538e66af 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -8,6 +8,7 @@ @inject ThemeLayoutRenderer _themeLayoutRenderer @{ + // capture the page body and its scripts, so the themed shell can wrap them instead of rendering them directly string bodyHtml; using (StringWriter bodyWriter = new()) { @@ -19,6 +20,7 @@ string scriptsHtml; using (StringWriter scriptsWriter = new()) { + // RenderSectionAsync writes to ViewContext.Writer, so swap it to capture the section content TextWriter originalWriter = ViewContext.Writer; ViewContext.Writer = scriptsWriter; await RenderSectionAsync("Scripts", required: false); From f87fa04df5e3525e7f963205b4d2d434f7c79527 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 00:41:13 -0700 Subject: [PATCH 07/31] Validates antiforgery tokens after authentication --- src/Lumina.Presentation.Web/Program.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Lumina.Presentation.Web/Program.cs b/src/Lumina.Presentation.Web/Program.cs index b0fa5cac..c1e4d5bf 100644 --- a/src/Lumina.Presentation.Web/Program.cs +++ b/src/Lumina.Presentation.Web/Program.cs @@ -90,11 +90,13 @@ public class Program app.UseCultureRedirect(); // if the user attempts to go to a localized route without providing a culture, redirect to default culture app.UseApiExceptionHandling(); // handle any problem details returned by the API app.UseRouting(); - app.UseAntiforgeryFE(additionalContentTypes: ["application/json"]); // validate the antiforgery token of the JSON requests, sent via the RequestVerificationToken header app.UseRequestLocalization(); // set the culture from the localized routes app.UseSession(); app.UseAuthentication(); app.UseAuthorization(); + // validate the antiforgery token after authentication, because the token is bound to the authenticated user and + // validating it before the user is known would reject every request made by a logged-in user + app.UseAntiforgeryFE(additionalContentTypes: ["application/json"]); app.UseForwardedHeaders(); // handle path base from reverse proxies From 351368e7b573df1ea77a5d39f1809e735f3caebd Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 00:41:14 -0700 Subject: [PATCH 08/31] Sends a JSON body with delete requests to the FastEndpoints endpoints --- src/Lumina.Presentation.Web/wwwroot/js/site.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index ae4d902a..ddd86761 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -189,7 +189,8 @@ async function callApiDeleteAsync(url, options = {}) { // make the request const response = await fetch(url, { method: 'DELETE', - headers: headers + headers: headers, + body: '{}' // FastEndpoints parses the JSON body when the content type is application/json, so an empty body would fail to deserialize }); if (response.redirected) // if a redirect is requested, perform it window.location.href = response.url; From 932fe2be28a486af55fda4519c881a5351ea4254 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 00:41:47 -0700 Subject: [PATCH 09/31] Adds a themes management page to the administrator menu --- .../Common/Routes/WebRoutes.Admin.cs | 1 + .../Admin/Themes/ThemesIndexViewEndpoint.cs | 63 +++++++ .../Resources/Views/Admin/Themes.de-DE.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.en-US.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.es-ES.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.fr-FR.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.it-IT.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.ja-JP.resx | 156 ++++++++++++++++ .../Core/Resources/Views/Admin/Themes.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.ro-RO.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.ru-RU.resx | 156 ++++++++++++++++ .../Resources/Views/Admin/Themes.zh-CN.resx | 156 ++++++++++++++++ .../Views/Shared/_NavMenu.de-DE.resx | 3 + .../Views/Shared/_NavMenu.en-US.resx | 3 + .../Views/Shared/_NavMenu.es-ES.resx | 3 + .../Views/Shared/_NavMenu.fr-FR.resx | 3 + .../Views/Shared/_NavMenu.it-IT.resx | 3 + .../Views/Shared/_NavMenu.ja-JP.resx | 3 + .../Core/Resources/Views/Shared/_NavMenu.resx | 3 + .../Views/Shared/_NavMenu.ro-RO.resx | 3 + .../Views/Shared/_NavMenu.ru-RU.resx | 3 + .../Views/Shared/_NavMenu.zh-CN.resx | 3 + .../Core/Themes/ThemeNavBuilder.cs | 3 +- .../Core/Views/Admin/Themes.cshtml | 166 ++++++++++++++++++ .../Core/Views/Shared/_NavMenu.cshtml | 2 + 25 files changed, 1824 insertions(+), 1 deletion(-) create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx create mode 100644 src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs index 618d0b55..88a84d5d 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Admin.cs @@ -12,6 +12,7 @@ public static partial class WebRoutes { public const string MANAGE_ROLES = "{culture}/admin/manage-roles"; public const string MANAGE_PERMISSIONS = "{culture}/admin/manage-permissions"; + public const string MANAGE_THEMES = "{culture}/admin/manage-themes"; public const string GET_PERMISSIONS_BY_ROLE_ID = "{culture}/admin/api-get-permissions-by-role-id/{roleId}"; public const string GET_PERMISSIONS_BY_USER_ID = "{culture}/admin/api-get-permissions-by-user-id/{userId}"; public const string GET_ROLE_BY_USER_ID = "{culture}/admin/api-get-role-by-user-id/{userId}"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpoint.cs new file mode 100644 index 00000000..32679465 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes; + +/// +/// API endpoint for the /{culture}/admin/manage-themes route. +/// +public class ThemesIndexViewEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for the theme operations of the remote API. + public ThemesIndexViewEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Admin.MANAGE_THEMES); + DontAutoTag(); + Options(options => options.WithTags("Admin")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Displays the themes management view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + IReadOnlyList themes = await _themeService.GetThemesAsync(cancellationToken).ConfigureAwait(false); + ThemeInfoDto currentTheme = await _themeService.GetCurrentThemeAsync(cancellationToken).ConfigureAwait(false); + + Dictionary viewData = new() + { + ["themes"] = themes, + ["currentThemeId"] = currentTheme.Id + }; + return View("/Core/Views/Admin/Themes.cshtml", viewData: viewData); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx new file mode 100644 index 00000000..516665ea --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Themen + + + Es sind keine Themen installiert. + + + Name + + + Version + + + Autor + + + Aktionen + + + Aktivieren + + + Löschen + + + Herunterladen + + + Hochladen + + + Das Themenarchiv konnte nicht hochgeladen werden. + + + Möchten Sie das angegebene Thema wirklich löschen? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx new file mode 100644 index 00000000..991cc6c5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Themes + + + No themes are installed. + + + Name + + + Version + + + Author + + + Actions + + + Activate + + + Delete + + + Download + + + Upload + + + The theme archive could not be uploaded. + + + Are you sure you want to delete the specified theme? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx new file mode 100644 index 00000000..02b45645 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Temas + + + No hay temas instalados. + + + Nombre + + + Versión + + + Autor + + + Acciones + + + Activar + + + Eliminar + + + Descargar + + + Subir + + + No se pudo subir el archivo del tema. + + + ¿Está seguro de que desea eliminar el tema especificado? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx new file mode 100644 index 00000000..88542f72 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Thèmes + + + Aucun thème installé. + + + Nom + + + Version + + + Auteur + + + Actions + + + Activer + + + Supprimer + + + Télécharger + + + Téléverser + + + Impossible de téléverser l'archive du thème. + + + Voulez-vous vraiment supprimer le thème spécifié ? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx new file mode 100644 index 00000000..e06fdb86 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Temi + + + Nessun tema installato. + + + Nome + + + Versione + + + Autore + + + Azioni + + + Attiva + + + Elimina + + + Scarica + + + Carica + + + Impossibile caricare l'archivio del tema. + + + Sei sicuro di voler eliminare il tema specificato? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx new file mode 100644 index 00000000..fa0b889f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + テーマ + + + インストールされたテーマがありません。 + + + 名前 + + + バージョン + + + 作者 + + + 操作 + + + 有効化 + + + 削除 + + + ダウンロード + + + アップロード + + + テーマアーカイブをアップロードできませんでした。 + + + 指定されたテーマを削除しますか? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx new file mode 100644 index 00000000..991cc6c5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Themes + + + No themes are installed. + + + Name + + + Version + + + Author + + + Actions + + + Activate + + + Delete + + + Download + + + Upload + + + The theme archive could not be uploaded. + + + Are you sure you want to delete the specified theme? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx new file mode 100644 index 00000000..6b43770f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Teme + + + Nu sunt instalate teme. + + + Nume + + + Versiune + + + Autor + + + Acțiuni + + + Activează + + + Șterge + + + Descarcă + + + Încarcă + + + Arhiva temei nu a putut fi încărcată. + + + Sigur doriți să ștergeți tema specificată? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx new file mode 100644 index 00000000..a4efd826 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Темы + + + Не установлено ни одной темы. + + + Имя + + + Версия + + + Автор + + + Действия + + + Активировать + + + Удалить + + + Скачать + + + Загрузить + + + Не удалось загрузить архив темы. + + + Вы уверены, что хотите удалить указанную тему? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx new file mode 100644 index 00000000..1dd9fb48 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 主题 + + + 未安装主题。 + + + 名称 + + + 版本 + + + 作者 + + + 操作 + + + 激活 + + + 删除 + + + 下载 + + + 上传 + + + 无法上传主题文件。 + + + 确定要删除指定的主题吗? + + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx index 03c1b8ff..f3ebdbb9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx @@ -192,6 +192,9 @@ Berechtigungen verwalten + + Themen + Werkzeuge diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx index 97405612..b5fe9ac8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx @@ -192,6 +192,9 @@ Manage permissions + + Themes + Tools diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx index f4a8dc79..3f9f977d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx @@ -192,6 +192,9 @@ Administrar permisos + + Temas + Herramientas diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx index 7b2508f7..0435e966 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx @@ -192,6 +192,9 @@ Gérer les permissions + + Thèmes + Outils diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx index da66d075..17e96520 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx @@ -192,6 +192,9 @@ Gestire i permessi + + Temi + Strumenti diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx index aa2febca..3c981f56 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx @@ -192,6 +192,9 @@ 権限を管理する + + テーマ + ツール diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx index 97405612..b5fe9ac8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx @@ -192,6 +192,9 @@ Manage permissions + + Themes + Tools diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx index 37ac6ac7..1a2524c1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx @@ -192,6 +192,9 @@ Gestionare permisiuni + + Teme + Unelte diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ru-RU.resx index 07c3cce4..016fd3d8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ru-RU.resx @@ -192,6 +192,9 @@ Управление разрешениями + + Темы + Инструменты diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx index f9ca0bee..93af2571 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx @@ -192,6 +192,9 @@ 管理权限 + + 主题 + 工具 diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs index eed43d75..22df9021 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs @@ -133,7 +133,8 @@ public sealed class ThemeNavBuilder [ new ThemeNavEntryDto(Localize("ManageRoles"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES), "nav-link", []), new ThemeNavEntryDto(Localize("ManagePermissions"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS), "nav-link", []), - new ThemeNavEntryDto(Localize("Plugins"), _urlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX), "nav-link", []) + new ThemeNavEntryDto(Localize("Plugins"), _urlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX), "nav-link", []), + new ThemeNavEntryDto(Localize("Themes"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES), "nav-link", []) ]); } diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml new file mode 100644 index 00000000..f8f7b834 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -0,0 +1,166 @@ +@* +/admin/manage-themes/ +*@ + +@using Lumina.Presentation.Web.Common.DTO.Themes +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization + +@{ + var themes = ViewData["themes"] as IReadOnlyList; + var currentThemeId = ViewData["currentThemeId"] as string; + // generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + int bundledThemeCount = 0; + if (themes is not null) + foreach (ThemeInfoDto theme in themes) + if (theme.IsBundled) + bundledThemeCount++; +} + +@inject IViewLocalizer _localizer +@inject IUrlService _urlService + +@Html.AntiForgeryToken() + +
    +
    +
    +
    +
    +

    @_localizer["Themes"]

    +
    +
    + + +
    +
    + @if (themes is null || themes.Count == 0) + { +

    @_localizer["NoThemes"]

    + } + else + { + + + + + + + + + + + @foreach (ThemeInfoDto theme in themes) + { + bool isCurrent = theme.Id == currentThemeId; + bool isLastRemaining = themes.Count <= 1 || (theme.IsBundled && bundledThemeCount == 1); + + + + + + + } + +
    @_localizer["Name"]@_localizer["Version"]@_localizer["Author"]@_localizer["Actions"]
    @theme.Name@theme.Version@theme.Author + + + +
    + } +
    +
    +
    + +@section Scripts { + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml index cd8b1705..9ffa41fd 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml @@ -52,6 +52,7 @@
  • @_localizer["ManageRoles"]
  • @_localizer["ManagePermissions"]
  • @_localizer["Plugins"]
  • +
  • @_localizer["Themes"]
  • }
    @@ -157,6 +158,7 @@
  • @_localizer["ManageRoles"]
  • @_localizer["ManagePermissions"]
  • @_localizer["Plugins"]
  • +
  • @_localizer["Themes"]
  • } From 74e5efdf74cc19b75a1303167154044cb7ce93e4 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 00:58:09 -0700 Subject: [PATCH 10/31] Moves the plugins management page under the administrator area --- .../Common/Routes/WebRoutes.Plugins.cs | 8 +- .../GetPluginSettingsEndpoint.cs | 2 +- .../Plugins/GetPlugins/GetPluginsEndpoint.cs | 2 +- .../Plugins/Index/PluginsIndexViewEndpoint.cs | 4 +- .../UpdatePluginSettingsEndpoint.cs | 2 +- .../Plugins.de-DE.resx} | 0 .../Plugins.en-US.resx} | 0 .../Plugins.es-ES.resx} | 0 .../Plugins.fr-FR.resx} | 0 .../Plugins.it-IT.resx} | 0 .../Plugins.ja-JP.resx} | 0 .../Index.resx => Admin/Plugins.resx} | 0 .../Plugins.ro-RO.resx} | 0 .../Plugins.ru-RU.resx} | 0 .../Plugins.zh-CN.resx} | 0 .../Resources/Views/Plugins/Index.Designer.cs | 180 ------------------ .../Index.cshtml => Admin/Plugins.cshtml} | 2 +- .../Lumina.Presentation.Web.csproj | 32 ++-- 18 files changed, 26 insertions(+), 206 deletions(-) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.de-DE.resx => Admin/Plugins.de-DE.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.en-US.resx => Admin/Plugins.en-US.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.es-ES.resx => Admin/Plugins.es-ES.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.fr-FR.resx => Admin/Plugins.fr-FR.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.it-IT.resx => Admin/Plugins.it-IT.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.ja-JP.resx => Admin/Plugins.ja-JP.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.resx => Admin/Plugins.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.ro-RO.resx => Admin/Plugins.ro-RO.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.ru-RU.resx => Admin/Plugins.ru-RU.resx} (100%) rename src/Lumina.Presentation.Web/Core/Resources/Views/{Plugins/Index.zh-CN.resx => Admin/Plugins.zh-CN.resx} (100%) delete mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs rename src/Lumina.Presentation.Web/Core/Views/{Plugins/Index.cshtml => Admin/Plugins.cshtml} (99%) diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs index 6008922e..7d054eaa 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Plugins.cs @@ -10,9 +10,9 @@ public static partial class WebRoutes ///
    public static class Plugins { - public const string INDEX = "{culture}/plugins"; - public const string GET_PLUGINS = "{culture}/plugins/api-get-plugins"; - public const string GET_PLUGIN_SETTINGS = "{culture}/plugins/api-get-plugin-settings/{pluginId}"; - public const string UPDATE_PLUGIN_SETTINGS = "{culture}/plugins/api-update-plugin-settings"; + public const string INDEX = "{culture}/admin/manage-plugins"; + public const string GET_PLUGINS = "{culture}/admin/manage-plugins/api-get-plugins"; + public const string GET_PLUGIN_SETTINGS = "{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId}"; + public const string UPDATE_PLUGIN_SETTINGS = "{culture}/admin/manage-plugins/api-update-plugin-settings"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs index 9d0be7f7..b0496a50 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpoint.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; /// -/// API endpoint for the /{culture}/plugins/api-get-plugin-settings/{pluginId} route. +/// API endpoint for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route. /// public class GetPluginSettingsEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs index 56e66099..c8b4c386 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpoint.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; /// -/// API endpoint for the /{culture}/plugins/api-get-plugins route. +/// API endpoint for the /{culture}/admin/manage-plugins/api-get-plugins route. /// public class GetPluginsEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs index b75707f4..63968658 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpoint.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; /// -/// API endpoint for the /{culture}/plugins route. +/// API endpoint for the /{culture}/admin/manage-plugins route. /// public class PluginsIndexViewEndpoint : BaseEndpoint { @@ -57,6 +57,6 @@ public class PluginsIndexViewEndpoint : BaseEndpoint if (plugin.LoadStatus == Lumina.Presentation.Web.Common.Enums.Plugins.PluginLoadStatus.Loaded) settingsByPluginId[plugin.Id] = await _apiHttpClient.GetAsync(ApiRoutes.Plugins.GET_PLUGIN_SETTINGS.Replace("{pluginId}", plugin.Id.ToString()), cancellationToken).ConfigureAwait(false); Dictionary viewData = new() { ["pluginSettings"] = settingsByPluginId }; - return View("/Core/Views/Plugins/Index.cshtml", plugins, viewData); + return View("/Core/Views/Admin/Plugins.cshtml", plugins, viewData); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs index 0cd1aba1..3931a8ff 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpoint.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; /// -/// API endpoint for the /{culture}/plugins/api-update-plugin-settings route. +/// API endpoint for the /{culture}/admin/manage-plugins/api-update-plugin-settings route. /// public class UpdatePluginSettingsEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.de-DE.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.de-DE.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.de-DE.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.en-US.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.en-US.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.en-US.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.es-ES.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.es-ES.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.es-ES.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.fr-FR.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.fr-FR.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.fr-FR.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.it-IT.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.it-IT.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.it-IT.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.ja-JP.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ja-JP.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.ja-JP.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.ro-RO.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ro-RO.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.ro-RO.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.ru-RU.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.ru-RU.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.ru-RU.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.zh-CN.resx similarity index 100% rename from src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.zh-CN.resx rename to src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Plugins.zh-CN.resx diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs b/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs deleted file mode 100644 index 03dfce55..00000000 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Plugins/Index.Designer.cs +++ /dev/null @@ -1,180 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Lumina.Presentation.Web.Core.Resources.Views.Plugins { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class Index { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Index() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Lumina.Presentation.Web.Core.Resources.Views.Plugins.Index", typeof(Index).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Author. - /// - public static string Author { - get { - return ResourceManager.GetString("Author", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Description. - /// - public static string Description { - get { - return ResourceManager.GetString("Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load. - /// - public static string FailedToLoad { - get { - return ResourceManager.GetString("FailedToLoad", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Loaded. - /// - public static string Loaded { - get { - return ResourceManager.GetString("Loaded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Load error. - /// - public static string LoadError { - get { - return ResourceManager.GetString("LoadError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Load status. - /// - public static string LoadStatus { - get { - return ResourceManager.GetString("LoadStatus", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Name. - /// - public static string Name { - get { - return ResourceManager.GetString("Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No plugins have been detected.. - /// - public static string NoPlugins { - get { - return ResourceManager.GetString("NoPlugins", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Plugins. - /// - public static string Plugins { - get { - return ResourceManager.GetString("Plugins", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Save. - /// - public static string Save { - get { - return ResourceManager.GetString("Save", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Settings. - /// - public static string Settings { - get { - return ResourceManager.GetString("Settings", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Settings saved. - /// - public static string SettingsSaved { - get { - return ResourceManager.GetString("SettingsSaved", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Version. - /// - public static string Version { - get { - return ResourceManager.GetString("Version", resourceCulture); - } - } - } -} diff --git a/src/Lumina.Presentation.Web/Core/Views/Plugins/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml similarity index 99% rename from src/Lumina.Presentation.Web/Core/Views/Plugins/Index.cshtml rename to src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml index 734f9ff4..bc74f5d1 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Plugins/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Plugins.cshtml @@ -1,5 +1,5 @@ @* -/plugins +/admin/manage-plugins *@ @using Lumina.Presentation.Web.Common.DTO.Plugins diff --git a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj index 34a7ce11..6b86fafb 100644 --- a/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj +++ b/src/Lumina.Presentation.Web/Lumina.Presentation.Web.csproj @@ -35,6 +35,11 @@ + + True + True + Plugins.resx + True True @@ -60,11 +65,6 @@ True Item.resx - - True - True - Index.resx - @@ -331,35 +331,35 @@ PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - Index.Designer.cs + Plugins.Designer.cs - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator - + PublicResXFileCodeGenerator From ebafd743b5493b077a1e733ac19a6349ba606c32 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 01:49:17 -0700 Subject: [PATCH 11/31] Adds theme previews to the themes list with a reusable image viewer --- .../Resources/Views/Admin/Themes.de-DE.resx | 3 + .../Resources/Views/Admin/Themes.en-US.resx | 3 + .../Resources/Views/Admin/Themes.es-ES.resx | 3 + .../Resources/Views/Admin/Themes.fr-FR.resx | 3 + .../Resources/Views/Admin/Themes.it-IT.resx | 3 + .../Resources/Views/Admin/Themes.ja-JP.resx | 3 + .../Core/Resources/Views/Admin/Themes.resx | 3 + .../Resources/Views/Admin/Themes.ro-RO.resx | 3 + .../Resources/Views/Admin/Themes.ru-RU.resx | 3 + .../Resources/Views/Admin/Themes.zh-CN.resx | 3 + .../Core/Views/Admin/Themes.cshtml | 69 ++++++- .../Core/Views/Shared/_ThemeLayoutHead.cshtml | 1 + .../Views/Shared/_ThemeLayoutScripts.cshtml | 1 + .../wwwroot/admin/theme-placeholder.svg | 8 + .../wwwroot/css/image-viewer.css | 146 +++++++++++++++ .../wwwroot/js/image-viewer.js | 168 ++++++++++++++++++ 16 files changed, 416 insertions(+), 7 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/admin/theme-placeholder.svg create mode 100644 src/Lumina.Presentation.Web/wwwroot/css/image-viewer.css create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/image-viewer.js diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx index 516665ea..240348fe 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx @@ -153,4 +153,7 @@ Möchten Sie das angegebene Thema wirklich löschen? + + Vorschau + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx index 991cc6c5..4dec7cdb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx @@ -153,4 +153,7 @@ Are you sure you want to delete the specified theme? + + Preview + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx index 02b45645..c51a5803 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx @@ -153,4 +153,7 @@ ¿Está seguro de que desea eliminar el tema especificado? + + Vista previa + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx index 88542f72..8184f456 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx @@ -153,4 +153,7 @@ Voulez-vous vraiment supprimer le thème spécifié ? + + Aperçu + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx index e06fdb86..4d90e27b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx @@ -153,4 +153,7 @@ Sei sicuro di voler eliminare il tema specificato? + + Anteprima + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx index fa0b889f..28c58547 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx @@ -153,4 +153,7 @@ 指定されたテーマを削除しますか? + + プレビュー + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx index 991cc6c5..4dec7cdb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx @@ -153,4 +153,7 @@ Are you sure you want to delete the specified theme? + + Preview + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx index 6b43770f..4a1d5054 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx @@ -153,4 +153,7 @@ Sigur doriți să ștergeți tema specificată? + + Previzualizare + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx index a4efd826..ae50882f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx @@ -153,4 +153,7 @@ Вы уверены, что хотите удалить указанную тему? + + Предпросмотр + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx index 1dd9fb48..36f8c200 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx @@ -153,4 +153,7 @@ 确定要删除指定的主题吗? + + 预览 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml index f8f7b834..4453cb70 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -23,6 +23,32 @@ @Html.AntiForgeryToken() + +
    @@ -30,7 +56,7 @@

    @_localizer["Themes"]

    -
    +
    @@ -44,10 +70,11 @@ - + + - + @@ -56,13 +83,20 @@ bool isCurrent = theme.Id == currentThemeId; bool isLastRemaining = themes.Count <= 1 || (theme.IsBundled && bundledThemeCount == 1); + - } @@ -115,6 +149,25 @@ window.location.href = button.dataset.url; } + // opens the image viewer with the preview of the clicked theme + function handlePreviewClick(event) { + const button = event.target.closest('.theme-preview-button'); + if (button) + imageViewer.open([{ src: button.dataset.previewUrl, title: button.dataset.previewTitle }]); + } + + // falls back to the placeholder image when the preview of a theme is missing or fails to load + function attachPreviewErrorFallbacks() { + const placeholderUrl = '@Url.Content("~/admin/theme-placeholder.svg")'; + document.querySelectorAll('.theme-preview-thumb').forEach(img => { + img.addEventListener('error', function handlePreviewError() { + img.removeEventListener('error', handlePreviewError); + img.src = placeholderUrl; + }); + }); + } + attachPreviewErrorFallbacks(); + // uploads the selected theme archive as a multipart request, keeping the antiforgery token async function handleUploadInputChange() { const file = uploadInput.files[0]; @@ -145,6 +198,7 @@ document.addEventListener('click', handleActivateClick); document.addEventListener('click', handleDownloadClick); document.addEventListener('click', handleDeleteClick); + document.addEventListener('click', handlePreviewClick); // register cleanup for these listeners cleanupFunctions.push(() => { @@ -153,6 +207,7 @@ document.removeEventListener('click', handleActivateClick); document.removeEventListener('click', handleDownloadClick); document.removeEventListener('click', handleDeleteClick); + document.removeEventListener('click', handlePreviewClick); }); // store all cleanups for this view on window object using the scriptId diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml index abe3dcc8..e31d4926 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml @@ -7,5 +7,6 @@ + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 68f3d5a5..436d303c 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -34,4 +34,5 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/admin/theme-placeholder.svg b/src/Lumina.Presentation.Web/wwwroot/admin/theme-placeholder.svg new file mode 100644 index 00000000..91342f4b --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/admin/theme-placeholder.svg @@ -0,0 +1,8 @@ + + + + + + + No preview + diff --git a/src/Lumina.Presentation.Web/wwwroot/css/image-viewer.css b/src/Lumina.Presentation.Web/wwwroot/css/image-viewer.css new file mode 100644 index 00000000..efa578fe --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/css/image-viewer.css @@ -0,0 +1,146 @@ +.image-viewer-overlay { + display: none; + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: 1001; + background-color: rgba(0, 0, 0, 0.85); + align-items: center; + justify-content: center; +} + +.image-viewer-overlay.open { + display: flex; + animation: fadeIn 0.3s ease-out; +} + +.image-viewer-stage { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + max-width: 92%; + max-height: 92%; +} + +.image-viewer-image { + max-width: 100%; + max-height: 88vh; + object-fit: contain; + opacity: 0; + border: 1px solid #505050; + background-color: #000; + box-shadow: 0 0 20px rgba(0, 0, 0, 0.6); +} + +.image-viewer-image.loaded { + opacity: 1; + transition: opacity 0.2s ease-out; +} + +.image-viewer-caption { + margin-top: 12px; + color: var(--text-foreground); + font-family: monospace; + font-size: 0.95rem; + text-align: center; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8); +} + +.image-viewer-spinner { + position: absolute; + top: 50%; + left: 50%; + width: 40px; + height: 40px; + margin: -20px 0 0 -20px; + border: 4px solid rgba(255, 255, 255, 0.25); + border-top-color: #fff; + border-radius: 50%; + animation: image-viewer-spin 0.8s linear infinite; +} + +@keyframes image-viewer-spin { + to { + transform: rotate(360deg); + } +} + +.image-viewer-button { + position: absolute; + width: 44px; + height: 44px; + border: 1px solid #505050; + border-radius: 50%; + background-color: rgba(0, 0, 0, 0.5); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; +} + +.image-viewer-button:hover { + border-color: var(--text-foreground); + background-color: rgba(0, 0, 0, 0.75); +} + +.image-viewer-button:disabled { + opacity: 0.35; + cursor: default; +} + +.image-viewer-close { + top: 18px; + right: 18px; +} + +.image-viewer-close::before, +.image-viewer-close::after { + content: ''; + position: absolute; + width: 20px; + height: 2px; + background-color: var(--text-foreground); +} + +.image-viewer-close::before { + transform: rotate(45deg); +} + +.image-viewer-close::after { + transform: rotate(-45deg); +} + +.image-viewer-prev { + left: 18px; + top: 50%; + transform: translateY(-50%); +} + +.image-viewer-prev::before { + content: ''; + width: 12px; + height: 12px; + margin-left: 5px; + border-left: 3px solid var(--text-foreground); + border-bottom: 3px solid var(--text-foreground); + transform: rotate(45deg); +} + +.image-viewer-next { + right: 18px; + top: 50%; + transform: translateY(-50%); +} + +.image-viewer-next::before { + content: ''; + width: 12px; + height: 12px; + margin-right: 5px; + border-right: 3px solid var(--text-foreground); + border-top: 3px solid var(--text-foreground); + transform: rotate(45deg); +} diff --git a/src/Lumina.Presentation.Web/wwwroot/js/image-viewer.js b/src/Lumina.Presentation.Web/wwwroot/js/image-viewer.js new file mode 100644 index 00000000..9ac1eeec --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/image-viewer.js @@ -0,0 +1,168 @@ +/** + * Manages the full-screen image viewer overlay, used to display a single image or a small photo gallery. + */ +class ImageViewerService { + constructor() { + this.overlay = null; + this.imageElement = null; + this.captionElement = null; + this.spinnerElement = null; + this.prevButton = null; + this.nextButton = null; + this.items = []; + this.currentIndex = 0; + this.keydownHandler = null; + } + + /** + * Opens the viewer with the given images. + * @param {Array<{src: string, title?: string}>|{src: string, title?: string}} items - The image(s) to display. + */ + open(items) { + this.items = Array.isArray(items) ? items : [items]; + if (this.items.length === 0) + return; + this.ensureOverlay(); + this.currentIndex = 0; + this.show(); + this.showItem(this.currentIndex); + } + + /** + * Closes the viewer and releases the currently displayed image. + */ + close() { + if (!this.overlay) + return; + this.overlay.classList.remove('open'); + if (this.keydownHandler) { + document.removeEventListener('keydown', this.keydownHandler); + this.keydownHandler = null; + } + // stop the browser from finishing the load of the previous image in the background + this.imageElement.removeAttribute('src'); + this.items = []; + } + + /** + * Displays the previous image of the gallery, when there is one. + */ + previous() { + if (this.currentIndex > 0) + this.showItem(this.currentIndex - 1); + } + + /** + * Displays the next image of the gallery, when there is one. + */ + next() { + if (this.currentIndex < this.items.length - 1) + this.showItem(this.currentIndex + 1); + } + + /** + * Builds the overlay and appends it to the document body the first time it is used. + * @private + */ + ensureOverlay() { + if (this.overlay) + return; + + this.overlay = document.createElement('div'); + this.overlay.className = 'image-viewer-overlay'; + this.overlay.innerHTML = ` + + +
    +
    + +
    +
    + + `; + + this.imageElement = this.overlay.querySelector('.image-viewer-image'); + this.captionElement = this.overlay.querySelector('.image-viewer-caption'); + this.spinnerElement = this.overlay.querySelector('.image-viewer-spinner'); + this.prevButton = this.overlay.querySelector('.image-viewer-prev'); + this.nextButton = this.overlay.querySelector('.image-viewer-next'); + + // clicking the dimmed background closes the viewer, but not the image or the controls + this.overlay.addEventListener('click', (e) => { + if (e.target === this.overlay) + this.close(); + }); + + // reveal the image only after it finished loading, so the spinner is visible meanwhile + const handleImageLoaded = () => { + this.spinnerElement.style.display = 'none'; + this.imageElement.classList.add('loaded'); + }; + this.imageElement.addEventListener('load', handleImageLoaded); + this.imageElement.addEventListener('error', handleImageLoaded); + + this.overlay.querySelector('.image-viewer-close').addEventListener('click', () => this.close()); + this.prevButton.addEventListener('click', (e) => { + e.stopPropagation(); + this.previous(); + }); + this.nextButton.addEventListener('click', (e) => { + e.stopPropagation(); + this.next(); + }); + + document.body.appendChild(this.overlay); + } + + /** + * Shows the overlay and registers the keyboard navigation. + * @private + */ + show() { + this.overlay.classList.add('open'); + this.keydownHandler = (e) => { + if (e.key === 'Escape') + this.close(); + else if (e.key === 'ArrowLeft') + this.previous(); + else if (e.key === 'ArrowRight') + this.next(); + }; + document.addEventListener('keydown', this.keydownHandler); + } + + /** + * Displays the image at the given index and updates the gallery controls. + * @private + * @param {number} index - The index of the image to display. + */ + showItem(index) { + if (index < 0 || index >= this.items.length) + return; + this.currentIndex = index; + const item = this.items[index]; + + this.spinnerElement.style.display = 'block'; + this.imageElement.classList.remove('loaded'); + this.imageElement.alt = item.title || ''; + this.imageElement.src = item.src; + + if (item.title) { + this.captionElement.textContent = item.title; + this.captionElement.style.display = 'block'; + } + else { + this.captionElement.textContent = ''; + this.captionElement.style.display = 'none'; + } + + const hasMultipleItems = this.items.length > 1; + this.prevButton.style.display = hasMultipleItems ? 'flex' : 'none'; + this.nextButton.style.display = hasMultipleItems ? 'flex' : 'none'; + this.prevButton.disabled = index === 0; + this.nextButton.disabled = index === this.items.length - 1; + } +} + +// create a global instance of the ImageViewerService +const imageViewer = new ImageViewerService(); From 6bb3449d4ffe0d14d453e3601920e53c0841ebbc Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 01:49:23 -0700 Subject: [PATCH 12/31] Uses the empty request type for the theme install endpoint --- .../Themes/InstallThemeRequestMapping.cs | 25 ------------------- .../Requests/Themes/InstallThemeRequest.cs | 12 --------- .../InstallTheme/InstallThemeEndpoint.cs | 9 +++---- .../InstallThemeEndpointSummary.cs | 3 +-- 4 files changed, 5 insertions(+), 44 deletions(-) delete mode 100644 src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs delete mode 100644 src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs diff --git a/src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs deleted file mode 100644 index 9e17d55b..00000000 --- a/src/Lumina.Application/Common/Mapping/Themes/InstallThemeRequestMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -#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; - -/// -/// Extension methods for converting . -/// -public static class InstallThemeRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The ZIP archive stream of the theme pack. - /// The file name of the uploaded archive. - /// The converted command. - public static InstallThemeCommand ToCommand(this InstallThemeRequest request, Stream? archive, string? fileName) - { - return new InstallThemeCommand(archive, fileName); - } -} diff --git a/src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs b/src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs deleted file mode 100644 index d000c42b..00000000 --- a/src/Lumina.Contracts/Requests/Themes/InstallThemeRequest.cs +++ /dev/null @@ -1,12 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.Themes; - -/// -/// Represents a request to install a theme pack, sent as a multipart form whose single file field contains the theme archive. -/// -[DebuggerDisplay("InstallThemeRequest")] -public record InstallThemeRequest; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs index 25a9a914..f3abd760 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs @@ -1,8 +1,6 @@ #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; @@ -18,7 +16,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme; /// /// API endpoint for the /themes route. /// -public class InstallThemeEndpoint : BaseEndpoint +public class InstallThemeEndpoint : BaseEndpoint { private readonly ICommandHandler> _installThemeCommandHandler; @@ -47,10 +45,11 @@ public class InstallThemeEndpoint : BaseEndpoint /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(InstallThemeRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault(); - Result result = await _installThemeCommandHandler.HandleAsync(request.ToCommand(archive?.OpenReadStream(), archive?.FileName), cancellationToken).ConfigureAwait(false); + InstallThemeCommand command = new(archive?.OpenReadStream(), archive?.FileName); + Result result = await _installThemeCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs index 298ed743..9513198f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Lumina.Contracts.Requests.Themes; using Lumina.Contracts.Responses.Themes; using Lumina.Domain.SharedKernel.Common.Enums.Themes; using System; @@ -14,7 +13,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme; /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class InstallThemeEndpointSummary : Summary +public class InstallThemeEndpointSummary : Summary { /// /// Initializes a new instance of the class. From 88db2e08013d508971e00dc1043c9b7ff272ca0c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 01:49:29 -0700 Subject: [PATCH 13/31] Resurrects soft deleted themes when they are reinstalled --- .../Commands/InstallTheme/InstallThemeCommandHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs index c804d7d1..e914fa89 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs @@ -103,7 +103,8 @@ public class InstallThemeCommandHandler : ICommandHandler Date: Fri, 21 Aug 2026 04:04:26 -0700 Subject: [PATCH 14/31] Caches the theme API responses --- .../PresentationWebLayerServices.cs | 5 +- .../Common/Services/CachedResponse.cs | 12 +- .../Common/Services/CachedThemeHandler.cs | 138 +++++++++++++++ .../Services/ThemeCachePreferenceService.cs | 75 +++++++++ .../Services/CachedThemeHandlerTests.cs | 157 ++++++++++++++++++ 5 files changed, 385 insertions(+), 2 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs create mode 100644 src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 757dc241..f409b4eb 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -292,10 +292,13 @@ public static class PresentationWebLayerServices // register the HTTP typed client used for the API interaction services.AddHttpClient() .AddHttpMessageHandler() + .AddHttpMessageHandler() .AddPolicyHandler(retryPolicy) .AddPolicyHandler(circuitBreakerPolicy); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); // enable access to the current HTTP context in non-controller classes services.AddHttpContextAccessor(); @@ -314,7 +317,7 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddSingleton(); services.AddSingleton(); - services.AddHybridCache(); // used for caching authorization roles, permissions and policies + services.AddHybridCache(); // used for caching authorization roles, permissions, policies and theme data return services; } diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs b/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs index 156cc880..93182587 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedResponse.cs @@ -12,10 +12,20 @@ namespace Lumina.Presentation.Web.Common.Services; public class CachedResponse { /// - /// Gets or sets the content of the cached HTTP response. + /// Gets or sets the textual content of the cached HTTP response. /// public string Content { get; set; } = string.Empty; + /// + /// Gets or sets the raw bytes of the cached HTTP response. + /// + public byte[] Bytes { get; set; } = []; + + /// + /// Gets or sets the content type of the cached HTTP response. + /// + public string? ContentType { get; set; } + /// /// Gets or sets the HTTP status code of the cached response. /// diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs new file mode 100644 index 00000000..4ec993a2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Delegating handler that intercepts the HTTP requests to the theme endpoints of the remote API and caches their responses, +/// because the theme data is read on every page render and is only changed by the theme management operations. +/// All other requests are forwarded directly. +/// +public class CachedThemeHandler : DelegatingHandler +{ + private const string THEMES_SEGMENT = "/api/v1/themes"; + private const string THEME_CACHE_TAG = "themes"; + // responses above this size are never kept in the cache, so large binary assets do not bloat the memory + private const int MAX_CACHEABLE_BYTES = 512 * 1024; + // themes only change when the user switches, reinstalls or deletes them, so the cached responses stay valid for a long time + private static readonly TimeSpan s_cacheExpiration = TimeSpan.FromMinutes(30); + + private readonly HybridCache _hybridCache; + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly ThemeCachePreferenceService _themeCachePreferenceService; + + /// + /// Initializes a new instance of the class. + /// + /// The hybrid caching mechanism used to store and retrieve the theme responses. + /// The used to access the currently authenticated user. + /// The service used to read the per-user theme cache preference. + public CachedThemeHandler(HybridCache hybridCache, IHttpContextAccessor httpContextAccessor, ThemeCachePreferenceService themeCachePreferenceService) + { + _hybridCache = hybridCache; + _httpContextAccessor = httpContextAccessor; + _themeCachePreferenceService = themeCachePreferenceService; + } + + /// + /// Processes the HTTP request, caching the responses of the GET requests to theme endpoints and invalidating the cached + /// responses whenever a theme mutation is performed. All other requests are forwarded to the next handler in the pipeline. + /// + /// The HTTP request message to process. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message from either the cache or the original API call. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + string requestPath = request.RequestUri!.AbsolutePath; + if (!requestPath.StartsWith(THEMES_SEGMENT, StringComparison.OrdinalIgnoreCase)) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + + // a theme mutation replaces the theme files or the active selection, so every cached theme response becomes stale + if (!request.Method.Equals(HttpMethod.Get)) + { + HttpResponseMessage mutationResponse = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + if (mutationResponse.IsSuccessStatusCode) + await _hybridCache.RemoveByTagAsync(THEME_CACHE_TAG, cancellationToken).ConfigureAwait(false); + return mutationResponse; + } + + // the current user can switch off the theme cache from the settings page, so their requests always receive the freshly edited theme files + Guid? userId = GetCurrentUserId(); + if (userId is not null) + { + bool isCachingEnabledForUser = await _themeCachePreferenceService.GetAsync(userId.Value, defaultValue: true, cancellationToken).ConfigureAwait(false); + if (!isCachingEnabledForUser) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + } + + // key the cached responses by the full request path and query, since each theme endpoint identifies a distinct resource + string cacheKey = $"themes:{request.RequestUri.PathAndQuery}"; + CachedResponse cached = await _hybridCache.GetOrCreateAsync( + cacheKey, + async (cancellationToken) => + { + HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + byte[] bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); + return new CachedResponse + { + Bytes = bytes, + StatusCode = response.StatusCode, + ContentType = response.Content.Headers.ContentType?.ToString() + }; + }, + new HybridCacheEntryOptions() + { + Expiration = s_cacheExpiration + }, + [THEME_CACHE_TAG], + cancellationToken); + + // failed responses are only served from the call that produced them, so a temporary failure can never be served from a stale entry + if (!IsSuccessful(cached.StatusCode) || cached.Bytes.Length > MAX_CACHEABLE_BYTES) + await _hybridCache.RemoveAsync(cacheKey, cancellationToken).ConfigureAwait(false); + + return BuildResponse(cached); + } + + /// + /// Gets the unique identifier of the currently authenticated user, when there is one. + /// + /// The unique identifier of the current user, or when the request is anonymous. + private Guid? GetCurrentUserId() + { + string? userId = _httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + return Guid.TryParse(userId, out Guid parsedUserId) ? parsedUserId : null; + } + + /// + /// Checks whether the given status code represents a successful HTTP response. + /// + /// The status code to check. + /// when the status code is a successful one, otherwise. + private static bool IsSuccessful(HttpStatusCode statusCode) + { + return statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices; + } + + /// + /// Rebuilds the HTTP response message from the cached response data. + /// + /// The cached response data. + /// The rebuilt HTTP response message. + private static HttpResponseMessage BuildResponse(CachedResponse cached) + { + HttpResponseMessage response = new(cached.StatusCode) { Content = new ByteArrayContent(cached.Bytes) }; + if (!string.IsNullOrWhiteSpace(cached.ContentType)) + response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(cached.ContentType); + return response; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs new file mode 100644 index 00000000..d6990cdb --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Caching.Hybrid; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Services; + +/// +/// Service that stores and retrieves the per-user preference for the theme cache, so the theme caching can be toggled for a user from the settings page. +/// The preference is stored in the user settings and kept in the cache so the theme cache handler can apply it on every request without querying the database. +/// +public class ThemeCachePreferenceService +{ + private const string PREFERENCE_KEY_PREFIX = "theme-cache-enabled:"; + private static readonly TimeSpan s_preferenceLifetime = TimeSpan.FromDays(30); + + private readonly HybridCache _hybridCache; + + /// + /// Initializes a new instance of the class. + /// + /// The hybrid caching mechanism used to store and retrieve the theme cache preference. + public ThemeCachePreferenceService(HybridCache hybridCache) + { + _hybridCache = hybridCache; + } + + /// + /// Gets whether the theme cache is enabled for the user identified by . + /// + /// The unique identifier of the user whose preference is read. + /// The value used when the user did not express a preference yet. + /// Cancellation token that can be used to stop the execution. + /// when the theme cache is enabled for the user, otherwise. + public async Task GetAsync(Guid userId, bool defaultValue, CancellationToken cancellationToken = default) + { + bool? preference = await _hybridCache.GetOrCreateAsync( + BuildKey(userId), + (cancellationToken) => new ValueTask(defaultValue), + new HybridCacheEntryOptions() + { + Expiration = s_preferenceLifetime + }, + cancellationToken: cancellationToken).ConfigureAwait(false); + return preference ?? defaultValue; + } + + /// + /// Sets whether the theme cache is enabled for the user identified by . + /// + /// The unique identifier of the user whose preference is written. + /// Whether the theme cache is enabled for the user, or not. + /// Cancellation token that can be used to stop the execution. + /// An awaitable task representing the asynchronous operation. + public async Task SetAsync(Guid userId, bool isEnabled, CancellationToken cancellationToken = default) + { + // the value is stored as a nullable bool, matching the read type, since HybridCache keys entries by their stored type + await _hybridCache.SetAsync(BuildKey(userId), (bool?)isEnabled, new HybridCacheEntryOptions() + { + Expiration = s_preferenceLifetime + }, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Builds the cache key of the theme cache preference of the user identified by . + /// + /// The unique identifier of the user. + /// The cache key of the preference. + private static string BuildKey(Guid userId) + { + return $"{PREFERENCE_KEY_PREFIX}{userId}"; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs new file mode 100644 index 00000000..c3579c3b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/CachedThemeHandlerTests.cs @@ -0,0 +1,157 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CachedThemeHandlerTests +{ + private readonly HybridCache _hybridCache; + private readonly ThemeCachePreferenceService _themeCachePreferenceService; + + /// + /// Initializes a new instance of the class. + /// + public CachedThemeHandlerTests() + { + ServiceCollection services = new(); + services.AddHybridCache(); + _hybridCache = services.BuildServiceProvider().GetRequiredService(); + _themeCachePreferenceService = new ThemeCachePreferenceService(_hybridCache); + } + + [Fact] + public async Task SendAsync_WhenThemeGetRequestIsServedTwice_ShouldCallInnerHandlerOnlyOnce() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}""")); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/templates/shared/layout", CancellationToken.None); + + // Assert + Assert.Single(messageHandler.Requests); + } + + [Fact] + public async Task SendAsync_WhenNonThemeGetRequestIsServedTwice_ShouldCallInnerHandlerTwice() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """[{"title":"Library One"}]""")); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/libraries", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenThemeMutationIsPerformed_ShouldInvalidateCachedThemeResponses() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}""")); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + await client.PutAsync("http://localhost:5214/api/v1/themes/current", new StringContent("""{"themeId":"lumina-default"}""", Encoding.UTF8, "application/json"), CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + + // Assert + Assert.Equal(3, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenThemeGetRequestFails_ShouldNotRetainTheFailedResponse() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError)); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenThemeGetResponseExceedsMaxCacheableSize_ShouldNotCacheIt() + { + // Arrange + byte[] largeContent = new byte[600 * 1024]; + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(largeContent) }); + HttpClient client = CreateClient(messageHandler); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/editorial-paper/assets/preview.png", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + [Fact] + public async Task SendAsync_WhenUserDisablesThemeCaching_ShouldCallInnerHandlerForEveryRequest() + { + // Arrange + Guid userId = Guid.NewGuid(); + TestApiHttpMessageHandler messageHandler = new(_ => CreateJsonResponse(HttpStatusCode.OK, """{"themeId":"editorial-paper"}""")); + HttpClient client = CreateClient(messageHandler, userId: userId); + await _themeCachePreferenceService.SetAsync(userId, isEnabled: false, CancellationToken.None); + + // Act + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + await client.GetAsync("http://localhost:5214/api/v1/themes/current", CancellationToken.None); + + // Assert + Assert.Equal(2, messageHandler.Requests.Count); + } + + private HttpClient CreateClient(TestApiHttpMessageHandler messageHandler, Guid? userId = null) + { + IHttpContextAccessor httpContextAccessor = Substitute.For(); + if (userId is not null) + { + DefaultHttpContext httpContext = new(); + httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuthentication")); + httpContextAccessor.HttpContext.Returns(httpContext); + } + CachedThemeHandler themeHandler = new(_hybridCache, httpContextAccessor, _themeCachePreferenceService) + { + InnerHandler = messageHandler + }; + return new HttpClient(themeHandler); + } + + private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) + { + return new HttpResponseMessage(statusCode) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + } +} From 3da7167538e6ad29e50c5ce64efafc295d7b7884 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 04:04:54 -0700 Subject: [PATCH 15/31] Adds a theme caching toggle to the user settings --- .../UsersManagement/UserSettingsEntity.cs | 5 + .../Users/UpdateUserSettingsRequestMapping.cs | 3 +- .../Users/UserSettingsEntityMapping.cs | 6 +- .../Users/UserSettingsMapping.cs | 6 +- .../UpdateUserSettingsCommand.cs | 4 +- .../UpdateUserSettingsCommandHandler.cs | 6 +- .../Settings/UpdateUserSettingsRequest.cs | 4 +- .../Settings/UserSettingsResponse.cs | 4 +- .../UserSettingsConfiguration.cs | 4 + ...meCachingEnabledToUserSettings.Designer.cs | 1306 +++++++++++++++++ ...AddsIsThemeCachingEnabledToUserSettings.cs | 30 + .../LuminaDbContextModelSnapshot.cs | 4 + .../UserSettingsAggregate/UserSettings.cs | 33 +- .../GetUserSettingsEndpointSummary.cs | 3 +- .../UpdateUserSettingsEndpointSummary.cs | 8 +- .../DTO/UsersManagement/UserSettingsDto.cs | 5 + .../GetUserSettingsEndpoint.cs | 24 +- .../UpdateUserSettingsEndpoint.cs | 24 +- .../Resources/Views/Tools/Settings.de-DE.resx | 6 + .../Resources/Views/Tools/Settings.en-US.resx | 6 + .../Resources/Views/Tools/Settings.es-ES.resx | 6 + .../Resources/Views/Tools/Settings.fr-FR.resx | 6 + .../Resources/Views/Tools/Settings.it-IT.resx | 6 + .../Resources/Views/Tools/Settings.ja-JP.resx | 6 + .../Core/Resources/Views/Tools/Settings.resx | 6 + .../Resources/Views/Tools/Settings.ro-RO.resx | 6 + .../Resources/Views/Tools/Settings.ru-RU.resx | 6 + .../Resources/Views/Tools/Settings.zh-CN.resx | 6 + .../Core/Views/Tools/Settings.cshtml | 18 +- .../UserSettingsEntityFixture.cs | 7 +- .../UpdateUserSettingsCommandFixture.cs | 7 +- .../UserSettingsFixture.cs | 7 +- .../UpdateUserSettingsEndpointTests.cs | 10 +- .../UpdateUserSettingsEndpointTests.cs | 9 +- .../UpdateUserSettingsRequestMappingTests.cs | 3 +- .../Users/UserSettingsEntityMappingTests.cs | 2 + .../UpdateUserSettingsRequestTests.cs | 7 +- .../Settings/UserSettingsResponseTests.cs | 7 +- .../UserSettingsTests.cs | 10 +- .../GetUserSettingsEndpointTests.cs | 6 +- .../UpdateUserSettingsEndpointTests.cs | 11 +- .../GetUserSettingsEndpointTests.cs | 12 +- .../UpdateUserSettingsEndpointTests.cs | 12 +- 43 files changed, 1611 insertions(+), 56 deletions(-) create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.cs diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 768de9e8..524544bb 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -37,6 +37,11 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// public bool IgnoreThePrefixForAlphaPicker { get; set; } + /// + /// Gets or sets whether the theme data served to this user is cached, or not. + /// + public bool IsThemeCachingEnabled { get; set; } = true; + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index 8eee0bcb..23504a3c 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -20,6 +20,7 @@ public static class UpdateUserSettingsRequestMapping return new UpdateUserSettingsCommand( request.IsPaginationEnabled, request.ItemsPerPage, - request.IgnoreThePrefixForAlphaPicker); + request.IgnoreThePrefixForAlphaPicker, + request.IsThemeCachingEnabled); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index a109efca..b96f8fdb 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -28,7 +28,8 @@ public static class UserSettingsEntityMapping UserId.Create(repositoryEntity.UserId), repositoryEntity.IsPaginationEnabled, repositoryEntity.ItemsPerPage, - repositoryEntity.IgnoreThePrefixForAlphaPicker); + repositoryEntity.IgnoreThePrefixForAlphaPicker, + repositoryEntity.IsThemeCachingEnabled); } /// @@ -42,6 +43,7 @@ public static class UserSettingsEntityMapping repositoryEntity.UserId, repositoryEntity.IsPaginationEnabled, repositoryEntity.ItemsPerPage, - repositoryEntity.IgnoreThePrefixForAlphaPicker); + repositoryEntity.IgnoreThePrefixForAlphaPicker, + repositoryEntity.IsThemeCachingEnabled); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index 45764c56..7a22ee1e 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -24,7 +24,8 @@ public static class UserSettingsMapping UserId = domainEntity.UserId.Value, IsPaginationEnabled = domainEntity.IsPaginationEnabled, ItemsPerPage = domainEntity.ItemsPerPage, - IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker + IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker, + IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled }; } @@ -39,6 +40,7 @@ public static class UserSettingsMapping domainEntity.UserId.Value, domainEntity.IsPaginationEnabled, domainEntity.ItemsPerPage, - domainEntity.IgnoreThePrefixForAlphaPicker); + domainEntity.IgnoreThePrefixForAlphaPicker, + domainEntity.IsThemeCachingEnabled); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index a7f081cf..0e798ccc 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -10,8 +10,10 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +/// Whether the theme data served to this user is cached, or not. public record UpdateUserSettingsCommand( bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker + bool IgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 4070ab3a..3028518b 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -72,7 +72,8 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler updateSettingsResult = toDomainEntityResult.Value.UpdateSettings( command.IsPaginationEnabled, command.ItemsPerPage, - command.IgnoreThePrefixForAlphaPicker); + command.IgnoreThePrefixForAlphaPicker, + command.IsThemeCachingEnabled); if (updateSettingsResult.IsFailure) return updateSettingsResult.Errors; diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index eb76b7ad..2b0ad237 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -10,9 +10,11 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// Whether pagination is enabled for the user, or not. Required. /// The number of library items displayed per page when pagination is enabled. Required. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. +/// Whether the theme data served to this user is cached, or not. Required. [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] public sealed record UpdateUserSettingsRequest( bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker + bool IgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled ); diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 2e29dd70..3c362b34 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -12,10 +12,12 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +/// Whether the theme data served to this user is cached, or not. [DebuggerDisplay("UserId: {UserId}")] public sealed record UserSettingsResponse( Guid UserId, bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker + bool IgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled ); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index a24022a1..ca160a72 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -47,6 +47,10 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.IsThemeCachingEnabled) + .IsRequired() + .HasColumnOrder(9); + // audit builder.Property(settings => settings.CreatedOnUtc) .IsRequired() diff --git a/src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.Designer.cs new file mode 100644 index 00000000..5f59be74 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.Designer.cs @@ -0,0 +1,1306 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260821092546_AddsIsThemeCachingEnabledToUserSettings")] + partial class AddsIsThemeCachingEnabledToUserSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("DownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.cs b/src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.cs new file mode 100644 index 00000000..60fddf8c --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260821092546_AddsIsThemeCachingEnabledToUserSettings.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsIsThemeCachingEnabledToUserSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsThemeCachingEnabled", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: true) + .Annotation("Relational:ColumnOrder", 9); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsThemeCachingEnabled", + table: "UserSettings"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index d21b069d..3bf74c6a 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -972,6 +972,10 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(2); + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + b.Property("ItemsPerPage") .HasColumnType("INTEGER") .HasColumnOrder(3); diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index 46f5d0df..6cd60fc9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -19,6 +19,7 @@ public class UserSettings : AggregateRoot private const bool DEFAULT_IS_PAGINATION_ENABLED = true; private const int DEFAULT_ITEMS_PER_PAGE = 48; private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false; + private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true; /// /// Gets the object representing the unique identifier of the user that owns these settings. @@ -40,6 +41,11 @@ public class UserSettings : AggregateRoot /// public bool IgnoreThePrefixForAlphaPicker { get; private set; } + /// + /// Gets whether the theme data served to this user is cached, or not. + /// + public bool IsThemeCachingEnabled { get; private set; } + /// /// Initializes a new instance of the class. /// @@ -48,17 +54,20 @@ public class UserSettings : AggregateRoot /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the theme data served to this user is cached, or not. private UserSettings( UserSettingsId id, UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker) : base(id) + bool ignoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled) : base(id) { UserId = userId; IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + IsThemeCachingEnabled = isThemeCachingEnabled; } /// @@ -69,7 +78,7 @@ public class UserSettings : AggregateRoot /// public static Result Create() { - return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER); + return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED); } /// @@ -81,7 +90,7 @@ public class UserSettings : AggregateRoot /// public static Result Create(UserId userId) { - return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER); + return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED); } /// @@ -91,6 +100,7 @@ public class UserSettings : AggregateRoot /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the theme data served to this user is cached, or not. /// /// An containing either a successfully created , or an error message. /// @@ -98,7 +108,8 @@ public class UserSettings : AggregateRoot UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker) + bool ignoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; @@ -108,7 +119,8 @@ public class UserSettings : AggregateRoot userId, isPaginationEnabled, itemsPerPage, - ignoreThePrefixForAlphaPicker); + ignoreThePrefixForAlphaPicker, + isThemeCachingEnabled); } /// @@ -119,6 +131,7 @@ public class UserSettings : AggregateRoot /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the theme data served to this user is cached, or not. /// /// An containing either a successfully created , or an error message. /// @@ -127,12 +140,13 @@ public class UserSettings : AggregateRoot UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker) + bool ignoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker); + return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker, isThemeCachingEnabled); } /// @@ -141,11 +155,13 @@ public class UserSettings : AggregateRoot /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the theme data served to this user is cached, or not. /// An representing either a successful update, or an error. public Result UpdateSettings( bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker) + bool ignoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; @@ -153,6 +169,7 @@ public class UserSettings : AggregateRoot IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + IsThemeCachingEnabled = isThemeCachingEnabled; return Result.Updated; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs index a8446d03..4d0df558 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointSummary.cs @@ -26,7 +26,8 @@ public class GetUserSettingsEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required."); + RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required."); + RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); + RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required."); + Response(200, "The settings of the current user were successfully updated."); Response(401, "Authentication required.", "application/problem+json", diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index ad009888..c074a3c6 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -30,4 +30,9 @@ public class UserSettingsDto /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// public bool IgnoreThePrefixForAlphaPicker { get; set; } + + /// + /// Gets or sets whether the theme data served to this user is cached, or not. + /// + public bool IsThemeCachingEnabled { get; set; } = true; } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs index 9dd135dc..4e899751 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpoint.cs @@ -3,9 +3,12 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using System; +using System.Security.Claims; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,14 +21,17 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; public class GetUserSettingsEndpoint : BaseEndpoint { private readonly IApiHttpClient _apiHttpClient; + private readonly ThemeCachePreferenceService _themeCachePreferenceService; /// /// Initializes a new instance of the class. /// /// Injected service for interactions with the API. - public GetUserSettingsEndpoint(IApiHttpClient apiHttpClient) + /// Injected service for storing the per-user theme cache preference. + public GetUserSettingsEndpoint(IApiHttpClient apiHttpClient, ThemeCachePreferenceService themeCachePreferenceService) { _apiHttpClient = apiHttpClient; + _themeCachePreferenceService = themeCachePreferenceService; } /// @@ -48,6 +54,22 @@ public class GetUserSettingsEndpoint : BaseEndpoint public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { UserSettingsDto response = await _apiHttpClient.GetAsync(ApiRoutes.Users.GET_USER_SETTINGS, cancellationToken).ConfigureAwait(false); + + // refresh the per-user theme cache preference from the stored settings, so the handler always applies the latest value + Guid? userId = GetCurrentUserId(); + if (userId is not null) + await _themeCachePreferenceService.SetAsync(userId.Value, response.IsThemeCachingEnabled, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); } + + /// + /// Gets the unique identifier of the currently authenticated user. + /// + /// The unique identifier of the current user, or when the request is anonymous. + private Guid? GetCurrentUserId() + { + string? userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + return Guid.TryParse(userId, out Guid parsedUserId) ? parsedUserId : null; + } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs index 044f7440..82530e78 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpoint.cs @@ -3,9 +3,12 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Common; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using System; +using System.Security.Claims; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,14 +21,17 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettin public class UpdateUserSettingsEndpoint : BaseEndpoint { private readonly IApiHttpClient _apiHttpClient; + private readonly ThemeCachePreferenceService _themeCachePreferenceService; /// /// Initializes a new instance of the class. /// /// Injected service for interactions with the API. - public UpdateUserSettingsEndpoint(IApiHttpClient apiHttpClient) + /// Injected service for storing the per-user theme cache preference. + public UpdateUserSettingsEndpoint(IApiHttpClient apiHttpClient, ThemeCachePreferenceService themeCachePreferenceService) { _apiHttpClient = apiHttpClient; + _themeCachePreferenceService = themeCachePreferenceService; } /// @@ -49,6 +55,22 @@ public class UpdateUserSettingsEndpoint : BaseEndpoint public override async Task ExecuteAsync(UserSettingsDto request, CancellationToken cancellationToken) { await _apiHttpClient.PutAsync(ApiRoutes.Users.UPDATE_USER_SETTINGS, request, cancellationToken).ConfigureAwait(false); + + // keep the per-user theme cache preference in sync with the stored settings, so the handler applies it immediately + Guid? userId = GetCurrentUserId(); + if (userId is not null) + await _themeCachePreferenceService.SetAsync(userId.Value, request.IsThemeCachingEnabled, cancellationToken).ConfigureAwait(false); + return JsonSuccess(new { isUpdated = true }); } + + /// + /// Gets the unique identifier of the currently authenticated user. + /// + /// The unique identifier of the current user, or when the request is anonymous. + private Guid? GetCurrentUserId() + { + string? userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + return Guid.TryParse(userId, out Guid parsedUserId) ? parsedUserId : null; + } } diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx index 7f312406..5f1d8361 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.de-DE.resx @@ -39,4 +39,10 @@ Wenn aktiviert, werden Bibliothekselemente, deren Titel mit "The" beginnt, in der Alpha-Auswahl unter dem ersten Buchstaben des folgenden Wortes gruppiert, z. B. wird "The Rasmus" unter R aufgeführt. + + Themencache aktivieren + + + Gibt an, ob die von der Anwendung bereitgestellten Themendateien zwischengespeichert werden. Deaktivieren Sie diese Option beim Bearbeiten von Themendateien, damit die Änderungen sofort erscheinen. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx index d7ecb8c2..da463e75 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.en-US.resx @@ -39,4 +39,10 @@ When enabled, library items whose title begins with "The" are grouped under the first letter of the following word in the alpha picker, e.g. "The Rasmus" is listed under R. + + Enable theme caching + + + Whether the theme files served by the application are cached. Turn this off while editing theme files so the changes appear immediately. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx index 46197a4f..0cfad2b5 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.es-ES.resx @@ -39,4 +39,10 @@ Cuando está habilitado, los elementos de la biblioteca cuyo título comienza con "The" se agrupan bajo la primera letra de la palabra siguiente en el selector alfabético, por ejemplo, "The Rasmus" se lista bajo R. + + Habilitar caché de temas + + + Controla si los archivos de temas servidos por la aplicación se almacenan en caché. Desactívelo mientras edita archivos de temas para que los cambios aparezcan inmediatamente. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx index 0d086bdd..7327abbf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.fr-FR.resx @@ -39,4 +39,10 @@ Lorsque cette option est activée, les éléments de la bibliothèque dont le titre commence par "The" sont regroupés sous la première lettre du mot suivant dans le sélecteur alphabétique, par exemple "The Rasmus" est répertorié sous R. + + Activer le cache des thèmes + + + Contrôle si les fichiers de thèmes servis par l'application sont mis en cache. Désactivez-le pendant la modification des fichiers de thèmes afin que les changements apparaissent immédiatement. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx index f88da291..c29b3a31 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.it-IT.resx @@ -39,4 +39,10 @@ Se abilitato, gli elementi della libreria il cui titolo inizia con "The" vengono raggruppati sotto la prima lettera della parola successiva nel selettore alfabetico, ad esempio "The Rasmus" è elencato sotto R. + + Abilita la cache dei temi + + + Controlla se i file dei temi serviti dall'applicazione vengono memorizzati nella cache. Disattivalo mentre modifichi i file dei temi affinché le modifiche appaiano immediatamente. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx index 78c7e46f..6dc95ed9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ja-JP.resx @@ -39,4 +39,10 @@ 有効にすると、タイトルが「The」で始まるライブラリの項目は、アルファピッカーで次の単語の最初の文字の下にグループ化されます。たとえば「The Rasmus」は「R」の下に表示されます。 + + テーマキャッシュを有効にする + + + アプリケーションが提供するテーマファイルをキャッシュするかどうかを制御します。テーマファイルを編集している間はオフにして、変更がすぐに反映されるようにします。 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx index d7ecb8c2..da463e75 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.resx @@ -39,4 +39,10 @@ When enabled, library items whose title begins with "The" are grouped under the first letter of the following word in the alpha picker, e.g. "The Rasmus" is listed under R. + + Enable theme caching + + + Whether the theme files served by the application are cached. Turn this off while editing theme files so the changes appear immediately. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx index add6888f..b36b2406 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ro-RO.resx @@ -39,4 +39,10 @@ Când este activată, elementele bibliotecii al căror titlu începe cu "The" sunt grupate sub prima literă a cuvântului următor în selectorul alfabetic, de exemplu "The Rasmus" este listat sub R. + + Activează cache-ul temelor + + + Controlează dacă fișierele temelor servite de aplicație sunt puse în cache. Dezactivați această opțiune în timp ce editați fișierele temelor, pentru ca modificările să apară imediat. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ru-RU.resx index 5657d5a6..e44f8385 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.ru-RU.resx @@ -39,4 +39,10 @@ При включении элементы библиотеки, название которых начинается с "The", группируются в алфавитном указателе под первой буквой следующего слова, например "The Rasmus" отображается под буквой R. + + Включить кэширование тем + + + Определяет, кэшируются ли файлы тем, предоставляемые приложением. Отключите эту опцию при редактировании файлов тем, чтобы изменения отображались сразу. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx index 00301a1b..857dd54f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Tools/Settings.zh-CN.resx @@ -39,4 +39,10 @@ 启用后,标题以"The"开头的库项目将在字母选择器中按后一个词的首字母分组,例如"The Rasmus"会列在R下。 + + 启用主题缓存 + + + 控制应用程序提供的主题文件是否缓存。编辑主题文件时请关闭此选项,以便更改立即生效。 + diff --git a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml index 7ea8be9a..7f62b856 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Tools/Settings.cshtml @@ -65,6 +65,19 @@ @_localizer["DescriptionIgnoreThePrefixForAlphaPicker"] + +
    +
    + : +
    +
    + +
    + @_localizer["DescriptionEnableThemeCaching"] +
    @@ -82,6 +95,7 @@ const checkboxIsPaginationEnabled = document.getElementById('IsPaginationEnabled'); const inputItemsPerPage = document.getElementById('ItemsPerPage'); const checkboxIgnoreThePrefixForAlphaPicker = document.getElementById('IgnoreThePrefixForAlphaPicker'); + const checkboxIsThemeCachingEnabled = document.getElementById('IsThemeCachingEnabled'); // toggle the enabled state of the items per page input based on the pagination checkbox function updateItemsPerPageEnabledState() { @@ -95,6 +109,7 @@ checkboxIsPaginationEnabled.checked = data.isPaginationEnabled === true; inputItemsPerPage.value = data.itemsPerPage; checkboxIgnoreThePrefixForAlphaPicker.checked = data.ignoreThePrefixForAlphaPicker === true; + checkboxIsThemeCachingEnabled.checked = data.isThemeCachingEnabled === true; updateItemsPerPageEnabledState(); } } @@ -104,7 +119,8 @@ const formData = { IsPaginationEnabled: checkboxIsPaginationEnabled.checked, ItemsPerPage: Number(inputItemsPerPage.value), - IgnoreThePrefixForAlphaPicker: checkboxIgnoreThePrefixForAlphaPicker.checked + IgnoreThePrefixForAlphaPicker: checkboxIgnoreThePrefixForAlphaPicker.checked, + IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); if (data && data.isUpdated === true) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs index d11a1fdc..e6e86104 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs @@ -23,13 +23,15 @@ public class UserSettingsEntityFixture /// Optional. Whether pagination is enabled for the user, or not. /// Optional. The number of library items displayed per page when pagination is enabled. /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// Optional. Whether the theme data served to this user is cached, or not. /// The created user settings entity. public UserSettingsEntity Create( Guid? id = null, Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, - bool? ignoreThePrefixForAlphaPicker = null) + bool? ignoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null) { return new Faker() .CustomInstantiator(f => new UserSettingsEntity @@ -38,7 +40,8 @@ public class UserSettingsEntityFixture UserId = userId ?? Guid.NewGuid(), IsPaginationEnabled = isPaginationEnabled ?? f.Random.Bool(), ItemsPerPage = itemsPerPage ?? f.Random.Int(1, 100), - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool() + IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool(), + IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool() }) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs index 7fc9e855..d26b85c7 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -20,17 +20,20 @@ public class UpdateUserSettingsCommandFixture /// Optional. Whether pagination is enabled for the user, or not. /// Optional. The number of library items displayed per page when pagination is enabled. /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// Optional. Whether the theme data served to this user is cached, or not. /// The created command. public UpdateUserSettingsCommand Create( bool? isPaginationEnabled = null, int? itemsPerPage = null, - bool? ignoreThePrefixForAlphaPicker = null) + bool? ignoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null) { return new Faker() - .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default)) + .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default)) .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) .RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100)) .RuleFor(x => x.IgnoreThePrefixForAlphaPicker, f => ignoreThePrefixForAlphaPicker ?? f.Random.Bool()) + .RuleFor(x => x.IsThemeCachingEnabled, f => isThemeCachingEnabled ?? f.Random.Bool()) .Generate(); } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs index dc4ffd36..89134b4e 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs @@ -23,18 +23,21 @@ public class UserSettingsFixture /// Whether pagination is enabled for the user. /// The number of library items displayed per page when pagination is enabled. /// Whether the "The" prefix of library item titles is ignored by the alpha picker. + /// Whether the theme data served to this user is cached. /// The created . public UserSettings Create( Guid? userId = null, bool isPaginationEnabled = true, int itemsPerPage = 48, - bool ignoreThePrefixForAlphaPicker = false) + bool ignoreThePrefixForAlphaPicker = false, + bool isThemeCachingEnabled = true) { Result settings = UserSettings.Create( userId is null ? UserId.CreateUnique() : UserId.Create(userId.Value), isPaginationEnabled, itemsPerPage, - ignoreThePrefixForAlphaPicker); + ignoreThePrefixForAlphaPicker, + isThemeCachingEnabled); return settings.Value; } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 34faea2e..105106e8 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -59,7 +59,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture UpdateUserSettingsRequest request = new( IsPaginationEnabled: true, ItemsPerPage: 48, - IgnoreThePrefixForAlphaPicker: false + IgnoreThePrefixForAlphaPicker: false, + IsThemeCachingEnabled: true ); // Act @@ -79,7 +80,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture UpdateUserSettingsRequest request = new( IsPaginationEnabled: true, ItemsPerPage: int.MaxValue, - IgnoreThePrefixForAlphaPicker: false + IgnoreThePrefixForAlphaPicker: false, + IsThemeCachingEnabled: true ); // Act @@ -101,7 +103,8 @@ public class UpdateUserSettingsEndpointTests : IClassFixture UpdateUserSettingsRequest request = new( IsPaginationEnabled: true, ItemsPerPage: int.MinValue, - IgnoreThePrefixForAlphaPicker: false + IgnoreThePrefixForAlphaPicker: false, + IsThemeCachingEnabled: true ); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs index 52e66af8..3a7aa785 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs @@ -17,7 +17,7 @@ public class UpdateUserSettingsRequestMappingTests public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false); + UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false, IsThemeCachingEnabled: true); // Act UpdateUserSettingsCommand result = request.ToCommand(); @@ -27,5 +27,6 @@ public class UpdateUserSettingsRequestMappingTests Assert.Equal(request.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(request.ItemsPerPage, result.ItemsPerPage); Assert.Equal(request.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs index 5ac4822a..f87c367b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs @@ -34,6 +34,7 @@ public class UserSettingsEntityMappingTests Assert.Equal(entity.IsPaginationEnabled, result.Value.IsPaginationEnabled); Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage); Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + Assert.Equal(entity.IsThemeCachingEnabled, result.Value.IsThemeCachingEnabled); } [Fact] @@ -51,5 +52,6 @@ public class UserSettingsEntityMappingTests Assert.Equal(entity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage); Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(entity.IsThemeCachingEnabled, result.IsThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs index 44bfcd8b..a8b6cbfc 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs @@ -21,7 +21,7 @@ public class UpdateUserSettingsRequestTests public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues() { // Arrange - UpdateUserSettingsRequest expected = new(true, 50, true); + UpdateUserSettingsRequest expected = new(true, 50, true, true); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); @@ -36,14 +36,15 @@ public class UpdateUserSettingsRequestTests public void Deconstruct_WhenCalled_ShouldReturnAllProperties() { // Arrange - UpdateUserSettingsRequest sut = new(false, 25, false); + UpdateUserSettingsRequest sut = new(false, 25, false, false); // Act - (bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker) = sut; + (bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut; // Assert Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); Assert.Equal(sut.ItemsPerPage, itemsPerPage); Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs index ac566276..0bd9c3ff 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs @@ -23,7 +23,7 @@ public class UserSettingsResponseTests { // Arrange Guid userId = Guid.NewGuid(); - UserSettingsResponse expected = new(userId, true, 50, true); + UserSettingsResponse expected = new(userId, true, 50, true, true); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); @@ -39,15 +39,16 @@ public class UserSettingsResponseTests { // Arrange Guid userId = Guid.NewGuid(); - UserSettingsResponse sut = new(userId, false, 25, false); + UserSettingsResponse sut = new(userId, false, 25, false, false); // Act - (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker) = sut; + (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut; // Assert Assert.Equal(sut.UserId, sutUserId); Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); Assert.Equal(sut.ItemsPerPage, itemsPerPage); Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index 8b0460c0..d1abc2cf 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -72,7 +72,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true); // Assert Assert.False(result.IsFailure); @@ -80,6 +80,7 @@ public class UserSettingsTests Assert.False(result.Value.IsPaginationEnabled); Assert.Equal(24, result.Value.ItemsPerPage); Assert.True(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.True(result.Value.IsThemeCachingEnabled); } [Fact] @@ -105,7 +106,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); + Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true); // Assert Assert.True(result.IsFailure); @@ -119,13 +120,14 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true); + Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false); // Assert Assert.False(result.IsFailure); Assert.False(userSettings.IsPaginationEnabled); Assert.Equal(12, userSettings.ItemsPerPage); Assert.True(userSettings.IgnoreThePrefixForAlphaPicker); + Assert.False(userSettings.IsThemeCachingEnabled); } [Theory] @@ -137,7 +139,7 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); + Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 122bb46c..190e76d7 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -39,7 +39,7 @@ public class GetUserSettingsEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false); + UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false, true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -79,7 +79,7 @@ public class GetUserSettingsEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false))); + .Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true))); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); @@ -104,7 +104,7 @@ public class GetUserSettingsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false)); + return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true)); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 03c65397..5e15bdf4 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -37,7 +37,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker() { // Arrange - UpdateUserSettingsRequest request = new(true, 48, false); + UpdateUserSettingsRequest request = new(true, 48, false, true); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -54,7 +54,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - UpdateUserSettingsRequest request = new(true, 0, false); + UpdateUserSettingsRequest request = new(true, 0, false, true); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -76,7 +76,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler() { // Arrange - UpdateUserSettingsRequest request = new(true, 24, true); + UpdateUserSettingsRequest request = new(true, 24, true, true); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -89,7 +89,8 @@ public class UpdateUserSettingsEndpointTests Arg.Is(command => command.IsPaginationEnabled == request.IsPaginationEnabled && command.ItemsPerPage == request.ItemsPerPage && - command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker), + command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker && + command.IsThemeCachingEnabled == request.IsThemeCachingEnabled), Arg.Is(cancellationToken)); } @@ -111,7 +112,7 @@ public class UpdateUserSettingsEndpointTests }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false), cts.Token); + Task operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false, true), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index b55cfc50..3a553dc4 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -3,10 +3,13 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Text.Json; @@ -32,7 +35,14 @@ public class GetUserSettingsEndpointTests public GetUserSettingsEndpointTests() { _mockApiHttpClient = Substitute.For(); - _sut = Factory.Create(_mockApiHttpClient); + _sut = Factory.Create(_mockApiHttpClient, CreateThemeCachePreferenceService()); + } + + private static ThemeCachePreferenceService CreateThemeCachePreferenceService() + { + ServiceCollection services = new(); + services.AddHybridCache(); + return new ThemeCachePreferenceService(services.BuildServiceProvider().GetRequiredService()); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 3691a19a..0edb17c5 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -3,10 +3,13 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; using NSubstitute; using System.Diagnostics.CodeAnalysis; using System.Text.Json; @@ -32,7 +35,14 @@ public class UpdateUserSettingsEndpointTests public UpdateUserSettingsEndpointTests() { _mockApiHttpClient = Substitute.For(); - _sut = Factory.Create(_mockApiHttpClient); + _sut = Factory.Create(_mockApiHttpClient, CreateThemeCachePreferenceService()); + } + + private static ThemeCachePreferenceService CreateThemeCachePreferenceService() + { + ServiceCollection services = new(); + services.AddHybridCache(); + return new ThemeCachePreferenceService(services.BuildServiceProvider().GetRequiredService()); } [Fact] From dcb231e393bfdb3a3bef19d2165c9895d9ed6924 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 04:05:04 -0700 Subject: [PATCH 16/31] Aligns the endpoint summaries with the request parameter convention --- .../GetDrives/GetDrivesEndpointSummary.cs | 3 +-- .../GetType/GetTypeEndpointSummary.cs | 2 +- .../GetPathSeparatorEndpointSummary.cs | 2 +- .../ScanLibrary/ScanLibraryEndpointSummary.cs | 9 ++++++- .../Books/GetBooks/GetBooksEndpointSummary.cs | 19 ++++++++++++++- .../GetBooksLiteEndpointSummary.cs | 24 ++++++++++++++++++- .../CheckInitializationEndpointSummary.cs | 2 +- 7 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs index 77c554b1..9021510e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointSummary.cs @@ -2,7 +2,6 @@ using FastEndpoints; using Lumina.Contracts.Responses.FileSystemManagement.Common; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -12,7 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.Get /// Class used for providing a textual description for the API endpoint, for OpenAPI. ///
    [ExcludeFromCodeCoverage] -public class GetDrivesEndpointSummary : Summary +public class GetDrivesEndpointSummary : Summary { /// /// Initializes a new instance of the class. diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs index 528c5c53..9ca34185 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs @@ -11,7 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetTypeEndpointSummary : Summary +public class GetTypeEndpointSummary : Summary { /// /// Initializes a new instance of the class. diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs index d2321cb0..9bad080f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointSummary.cs @@ -10,7 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPa /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetPathSeparatorEndpointSummary : Summary +public class GetPathSeparatorEndpointSummary : Summary { /// /// Initializes a new instance of the class. diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs index ec9af2ea..b85f1e80 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using System; using System.Collections.Generic; @@ -12,7 +13,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary; /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class ScanLibraryEndpointSummary : Summary +public class ScanLibraryEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -22,6 +23,12 @@ public class ScanLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library to be scanned. Required."); + Response(200, "The media library scan was successfully started.", example: new MediaLibraryScanResponse( ScanId: Guid.NewGuid(), diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs index 5555d764..a128d00d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs @@ -3,9 +3,11 @@ using FastEndpoints; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,7 +19,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetBooksEndpointSummary : Summary +public class GetBooksEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -27,6 +29,21 @@ public class GetBooksEndpointSummary : Summary Summary = "Retrieves the list of books."; Description = "Returns the entire list of books."; + ExampleRequest = new GetBooksRequest( + LibraryId: Guid.NewGuid(), + CurrentPage: 1, + PerPage: 48, + SearchTerm: "fellowship", + SortBy: "title", + SortOrder: SortOrder.Ascending + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required."); + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); + RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); + RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); + RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); Response(200, "The paginated list of books is returned.", example: new PaginatedResponse diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs index b8dfb1fe..8a35a6c6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -13,7 +15,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetBooksLiteEndpointSummary : Summary +public class GetBooksLiteEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -23,6 +25,26 @@ public class GetBooksLiteEndpointSummary : Summary Summary = "Retrieves the lightweight details of the list of books."; Description = "Returns a paginated list of the lightweight details of the books of the media library, suitable for card-style navigation."; + ExampleRequest = new GetBooksLiteRequest( + LibraryId: Guid.NewGuid(), + CurrentPage: 1, + PerPage: 48, + SearchTerm: "fellowship", + FilterAlphaKey: "f", + IgnoreThePrefixForAlphaPicker: true, + SortBy: "title", + SortOrder: SortOrder.Ascending + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required."); + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); + RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); + RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional."); + RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required."); + RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); + RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); + Response(200, "The paginated list of lightweight book details is returned.", example: new PaginatedResponse { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs index db52a732..13007526 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointSummary.cs @@ -10,7 +10,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class CheckInitializationEndpointSummary : Summary +public class CheckInitializationEndpointSummary : Summary { /// /// Initializes a new instance of the class. From 148377a69f3a782ccf7f1804a9c648857f243c73 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 04:06:15 -0700 Subject: [PATCH 17/31] Moves the bundled themes under the Core directory --- .gitignore | 3 ++- .../Core/Themes/Bundled/editorial-paper.zip | Bin 0 -> 6690 bytes .../Lumina.Presentation.Api.csproj | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip diff --git a/.gitignore b/.gitignore index ca957e19..12452e6a 100644 --- a/.gitignore +++ b/.gitignore @@ -57,7 +57,8 @@ $RECYCLE.BIN/ # Archives *.zip -!src/Lumina.Presentation.Api/Themes/Bundled/*.zip # bundled themes should be tracked +# bundled themes should be tracked +!src/Lumina.Presentation.Api/Core/Themes/Bundled/*.zip *.tar.gz *.rar diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip new file mode 100644 index 0000000000000000000000000000000000000000..9aefc9ce38914200b381ec7136d5ded662cdc3b3 GIT binary patch literal 6690 zcmbW5Wl-DO*2aSur?|VjOQE<0cXtxpog&4d#e=();#ORWySrO)E6_q4ynQ)m=H8z6 zo=2z>Y2s<{n^o z4qGP>*oWQ5!_mPpz6T?e5-sAw4`pYv-&OmYF`Wv+ZtU?gj>NIGFo7dwTqB-!ti@a~~yE#PtJ;!h0o8U^7NS z0fk1SLe)Gw8HY=(I+tFMrcCNjzaIM7IZTe5mg`NwNwYw&YmfUosK4sTa{Bj>!*Ie{ zLy4K$kHPtis1Wi^Gk9wIFEH=&js0t?k43-*5)$6TVupt_bh9f_{6MkBw~cBobJ!JJ zEtIP#r9D~_Arh{htuORs$k40r1C1hswe~*PHy}(FkC&d@(>0t)S&&4OjoaKyh!9Ii zt&^bfSxA_lC?#=^cr4+9Nb#G;#wVqN+;WX3yZuMz;>drPxO7%p1`6JOV3Kf1ni z(ObrgP#*{!^?_T(zL-ts?b6_ewJIm=+%qFQD&s(+XylbI0v?4dE-cu6m(sjTs}Zrh z;TKYx6-?>;hPXGh*gjca-ZIB$4ZK?Os${LwenHn<<(3r|{bP!H^6kEZQ|gfLV8CmP zoZ0i0Zt_PofxLY&WT-Hg{g0pi=&R>p?rj_#v#0zKp_=TvSOqAI@4WbpbAaN9^J6Xs zd>L;18|faKyYW{Dzh{VGL74`5$}kWK03iRj44urq*c`!5o`0t}ki6j(N{Kskag7^h zOacWQO^};kE2^oo5Ea6FZo}FNc;+#%xN7CdpHw`0dq*btnlbIsEaCQqYDgPyL2l)Y zYsWK=WHB{#HDvT7rfiCt!J#1gN%1{=_;aS*QZu@!qi)w!snpgx>w65>; z8f;w)YU~&tjvP}Spnjkhn9jw2TU@?fs6$Cm>0Myd-)gcHiDIG_L5z?^YADR8i=b+5 z(4`{1>qA)&Z8;Df{#xdfgcFbLNQ8td5uSutRt# zx;{Gwo=)YZN=^T6YZ_1~vegYvo7)r1+Q3{xp_ctU0V$D=n|`0@5Qo@O*zuiGH%1u6 zLRl=%W4IyBMuj||`>V=0Qu}`U^vQ2(5r)kBrsRWJX1WE=G)nRp6oX-2$~M7vjuRdGwP)0+$`2!?xH89J1tk2R#;(jPWAsTBh$+ zCqp~-34G!tadU>+jC~+`0jh$-V9xVQEgDeI_Yd%av`8`}{43`Ov*lL1vikJuo)85_ z*vz7`)G{$m{>-74iRqIpv?>Y3arbEA!oA+_XlwW+uv0o_i2OU}kGWM#W_CJzE2PUT z5_Mrq+UJo>^E~Vd;IG>cEOYe*?&w-QB?+?i?OAU`H^!rMr6-WW#BV6D|DW3Rl|i16%Fou7}Jv zO#8+LdqfAoQJr619~ZQbDYX?4vw=900Mn-icZq;ZP8JY3CX}$x`er68Dp3RBj;Hlq zuGz5MQ~^TF43B;SK%Y7a?o4$7kw@`{Q~dP3tXSMM;A-DNqCmNY#-7_+^@}~?9p8@3 zMGMEqJ3klG!OWzD*uLDy45O zi2qT@6`>AeJ)ci6cVroPkP(NNH7?wSaKW7=@NQE1Q`*(odciT|s4#oyoXNpn>1S$0 z8J+d9a|CyARzH55^Wa?EN1+r!O-$1s%YeAYNBolu0gHlwvXwbK9Rr3c6bAJ%rl+T z;biRZ&!Ex?N`tw0Dat1ApN|lr1|_SajOy!PATYTlCL_yFZIq`vCaSPc0(kz2gw+biA?o^m~vl-P=i+>b9``BwBS)hf%cq-x-C=HUDU`NT+Is%aS;}+ zviJZ9o;DC-!;ckn$(cJG4#U)pplL`v57MI-7^=e~mF-EK*c-aK+VK_dc9O(DwC%rf zs9nSJ7%`cHAQtZB!#x*KIJtieQhM2*u4_|qz(23h5r3y^xk|L$TaMT!)P3=)JSdKH zLg?8`Q+A2zk`E%{1TjYH=vOH4DYHU~NP%=TWbk6jIn{^k8c=^3Mzt||6sCHIzi-h7Z`|c~9u)0S0Ck z%P29(U-Kc1dzCw!kM4Afqdw&LP5TtP5f#H9sHJqd z`evIL!TJ;#rF4kvh&13Zh(Qz(Ok2}0Vd~(II78JW4U`|tex0(`B0MDc+UAf!I?-Fa z(0MB^E++4;;>Yq?Ck~bBTWs1d6ODIvVN1shZN+w;;?!oM5{?#V+R@I`XqnFqIjc)m zOKA7d>Ugt5XDXQ~yV!A-zv>+Ha7XO5s4UCE_7PEm?Yd1XSf$&agJgf)_|U;<$OpXf zNs?#_6~APN{#;NM;s6f4O%J~(~BXimU zN2}~KRw)LlH2uw@+@}=o?Ooht?H9D&B(Kxne5MTM-ᐆqg^cs|>Zci?YBbHL=T zChHa0%~O6l(8w=_j7TJs6L3dgTHv!v57OZU_iW)aKh3U)`Dx14(8zJ_kYbnRkf5ro z*J3@Wk0kk98BzrZSLnFQ%fKtVqHe12&6S+#7@p(Z3fi4)#wIYrze=e{c}@BJ%l)=@ z9}o8f%nx`8mocFYMAY0GSz+<<)b#$>4;i1QhL6Oo;h{shLm)3HaA>*Z1ZT=6R&z&493cN9n(^Re@@<6oY9ylrU!dkR;qozk#1tWm zRlb6ZR`{G0=Sxco5Dj~1tLT<)#yGloms|QIRJ{9|Lgj9RoG(X;o)v?5KIboBmV`hw z5{tB2JJMXA(V*?#%&y%h6ja?Su!wfYUVJcXcD#i+xLM!4*uDpi=yT-=#c$Z2VfV!} zX}9saG}%Gb*Wa=Wi;z$*kVA^A`I*Ur!hFgrOnpdRYR{D_yzWx)va zks!NB5)ON*UN0h&ZlPOf;(J!s8QQrSPQ4F|!7n1M^cWBldM<1U<7-C-v)|^ySXcN@ z6tR*y_G_*8$}TDikx)8t1G+8n1_pS^qoFP)O6#%oz#L7p7NC2PIMu))$L3}xK3^D zv|x!i-!TMMIvn5;Cq@r+5~#j7`{HbWg|O-Ie!o8Rn3@^$^wnQ|Zx&64zt# zNm(x?TR)HxXS4^a-a~Qmjr_rpUdU9pzh^n#0N(|<%mq}$le&ht=$%(7f zJUfkRrx~_aP}XzC%ZYKUN)pmop)lgIvK1Oe+A5ulYN;>B0F-MOjP)0md@uckE0CP) z=x6Hrg$l05nPUd$=dvW+!{6T>m#I=M`>Muj1plmsi%g;RXm!*K>X1YlaAKl` zRr^)OaJQjkbYaics13hCZV<2m=MddSab6=&P#PN`cZt%%W4e;Hqq99%YrLTQ(xR5s zbM%4Gj$Pjy+1(#WJxhW0Sn<`lbz3fn#r1~<#M-kA5p?g0ny*Yvu<<`+=H44%`Kw}T?juJX)s}A;sVX&DF`cqbq?ll2&>-odHGp+8(MRm})AbEnMw1D*( zPrGsc#a#wcA|fd!L(G6wu>2Geub|gDkqI_Sah`?2%~Xy(86<=_G6DOLih)8M-A`^K zl&CKy!?%E-Qr!@yzdxmQhUW047Y1ds(P9!y0G9s#rwhMqVfg{c0=P1*XT!2UtKL!J z{vTJtA%*@)v4pZX%{PhBJ%_8~7YoUKUvUt^d`U%3>k+DE-S+y43=1E@d6$R*i=+xW zjN3|%cOD&lOIe~D3-xPWT8q`6h}J47z8stTxpUDjb|e&RM&#gpj8D1-X`IR;>Oq4V z?(e!*^v^hW>n%d+_{zr!=f?A4BSY32d525IX~$dzkqZJ~ZncdP{hrT;d>_b>f+^k- z%$l!)EmqlJ)@xGn^)Fo~^v!n?pbJO6e7pwTA>};y3g2E2F_r2hv+enO{@^4`+oU!2 z00+_uL}Kd6j1OyXwJg5+~-wO7bN4sYy=469zk}Ri1Wpc96{}rYL?JApsQI< zi8Pyo+DaBW5?=6Z*x7iv9G12!`%n9%O$KeCdlMNmC@vfxlrJoBNRD)lAL3)S8EfEA z$2vFNXXRL43&r87#AD`kjCzCap|>jDRwZZk?a<2#NnLoyRQ51!17sFucaP35 z#5xgDxIa=mo3bR0@|n1)*HoG#Rd1PV)>LyvWj57q=q`m6Vtq1@%ci*L;qAF<|2-BiVn8*+)m5gG{uIh39a12r+e4OcN$ zE|JD3V@#4HdSM(_p~Nrvv%NX@877PwCOrYRi6%%DXo{Q0tcX^1$S*rb?Yxd!rX{j@ zvv;Mc_EzdPD5Z>*^V?VnBo!6~>#(|*_o_PZR?_RfLbOOM;=r(~FJ2JWTcmaOVxp=Q z1J}p3y3+uGK!-|*k#-{OT?wW>vvO4W=UltnQcTqCDvF0!<$=43ALpQSn?GTG&4b~{ zc*d*@8FGzJb0E>vY>)ESJoxuOZ|CmpBoo)}1j~gbiqYhqMoweY2X5i(Z$|a8V$aWu2jMJdh{UG91cYvo^1C z@qH-2)y(zgBH2EC{w(yU?IAXb5;PUEDw&3Oex2h3oi*fW_ng_OWI#4)ocHwX_`@6q zRb(pmld*s&;Dh}OTDZ7@y==kW?CxIHDUb=3FixzY3(E}iU711>-+SC&U)3pj)e2Ok8O&E8h^|+C;id8Y3_BHGK<3?6o5dyfA zn7i_c^DC1dtD^GNXLHQ4swFv44nbl<-a8VQ6@0!x<%HXcQ89p;A`C3<-<HX6& z{^Rv;EdNi1KSB7f^6RIszZCu#i~p(gCyxE4)c%z4|0w+iXaCgt69)d$dISG&TEC&e zKgIr}W52`(5dN2y{aO7dllfI0`^24p+4>KO`F|0be{TA3jsI)Y9K5GZ|9cJmS@&m8 g{i=I~|6i;B=rA=!1jN67^X%!Z_LR~`g1=V(2j3^y*Z=?k literal 0 HcmV?d00001 diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index f7c8f7f0..da5dda00 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -51,7 +51,7 @@ - + PreserveNewest PreserveNewest themes\bundled\%(Filename)%(Extension) From 67ceee53b7de4472a8d7eb6f0e3c7331eeb7d1e4 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 04:06:16 -0700 Subject: [PATCH 18/31] Adds a trust warning and a source column to the themes page --- .../Resources/Views/Admin/Themes.de-DE.resx | 12 +++++++ .../Resources/Views/Admin/Themes.en-US.resx | 12 +++++++ .../Resources/Views/Admin/Themes.es-ES.resx | 12 +++++++ .../Resources/Views/Admin/Themes.fr-FR.resx | 12 +++++++ .../Resources/Views/Admin/Themes.it-IT.resx | 12 +++++++ .../Resources/Views/Admin/Themes.ja-JP.resx | 12 +++++++ .../Core/Resources/Views/Admin/Themes.resx | 12 +++++++ .../Resources/Views/Admin/Themes.ro-RO.resx | 12 +++++++ .../Resources/Views/Admin/Themes.ru-RU.resx | 12 +++++++ .../Resources/Views/Admin/Themes.zh-CN.resx | 12 +++++++ .../Core/Views/Admin/Themes.cshtml | 35 +++++++++++++++++-- .../Core/UoW/LuminaDbContextTests.cs | 3 +- 12 files changed, 154 insertions(+), 4 deletions(-) diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx index 240348fe..646913fe 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx @@ -156,4 +156,16 @@ Vorschau + + Themes sind Inhalte von Drittanbietern und können Code, einschließlich JavaScript, in Ihrem Browser ausführen. Installieren Sie nur Themes aus vertrauenswürdigen Quellen. Die mit der Anwendung gebündelten Themes sind geprüft und sicher. + + + Quelle + + + Gebündelt + + + Benutzer + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx index 4dec7cdb..cdff40e2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx @@ -156,4 +156,16 @@ Preview + + Themes are third-party content and can execute code, including JavaScript, in your browser. Install only themes from sources you trust. The themes bundled with the application are reviewed and safe. + + + Source + + + Bundled + + + User + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx index c51a5803..dbd389c0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx @@ -156,4 +156,16 @@ Vista previa + + Los temas son contenido de terceros y pueden ejecutar código, incluido JavaScript, en su navegador. Instale solo temas de fuentes confiables. Los temas incluidos con la aplicación están revisados y son seguros. + + + Origen + + + Incluido + + + Usuario + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx index 8184f456..86823228 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx @@ -156,4 +156,16 @@ Aperçu + + Les thèmes sont des contenus tiers et peuvent exécuter du code, y compris du JavaScript, dans votre navigateur. N'installez que des thèmes provenant de sources fiables. Les thèmes fournis avec l'application sont vérifiés et sûrs. + + + Source + + + Intégré + + + Utilisateur + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx index 4d90e27b..8bf1478b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx @@ -156,4 +156,16 @@ Anteprima + + I temi sono contenuti di terze parti e possono eseguire codice, incluso JavaScript, nel tuo browser. Installa solo temi da fonti affidabili. I temi inclusi con l'applicazione sono revisionati e sicuri. + + + Origine + + + Incluso + + + Utente + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx index 28c58547..4cf2bc83 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx @@ -156,4 +156,16 @@ プレビュー + + テーマはサードパーティのコンテンツであり、ブラウザでJavaScriptなどのコードを実行する可能性があります。信頼できるソースからのテーマのみをインストールしてください。アプリケーションにバンドルされているテーマは審査済みで安全です。 + + + ソース + + + 同梱 + + + ユーザー + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx index 4dec7cdb..cdff40e2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx @@ -156,4 +156,16 @@ Preview + + Themes are third-party content and can execute code, including JavaScript, in your browser. Install only themes from sources you trust. The themes bundled with the application are reviewed and safe. + + + Source + + + Bundled + + + User + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx index 4a1d5054..502efbd1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx @@ -156,4 +156,16 @@ Previzualizare + + Temele sunt conținut de la terți și pot executa cod, inclusiv JavaScript, în browser. Instalați numai teme din surse de încredere. Temele incluse cu aplicația sunt verificate și sigure. + + + Sursă + + + Încorporat + + + Utilizator + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx index ae50882f..720ec102 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx @@ -156,4 +156,16 @@ Предпросмотр + + Темы являются сторонним содержимым и могут выполнять код, включая JavaScript, в вашем браузере. Устанавливайте только темы из надежных источников. Темы, поставляемые с приложением, проверены и безопасны. + + + Источник + + + Встроенный + + + Пользователь + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx index 36f8c200..3cb35acf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx @@ -156,4 +156,16 @@ 预览 + + 主题是第三方内容,可能在您的浏览器中执行代码(包括 JavaScript)。请只安装来自可信来源的主题。随应用程序附带的主题已经过审查,是安全的。 + + + 来源 + + + 内置 + + + 用户 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml index 4453cb70..6529ff80 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -47,6 +47,27 @@ #themes-table td { vertical-align: middle; } + + .theme-trust-warning { + display: flex; + align-items: flex-start; + gap: 0.5rem; + width: 100%; + padding: 0.5rem 0.75rem; + border: 1px solid #b8860b; + border-radius: 4px; + background-color: rgba(184, 134, 11, 0.15); + color: var(--text-foreground); + font-family: monospace; + font-size: 0.85rem; + } + + .theme-trust-warning-icon { + width: 20px; + height: 20px; + flex-shrink: 0; + margin-top: 1px; + }
    @@ -60,6 +81,12 @@
    +
    +
    + + @_localizer["ThemeTrustWarning"] +
    +
    @if (themes is null || themes.Count == 0) { @@ -71,10 +98,11 @@
    - + - - + + + @@ -91,6 +119,7 @@ + @@ -171,6 +179,16 @@ } } + // restores the soft deleted bundled theme of the clicked row + async function handleRestoreClick(event) { + const button = event.target.closest('.restore-theme-button'); + if (!button) + return; + // an empty JSON body is sent so the antiforgery-protected POST request binds the route theme id without a JsonException + await callApiPostAsync(button.dataset.url, {}); + reloadPage(); + } + // downloads the archive of the theme of the clicked row function handleDownloadClick(event) { const button = event.target.closest('.download-theme-button'); @@ -227,6 +245,7 @@ document.addEventListener('click', handleActivateClick); document.addEventListener('click', handleDownloadClick); document.addEventListener('click', handleDeleteClick); + document.addEventListener('click', handleRestoreClick); document.addEventListener('click', handlePreviewClick); // register cleanup for these listeners @@ -236,6 +255,7 @@ document.removeEventListener('click', handleActivateClick); document.removeEventListener('click', handleDownloadClick); document.removeEventListener('click', handleDeleteClick); + document.removeEventListener('click', handleRestoreClick); document.removeEventListener('click', handlePreviewClick); }); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs new file mode 100644 index 00000000..5df2db9c --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme to restore. + /// The created . + public RestoreThemeCommand Create(string? themeId = null) + { + return new RestoreThemeCommand(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs new file mode 100644 index 00000000..74c725ca --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme to restore. + /// The created . + public RestoreThemeRequest Create(string? themeId = null) + { + return new RestoreThemeRequest(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs index c0c03b0d..780ed917 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs @@ -33,6 +33,7 @@ public class ThemeResponseFixture /// Optional. Whether the theme is the currently active one. /// Whether to set , or when . /// Optional. The UTC timestamp when the theme was installed. + /// Optional. Whether the theme was deleted by the user. /// The created . public ThemeResponse Create( Guid? id = null, @@ -46,7 +47,8 @@ public class ThemeResponseFixture ThemeInstallSource? installSource = null, bool? isCurrent = null, bool includeIsCurrent = false, - DateTime? installedAtUtc = null) + DateTime? installedAtUtc = null, + bool? isDeleted = null) { return new ThemeResponse( id ?? Guid.NewGuid(), @@ -58,7 +60,8 @@ public class ThemeResponseFixture includePreviewPath ? (previewPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)) : null, installSource ?? _faker.PickRandom(), includeIsCurrent ? (isCurrent ?? (_faker.Random.Bool() ? true : null)) : null, - installedAtUtc ?? _faker.Date.Recent().ToUniversalTime()); + installedAtUtc ?? _faker.Date.Recent().ToUniversalTime(), + isDeleted ?? _faker.Random.Bool()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs index a7f32034..7fa24e10 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs @@ -25,6 +25,7 @@ public class ThemeInfoDtoFixture /// Optional semantic version of the theme. /// Optional URL of the theme preview image. /// Whether the theme ships with the application. + /// Whether the theme was deleted by the user. /// A configured instance. public ThemeInfoDto Create( string? id = null, @@ -33,7 +34,8 @@ public class ThemeInfoDtoFixture string? author = null, string? version = null, string? previewUrl = null, - bool? isBundled = null) + bool? isBundled = null, + bool? isDeleted = null) { Faker faker = new(); return new ThemeInfoDto( @@ -43,7 +45,8 @@ public class ThemeInfoDtoFixture Author: author ?? faker.Name.FullName(), Version: version ?? faker.System.Semver(), PreviewUrl: previewUrl ?? $"/theme-assets/{faker.Lorem.Word()}/preview.png", - IsBundled: isBundled ?? faker.Random.Bool() + IsBundled: isBundled ?? faker.Random.Bool(), + IsDeleted: isDeleted ?? faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs index 9abbbf15..ab1803a5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs @@ -31,6 +31,7 @@ public class ThemeResponseDtoFixture /// Optional value indicating whether the theme is the active one. /// Whether to set , or when . /// Optional UTC timestamp at which the theme was installed. + /// Optional value indicating whether the theme was deleted by the user. /// A configured instance. public ThemeResponseDto Create( Guid? id = null, @@ -44,7 +45,8 @@ public class ThemeResponseDtoFixture ThemeInstallSource? installSource = null, bool? isCurrent = null, bool includeIsCurrent = false, - DateTime? installedAtUtc = null) + DateTime? installedAtUtc = null, + bool? isDeleted = null) { Faker faker = new(); return new ThemeResponseDto( @@ -57,7 +59,8 @@ public class ThemeResponseDtoFixture PreviewPath: includePreviewPath ? (previewPath ?? (faker.Random.Bool() ? faker.System.FilePath() : null)) : null, InstallSource: installSource ?? ThemeInstallSource.Uploaded, IsCurrent: includeIsCurrent ? (isCurrent ?? (faker.Random.Bool() ? true : null)) : null, - InstalledAtUtc: installedAtUtc ?? faker.Date.Recent() + InstalledAtUtc: installedAtUtc ?? faker.Date.Recent(), + IsDeleted: isDeleted ?? faker.Random.Bool() ); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..c62ba506 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,231 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithDeletedBundledTheme_ShouldRestoreTheme() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper"); + Assert.NotNull(theme); + theme!.IsDeleted = true; + theme.IsCurrent = null; + await dbContext.SaveChangesAsync(); + } + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + + // the theme is available again and appears in the list + using IServiceScope verificationScope = _apiFactory.Services.CreateScope(); + LuminaDbContext verificationContext = verificationScope.ServiceProvider.GetRequiredService(); + ThemeEntity? restoredTheme = await verificationContext.Themes.FirstOrDefaultAsync(candidate => candidate.ThemeId == "editorial-paper"); + Assert.NotNull(restoredTheme); + Assert.False(restoredTheme!.IsDeleted); + + HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes"); + List? themes = await listResponse.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(themes); + Assert.Contains(themes!, theme => theme.ThemeId == "editorial-paper" && !theme.IsDeleted); + } + + [Fact] + public async Task RestoreTheme_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + string themeId = "nonexistent-theme"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/themes/{themeId}/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/restore", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task RestoreTheme_WhenThemeIsNotDeleted_ShouldReturnForbiddenResult() + { + // Arrange + string themeId = await InstallUserThemeAsync(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/themes/{themeId}/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("ThemeCannotBeRestored", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/restore", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync(); + + // Act + HttpResponseMessage response = await nonAdminClient.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/editorial-paper/restore", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.PostAsJsonAsync("/api/v1/themes/editorial-paper/restore", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Installs a test theme through the API and returns its manifest id. + /// + /// The manifest id of the installed theme. + private async Task InstallUserThemeAsync() + { + string themeId = $"test-theme-{Guid.NewGuid():N}"; + byte[] archiveBytes = _themeArchiveFixture.Create(themeId); + + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + response.EnsureSuccessStatusCode(); + + _installedThemeIds.Add(themeId); + return themeId; + } + + /// + /// Removes any test theme installed by a failed test and clears the authorization seed data of the admin test user. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + foreach (string themeId in _installedThemeIds) + { + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == themeId); + if (theme is not null) + dbContext.Themes.Remove(theme); + } + + await dbContext.SaveChangesAsync(); + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + foreach (string themeId in _installedThemeIds) + await themeService.DeleteAsync(themeId, CancellationToken.None); + + // the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..8cf6dff8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,193 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Contains security tests for the POST /api/v1/themes/{themeId}/restore route. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly string _themeId; + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RestoreThemeEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + _themeId = $"testtheme{Guid.NewGuid():N}"; + } + + [Fact] + public async Task RestoreTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/themes/{Guid.NewGuid():N}/restore"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { }); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task RestoreTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateUserAsync(client); + string url = $"/api/v1/themes/{Guid.NewGuid():N}/restore"; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync(url, new { }); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task RestoreTheme_WhenThemeIsNotDeleted_ShouldReturnForbiddenResultWithoutReactivatingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedThemeAsync(isDeleted: false); + string url = $"/api/v1/themes/{_themeId}/restore"; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync(url, new { }); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("ThemeCannotBeRestored", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task RestoreTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + string url = $"/api/v1/themes/{maliciousThemeId}/restore"; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync(url, new { }); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem + if (!string.IsNullOrWhiteSpace(content)) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + } + } + + /// + /// Seeds a with the unique test theme id. + /// + /// Whether the seeded theme is marked as deleted. + /// A task representing the asynchronous operation. + private async Task SeedThemeAsync(bool isDeleted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: isDeleted)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Removes the seeded theme. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId); + if (theme is not null) + { + dbContext.Themes.Remove(theme); + dbContext.SaveChanges(); + } + + _client.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs new file mode 100644 index 00000000..df9b6e8c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeRequestMappingTests +{ + private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingRequest_ShouldMapThemeId() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(themeId: "editorial-paper"); + + // Act + RestoreThemeCommand command = request.ToCommand(); + + // Assert + Assert.NotNull(command); + Assert.Equal(request.ThemeId, command.ThemeId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs index 17f390ee..4b9cf5b3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs @@ -48,6 +48,7 @@ public class ThemeEntityMappingTests Assert.Equal(theme.InstallSource, result.InstallSource); Assert.Equal(theme.IsCurrent, result.IsCurrent); Assert.Equal(theme.InstalledAtUtc, result.InstalledAtUtc); + Assert.Equal(theme.IsDeleted, result.IsDeleted); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs new file mode 100644 index 00000000..0a3ffd43 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +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.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly RestoreThemeCommandHandler _sut; + private readonly RestoreThemeCommandFixture _restoreThemeCommandFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockThemeService.RestoreBundledThemeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + _sut = new RestoreThemeCommandHandler( + _mockUnitOfWork, + _mockThemeService, + _mockCurrentUserService, + _mockAuthorizationService, + _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsNotDeleted_ShouldReturnThemeCannotBeRestoredError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeCannotBeRestored, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsDeletedButNotBundled_ShouldReturnThemeCannotBeRestoredError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeCannotBeRestored, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenFileRestorationFails_ShouldReturnErrorWithoutReactivatingTheme() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: true); + Error error = Error.Failure("Theme.FilesUnreadable", "Failed to restore theme files"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoringDeletedBundledTheme_ShouldRestoreFilesAndReactivateTheme() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && !entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs new file mode 100644 index 00000000..98383d69 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeCommandValidatorTests +{ + private readonly RestoreThemeCommandValidator _validator = new(); + private readonly RestoreThemeCommandFixture _restoreThemeCommandFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + command = command with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveValidationErrors() + { + // Arrange + RestoreThemeCommand command = _restoreThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs index 3066d68c..a6e2b80c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs @@ -41,7 +41,7 @@ public class GetThemesQueryHandlerTests } [Fact] - public async Task HandleAsync_WhenCalled_ShouldReturnAllAvailableThemesOrderedBundledFirstThenByName() + public async Task HandleAsync_WhenCalled_ShouldReturnAllThemesOrderedAvailableBundledFirstThenByNameWithDeletedLast() { // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); @@ -57,13 +57,15 @@ public class GetThemesQueryHandlerTests // Assert Assert.False(result.IsFailure); - Assert.Equal(3, result.Value.Count); + Assert.Equal(4, result.Value.Count); Assert.Equal(bundledLowerTheme.Id, result.Value[0].Id); Assert.Equal(bundledUpperTheme.Id, result.Value[1].Id); Assert.Equal(uploadedTheme.Id, result.Value[2].Id); + Assert.Equal(deletedTheme.Id, result.Value[3].Id); Assert.Equal(ThemeInstallSource.Bundled, result.Value[0].InstallSource); Assert.Equal(ThemeInstallSource.Bundled, result.Value[1].InstallSource); Assert.Equal(ThemeInstallSource.Uploaded, result.Value[2].InstallSource); + Assert.True(result.Value[3].IsDeleted); } [Fact] diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..cc96569a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,202 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.RestoreTheme; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly RestoreThemeEndpoint _sut; + private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContentResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsForbiddenError_ShouldReturnProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeCannotBeRestored; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Forbidden", problemDetailsBody.Title); + Assert.Equal("ThemeCannotBeRestored", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRestoreThemeCommandToHandler() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..96d7f0f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RestoreThemeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldRestoreThemeAndReturnSuccessJson() + { + // Arrange + string themeId = "editorial-paper"; + + // Act + IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body)) + { + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldRestoreThemeWithResolvedEndpoint() + { + // Arrange + string themeId = "editorial-paper"; + string expectedEndpoint = ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId); + + // Act + await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync(expectedEndpoint, Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData(null)] // missing theme id + [InlineData("")] // empty theme id + [InlineData(" ")] // whitespace theme id + public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) + { + // Act + IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().PostAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} From 6cd5e1d6d956c184e2bb3d32b32fdd7822337692 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 11:48:18 -0700 Subject: [PATCH 30/31] Keeps media playback running when the themes page is refreshed --- .../Core/Views/Admin/Themes.cshtml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml index 7d2756f8..1b8b1586 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -159,6 +159,11 @@ window.location.reload(); } + // refreshes the current page content without reloading the page, so the media player keeps playing + function refreshPageContent() { + updateContentAsync(window.location.href, false); + } + // activates the theme of the clicked row async function handleActivateClick(event) { const button = event.target.closest('.activate-theme-button'); @@ -175,7 +180,7 @@ return; if (await dialogService.show('@_localizer["DeleteThemeConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) { await callApiDeleteAsync(button.dataset.url); - reloadPage(); + refreshPageContent(); } } @@ -186,7 +191,7 @@ return; // an empty JSON body is sent so the antiforgery-protected POST request binds the route theme id without a JsonException await callApiPostAsync(button.dataset.url, {}); - reloadPage(); + refreshPageContent(); } // downloads the archive of the theme of the clicked row @@ -229,7 +234,7 @@ body: formData }); if (response.ok) - reloadPage(); + refreshPageContent(); else notificationService.show('@_localizer["UploadFailed"]', NotificationType.ERROR); } From 8e2123c2c54ad225f0593570383f84b133ba4615 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 11:48:30 -0700 Subject: [PATCH 31/31] Adds the theme authoring documentation --- docs/technical/theming/Theming.md | 334 ++++++++++++++++++++++++++++++ src/Lumina.sln | 6 + 2 files changed, 340 insertions(+) create mode 100644 docs/technical/theming/Theming.md diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md new file mode 100644 index 00000000..3a206beb --- /dev/null +++ b/docs/technical/theming/Theming.md @@ -0,0 +1,334 @@ +# Lumina Theming + +The web client of Lumina is a themed shell: every page is rendered inside the templates of an active theme. A theme is a self contained ZIP archive with a manifest, HTML templates and static assets. This document explains how themes are structured, how the template engine works, and how to create, install and manage a theme. + +- [Lumina Theming](#lumina-theming) + - [Overview](#overview) + - [Theme Pack Structure](#theme-pack-structure) + - [The Manifest (theme.json)](#the-manifest-themejson) + - [Pack Validation Rules](#pack-validation-rules) + - [Templates](#templates) + - [Template Syntax](#template-syntax) + - [Expressions](#expressions) + - [Safety Limits](#safety-limits) + - [Template Resolution](#template-resolution) + - [The Layout Template (shared/layout)](#the-layout-template-sharedlayout) + - [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu) + - [Page Templates](#page-templates) + - [The Scripts Section](#the-scripts-section) + - [Assets](#assets) + - [Configuration Options](#configuration-options) + - [Creating a Theme](#creating-a-theme) + - [Installing a Theme](#installing-a-theme) + - [Bundled Themes](#bundled-themes) + - [Selecting the Current Theme](#selecting-the-current-theme) + - [Managing Themes from the Administration Page](#managing-themes-from-the-administration-page) + - [Security Notes](#security-notes) + +## Overview + +The application stores installed themes on the API server and serves their templates and assets. The web client fetches the templates of the active theme and renders them locally with a small, non-executable Mustache-style template engine. Theme templates can interpolate values, iterate collections and test truthiness, but they cannot run code. + +Because the templates are HTML, a theme can restyle the whole application, rearrange the layout and navigation, and provide custom pages for the built-in routes. A theme cannot extend the functionality of the application: it only shapes how the existing pages look and are structured. + +## Theme Pack Structure + +A theme pack is a directory that is shipped as a ZIP archive with `theme.json` at its root: + +``` +my-theme/ + theme.json + assets/ + preview.svg + theme.css + templates/ + index.html + shared/ + layout.html + nav-menu.html + not-found.html + library/ + written-content-library/ + book-library/ + books/ + index.html +``` + +Only three locations may exist inside a pack: + +- `theme.json`, the manifest, at the root of the archive. +- `templates/`, holding the HTML templates. +- `assets/`, holding any static file served to the browser (stylesheets, images, fonts, scripts). + +The bundled reference theme `editorial-paper` follows exactly this layout and is the best starting point when authoring a new theme. + +## The Manifest (theme.json) + +The manifest is a JSON object describing the theme. The example below is the manifest of the bundled `editorial-paper` theme: + +```json +{ + "schemaVersion": 1, + "id": "editorial-paper", + "name": "Editorial Paper", + "description": "A clean, readable proof of concept theme.", + "author": "Lumina", + "version": "1.4.0", + "preview": "assets/preview.svg", + "templates": { + "default": "templates/index.html" + } +} +``` + +| Field | Required | Rule | +| --- | --- | --- | +| `schemaVersion` | yes | Must be `1`. | +| `id` | yes | A lowercase kebab-case value, up to 64 characters, used to reference the theme. For example `editorial-paper` or `my-dark-theme`. | +| `name` | yes | Display name, up to 80 characters. | +| `description` | yes | Description of the theme, up to 300 characters. | +| `author` | yes | Author of the theme, up to 80 characters. | +| `version` | yes | Semantic version form, for example `1.0.0`. Up to 40 characters. | +| `preview` | no | Path to a preview image, relative to the pack root and under `assets/`. Shown on the administration page. | +| `templates` | yes | A mapping from template key to a file under `templates/`, with 1 to 32 entries. Must include the `default` key. | + +All text fields must be non-empty and must not contain control characters. Template keys follow the same lowercase kebab-case rule as the theme id and are at most 40 characters. Template paths are normalized and must point to an existing file under `templates/`. + +## Pack Validation Rules + +A theme archive is validated on install: + +- `theme.json` must exist at the root of the archive and be at most 64 KB. +- Only `theme.json`, files under `templates/` and files under `assets/` are allowed. Anything else makes the archive invalid. +- Paths are normalized and any path that would escape the pack is rejected. +- `theme.json` must contain a valid manifest object that satisfies the rules in the previous section. + +Installing a theme is an atomic operation: an invalid pack is rejected entirely and nothing is left behind. + +## Templates + +Templates are rendered with the built-in template engine. The engine is intentionally small and safe: it parses Mustache-style tags and renders them against a model. It never executes arbitrary code. + +### Template Syntax + +| Syntax | Meaning | +| --- | --- | +| `{{name}}` | Outputs the value of `name`, HTML-escaped. | +| `{{{name}}}` | Outputs the value of `name` without escaping. | +| `{{&name}}` | Outputs the value of `name` without escaping. | +| `{{!comment}}` | A comment, produces no output. | +| `{{#name}}...{{/name}}` | A section. Renders its children when the value is truthy. When the value is a collection, the children are rendered once per item. | +| `{{^name}}...{{/name}}` | An inverted section. Renders its children when the value is falsy. | + +### Expressions + +Expressions resolve against the model and support: + +- Dotted property paths, for example `{{user.name}}`. Dictionary keys and public properties are matched case-insensitively. +- Parent traversal, for example `{{../title}}`, to reach values outside the current section scope. +- The current value, for example `{{.}}`. +- `{{#count}}` on a collection, where `Count` is exposed for collections. + +Values that do not exist resolve to an empty string for variables, or to falsy for sections. Truthiness follows these rules: `null`, `false`, empty strings and empty collections are falsy; everything else is truthy. + +### Safety Limits + +The template engine enforces hard limits so a single theme cannot exhaust the server: + +| Limit | Value | +| --- | --- | +| Maximum section nesting depth | 32 levels | +| Maximum expression length | 120 characters | +| Maximum rendered output | 4 MB per page | + +A template that exceeds any of these limits is rejected with a template error and the page falls back to the application layout. + +### Template Resolution + +Every themed page is identified by a page key that mirrors the path of the corresponding Razor view. When a page is rendered, its template is selected in this order: + +1. An explicit mapping in `templates` when the manifest declares the page key. +2. A mirrored template file at `templates/{pageKey}.html`, walking up the scope of the path when the exact mirror does not exist. +3. The `default` template from the manifest. + +For example, the books index page has the page key `library/written-content-library/book-library/books/index`. The engine tries, in order: the explicit `templates` entry for that key, `templates/library/written-content-library/book-library/books/index.html`, then the parent scopes such as `templates/library/written-content-library/book-library/books.html`, and finally the `default` template. + +Known page keys: + +| Page key | Purpose | +| --- | --- | +| `shared/layout` | The layout that wraps the shell of every page. | +| `shared/nav-menu` | The navigation menu of the theme. | +| `shared/not-found` | The 404 page. | +| `library/written-content-library/book-library/books/index` | The books browsing page. | + +### The Layout Template (shared/layout) + +Every page is rendered inside the layout template. The layout receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `title` | The title of the page. | +| `assetBase` | The base URL of the theme assets, for example `/theme-assets/editorial-paper/assets`. | +| `appHead` | The head links of the application, such as its global stylesheets. | +| `nav` | The fully rendered navigation menu HTML. | +| `content` | The fully rendered content section of the page. | +| `audioPlayer` | The rendered audio player when the user is authenticated, empty otherwise. | +| `appScripts` | The global scripts of the application. | +| `scripts` | The rendered script section of the page. | +| `mainStyle` | An inline style for the main content area, `bottom: 0px;` when the user is not authenticated and empty otherwise. | + +The layout template of the bundled theme shows the intended shape: + +```html + + + + + + {{title}} - Lumina + {{&appHead}} + + + +
    +
    + {{&nav}} +
    +
    +
    + {{&content}} +
    +
    +
    +
    + {{#audioPlayer}} + {{&audioPlayer}} + {{/audioPlayer}} +
    + + {{&appScripts}} +
    + {{&scripts}} +
    + + +``` + +The rendered page content, navigation and scripts are inserted unescaped with `{{&...}}`, because they are trusted application HTML. The layout is best effort: when the theme cannot be loaded or rendered, the application falls back to its built-in layout, so a broken theme never takes the whole site down. + +### The Navigation Template (shared/nav-menu) + +The navigation template renders the menu of the active theme. Its model contains the site name and two menu structures, one for the mobile menu and one for the desktop menu bar: + +- `siteName` is the site name. +- `mobileSections` and `menubarSections` are lists of sections. +- A section has a `label` and a list of `items`. +- An item has a `label`, an optional `url`, an optional `cssClass` and a list of `children`. Items with children are submenus, items without children are plain links. + +The navigation template is also best effort: when its template cannot be rendered, the application menu is used instead. + +### Page Templates + +The remaining templates render individual pages. Each page exposes its own data, so the available fields depend on the page. In addition to page specific values, pages expose a `strings` dictionary with the localized strings of the page, keyed by their resource names, so templates can pull any label without hardcoding text. + +Page templates are rendered into a content section that the layout wraps. A page template can also declare a reserved top-level `scripts` section, whose content is rendered separately and passed to the layout, mirroring the `Scripts` section of a Razor view: + +```html +{{#title}} +

    {{title}}

    +{{/title}} + +{{^title}} +

    No title available.

    +{{/title}} + +{{#sections}} +
    +

    {{label}}

    +
    +{{/sections}} + +{{#scripts}} + +{{/scripts}} +``` + +### The Scripts Section + +JavaScript is always allowed in themes: script elements in templates are served and rendered as-is, and script files under `assets/` are served normally. A theme relies on scripts for the client side navigation of the application, because pages are swapped in place by the global AJAX navigator, so themes are expected to ship their own JavaScript. Because JavaScript is enabled, *themes can execute malicious code*, so, be aware about the source of your installed themes! Themes bundled with the application are reviewed and safe. + +## Assets + +Static files under `assets/` are served to the browser. The asset base URL is available to the layout and page templates as `assetBase`, so a stylesheet is referenced as `{{assetBase}}/theme.css`. Assets are served only from within the pack, and paths that would escape the pack are rejected. + +The `preview` field of the manifest points at an asset that is shown as the theme thumbnail on the administration page. + +## Configuration Options + +The theme engine is configured through the `ThemeEngine` section of the API configuration (`appsettings.shared.json`): + +| Option | Default | Meaning | +| --- | --- | --- | +| `StoragePath` | `themes` | Directory where installed theme packs are stored, relative to the API base directory when not rooted. | +| `BundledThemesPath` | `themes/bundled` | Directory where the theme archives shipped with the application are located. | +| `DefaultThemeId` | `lumina-default` | Identifier of the theme selected when no valid current theme is persisted. | +| `MaxArchiveBytes` | `8388608` | Maximum size of an uploaded theme archive, in bytes (8 MB). | +| `MaxExpandedBytes` | `25165824` | Maximum total size of an extracted theme pack, in bytes (24 MB). | +| `MaxSingleFileBytes` | `6291456` | Maximum size of a single file within a theme pack, in bytes (6 MB). | +| `MaxEntries` | `250` | Maximum number of entries in a theme pack archive. | + +## Creating a Theme + +1. Create a directory for the theme with `theme.json`, a `templates/` directory and an `assets/` directory, following the layout of `editorial-paper`. +2. Write the manifest following the field rules in [The Manifest (theme.json)](#the-manifest-themejson). +3. Author the templates. Start with `templates/shared/layout.html` and `templates/shared/nav-menu.html`, then add page templates and the `default` template. +4. Add the static files under `assets/`, for example a stylesheet referenced from the layout. +5. Keep the pack within the size limits: the archive at most 8 MB, the extracted pack at most 24 MB, no single file larger than 6 MB and at most 250 entries. +6. Compress the directory into a ZIP archive with `theme.json` at the root of the archive, not nested inside an extra folder. + +## Installing a Theme + +A theme is installed by uploading its ZIP archive: + +- From the administration themes page, using the upload control. +- Directly against the API with a `multipart/form-data` POST to `POST /api/v1/themes`, sending the archive in a form field named `archive`. + +The archive is validated against the pack rules and stored on the server under `themes/{id}`. Installing a theme with an id that already exists replaces the files of the existing theme. A newly installed theme is not active until it is selected as the current theme. + +Validation failures are returned as problem details, for example when the archive is unreadable, the manifest is invalid, or a template references a missing file. + +## Bundled Themes + +The archives shipped with the application live in the API under `Core/Themes/Bundled` and are installed automatically at startup by the theme detection job. `editorial-paper` is the bundled reference theme. + +A bundled theme whose files go missing or are corrupted is restored automatically from its shipped archive on the next startup, unless the user explicitly deleted the theme from the Administrator - Themes page. This means bundled themes always come back unless the user removes them. The last available theme cannot be deleted. + +## Selecting the Current Theme + +The current theme is the one whose templates are used for page rendering. At startup, when no theme is current, the application activates one automatically, preferring the configured default theme id. The active theme is exposed at `GET /api/v1/themes/current` and can be changed from the administration page, which calls `PUT /api/v1/themes/current`. + +## Managing Themes from the Administration Page + +The administration themes page lists every installed theme and provides: + +- A preview thumbnail for each theme, taken from the `preview` field of the manifest. +- The source of the theme, either bundled with the application or provided by a user. +- The ability to set the current theme, download a theme as a ZIP archive and install a new theme. +- The ability to delete a theme, subject to these rules: + - Only administrators can delete themes. + - The last remaining bundled theme cannot be deleted, so the application never ends up without a theme. + - When the active theme is deleted, another available theme is activated automatically, preferring the configured default. + - Bundled themes are soft deleted (the theme files are deleted, but the theme zip archive is kept), so they can be restored; user themes are removed entirely, because their files are not shipped with the application. + +## Security Notes + +Theme packs are treated as untrusted input: + +- Values rendered with `{{name}}` are HTML-encoded, so a theme cannot inject markup through a model value. +- Themes can contain javascript, which means, they can run malicious code. Only install themes from sources you trust, or review the code of the theme files. +- Paths are normalized and validated so that templates and assets cannot escape the theme pack or the storage directory. +- The template engine has no access to the application and cannot execute code, only render values against the model. +- Size and count limits prevent an archive from exhausting server memory or disk. diff --git a/src/Lumina.sln b/src/Lumina.sln index 4b86d8cb..678d100f 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -246,6 +246,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.TestPlugin", "..\tests\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj", "{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "theming", "theming", "{2872042D-061F-4C76-8017-0A518A7E28A7}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\theming\Theming.md = ..\docs\technical\theming\Theming.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -736,6 +741,7 @@ Global {FEC00EBD-6A64-4280-B0F7-1EC5321C294A} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} {16F65859-93AB-499F-A0BE-9EC05E20435F} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {65AA7896-2DE2-4F07-A1B2-C1E1774521C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {2872042D-061F-4C76-8017-0A518A7E28A7} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E}
    @_localizer["Name"]@_localizer["Preview"]@_localizer["Name"] @_localizer["Version"] @_localizer["Author"]@_localizer["Actions"]@_localizer["Actions"]
    + + @theme.Name @theme.Version @theme.Author - - - + +
    + + + +
    @_localizer["Preview"]@_localizer["Name"]@_localizer["Name"] @_localizer["Version"]@_localizer["Author"]@_localizer["Actions"]@_localizer["Author"]@_localizer["Source"]@_localizer["Actions"]
    @theme.Name @theme.Version @theme.Author@(theme.IsBundled ? _localizer["Bundled"] : _localizer["UserProvided"])
    diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs index aa080525..fe5586a3 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs @@ -46,7 +46,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(23, tableNames.Length); + Assert.Equal(24, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -70,6 +70,7 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("BookGenres", tableNames); Assert.Contains("BookRatings", tableNames); Assert.Contains("BookISBNs", tableNames); + Assert.Contains("Themes", tableNames); } [Fact] From a7e722321c39232df4709aec13bd4014d4715f47 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:42:13 -0700 Subject: [PATCH 19/31] Serializes theme storage mutations across hosts sharing the storage directory --- .../Core/Themes/ThemeService.cs | 50 ++++++++++++++++--- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index 7af797f9..aa90d83e 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -7,6 +7,7 @@ using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.IO.Compression; @@ -61,8 +62,14 @@ public sealed class ThemeService : IThemeService private readonly string _storageRoot; private readonly string _stagingRoot; private readonly string _bundledRoot; - // serializes theme pack mutations, so concurrent installs and deletes cannot race on the same files - private readonly SemaphoreSlim _mutationGate = new(1, 1); + // serializes theme pack mutations, so concurrent installs and deletes cannot race on the same files; the gate is + // shared by every instance that writes to the same storage root, because several hosts can run against the same + // storage directory at once (for example the parallel in-memory hosts started by the test factories). A per-instance + // gate is NOT enough: concurrent hosts raced on the shared staging cleanup and one host's directory move failed with + // an access denied exception, which crashed that host and disposed its service provider. Keep the gate keyed on the + // resolved storage root. + private static readonly ConcurrentDictionary s_storageGates = new(StringComparer.Ordinal); + private readonly SemaphoreSlim _mutationGate; /// /// Initializes a new instance of the class. @@ -77,6 +84,7 @@ public sealed class ThemeService : IThemeService _storageRoot = ResolvePath(basePath, _options.StoragePath); _stagingRoot = Path.Combine(_storageRoot, ".staging"); _bundledRoot = ResolvePath(basePath, _options.BundledThemesPath); + _mutationGate = s_storageGates.GetOrAdd(_storageRoot, static _ => new SemaphoreSlim(1, 1)); } /// @@ -153,10 +161,7 @@ public sealed class ThemeService : IThemeService // 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); + await SwapIntoDestinationAsync(extractionPath, destination, cancellationToken); return manifestResult.Value; } catch (InvalidDataException exception) @@ -818,6 +823,39 @@ public sealed class ThemeService : IThemeService } } + /// + /// Moves an extracted theme pack into the storage directory, replacing an existing pack with the same manifest id. + /// + /// + /// The move is retried on transient file system errors, because a concurrent process may briefly hold a file of the + /// destination directory open (for example another host serving a template while this installation replaces the pack). + /// Without the retry, that transient contention aborts the install and, when triggered by the startup job, crashes the + /// whole host. + /// + /// The directory of the extracted theme pack in the staging area. + /// The storage directory the theme pack is moved to. + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + private static async Task SwapIntoDestinationAsync(string extractionPath, string destination, CancellationToken cancellationToken) + { + const int maxAttempts = 10; + for (int attempt = 1; ; attempt++) + { + try + { + if (Directory.Exists(destination)) + Directory.Delete(destination, recursive: true); + + Directory.Move(extractionPath, destination); + return; + } + catch (IOException) when (attempt < maxAttempts) + { + await Task.Delay(100 * attempt, cancellationToken); + } + } + } + /// /// Resolves a configured path to an absolute path, rooted against the base directory when relative. /// From a09876525beeeb9a176116b921843184df013d62 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:42:20 -0700 Subject: [PATCH 20/31] Prevents the theme detection job from crashing the host on file system errors --- .../Core/Themes/ThemeDetectionSyncJob.cs | 66 +++++++++++-------- 1 file changed, 40 insertions(+), 26 deletions(-) diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index 9bdd21e5..35feb9c3 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -72,35 +72,49 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService if (knownThemeIds.Contains(manifestResult.Value.Id)) continue; - await using FileStream archive = File.OpenRead(archivePath); - Result installResult = await _themeService.InstallAsync(archive, stoppingToken); - if (installResult.IsFailure) + // installing a bundled theme at startup is best effort: a file system failure here must never crash the host, + // because the default BackgroundServiceExceptionBehavior (StopHost) shuts down the whole application and + // disposes its service provider, making every later request fail + try { - _logger.LogWarning("Failed to install bundled theme '{ThemeId}': {Error}", manifestResult.Value.Id, installResult.FirstError.Description); - continue; + await using FileStream archive = File.OpenRead(archivePath); + Result 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 insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken); + if (insertResult.IsFailure) + _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); + else + themes.Add(themeEntity); } - - ThemeEntity themeEntity = new() + catch (IOException exception) { - 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 insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken); - if (insertResult.IsFailure) - _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); - else - themes.Add(themeEntity); + _logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': the theme files could not be written.", manifestResult.Value.Id); + } + catch (UnauthorizedAccessException exception) + { + _logger.LogWarning(exception, "Failed to install bundled theme '{ThemeId}': access to the theme files was denied.", manifestResult.Value.Id); + } } await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken); From 170b3a09172cb94cb8e4bd27709a9808c41b2546 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:42:30 -0700 Subject: [PATCH 21/31] Falls back to the application layout when the active theme cannot be loaded --- .../Core/Themes/ThemeLayoutRenderer.cs | 57 ++++++++++++------- .../Core/Themes/ThemePageRenderer.cs | 27 +++++++-- 2 files changed, 57 insertions(+), 27 deletions(-) diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs index 65a7ca79..69540cac 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs @@ -2,6 +2,7 @@ using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Primitives; using Microsoft.AspNetCore.Http; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -49,31 +50,45 @@ public class ThemeLayoutRenderer /// An containing either the full page HTML, or an error. public virtual async Task> RenderAsync(ThemeLayoutPageDto page, string? requestedThemeId = null, CancellationToken cancellationToken = default) { - ThemeRenderDocumentDto layoutDocument = await _themeService.GetRenderDocumentAsync(LAYOUT_PAGE_KEY, requestedThemeId, cancellationToken); - string themeId = layoutDocument.Theme.Id; - bool isAuthenticated = _httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated == true; + try + { + ThemeRenderDocumentDto layoutDocument = await _themeService.GetRenderDocumentAsync(LAYOUT_PAGE_KEY, requestedThemeId, cancellationToken); + string themeId = layoutDocument.Theme.Id; + bool isAuthenticated = _httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated == true; - string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken); - string nav = await RenderNavAsync(themeId, cancellationToken); - string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty; - string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken); + string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken); + string nav = await RenderNavAsync(themeId, cancellationToken); + string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty; + string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken); - ThemeLayoutModelDto layoutModel = new( - page.Title, - $"/theme-assets/{themeId}/assets", - appHead, - nav, - page.Content, - audioPlayer, - appScripts, - page.Script, - isAuthenticated ? string.Empty : "bottom: 0px;"); + ThemeLayoutModelDto layoutModel = new( + page.Title, + $"/theme-assets/{themeId}/assets", + appHead, + nav, + page.Content, + audioPlayer, + appScripts, + page.Script, + isAuthenticated ? string.Empty : "bottom: 0px;"); - Result renderResult = _templateEngine.RenderPage(layoutDocument.Template, layoutModel); - if (renderResult.IsFailure) - return renderResult.Errors; + Result renderResult = _templateEngine.RenderPage(layoutDocument.Template, layoutModel); + if (renderResult.IsFailure) + return renderResult.Errors; - return renderResult.Value.Content; + return renderResult.Value.Content; + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // the themed shell is best effort: when the active theme cannot be loaded, the application layout renders the + // page instead. The exception must not propagate, otherwise the exception handling middleware turns the page + // into a JSON error instead of the fallback layout, so any page breaks whenever the theme API is unavailable. + return Error.NotFound(code: "Theme.Template.Unavailable", description: "The active theme could not be loaded."); + } } /// diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs index bbcc3f8b..2dc72ac6 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs @@ -2,6 +2,7 @@ using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Services; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -36,13 +37,27 @@ public class ThemePageRenderer /// An containing either the rendered page, or an error. public virtual async Task> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default) { - ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken); + try + { + ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken); - model.ThemeId = document.Theme.Id; - model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets"; - // a fresh script id per render lets the AJAX navigator unload this view's script when navigating away - model.ScriptId = ScriptIdentifierHelper.GenerateScriptId(); + model.ThemeId = document.Theme.Id; + model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets"; + // a fresh script id per render lets the AJAX navigator unload this view's script when navigating away + model.ScriptId = ScriptIdentifierHelper.GenerateScriptId(); - return _templateEngine.RenderPage(document.Template, model); + return _templateEngine.RenderPage(document.Template, model); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + // themed rendering is best effort: when the active theme cannot be loaded, the caller falls back to the Razor + // view. The exception must not propagate, otherwise the exception handling middleware turns the page into a + // JSON error instead of the Razor fallback, so any themed page breaks whenever the theme API is unavailable. + return Error.NotFound(code: "Theme.Template.Unavailable", description: "The active theme could not be loaded."); + } } } From 1d85ff8ed934c46b08b2ea0d0d9fdc5cde64ec65 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:42:37 -0700 Subject: [PATCH 22/31] Captures a fresh antiforgery token after login in the web test helper --- .../Common/TestHelpers/WebTestHelpers.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs index ba8de2a2..edf90f82 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/TestHelpers/WebTestHelpers.cs @@ -18,7 +18,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.TestHelpers; /// Represents an HTTP client that has been authenticated through the real login flow of the Web application. /// /// The authenticated HTTP client. -/// The antiforgery token captured before the login, valid for subsequent mutating requests. +/// The antiforgery token captured after the login, valid for subsequent mutating requests made by the authenticated user. [ExcludeFromCodeCoverage] public record AuthenticatedWebClient(HttpClient Client, string AntiforgeryToken); @@ -30,6 +30,8 @@ public static partial class WebTestHelpers { private const string LOGIN_PAGE_PATH = "/en-us/auth/login"; private const string LOGIN_ENDPOINT_PATH = "/en-us/auth/api-login"; + // the change password page renders an antiforgery token for the authenticated user without calling the remote API + private const string AUTHENTICATED_TOKEN_PAGE_PATH = "/en-us/auth/change-password"; [GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]*)\"")] private static partial Regex AntiforgeryTokenRegex(); @@ -61,7 +63,11 @@ public static partial class WebTestHelpers }); string antiforgeryToken = await GetAntiforgeryTokenAsync(client); await LoginAsync(client, username!, password!, antiforgeryToken); - return new AuthenticatedWebClient(client, antiforgeryToken); + // the antiforgery token is bound to the authenticated user, because the antiforgery middleware runs after + // authentication; the token captured from the anonymous login page is rejected with a 400 for authenticated + // mutating requests, so a fresh token must be captured after the login + string authenticatedAntiforgeryToken = await GetAntiforgeryTokenAsync(client, AUTHENTICATED_TOKEN_PAGE_PATH); + return new AuthenticatedWebClient(client, authenticatedAntiforgeryToken); } /// @@ -86,18 +92,19 @@ public static partial class WebTestHelpers } /// - /// Retrieves the antiforgery token and cookie by requesting the login page. + /// Retrieves the antiforgery token and cookie by requesting a page that renders an antiforgery token. /// /// The HTTP client to retrieve the token through. + /// The page that renders the antiforgery token, defaults to the login page. /// The antiforgery token value. - public static async Task GetAntiforgeryTokenAsync(HttpClient client) + public static async Task GetAntiforgeryTokenAsync(HttpClient client, string? pagePath = null) { - HttpResponseMessage loginPageResponse = await client.GetAsync(LOGIN_PAGE_PATH); + HttpResponseMessage loginPageResponse = await client.GetAsync(pagePath ?? LOGIN_PAGE_PATH); loginPageResponse.EnsureSuccessStatusCode(); string loginPageHtml = await loginPageResponse.Content.ReadAsStringAsync(); Match match = AntiforgeryTokenRegex().Match(loginPageHtml); if (!match.Success) - throw new InvalidOperationException("Could not find the antiforgery token on the login page."); + throw new InvalidOperationException("Could not find the antiforgery token on the page."); return System.Net.WebUtility.HtmlDecode(match.Groups[1].Value); } From 07bc20a9e6a181420a2252e27eb0c9f6d39e7d28 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:42:45 -0700 Subject: [PATCH 23/31] Returns a clean validation error when a theme install archive cannot be parsed --- .../InstallTheme/InstallThemeEndpoint.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs index f3abd760..e43ae08e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpoint.cs @@ -6,6 +6,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Themes; using Lumina.Presentation.Api.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -47,7 +48,20 @@ public class InstallThemeEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { - IFormFile? archive = HttpContext.Request.Form.Files.FirstOrDefault(); + // a multipart body without any part cannot be parsed as a form, so a malformed upload is treated as a missing archive + IFormFile? archive = null; + if (HttpContext.Request.HasFormContentType) + { + try + { + archive = HttpContext.Request.Form.Files.FirstOrDefault(); + } + catch (InvalidDataException) + { + archive = null; + } + } + InstallThemeCommand command = new(archive?.OpenReadStream(), archive?.FileName); Result result = await _installThemeCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); From 9c83e5dfa73dc05329b2f4bfe940af9bdfb64e71 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:42:57 -0700 Subject: [PATCH 24/31] Adds the shared fixtures for the theming feature tests --- .../Entities/Themes/ThemeEntityFixture.cs | 110 +++++++++++++ .../DTO/Themes/ThemeManifestDtoFixture.cs | 74 +++++++++ .../DeleteTheme/DeleteThemeCommandFixture.cs | 38 +++++ .../InstallThemeCommandFixture.cs | 42 +++++ .../SetCurrentThemeCommandFixture.cs | 38 +++++ .../GetCurrentThemeQueryFixture.cs | 34 ++++ .../GetThemeArchiveQueryFixture.cs | 38 +++++ .../GetThemeAssetQueryFixture.cs | 41 +++++ .../GetThemeSettingsQueryFixture.cs | 34 ++++ .../GetThemeTemplateQueryFixture.cs | 41 +++++ .../GetThemes/GetThemesQueryFixture.cs | 34 ++++ .../Themes/DeleteThemeRequestFixture.cs | 38 +++++ .../Themes/GetThemeArchiveRequestFixture.cs | 38 +++++ .../Themes/GetThemeAssetRequestFixture.cs | 41 +++++ .../Themes/GetThemeTemplateRequestFixture.cs | 41 +++++ .../Themes/SetCurrentThemeRequestFixture.cs | 38 +++++ .../Themes/ThemeArchiveResponseFixture.cs | 45 ++++++ .../Themes/ThemeAssetResponseFixture.cs | 43 +++++ .../Responses/Themes/ThemeResponseFixture.cs | 73 +++++++++ .../Themes/ThemeSettingsResponseFixture.cs | 46 ++++++ .../Themes/ThemeTemplateResponseFixture.cs | 42 +++++ .../ThemeEngineOptionsDtoFixture.cs | 63 ++++++++ .../Core/Themes/ThemeArchiveEntry.cs | 14 ++ .../Core/Themes/ThemePackFixture.cs | 148 ++++++++++++++++++ .../Themes/TestThemeArchiveFixture.cs | 54 +++++++ .../Common/DTO/Themes/ThemeInfoDtoFixture.cs | 59 +++++++ .../DTO/Themes/ThemeNavMenuDtoFixture.cs | 90 +++++++++++ .../Common/DTO/Themes/ThemePageDtoFixture.cs | 51 ++++++ .../Themes/ThemeRenderDocumentDtoFixture.cs | 43 +++++ .../DTO/Themes/ThemeResponseDtoFixture.cs | 73 +++++++++ .../Themes/ThemeSettingsResponseDtoFixture.cs | 46 ++++++ .../Themes/ThemeTemplateResponseDtoFixture.cs | 46 ++++++ .../Common/Models/SectionModel.cs | 17 ++ .../Common/Models/SectionModelFixture.cs | 37 +++++ 34 files changed, 1710 insertions(+) create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemes/GetThemesQueryFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeArchiveResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeAssetResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeTemplateResponseFixture.cs create mode 100644 tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs create mode 100644 tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemeArchiveEntry.cs create mode 100644 tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Themes/TestThemeArchiveFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModel.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs new file mode 100644 index 00000000..f51fec10 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional database Id of the theme. + /// Optional manifest id of the theme. + /// Optional display name of the theme. + /// Optional description of the theme. + /// Optional author of the theme. + /// Optional version of the theme. + /// Optional preview image path of the theme, or when the theme has no preview. + /// Whether to set , or when . + /// Optional source the theme was installed from. + /// Optional value indicating whether the theme is the currently active one. + /// Whether to set , or when . + /// Optional value indicating whether the theme was soft deleted. + /// Optional UTC timestamp when the theme was installed. + /// Optional UTC timestamp when the entity was created. + /// Optional Id of the user that created the entity. + /// Optional UTC timestamp when the entity was updated. + /// Whether to set , or when . + /// Optional Id of the user that updated the entity. + /// Whether to set , or when . + /// A configured instance. + public ThemeEntity Create( + Guid? id = null, + string? themeId = null, + string? name = null, + string? description = null, + string? author = null, + string? version = null, + string? previewPath = null, + bool includePreviewPath = false, + ThemeInstallSource? installSource = null, + bool? isCurrent = null, + bool includeIsCurrent = false, + bool? isDeleted = null, + DateTime? installedAtUtc = null, + DateTime? createdOnUtc = null, + Guid? createdBy = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = false, + Guid? updatedBy = null, + bool includeUpdatedBy = false) + { + Guid resolvedCreatedBy = createdBy ?? Guid.NewGuid(); + return new Faker() + .CustomInstantiator(f => new ThemeEntity + { + Id = default, + ThemeId = default!, + Name = default!, + Description = default!, + Author = default!, + Version = default!, + PreviewPath = default, + InstallSource = default, + IsCurrent = default, + IsDeleted = default, + InstalledAtUtc = default, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedOnUtc = default, + UpdatedBy = default + }) + .RuleFor(theme => theme.Id, f => id ?? f.Random.Guid()) + .RuleFor(theme => theme.ThemeId, f => themeId ?? f.Lorem.Slug(2)) + .RuleFor(theme => theme.Name, f => name ?? f.Commerce.ProductName()) + .RuleFor(theme => theme.Description, f => description ?? f.Lorem.Sentence()) + .RuleFor(theme => theme.Author, f => author ?? f.Name.FullName()) + .RuleFor(theme => theme.Version, f => version ?? f.System.Semver()) + .RuleFor(theme => theme.PreviewPath, f => includePreviewPath ? (previewPath ?? f.System.FilePath()) : null) + .RuleFor(theme => theme.InstallSource, f => installSource ?? f.PickRandom()) + .RuleFor(theme => theme.IsCurrent, f => includeIsCurrent ? (isCurrent ?? (f.Random.Bool() ? true : null)) : null) + .RuleFor(theme => theme.IsDeleted, f => isDeleted ?? f.Random.Bool()) + .RuleFor(theme => theme.InstalledAtUtc, f => installedAtUtc ?? f.Date.Recent().ToUniversalTime()) + .RuleFor(theme => theme.CreatedOnUtc, f => createdOnUtc ?? f.Date.Past().ToUniversalTime()) + .RuleFor(theme => theme.CreatedBy, resolvedCreatedBy) + .RuleFor(theme => theme.UpdatedOnUtc, f => includeUpdatedOnUtc ? (updatedOnUtc ?? f.Date.Recent().ToUniversalTime()) : null) + .RuleFor(theme => theme.UpdatedBy, f => includeUpdatedBy ? (updatedBy ?? f.Random.Guid()) : null) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs new file mode 100644 index 00000000..de55b6c4 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeManifestDtoFixture +{ + /// + /// Creates a random valid . + /// + /// Optional schema version of the manifest. + /// Optional unique identifier of the theme. + /// Optional display name of the theme. + /// Optional description of the theme. + /// Optional author of the theme. + /// Optional version of the theme. + /// Optional preview image path of the theme, or when the theme has no preview. + /// Whether to set , or when . + /// Optional template mappings of the theme. + /// A configured instance. + public ThemeManifestDto Create( + int? schemaVersion = null, + string? id = null, + string? name = null, + string? description = null, + string? author = null, + string? version = null, + string? preview = null, + bool includePreview = false, + Dictionary? templates = null) + { + return new Faker() + .CustomInstantiator(f => new ThemeManifestDto + { + SchemaVersion = default, + Id = default!, + Name = default!, + Description = default!, + Author = default!, + Version = default!, + Preview = default, + Templates = default! + }) + .RuleFor(manifest => manifest.SchemaVersion, f => schemaVersion ?? f.Random.Int(1, 5)) + .RuleFor(manifest => manifest.Id, f => id ?? f.Lorem.Slug(2)) + .RuleFor(manifest => manifest.Name, f => name ?? f.Commerce.ProductName()) + .RuleFor(manifest => manifest.Description, f => description ?? f.Lorem.Sentence()) + .RuleFor(manifest => manifest.Author, f => author ?? f.Name.FullName()) + .RuleFor(manifest => manifest.Version, f => version ?? f.System.Semver()) + .RuleFor(manifest => manifest.Preview, f => includePreview ? (preview ?? (f.Random.Bool() ? f.System.FilePath() : null)) : null) + .RuleFor(manifest => manifest.Templates, f => templates ?? new Dictionary(StringComparer.OrdinalIgnoreCase) { ["home"] = "templates/home.html" }) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandFixture.cs new file mode 100644 index 00000000..bea20392 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Commands.DeleteTheme; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme to delete. + /// The created . + public DeleteThemeCommand Create(string? themeId = null) + { + return new DeleteThemeCommand(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandFixture.cs new file mode 100644 index 00000000..78cb9985 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Commands.InstallTheme; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Commands.InstallTheme; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional ZIP archive stream of the theme pack. + /// Optional file name of the uploaded archive. + /// The created . + public InstallThemeCommand Create(Stream? archive = null, string? fileName = null) + { + Stream resolvedArchive = archive ?? new MemoryStream(Encoding.UTF8.GetBytes(_faker.Lorem.Paragraph())); + return new InstallThemeCommand(resolvedArchive, fileName ?? $"{_faker.Lorem.Word()}.zip"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandFixture.cs new file mode 100644 index 00000000..a7257669 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Commands.SetCurrentTheme; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme to activate. + /// The created . + public SetCurrentThemeCommand Create(string? themeId = null) + { + return new SetCurrentThemeCommand(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryFixture.cs new file mode 100644 index 00000000..531fd197 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetCurrentTheme; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetCurrentThemeQuery Create() + { + return new GetCurrentThemeQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryFixture.cs new file mode 100644 index 00000000..c17f60a6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeArchive; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveQueryFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme. + /// The created . + public GetThemeArchiveQuery Create(string? themeId = null) + { + return new GetThemeArchiveQuery(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryFixture.cs new file mode 100644 index 00000000..4397337e --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeAsset; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetQueryFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme. + /// Optional asset path relative to the theme pack root. + /// The created . + public GetThemeAssetQuery Create(string? themeId = null, string? assetPath = null) + { + return new GetThemeAssetQuery( + themeId ?? _faker.Lorem.Slug(2), + assetPath ?? _faker.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryFixture.cs new file mode 100644 index 00000000..bb1a652f --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeSettings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetThemeSettingsQuery Create() + { + return new GetThemeSettingsQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryFixture.cs new file mode 100644 index 00000000..84cba75d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeTemplate; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateQueryFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional manifest id of the theme. + /// Optional page key that selects the template. + /// The created . + public GetThemeTemplateQuery Create(string? themeId = null, string? pageKey = null) + { + return new GetThemeTemplateQuery( + themeId ?? _faker.Lorem.Slug(2), + pageKey ?? _faker.Lorem.Word()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemes/GetThemesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemes/GetThemesQueryFixture.cs new file mode 100644 index 00000000..8c189e25 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Queries/GetThemes/GetThemesQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Queries.GetThemes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemes; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetThemesQuery Create() + { + return new GetThemesQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs new file mode 100644 index 00000000..4034dfff --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/DeleteThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme to delete. + /// The created . + public DeleteThemeRequest Create(string? themeId = null) + { + return new DeleteThemeRequest(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs new file mode 100644 index 00000000..a7421ee3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeArchiveRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme. + /// The created . + public GetThemeArchiveRequest Create(string? themeId = null) + { + return new GetThemeArchiveRequest(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs new file mode 100644 index 00000000..b78f5459 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeAssetRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme. + /// Optional. The asset path relative to the theme pack root. + /// The created . + public GetThemeAssetRequest Create(string? themeId = null, string? assetPath = null) + { + return new GetThemeAssetRequest( + themeId ?? _faker.Lorem.Slug(2), + assetPath ?? _faker.System.FilePath()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs new file mode 100644 index 00000000..1b9da5de --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/GetThemeTemplateRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme. + /// Optional. The page key that selects the template. + /// The created . + public GetThemeTemplateRequest Create(string? themeId = null, string? pageKey = null) + { + return new GetThemeTemplateRequest( + themeId ?? _faker.Lorem.Slug(2), + pageKey ?? _faker.Lorem.Word()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs new file mode 100644 index 00000000..78d68248 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/SetCurrentThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The manifest id of the theme to activate. + /// The created . + public SetCurrentThemeRequest Create(string? themeId = null) + { + return new SetCurrentThemeRequest(themeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeArchiveResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeArchiveResponseFixture.cs new file mode 100644 index 00000000..ea08780b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeArchiveResponseFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeArchiveResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The bytes of the ZIP archive. + /// Optional. The file name to expose when downloading the archive. + /// Optional. The MIME content type of the archive. + /// The created . + public ThemeArchiveResponse Create(byte[]? bytes = null, string? fileName = null, string? contentType = null) + { + return new ThemeArchiveResponse( + bytes ?? Encoding.UTF8.GetBytes(_faker.Lorem.Paragraph()), + fileName ?? $"{_faker.Lorem.Word()}.zip", + contentType ?? _faker.System.MimeType()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeAssetResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeAssetResponseFixture.cs new file mode 100644 index 00000000..da27cd1b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeAssetResponseFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The bytes of the asset file. + /// Optional. The MIME content type of the asset file. + /// The created . + public ThemeAssetResponse Create(byte[]? bytes = null, string? contentType = null) + { + return new ThemeAssetResponse( + bytes ?? Encoding.UTF8.GetBytes(_faker.Lorem.Paragraph()), + contentType ?? _faker.System.MimeType()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs new file mode 100644 index 00000000..c0c03b0d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the theme. + /// Optional. The manifest id of the theme. + /// Optional. The display name of the theme. + /// Optional. The description of the theme. + /// Optional. The author of the theme. + /// Optional. The version of the theme. + /// Optional. The preview image path of the theme, or when the theme has no preview. + /// Whether to set , or when . + /// Optional. The source the theme was installed from. + /// Optional. Whether the theme is the currently active one. + /// Whether to set , or when . + /// Optional. The UTC timestamp when the theme was installed. + /// The created . + public ThemeResponse Create( + Guid? id = null, + string? themeId = null, + string? name = null, + string? description = null, + string? author = null, + string? version = null, + string? previewPath = null, + bool includePreviewPath = false, + ThemeInstallSource? installSource = null, + bool? isCurrent = null, + bool includeIsCurrent = false, + DateTime? installedAtUtc = null) + { + return new ThemeResponse( + id ?? Guid.NewGuid(), + themeId ?? _faker.Lorem.Slug(2), + name ?? _faker.Commerce.ProductName(), + description ?? _faker.Lorem.Sentence(), + author ?? _faker.Name.FullName(), + version ?? _faker.System.Semver(), + includePreviewPath ? (previewPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)) : null, + installSource ?? _faker.PickRandom(), + includeIsCurrent ? (isCurrent ?? (_faker.Random.Bool() ? true : null)) : null, + installedAtUtc ?? _faker.Date.Recent().ToUniversalTime()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs new file mode 100644 index 00000000..1a807539 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeSettingsResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The maximum allowed size of a theme archive, in bytes. + /// Optional. Whether theme templates may contain script elements. + /// Optional. The identifier of the default theme. + /// The created . + public ThemeSettingsResponse Create( + long? maxArchiveBytes = null, + bool? allowThemeScripts = null, + string? defaultThemeId = null) + { + return new ThemeSettingsResponse( + maxArchiveBytes ?? _faker.Random.Long(1_000_000, 100_000_000), + allowThemeScripts ?? _faker.Random.Bool(), + defaultThemeId ?? _faker.Lorem.Slug(2)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeTemplateResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeTemplateResponseFixture.cs new file mode 100644 index 00000000..be29df78 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeTemplateResponseFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeTemplateResponseFixture +{ + private readonly Faker _faker = new(); + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The theme the template belongs to. + /// Optional. The sanitized content of the template. + /// The created . + public ThemeTemplateResponse Create(ThemeResponse? theme = null, string? template = null) + { + return new ThemeTemplateResponse( + theme ?? _themeResponseFixture.Create(), + template ?? _faker.Lorem.Paragraph()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs new file mode 100644 index 00000000..b61fbdd5 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeEngineOptionsDtoFixture +{ + /// + /// Creates a random valid . + /// + /// Optional directory where installed theme packs are stored. + /// Optional directory where the shipped theme pack archives are located. + /// Optional identifier of the default theme. + /// Optional maximum size of an uploaded theme archive, in bytes. + /// Optional maximum total size of an extracted theme pack, in bytes. + /// Optional maximum size of a single file within a theme pack, in bytes. + /// Optional maximum number of entries in a theme pack archive. + /// Optional value indicating whether script elements are allowed. + /// A configured instance. + public ThemeEngineOptionsDto Create( + string? storagePath = null, + string? bundledThemesPath = null, + string? defaultThemeId = null, + long? maxArchiveBytes = null, + long? maxExpandedBytes = null, + long? maxSingleFileBytes = null, + int? maxEntries = null, + bool? allowThemeScripts = null) + { + Faker faker = new(); + return new ThemeEngineOptionsDto + { + StoragePath = storagePath ?? faker.System.DirectoryPath(), + BundledThemesPath = bundledThemesPath ?? faker.System.DirectoryPath(), + DefaultThemeId = defaultThemeId ?? faker.Lorem.Word(), + MaxArchiveBytes = maxArchiveBytes ?? faker.Random.Long(1_000_000, 100_000_000), + MaxExpandedBytes = maxExpandedBytes ?? faker.Random.Long(10_000_000, 500_000_000), + MaxSingleFileBytes = maxSingleFileBytes ?? faker.Random.Long(1_000_000, 50_000_000), + MaxEntries = maxEntries ?? faker.Random.Int(1, 1000), + AllowThemeScripts = allowThemeScripts ?? faker.Random.Bool() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemeArchiveEntry.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemeArchiveEntry.cs new file mode 100644 index 00000000..f106c330 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemeArchiveEntry.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Core.Themes; + +/// +/// Describes a single entry of a theme pack ZIP archive built by the . +/// +/// The entry path inside the archive. +/// The text content of the entry. +/// Optional Unix file type for the entry, used to simulate special file types such as symbolic links. +[ExcludeFromCodeCoverage] +public sealed record ThemeArchiveEntry(string Path, string Content, int? UnixFileType = null); diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs new file mode 100644 index 00000000..f87a516f --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text.Json; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Core.Themes; + +/// +/// Fixture class for generating theme pack ZIP archives used by theme tests. +/// +[ExcludeFromCodeCoverage] +public sealed class ThemePackFixture +{ + /// + /// Creates a valid theme pack ZIP archive containing a manifest, the template files referenced by it and a preview asset. + /// + /// Optional theme id written to the manifest. + /// Optional display name written to the manifest. + /// Optional description written to the manifest. + /// Optional author written to the manifest. + /// Optional version written to the manifest. + /// Optional schema version written to the manifest. + /// Optional template mappings written to the manifest. + /// Optional preview path written to the manifest, or to omit the preview. + /// Optional content for the default template file. + /// Whether to include the preview asset file in the archive. + /// Optional additional files written into the archive. + /// The created theme pack ZIP archive. + public byte[] Create( + string themeId = "test-theme", + string? name = null, + string? description = null, + string? author = null, + string? version = null, + int? schemaVersion = null, + Dictionary? templates = null, + string? preview = "assets/preview.png", + string? defaultTemplateContent = null, + bool includePreviewAsset = true, + IReadOnlyDictionary? additionalFiles = null) + { + Dictionary manifestTemplates = templates ?? new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html" + }; + + string manifestJson = CreateManifestJson( + themeId, + name, + description, + author, + version, + schemaVersion, + manifestTemplates, + preview); + + List entries = [new("theme.json", manifestJson)]; + foreach ((string key, string templatePath) in manifestTemplates) + entries.Add(new(templatePath, defaultTemplateContent ?? $"{key} template")); + + if (preview is not null && includePreviewAsset) + entries.Add(new("assets/preview.png", "preview-image-bytes")); + + if (additionalFiles is not null) + entries.AddRange(additionalFiles.Select(file => new ThemeArchiveEntry(file.Key, file.Value))); + + return CreateArchive([.. entries]); + } + + /// + /// Creates the JSON content of a theme manifest with test defaults that can be overridden per field. + /// + /// Optional theme id written to the manifest. + /// Optional display name written to the manifest. + /// Optional description written to the manifest. + /// Optional author written to the manifest. + /// Optional version written to the manifest. + /// Optional schema version written to the manifest. + /// Optional template mappings written to the manifest. + /// Optional preview path written to the manifest, or to omit the preview. + /// The created manifest JSON content. + public string CreateManifestJson( + string themeId = "test-theme", + string? name = null, + string? description = null, + string? author = null, + string? version = null, + int? schemaVersion = null, + Dictionary? templates = null, + string? preview = "assets/preview.png") + { + object manifest = new + { + schemaVersion = schemaVersion ?? 1, + id = themeId, + name = name ?? "Test Theme", + description = description ?? "A theme used for testing.", + author = author ?? "Lumina Tests", + version = version ?? "1.0.0", + preview, + templates = templates ?? new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html" + } + }; + + return JsonSerializer.Serialize(manifest); + } + + /// + /// Creates a ZIP archive from the provided entries, allowing tests to build arbitrary valid and invalid theme packs. + /// + /// The entries to write into the archive. + /// The created ZIP archive bytes. + public byte[] CreateArchive(params ThemeArchiveEntry[] entries) + { + using MemoryStream output = new(); + using (ZipArchive archive = new(output, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach (ThemeArchiveEntry entry in entries) + { + ZipArchiveEntry zipEntry = archive.CreateEntry(entry.Path); + if (entry.UnixFileType is not null) + zipEntry.ExternalAttributes = (entry.UnixFileType.Value << 16) | 0x81A4; + + using StreamWriter writer = new(zipEntry.Open()); + writer.Write(entry.Content); + } + } + + return output.ToArray(); + } + + /// + /// Creates multiple valid theme pack ZIP archives with randomized test data. + /// + /// Number of archives to create. + /// List of configured theme pack ZIP archives. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(themeId: $"test-theme-{index}"))]; + } +} diff --git a/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Themes/TestThemeArchiveFixture.cs b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Themes/TestThemeArchiveFixture.cs new file mode 100644 index 00000000..3fe523ab --- /dev/null +++ b/tests/Common/Lumina.Presentation.Api.Fixtures/Core/Endpoints/Themes/TestThemeArchiveFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Text; +#endregion + +namespace Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes; + +/// +/// Fixture class for building theme pack ZIP archives used by the theme integration tests. +/// +[ExcludeFromCodeCoverage] +public class TestThemeArchiveFixture +{ + /// + /// Builds a valid theme pack ZIP archive in memory, containing a theme.json manifest and a default template. + /// + /// Optional manifest id of the theme; a unique id is generated when not supplied. + /// The bytes of the theme pack ZIP archive. + public byte[] Create(string? themeId = null) + { + string resolvedThemeId = themeId ?? $"test-theme-{Guid.NewGuid():N}"; + + using MemoryStream stream = new(); + using (ZipArchive archive = new(stream, ZipArchiveMode.Create, leaveOpen: true)) + { + ZipArchiveEntry manifestEntry = archive.CreateEntry("theme.json"); + using (StreamWriter writer = new(manifestEntry.Open(), Encoding.UTF8)) + { + writer.Write($$""" + { + "schemaVersion": 1, + "id": "{{resolvedThemeId}}", + "name": "Test Theme", + "description": "A test theme used by the integration tests.", + "author": "Test Author", + "version": "1.0.0", + "templates": { + "default": "templates/default.html" + } + } + """); + } + + ZipArchiveEntry templateEntry = archive.CreateEntry("templates/default.html"); + using (StreamWriter writer = new(templateEntry.Open(), Encoding.UTF8)) + writer.Write("

    Default template

    "); + } + + return stream.ToArray(); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs new file mode 100644 index 00000000..a7f32034 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemeInfoDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional manifest id of the theme. + /// Optional display name of the theme. + /// Optional description of the theme. + /// Optional author of the theme. + /// Optional semantic version of the theme. + /// Optional URL of the theme preview image. + /// Whether the theme ships with the application. + /// A configured instance. + public ThemeInfoDto Create( + string? id = null, + string? name = null, + string? description = null, + string? author = null, + string? version = null, + string? previewUrl = null, + bool? isBundled = null) + { + Faker faker = new(); + return new ThemeInfoDto( + Id: id ?? faker.Lorem.Word(), + Name: name ?? faker.Commerce.ProductName(), + Description: description ?? faker.Lorem.Sentence(), + Author: author ?? faker.Name.FullName(), + Version: version ?? faker.System.Semver(), + PreviewUrl: previewUrl ?? $"/theme-assets/{faker.Lorem.Word()}/preview.png", + IsBundled: isBundled ?? faker.Random.Bool() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs new file mode 100644 index 00000000..5016ae36 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemeNavMenuDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional name of the site displayed by the navigation menu. + /// Optional sections of the mobile navigation menu. + /// Optional sections of the desktop navigation menu bar. + /// A configured instance. + public ThemeNavMenuDto Create( + string? siteName = null, + IReadOnlyList? mobileSections = null, + IReadOnlyList? menubarSections = null) + { + Faker faker = new(); + ThemeNavSectionDto[] generatedSections = [CreateSection()]; + return new ThemeNavMenuDto( + SiteName: siteName ?? faker.Company.CompanyName(), + MobileSections: mobileSections ?? generatedSections, + MenubarSections: menubarSections ?? generatedSections + ); + } + + /// + /// Creates a single instance with randomized test data. + /// + /// Optional label of the section. + /// Optional entries of the section. + /// A configured instance. + public ThemeNavSectionDto CreateSection(string? label = null, IReadOnlyList? items = null) + { + Faker faker = new(); + return new ThemeNavSectionDto( + Label: label ?? faker.Lorem.Word(), + Items: items ?? [CreateEntry()] + ); + } + + /// + /// Creates a single instance with randomized test data. + /// + /// Optional label of the entry. + /// Optional URL of the link, or for a submenu. + /// Whether to set , or when . + /// Optional CSS classes of the link. + /// Whether to set , or when . + /// Optional child links of a submenu. + /// A configured instance. + public ThemeNavEntryDto CreateEntry( + string? label = null, + string? url = null, + bool includeUrl = false, + string? cssClass = null, + bool includeCssClass = false, + IReadOnlyList? children = null) + { + Faker faker = new(); + return new ThemeNavEntryDto( + Label: label ?? faker.Lorem.Word(), + Url: includeUrl ? (url ?? faker.Internet.Url()) : null, + CssClass: includeCssClass ? (cssClass ?? faker.Lorem.Word()) : null, + Children: children ?? [] + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs new file mode 100644 index 00000000..684f568a --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemePageDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional key of the page, used to select the template to render. + /// Optional title of the page. + /// Optional description of the page. + /// Optional resolved values exposed to the theme template. + /// A configured instance. + public ThemePageDto Create( + string? pageKey = null, + string? title = null, + string? description = null, + IReadOnlyDictionary? pageData = null) + { + Faker faker = new(); + return new ThemePageDto + { + PageKey = pageKey ?? faker.Lorem.Word(), + Title = title ?? faker.Lorem.Sentence(), + Description = description ?? faker.Lorem.Sentence(), + PageData = pageData ?? new Dictionary() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs new file mode 100644 index 00000000..45a22191 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemeRenderDocumentDtoFixture +{ + private readonly ThemeInfoDtoFixture _themeInfoDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional metadata of the resolved theme. + /// Optional raw template source to render. + /// A configured instance. + public ThemeRenderDocumentDto Create(ThemeInfoDto? theme = null, string? template = null) + { + Faker faker = new(); + return new ThemeRenderDocumentDto( + Theme: theme ?? _themeInfoDtoFixture.Create(), + Template: template ?? faker.Lorem.Paragraph() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs new file mode 100644 index 00000000..9abbbf15 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemeResponseDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional database identifier of the theme. + /// Optional manifest id of the theme. + /// Optional display name of the theme. + /// Optional description of the theme. + /// Optional author of the theme. + /// Optional semantic version of the theme. + /// Optional preview image path of the theme, or when the theme has no preview. + /// Whether to set , or when . + /// Optional source the theme was installed from. + /// Optional value indicating whether the theme is the active one. + /// Whether to set , or when . + /// Optional UTC timestamp at which the theme was installed. + /// A configured instance. + public ThemeResponseDto Create( + Guid? id = null, + string? themeId = null, + string? name = null, + string? description = null, + string? author = null, + string? version = null, + string? previewPath = null, + bool includePreviewPath = false, + ThemeInstallSource? installSource = null, + bool? isCurrent = null, + bool includeIsCurrent = false, + DateTime? installedAtUtc = null) + { + Faker faker = new(); + return new ThemeResponseDto( + Id: id ?? Guid.NewGuid(), + ThemeId: themeId ?? faker.Lorem.Word(), + Name: name ?? faker.Commerce.ProductName(), + Description: description ?? faker.Lorem.Sentence(), + Author: author ?? faker.Name.FullName(), + Version: version ?? faker.System.Semver(), + PreviewPath: includePreviewPath ? (previewPath ?? (faker.Random.Bool() ? faker.System.FilePath() : null)) : null, + InstallSource: installSource ?? ThemeInstallSource.Uploaded, + IsCurrent: includeIsCurrent ? (isCurrent ?? (faker.Random.Bool() ? true : null)) : null, + InstalledAtUtc: installedAtUtc ?? faker.Date.Recent() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs new file mode 100644 index 00000000..fcb6ece5 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemeSettingsResponseDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional maximum allowed archive size, in bytes. + /// Whether theme templates may load script files. + /// Optional identifier of the fallback theme. + /// A configured instance. + public ThemeSettingsResponseDto Create( + long? maxArchiveBytes = null, + bool? allowThemeScripts = null, + string? defaultThemeId = null) + { + Faker faker = new(); + return new ThemeSettingsResponseDto( + MaxArchiveBytes: maxArchiveBytes ?? faker.Random.Long(1024 * 1024, 256 * 1024 * 1024), + AllowThemeScripts: allowThemeScripts ?? faker.Random.Bool(), + DefaultThemeId: defaultThemeId ?? faker.Lorem.Word() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs new file mode 100644 index 00000000..fe00f0b4 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemeTemplateResponseDtoFixture +{ + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional theme the template belongs to. + /// Optional sanitized template content. + /// A configured instance. + public ThemeTemplateResponseDto Create( + ThemeResponseDto? theme = null, + string? template = null) + { + Faker faker = new(); + return new ThemeTemplateResponseDto( + Theme: theme ?? _themeResponseDtoFixture.Create(), + Template: template ?? faker.Lorem.Paragraph() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModel.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModel.cs new file mode 100644 index 00000000..201c8d07 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModel.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Models; + +/// +/// Small model class used to verify section rendering against a plain object scope. +/// +[ExcludeFromCodeCoverage] +public sealed class SectionModel +{ + /// + /// Gets the text rendered by the section. + /// + public string Text { get; init; } = string.Empty; +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs new file mode 100644 index 00000000..e6a005bf --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Models; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SectionModelFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional text rendered by the section. + /// A configured instance. + public SectionModel Create(string? text = null) + { + Faker faker = new(); + return new SectionModel { Text = text ?? faker.Lorem.Word() }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} From baa6450406f2dfd4537f4b0a14f16059147463a9 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:43:10 -0700 Subject: [PATCH 25/31] Adds the unit tests for the theming feature --- .../Themes/DeleteThemeRequestMappingTests.cs | 80 + .../GetThemeArchiveRequestMappingTests.cs | 80 + .../GetThemeAssetRequestMappingTests.cs | 86 ++ .../GetThemeTemplateRequestMappingTests.cs | 86 ++ .../SetCurrentThemeRequestMappingTests.cs | 80 + .../Mapping/Themes/ThemeEntityMappingTests.cs | 93 ++ .../DeleteThemeCommandHandlerTests.cs | 406 +++++ .../DeleteThemeCommandValidatorTests.cs | 74 + .../InstallThemeCommandHandlerTests.cs | 302 ++++ .../InstallThemeCommandValidatorTests.cs | 62 + .../SetCurrentThemeCommandHandlerTests.cs | 296 ++++ .../SetCurrentThemeCommandValidatorTests.cs | 74 + .../GetCurrentThemeQueryHandlerTests.cs | 101 ++ .../GetThemeArchiveQueryHandlerTests.cs | 170 +++ .../GetThemeArchiveQueryValidatorTests.cs | 74 + .../GetThemeAssetQueryHandlerTests.cs | 243 +++ .../GetThemeAssetQueryValidatorTests.cs | 114 ++ .../GetThemeSettingsQueryHandlerTests.cs | 55 + .../GetThemeTemplateQueryHandlerTests.cs | 333 ++++ .../GetThemeTemplateQueryValidatorTests.cs | 114 ++ .../GetThemes/GetThemesQueryHandlerTests.cs | 101 ++ .../ThemeEngineOptionsDtoValidatorTests.cs | 18 +- .../Core/Themes/ThemeDetectionSyncJobTests.cs | 402 +++++ .../Core/Themes/ThemeMimeTypesTests.cs | 81 + .../Core/Themes/ThemeServiceTests.cs | 1336 +++++++++++++++++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 202 +++ .../InstallTheme/InstallThemeEndpointTests.cs | 178 +++ .../SetCurrentThemeEndpointTests.cs | 183 +++ .../GetCurrentThemeEndpointTests.cs | 124 ++ .../GetThemeArchiveEndpointTests.cs | 160 ++ .../GetThemeAssetEndpointTests.cs | 161 ++ .../GetThemeSettingsEndpointTests.cs | 124 ++ .../GetThemeTemplateEndpointTests.cs | 159 ++ .../GetThemes/GetThemesEndpointTests.cs | 126 ++ .../ThemeCachePreferenceServiceTests.cs | 104 ++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 84 ++ .../DownloadThemeEndpointTests.cs | 87 ++ .../GetThemes/GetThemesEndpointTests.cs | 95 ++ .../InstallTheme/InstallThemeEndpointTests.cs | 103 ++ .../SetCurrentThemeEndpointTests.cs | 78 + .../Themes/ThemesIndexViewEndpointTests.cs | 73 + .../Core/Themes/ThemeLayoutRendererTests.cs | 195 +++ .../Core/Themes/ThemeNavBuilderTests.cs | 251 ++++ .../Core/Themes/ThemePageDataFactoryTests.cs | 61 + .../Core/Themes/ThemePageRendererTests.cs | 110 ++ .../Core/Themes/ThemeServiceTests.cs | 245 +++ .../Core/Themes/ThemeTemplateEngineTests.cs | 478 ++++++ 47 files changed, 8234 insertions(+), 8 deletions(-) create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs new file mode 100644 index 00000000..6dcb16ce --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/DeleteThemeRequestMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeRequestMappingTests +{ + private readonly DeleteThemeRequestFixture _deleteThemeRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + + // Act + DeleteThemeCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ThemeId, result.ThemeId); + } + + [Theory] + [InlineData("default-theme")] + [InlineData("my-uploaded-theme")] + [InlineData("T-123")] + public void ToCommand_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId) + { + // Arrange + DeleteThemeRequest request = new(themeId); + + // Act + DeleteThemeCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(themeId, result.ThemeId); + } + + [Fact] + public void ToCommand_WhenThemeIdIsNull_ShouldMapNull() + { + // Arrange + DeleteThemeRequest request = new(null); + + // Act + DeleteThemeCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.ThemeId); + } + + [Fact] + public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _deleteThemeRequestFixture.CreateMany(); + + // Act + List results = [.. requests.Select(r => r.ToCommand())]; + + // Assert + Assert.Equal(requests.Count, results.Count); + for (int i = 0; i < requests.Count; i++) + Assert.Equal(requests[i].ThemeId, results[i].ThemeId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs new file mode 100644 index 00000000..8c758111 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeArchiveRequestMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveRequestMappingTests +{ + private readonly GetThemeArchiveRequestFixture _getThemeArchiveRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + + // Act + GetThemeArchiveQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ThemeId, result.ThemeId); + } + + [Theory] + [InlineData("default-theme")] + [InlineData("my-uploaded-theme")] + [InlineData("T-123")] + public void ToQuery_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId) + { + // Arrange + GetThemeArchiveRequest request = new(themeId); + + // Act + GetThemeArchiveQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(themeId, result.ThemeId); + } + + [Fact] + public void ToQuery_WhenThemeIdIsNull_ShouldMapNull() + { + // Arrange + GetThemeArchiveRequest request = new(null); + + // Act + GetThemeArchiveQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.ThemeId); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _getThemeArchiveRequestFixture.CreateMany(); + + // Act + List results = [.. requests.Select(r => r.ToQuery())]; + + // Assert + Assert.Equal(requests.Count, results.Count); + for (int i = 0; i < requests.Count; i++) + Assert.Equal(requests[i].ThemeId, results[i].ThemeId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs new file mode 100644 index 00000000..d6775a90 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeAssetRequestMappingTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetRequestMappingTests +{ + private readonly GetThemeAssetRequestFixture _getThemeAssetRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); + + // Act + GetThemeAssetQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ThemeId, result.ThemeId); + Assert.Equal(request.AssetPath, result.AssetPath); + } + + [Theory] + [InlineData("default-theme", "assets/logo.png")] + [InlineData("my-theme", "css/main.css")] + [InlineData("T-123", "js/app.js")] + public void ToQuery_WhenMappingDifferentThemeIdsAndAssetPaths_ShouldMapCorrectly(string themeId, string assetPath) + { + // Arrange + GetThemeAssetRequest request = new(themeId, assetPath); + + // Act + GetThemeAssetQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(themeId, result.ThemeId); + Assert.Equal(assetPath, result.AssetPath); + } + + [Fact] + public void ToQuery_WhenFieldsAreNull_ShouldMapNull() + { + // Arrange + GetThemeAssetRequest request = new(null, null); + + // Act + GetThemeAssetQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.ThemeId); + Assert.Null(result.AssetPath); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _getThemeAssetRequestFixture.CreateMany(); + + // Act + List results = [.. requests.Select(r => r.ToQuery())]; + + // Assert + Assert.Equal(requests.Count, results.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].ThemeId, results[i].ThemeId); + Assert.Equal(requests[i].AssetPath, results[i].AssetPath); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs new file mode 100644 index 00000000..ff5f7043 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/GetThemeTemplateRequestMappingTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateRequestMappingTests +{ + private readonly GetThemeTemplateRequestFixture _getThemeTemplateRequestFixture = new(); + + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); + + // Act + GetThemeTemplateQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ThemeId, result.ThemeId); + Assert.Equal(request.PageKey, result.PageKey); + } + + [Theory] + [InlineData("default-theme", "home")] + [InlineData("my-theme", "library")] + [InlineData("T-123", "settings")] + public void ToQuery_WhenMappingDifferentThemeIdsAndPageKeys_ShouldMapCorrectly(string themeId, string pageKey) + { + // Arrange + GetThemeTemplateRequest request = new(themeId, pageKey); + + // Act + GetThemeTemplateQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(themeId, result.ThemeId); + Assert.Equal(pageKey, result.PageKey); + } + + [Fact] + public void ToQuery_WhenFieldsAreNull_ShouldMapNull() + { + // Arrange + GetThemeTemplateRequest request = new(null, null); + + // Act + GetThemeTemplateQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.ThemeId); + Assert.Null(result.PageKey); + } + + [Fact] + public void ToQuery_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _getThemeTemplateRequestFixture.CreateMany(); + + // Act + List results = [.. requests.Select(r => r.ToQuery())]; + + // Assert + Assert.Equal(requests.Count, results.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].ThemeId, results[i].ThemeId); + Assert.Equal(requests[i].PageKey, results[i].PageKey); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs new file mode 100644 index 00000000..cdde81c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/SetCurrentThemeRequestMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeRequestMappingTests +{ + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + + // Act + SetCurrentThemeCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.ThemeId, result.ThemeId); + } + + [Theory] + [InlineData("default-theme")] + [InlineData("my-uploaded-theme")] + [InlineData("T-123")] + public void ToCommand_WhenMappingDifferentThemeIds_ShouldMapCorrectly(string themeId) + { + // Arrange + SetCurrentThemeRequest request = new(themeId); + + // Act + SetCurrentThemeCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(themeId, result.ThemeId); + } + + [Fact] + public void ToCommand_WhenThemeIdIsNull_ShouldMapNull() + { + // Arrange + SetCurrentThemeRequest request = new(null); + + // Act + SetCurrentThemeCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.ThemeId); + } + + [Fact] + public void ToCommand_WhenMappingMultipleRequests_ShouldMapAllCorrectly() + { + // Arrange + List requests = _setCurrentThemeRequestFixture.CreateMany(); + + // Act + List results = [.. requests.Select(r => r.ToCommand())]; + + // Assert + Assert.Equal(requests.Count, results.Count); + for (int i = 0; i < requests.Count; i++) + Assert.Equal(requests[i].ThemeId, results[i].ThemeId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs new file mode 100644 index 00000000..17f390ee --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/ThemeEntityMappingTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.Mapping.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeEntityMappingTests +{ + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidThemeEntity_ShouldMapAllFields() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create( + themeId: "my-theme", + name: "My Theme", + description: "A nice theme", + author: "Jane Doe", + version: "1.2.3", + previewPath: "preview.png", + installSource: ThemeInstallSource.Bundled, + isCurrent: true, + isDeleted: false); + + // Act + ThemeResponse result = theme.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(theme.Id, result.Id); + Assert.Equal(theme.ThemeId, result.ThemeId); + Assert.Equal(theme.Name, result.Name); + Assert.Equal(theme.Description, result.Description); + Assert.Equal(theme.Author, result.Author); + Assert.Equal(theme.Version, result.Version); + Assert.Equal(theme.PreviewPath, result.PreviewPath); + Assert.Equal(theme.InstallSource, result.InstallSource); + Assert.Equal(theme.IsCurrent, result.IsCurrent); + Assert.Equal(theme.InstalledAtUtc, result.InstalledAtUtc); + } + + [Fact] + public void ToResponse_WhenPreviewPathIsNull_ShouldMapNullPreviewPath() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(); + theme.PreviewPath = null; + + // Act + ThemeResponse result = theme.ToResponse(); + + // Assert + Assert.Null(result.PreviewPath); + } + + [Fact] + public void ToResponse_WhenIsCurrentIsNull_ShouldMapNullIsCurrent() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(); + theme.IsCurrent = null; + + // Act + ThemeResponse result = theme.ToResponse(); + + // Assert + Assert.Null(result.IsCurrent); + } + + [Fact] + public void ToResponse_WhenMappingUploadedTheme_ShouldMapInstallSourceAsUploaded() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isCurrent: null); + + // Act + ThemeResponse result = theme.ToResponse(); + + // Assert + Assert.Equal(ThemeInstallSource.Uploaded, result.InstallSource); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs new file mode 100644 index 00000000..f0d763af --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandlerTests.cs @@ -0,0 +1,406 @@ +#region ========================================================================= USING ===================================================================================== +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.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.DeleteTheme; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.DeleteTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly DeleteThemeCommandHandler _sut; + private readonly DeleteThemeCommandFixture _deleteThemeCommandFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockThemeService.DeleteAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + _sut = new DeleteThemeCommandHandler( + _mockUnitOfWork, + _mockThemeService, + _mockCurrentUserService, + _mockAuthorizationService, + _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsAlreadyDeleted_ShouldReturnThemeNotFoundError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllThemesFails_ShouldReturnError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: false); + Error error = Error.Failure("Database.Error", "Failed to get all themes"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingLastBundledTheme_ShouldReturnLastBundledThemeCannotBeDeletedError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, userTheme])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.LastBundledThemeCannotBeDeleted, result.FirstError); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingCurrentThemeWithoutReplacement_ShouldReturnThemeCannotBeDeletedError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: true, includeIsCurrent: true, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeCannotBeDeleted, result.FirstError); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingBundledTheme_ShouldSoftDeleteItAndRemoveStoredFiles() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false); + ThemeEntity otherBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, otherBundledTheme])); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingUserTheme_ShouldHardDeleteItAndRemoveStoredFiles() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: false, includeIsCurrent: true, isDeleted: false); + ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) + .Returns(Result.Deleted); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).DeleteByIdAsync(theme.Id, Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenHardDeleteFails_ShouldReturnErrorWithoutRemovingStoredFiles() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: false, includeIsCurrent: true, isDeleted: false); + ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error error = Error.Failure("Database.Error", "Failed to delete theme"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockThemeService.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeletingCurrentBundledTheme_ShouldSwitchToDefaultReplacementThemeAndSoftDelete() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false); + ThemeEntity replacementTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false); + _mockThemeService.DefaultThemeId.Returns(replacementTheme.ThemeId); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, replacementTheme])); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == replacementTheme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsDeleted && entity.IsCurrent == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockThemeService.Received(1).DeleteAsync(theme.ThemeId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoDefaultThemeMatches_ShouldSwitchToAlphabeticallyFirstReplacementTheme() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false); + ThemeEntity alphaTheme = _themeEntityFixture.Create(themeId: "alpha", installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false); + ThemeEntity betaTheme = _themeEntityFixture.Create(themeId: "beta", installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false); + _mockThemeService.DefaultThemeId.Returns("no-such-default"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, betaTheme, alphaTheme])); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == alphaTheme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsDeleted), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenFileDeletionFails_ShouldReturnError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: false, includeIsCurrent: true, isDeleted: false); + ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error error = Error.Failure("Theme.DeleteFailed", "Failed to delete theme files"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) + .Returns(Result.Deleted); + _mockThemeService.DeleteAsync(theme.ThemeId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs new file mode 100644 index 00000000..533e428b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandValidatorTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.DeleteTheme; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.DeleteTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeCommandValidatorTests +{ + private readonly DeleteThemeCommandValidator _validator = new(); + private readonly DeleteThemeCommandFixture _deleteThemeCommandFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + command = command with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + DeleteThemeCommand command = _deleteThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs new file mode 100644 index 00000000..833c6414 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs @@ -0,0 +1,302 @@ +#region ========================================================================= USING ===================================================================================== +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.Core.Themes.Management.Commands.InstallTheme; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.InstallTheme; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.InstallTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly InstallThemeCommandHandler _sut; + private readonly InstallThemeCommandFixture _installThemeCommandFixture = new(); + private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public InstallThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + + _sut = new InstallThemeCommandHandler( + _mockUnitOfWork, + _mockThemeService, + _mockCurrentUserService, + _mockAuthorizationService, + _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeArchiveCannotBeNull]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeArchiveCannotBeNull, result.FirstError); + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeInstallFails_ShouldReturnError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + Error error = Error.Failure("Theme.InstallFailed", "Failed to install theme"); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldInsertNewUploadedTheme() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(null)); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(manifest.Id, result.Value.ThemeId); + Assert.Equal(manifest.Name, result.Value.Name); + Assert.Equal(manifest.Description, result.Value.Description); + Assert.Equal(manifest.Author, result.Value.Author); + Assert.Equal(manifest.Version, result.Value.Version); + Assert.Equal(manifest.Preview, result.Value.PreviewPath); + Assert.Equal(ThemeInstallSource.Uploaded, result.Value.InstallSource); + Assert.Null(result.Value.IsCurrent); + await _mockThemeRepository.Received(1).InsertAsync( + Arg.Is(theme => + theme.ThemeId == manifest.Id && + theme.Name == manifest.Name && + theme.Description == manifest.Description && + theme.Author == manifest.Author && + theme.Version == manifest.Version && + theme.PreviewPath == manifest.Preview && + theme.InstallSource == ThemeInstallSource.Uploaded && + theme.IsDeleted == false && + theme.CreatedBy == _userId && + theme.UpdatedBy == _userId), + Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertFails_ShouldRollBackStoredThemeFiles() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to insert theme"); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(null)); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.Received(1).DeleteAsync(manifest.Id, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeAlreadyExists_ShouldUpdateExistingThemeAndResurrectIt() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + ThemeEntity existingTheme = _themeEntityFixture.Create( + themeId: manifest.Id, + installSource: ThemeInstallSource.Bundled, + isCurrent: true, includeIsCurrent: true, + isDeleted: true); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(existingTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(existingTheme.Id, result.Value.Id); + Assert.Equal(manifest.Name, result.Value.Name); + Assert.Equal(ThemeInstallSource.Bundled, result.Value.InstallSource); + Assert.True(result.Value.IsCurrent); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => + theme.Id == existingTheme.Id && + theme.ThemeId == manifest.Id && + theme.Name == manifest.Name && + theme.InstallSource == existingTheme.InstallSource && + theme.IsCurrent == existingTheme.IsCurrent && + theme.IsDeleted == false && + theme.CreatedOnUtc == existingTheme.CreatedOnUtc && + theme.CreatedBy == existingTheme.CreatedBy && + theme.UpdatedBy == _userId), + Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); + ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isCurrent: null, isDeleted: false); + Error error = Error.Failure("Database.Error", "Failed to update theme"); + _mockThemeService.InstallAsync(command.Archive!, Arg.Any()) + .Returns(Result.From(manifest)); + _mockThemeRepository.GetByThemeIdAsync(manifest.Id, Arg.Any()) + .Returns(Result.From(existingTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs new file mode 100644 index 00000000..7ccea36e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandValidatorTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.InstallTheme; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.InstallTheme; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.InstallTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeCommandValidatorTests +{ + private readonly InstallThemeCommandValidator _validator = new(); + private readonly InstallThemeCommandFixture _installThemeCommandFixture = new(); + + [Fact] + public void Validate_WhenArchiveIsNull_ShouldHaveValidationError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + command = command with { Archive = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeArchiveCannotBeNull); + } + + [Fact] + public void Validate_WhenArchiveIsProvided_ShouldNotHaveValidationError() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Themes.ThemeArchiveCannotBeNull); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + InstallThemeCommand command = _installThemeCommandFixture.Create(new MemoryStream()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs new file mode 100644 index 00000000..f63854be --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs @@ -0,0 +1,296 @@ +#region ========================================================================= USING ===================================================================================== +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.Validation; +using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.SetCurrentTheme; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.SetCurrentTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly SetCurrentThemeCommandHandler _sut; + private readonly SetCurrentThemeCommandFixture _setCurrentThemeCommandFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + + _sut = new SetCurrentThemeCommandHandler( + _mockUnitOfWork, + _mockCurrentUserService, + _mockAuthorizationService, + _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsAlreadyCurrent_ShouldReturnResponseWithoutAnyPersistence() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: true, includeIsCurrent: true, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(theme.Id, result.Value.Id); + Assert.Equal(theme.ThemeId, result.Value.ThemeId); + Assert.True(result.Value.IsCurrent); + await _mockThemeRepository.DidNotReceive().GetCurrentAsync(Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetCurrentThemeFails_ShouldReturnError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false); + Error error = Error.Failure("Database.Error", "Failed to get current theme"); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAnotherThemeIsCurrent_ShouldUnsetPreviousThemeAndActivateNewOne() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false); + ThemeEntity currentTheme = _themeEntityFixture.Create(isCurrent: true, includeIsCurrent: true, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(currentTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(theme.Id, result.Value.Id); + Assert.True(result.Value.IsCurrent); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == currentTheme.Id && entity.IsCurrent == null), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentThemeIsTheSameTheme_ShouldNotUpdateCurrentThemeTwice() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(theme.Id, result.Value.Id); + Assert.True(result.Value.IsCurrent); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoThemeIsCurrentlySet_ShouldActivateThemeWithoutUnsettingAnything() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, isCurrent: false, includeIsCurrent: true, isDeleted: false); + _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(null)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(theme.Id, result.Value.Id); + Assert.True(result.Value.IsCurrent); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsCurrent == true && entity.UpdatedBy == _userId), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs new file mode 100644 index 00000000..b4f86aeb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandValidatorTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme; +using Lumina.Application.Fixtures.Core.Themes.Management.Commands.SetCurrentTheme; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Commands.SetCurrentTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeCommandValidatorTests +{ + private readonly SetCurrentThemeCommandValidator _validator = new(); + private readonly SetCurrentThemeCommandFixture _setCurrentThemeCommandFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + command = command with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + SetCurrentThemeCommand command = _setCurrentThemeCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs new file mode 100644 index 00000000..abb8cead --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetCurrentTheme; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetCurrentTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetCurrentThemeQueryHandler _sut; + private readonly GetCurrentThemeQueryFixture _getCurrentThemeQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetCurrentThemeQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _sut = new GetCurrentThemeQueryHandler(_mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenCurrentThemeExists_ShouldReturnItsResponse() + { + // Arrange + GetCurrentThemeQuery query = _getCurrentThemeQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(isCurrent: true, includeIsCurrent: true); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(theme.Id, result.Value.Id); + Assert.Equal(theme.ThemeId, result.Value.ThemeId); + Assert.Equal(theme.Name, result.Value.Name); + Assert.Equal(theme.Description, result.Value.Description); + Assert.Equal(theme.Author, result.Value.Author); + Assert.Equal(theme.Version, result.Value.Version); + Assert.Equal(theme.PreviewPath, result.Value.PreviewPath); + Assert.Equal(theme.InstallSource, result.Value.InstallSource); + Assert.True(result.Value.IsCurrent); + Assert.Equal(theme.InstalledAtUtc, result.Value.InstalledAtUtc); + } + + [Fact] + public async Task HandleAsync_WhenNoCurrentThemeExists_ShouldReturnThemeNotFoundError() + { + // Arrange + GetCurrentThemeQuery query = _getCurrentThemeQueryFixture.Create(); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError() + { + // Arrange + GetCurrentThemeQuery query = _getCurrentThemeQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get current theme"); + _mockThemeRepository.GetCurrentAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs new file mode 100644 index 00000000..051aecfa --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs @@ -0,0 +1,170 @@ +#region ========================================================================= USING ===================================================================================== +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.Models.DTO.Themes; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeArchive; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeArchive; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemeArchiveQueryHandler _sut; + private readonly GetThemeArchiveQueryFixture _getThemeArchiveQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeArchiveQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + + _sut = new GetThemeArchiveQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockThemeService.DidNotReceive().BuildArchiveAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArchiveBuildsSuccessfully_ShouldReturnArchiveResponse() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false); + byte[] bytes = Encoding.UTF8.GetBytes("archive-content"); + string fileName = $"{theme.ThemeId}.zip"; + string contentType = "application/zip"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.From(new ThemeArchiveDto(bytes, fileName, contentType))); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bytes, result.Value.Bytes); + Assert.Equal(fileName, result.Value.FileName); + Assert.Equal(contentType, result.Value.ContentType); + } + + [Fact] + public async Task HandleAsync_WhenArchiveBuildFails_ShouldReturnError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false); + Error error = Error.Failure("Theme.ArchiveBuildFailed", "Failed to build archive"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs new file mode 100644 index 00000000..64f57510 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryValidatorTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeArchive; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeArchive; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveQueryValidatorTests +{ + private readonly GetThemeArchiveQueryValidator _validator = new(); + private readonly GetThemeArchiveQueryFixture _getThemeArchiveQueryFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + query = query with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetThemeArchiveQuery query = _getThemeArchiveQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs new file mode 100644 index 00000000..073979b0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs @@ -0,0 +1,243 @@ +#region ========================================================================= USING ===================================================================================== +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.Models.DTO.Themes; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeAsset; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeAsset; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemeAssetQueryHandler _sut; + private readonly GetThemeAssetQueryFixture _getThemeAssetQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeAssetQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + + _sut = new GetThemeAssetQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockThemeService.DidNotReceive().GetAssetAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAssetLoadsSuccessfully_ShouldReturnAssetResponse() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false); + byte[] bytes = Encoding.UTF8.GetBytes("asset-content"); + string contentType = "image/png"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(Result.From(new ThemeAssetDto(bytes, contentType))); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bytes, result.Value.Bytes); + Assert.Equal(contentType, result.Value.ContentType); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAssetLoadFailsForUserTheme_ShouldReturnAssetErrorWithoutRestoring() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: false); + Error error = Error.Failure("Theme.AssetMissing", "Asset missing"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAssetLoadFailsAndRestoreFails_ShouldReturnRestoreError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error assetError = Error.Failure("Theme.AssetMissing", "Asset missing"); + Error restoreError = Error.Failure("Theme.RestoreFailed", "Restore failed"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(assetError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(restoreError); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(restoreError, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenAssetLoadFailsAndRestoreSucceeds_ShouldRetryAndReturnAssetResponse() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error assetError = Error.Failure("Theme.AssetMissing", "Asset missing"); + byte[] restoredBytes = Encoding.UTF8.GetBytes("restored-asset"); + string contentType = "text/css"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(assetError, Result.From(new ThemeAssetDto(restoredBytes, contentType))); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredBytes, result.Value.Bytes); + Assert.Equal(contentType, result.Value.ContentType); + await _mockThemeService.Received(2).GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()); + await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoreSucceedsButRetryFails_ShouldReturnAssetError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error assetError = Error.Failure("Theme.AssetMissing", "Asset missing"); + Error retryError = Error.Failure("Theme.AssetMissingAgain", "Asset still missing"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) + .Returns(assetError, retryError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(retryError, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs new file mode 100644 index 00000000..2dee43e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryValidatorTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeAsset; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeAsset; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetQueryValidatorTests +{ + private readonly GetThemeAssetQueryValidator _validator = new(); + private readonly GetThemeAssetQueryFixture _getThemeAssetQueryFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + query = query with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAssetPathIsNull_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + query = query with { AssetPath = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAssetPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(assetPath: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAssetPathIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(assetPath: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeAssetPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetThemeAssetQuery query = _getThemeAssetQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs new file mode 100644 index 00000000..64904a3d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeSettings; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsQueryHandlerTests +{ + private readonly IThemeService _mockThemeService; + private readonly GetThemeSettingsQueryHandler _sut; + private readonly GetThemeSettingsQueryFixture _getThemeSettingsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeSettingsQueryHandlerTests() + { + _mockThemeService = Substitute.For(); + _sut = new GetThemeSettingsQueryHandler(_mockThemeService); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldReturnThemeSettingsFromThemeService() + { + // Arrange + GetThemeSettingsQuery query = _getThemeSettingsQueryFixture.Create(); + long maxArchiveBytes = 50_000_000; + bool allowThemeScripts = false; + string defaultThemeId = "default-theme"; + _mockThemeService.MaxArchiveBytes.Returns(maxArchiveBytes); + _mockThemeService.AllowThemeScripts.Returns(allowThemeScripts); + _mockThemeService.DefaultThemeId.Returns(defaultThemeId); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(maxArchiveBytes, result.Value.MaxArchiveBytes); + Assert.Equal(allowThemeScripts, result.Value.AllowThemeScripts); + Assert.Equal(defaultThemeId, result.Value.DefaultThemeId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs new file mode 100644 index 00000000..471af61e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs @@ -0,0 +1,333 @@ +#region ========================================================================= USING ===================================================================================== +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.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeTemplate; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeTemplate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeService _mockThemeService; + private readonly IValidator _mockValidator; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemeTemplateQueryHandler _sut; + private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeTemplateQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockThemeRepository = Substitute.For(); + + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + + _sut = new GetThemeTemplateQueryHandler(_mockUnitOfWork, _mockThemeService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutAnyDownstreamCalls() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Themes.ThemeIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeIdCannotBeEmpty, result.FirstError); + await _mockThemeRepository.DidNotReceive().GetByThemeIdAsync(Arg.Any(), Arg.Any()); + await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetThemeFails_ShouldReturnError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get theme"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThemeDoesNotExist_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenThemeIsDeleted_ShouldReturnThemeNotFoundError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: true); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Themes.ThemeNotFound, result.FirstError); + await _mockThemeService.DidNotReceive().GetTemplateAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTemplateLoadsSuccessfully_ShouldReturnTemplateResponse() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, isDeleted: false); + string template = "Hello"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(Result.From(template)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(theme.Id, result.Value.Theme.Id); + Assert.Equal(theme.ThemeId, result.Value.Theme.ThemeId); + Assert.Equal(template, result.Value.Template); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTemplateLoadFailsForUserTheme_ShouldReturnTemplateErrorWithoutRestoring() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Uploaded, isDeleted: false); + Error error = Error.Failure("Theme.TemplateMissing", "Template missing"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTemplateLoadFailsAndRestoreFails_ShouldReturnTemplateError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing"); + Error restoreError = Error.Failure("Theme.RestoreFailed", "Restore failed"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(restoreError); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(templateError, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenTemplateLoadFailsAndRestoreSucceeds_ShouldRetryAndReturnTemplateResponse() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: false, includeIsCurrent: true, isDeleted: false); + Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing"); + string restoredTemplate = "Restored"; + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredTemplate, result.Value.Template); + await _mockThemeService.Received(2).GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()); + await _mockThemeService.Received(1).RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoreSucceedsButRetryFails_ShouldReturnTemplateError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isDeleted: false); + Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing"); + Error retryError = Error.Failure("Theme.TemplateMissingAgain", "Template still missing"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, retryError); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(retryError, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenRestoringCurrentBundledTheme_ShouldSwitchActiveThemeToDefaultTheme() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false); + ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", isDeleted: false); + Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing"); + string restoredTemplate = "Restored"; + _mockThemeService.DefaultThemeId.Returns(defaultTheme.ThemeId); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetByThemeIdAsync(defaultTheme.ThemeId, Arg.Any()) + .Returns(Result.From(defaultTheme)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredTemplate, result.Value.Template); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == theme.Id && entity.IsCurrent == null), + Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.Id == defaultTheme.Id && entity.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRestoringCurrentBundledThemeWithNoDefaultTheme_ShouldNotSwitchActiveTheme() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false); + Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing"); + string restoredTemplate = "Restored"; + _mockThemeService.DefaultThemeId.Returns("missing-default"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetByThemeIdAsync("missing-default", Arg.Any()) + .Returns(Result.From(null)); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredTemplate, result.Value.Template); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGettingDefaultThemeFails_ShouldNotSwitchActiveThemeButStillRestore() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + ThemeEntity theme = _themeEntityFixture.Create(themeId: query.ThemeId, installSource: ThemeInstallSource.Bundled, isCurrent: true, includeIsCurrent: true, isDeleted: false); + Error templateError = Error.Failure("Theme.TemplateMissing", "Template missing"); + Error defaultError = Error.Failure("Database.Error", "Failed to get default theme"); + string restoredTemplate = "Restored"; + _mockThemeService.DefaultThemeId.Returns("default-theme"); + _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) + .Returns(Result.From(theme)); + _mockThemeRepository.GetByThemeIdAsync("default-theme", Arg.Any()) + .Returns(defaultError); + _mockThemeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, Arg.Any()) + .Returns(templateError, Result.From(restoredTemplate)); + _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) + .Returns(Result.Success); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(restoredTemplate, result.Value.Template); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs new file mode 100644 index 00000000..bbc5ec3d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryValidatorTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeTemplate; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemeTemplate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateQueryValidatorTests +{ + private readonly GetThemeTemplateQueryValidator _validator = new(); + private readonly GetThemeTemplateQueryFixture _getThemeTemplateQueryFixture = new(); + + [Fact] + public void Validate_WhenThemeIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + query = query with { ThemeId = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(themeId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenThemeIdIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(themeId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.ThemeIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPageKeyIsNull_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + query = query with { PageKey = null }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPageKeyIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(pageKey: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPageKeyIsWhiteSpace_ShouldHaveValidationError() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(pageKey: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Themes.PageKeyCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetThemeTemplateQuery query = _getThemeTemplateQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs new file mode 100644 index 00000000..3066d68c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandlerTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.Themes.Management.Queries.GetThemes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Themes.Management.Queries.GetThemes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeRepository _mockThemeRepository; + private readonly GetThemesQueryHandler _sut; + private readonly GetThemesQueryFixture _getThemesQueryFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemesQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _sut = new GetThemesQueryHandler(_mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldReturnAllAvailableThemesOrderedBundledFirstThenByName() + { + // Arrange + GetThemesQuery query = _getThemesQueryFixture.Create(); + ThemeEntity uploadedTheme = _themeEntityFixture.Create(themeId: "user-theme", name: "Zeta", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + ThemeEntity bundledLowerTheme = _themeEntityFixture.Create(themeId: "bundled-lower", name: "apple", installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity bundledUpperTheme = _themeEntityFixture.Create(themeId: "bundled-upper", name: "Banana", installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "deleted-theme", name: "Deleted", installSource: ThemeInstallSource.Uploaded, isDeleted: true); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count); + Assert.Equal(bundledLowerTheme.Id, result.Value[0].Id); + Assert.Equal(bundledUpperTheme.Id, result.Value[1].Id); + Assert.Equal(uploadedTheme.Id, result.Value[2].Id); + Assert.Equal(ThemeInstallSource.Bundled, result.Value[0].InstallSource); + Assert.Equal(ThemeInstallSource.Bundled, result.Value[1].InstallSource); + Assert.Equal(ThemeInstallSource.Uploaded, result.Value[2].InstallSource); + } + + [Fact] + public async Task HandleAsync_WhenNoThemesExist_ShouldReturnEmptyList() + { + // Arrange + GetThemesQuery query = _getThemesQueryFixture.Create(); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError() + { + // Arrange + GetThemesQuery query = _getThemesQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to get all themes"); + _mockThemeRepository.GetAllAsync(Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs index 05e9cc01..731f9845 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/ThemeEngineOptionsDtoValidatorTests.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Common.Errors; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Common.Validators; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -16,12 +17,13 @@ namespace Lumina.Infrastructure.UnitTests.Common.Validators; public class ThemeEngineOptionsDtoValidatorTests { private readonly ThemeEngineOptionsDtoValidator _validator = new(); + private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new(); [Fact] public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError() { // Arrange - ThemeEngineOptionsDto options = new(); + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(); // Act List result = _validator.Validate(options); @@ -34,7 +36,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError() { // Arrange - ThemeEngineOptionsDto options = new() { StoragePath = string.Empty }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(storagePath: string.Empty); // Act List result = _validator.Validate(options); @@ -48,7 +50,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenBundledThemesPathIsEmpty_ShouldHaveValidationError() { // Arrange - ThemeEngineOptionsDto options = new() { BundledThemesPath = string.Empty }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(bundledThemesPath: string.Empty); // Act List result = _validator.Validate(options); @@ -62,7 +64,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenDefaultThemeIdIsEmpty_ShouldHaveValidationError() { // Arrange - ThemeEngineOptionsDto options = new() { DefaultThemeId = string.Empty }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(defaultThemeId: string.Empty); // Act List result = _validator.Validate(options); @@ -78,7 +80,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenMaxArchiveBytesIsNotPositive_ShouldHaveValidationError(long maxArchiveBytes) { // Arrange - ThemeEngineOptionsDto options = new() { MaxArchiveBytes = maxArchiveBytes }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxArchiveBytes: maxArchiveBytes); // Act List result = _validator.Validate(options); @@ -94,7 +96,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenMaxExpandedBytesIsNotPositive_ShouldHaveValidationError(long maxExpandedBytes) { // Arrange - ThemeEngineOptionsDto options = new() { MaxExpandedBytes = maxExpandedBytes }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxExpandedBytes: maxExpandedBytes); // Act List result = _validator.Validate(options); @@ -110,7 +112,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenMaxSingleFileBytesIsNotPositive_ShouldHaveValidationError(long maxSingleFileBytes) { // Arrange - ThemeEngineOptionsDto options = new() { MaxSingleFileBytes = maxSingleFileBytes }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxSingleFileBytes: maxSingleFileBytes); // Act List result = _validator.Validate(options); @@ -126,7 +128,7 @@ public class ThemeEngineOptionsDtoValidatorTests public void Validate_WhenMaxEntriesIsNotPositive_ShouldHaveValidationError(int maxEntries) { // Arrange - ThemeEngineOptionsDto options = new() { MaxEntries = maxEntries }; + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxEntries: maxEntries); // Act List result = _validator.Validate(options); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs new file mode 100644 index 00000000..4ac21505 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeDetectionSyncJobTests.cs @@ -0,0 +1,402 @@ +#region ========================================================================= USING ===================================================================================== +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.Models.DTO.Themes; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using Lumina.Infrastructure.Core.Themes; +using Lumina.Infrastructure.Fixtures.Core.Themes; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeDetectionSyncJobTests : IDisposable +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IThemeRepository _mockThemeRepository; + private readonly IThemeService _mockThemeService; + private readonly ILogger _mockLogger; + private readonly ThemePackFixture _themePackFixture = new(); + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new(); + private readonly string _testRootPath; + + /// + /// Initializes a new instance of the class. + /// + public ThemeDetectionSyncJobTests() + { + _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-job-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_testRootPath); + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(new AsyncServiceScope(_mockServiceScope)); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockThemeRepository = Substitute.For(); + _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockThemeService = Substitute.For(); + _mockThemeService.HasThemePack(Arg.Any()).Returns(true); + _mockLogger = Substitute.For>(); + } + + /// + /// Cleans up the temporary storage used by the tests. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_testRootPath)) + Directory.Delete(_testRootPath, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the per-test temp directory + } + catch (UnauthorizedAccessException) + { + // best effort cleanup of the per-test temp directory + } + } + + [Fact] + public async Task StartAsync_WhenThereAreNoBundledThemesAndNoInstalledThemes_ShouldOnlySaveChanges() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeIsNotYetInstalled_ShouldInstallAndPersistTheTheme() + { + // Arrange + string archivePath = CreateBundledArchiveFile("bundled-theme"); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Created)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.Received(1).InsertAsync( + Arg.Is(theme => theme.ThemeId == "bundled-theme" + && theme.Name == manifest.Name + && theme.Description == manifest.Description + && theme.Version == manifest.Version + && theme.InstallSource == ThemeInstallSource.Bundled), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeIsAlreadyInstalled_ShouldSkipInstallingIt() + { + // Arrange + ThemeEntity existingTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([existingTheme])); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt() + { + // Arrange + ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isDeleted: true, installSource: ThemeInstallSource.Bundled); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([deletedTheme])); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\bundled-theme.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\bundled-theme.zip", Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledArchiveManifestCannotBeRead_ShouldSkipTheArchive() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["C:\\bundled\\broken.zip"]); + _mockThemeService.ReadManifestFromArchiveAsync("C:\\bundled\\broken.zip", Arg.Any()).Returns(Error.Failure("Theme.Files", "unreadable")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenBundledThemeInstallFails_ShouldNotPersistTheTheme() + { + // Arrange + string archivePath = CreateBundledArchiveFile("bundled-theme"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(_themeManifestDtoFixture.Create(id: "bundled-theme")); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Theme.Install", "install failed")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.DidNotReceiveWithAnyArgs().InsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenPersistingDetectedThemeFails_ShouldLogWarningAndContinue() + { + // Arrange + string archivePath = CreateBundledArchiveFile("bundled-theme"); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(id: "bundled-theme"); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(manifest); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(manifest); + _mockThemeRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Error.Failure("Database.Error", "failed to persist")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenReadingInstalledThemesFails_ShouldReturnWithoutPersistingChanges() + { + // Arrange + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Error.Failure("Database.Error", "failed to read themes")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + _mockThemeService.DidNotReceive().GetBundledThemeArchivePaths(); + await _mockUnitOfWork.DidNotReceiveWithAnyArgs().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenMissingBundledThemePackCanBeRestored_ShouldRestoreTheFiles() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("bundled-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Result.Success); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeService.Received(1).RestoreBundledThemeAsync("bundled-theme", Arg.Any()); + await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenMissingBundledThemePackCannotBeRestored_ShouldSoftDeleteTheTheme() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "bundled-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("bundled-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeService.RestoreBundledThemeAsync("bundled-theme", Arg.Any()).Returns(Error.Failure("Theme.Files", "restore failed")); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.ThemeId == "bundled-theme" && theme.IsDeleted && theme.IsCurrent == null), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenMissingUserThemePackExists_ShouldDeleteTheTheme() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("user-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Result.From(Result.Deleted)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); + await _mockThemeService.DidNotReceive().RestoreBundledThemeAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenDeletingMissingUserThemeFails_ShouldLogWarningAndContinue() + { + // Arrange + ThemeEntity brokenTheme = _themeEntityFixture.Create(themeId: "user-theme", installSource: ThemeInstallSource.Uploaded, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([brokenTheme])); + _mockThemeService.HasThemePack("user-theme").Returns(false); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.DeleteByIdAsync(brokenTheme.Id, Arg.Any()).Returns(Error.Failure("Database.Error", "delete failed")); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenTheme.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); + _mockThemeService.DefaultThemeId.Returns("default-theme"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenNoThemeIsCurrent_ShouldPreferTheConfiguredDefaultTheme() + { + // Arrange + ThemeEntity firstTheme = _themeEntityFixture.Create(themeId: "alpha-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "default-theme", installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([firstTheme, defaultTheme])); + _mockThemeService.DefaultThemeId.Returns("default-theme"); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.From(Result.Updated)); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(candidate => candidate.ThemeId == "default-theme" && candidate.IsCurrent == true), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenAThemeIsAlreadyCurrent_ShouldNotChangeActivation() + { + // Arrange + ThemeEntity theme = _themeEntityFixture.Create(themeId: "current-theme", isCurrent: true, includeIsCurrent: true, installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([theme])); + _mockThemeService.GetBundledThemeArchivePaths().Returns([]); + + // Act + await StartAndWaitForExecutionAsync(CreateSut()); + + // Assert + await _mockThemeRepository.DidNotReceiveWithAnyArgs().UpdateAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Invokes the protected of the job and awaits its completion. + /// + /// The job to execute. + private static async Task StartAndWaitForExecutionAsync(ThemeDetectionSyncJob sut) + { + MethodInfo executeAsyncMethod = typeof(ThemeDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; + Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!; + await executingTask; + } + + /// + /// Creates the system under test wired to the mocked dependencies. + /// + /// The created job instance. + private ThemeDetectionSyncJob CreateSut() + { + return new ThemeDetectionSyncJob(_mockServiceScopeFactory, _mockThemeService, _mockLogger); + } + + /// + /// Writes a bundled theme archive file into the per-test temporary directory. + /// + /// The theme id of the bundled archive. + /// The path of the written archive. + private string CreateBundledArchiveFile(string themeId) + { + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + string archivePath = Path.Combine(bundledPath, $"{themeId}.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: themeId)); + return archivePath; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs new file mode 100644 index 00000000..8600181e --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeMimeTypesTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.Themes; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeMimeTypesTests +{ + [Theory] + [InlineData("index.html", "text/html")] + [InlineData("index.htm", "text/html")] + [InlineData("style.css", "text/css")] + [InlineData("app.js", "application/javascript")] + [InlineData("manifest.json", "application/json")] + [InlineData("image.png", "image/png")] + [InlineData("photo.jpg", "image/jpeg")] + [InlineData("photo.jpeg", "image/jpeg")] + [InlineData("animation.gif", "image/gif")] + [InlineData("graphic.webp", "image/webp")] + [InlineData("icon.svg", "image/svg+xml")] + [InlineData("favicon.ico", "image/x-icon")] + [InlineData("font.woff", "font/woff")] + [InlineData("font.woff2", "font/woff2")] + [InlineData("font.ttf", "font/ttf")] + [InlineData("readme.txt", "text/plain")] + public void GetMimeType_WhenExtensionIsKnown_ShouldReturnMappedContentType(string filePath, string expectedContentType) + { + // Arrange + // filePath and expectedContentType are provided by the test data + + // Act + string result = ThemeMimeTypes.GetMimeType(filePath); + + // Assert + Assert.Equal(expectedContentType, result); + } + + [Fact] + public void GetMimeType_WhenExtensionIsUnknown_ShouldReturnApplicationOctetStream() + { + // Arrange + string filePath = "archive.unknown"; + + // Act + string result = ThemeMimeTypes.GetMimeType(filePath); + + // Assert + Assert.Equal("application/octet-stream", result); + } + + [Fact] + public void GetMimeType_WhenFileHasNoExtension_ShouldReturnApplicationOctetStream() + { + // Arrange + string filePath = "README"; + + // Act + string result = ThemeMimeTypes.GetMimeType(filePath); + + // Assert + Assert.Equal("application/octet-stream", result); + } + + [Fact] + public void GetMimeType_WhenExtensionIsMixedCase_ShouldResolveCaseInsensitively() + { + // Arrange + string filePath = "Photo.PNG"; + + // Act + string result = ThemeMimeTypes.GetMimeType(filePath); + + // Assert + Assert.Equal("image/png", result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs new file mode 100644 index 00000000..fd609d97 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -0,0 +1,1336 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Core.Themes; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Fixtures.Core.Themes; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeServiceTests : IDisposable +{ + private const string DEFAULT_TEMPLATE = "default template"; + private const string HOME_TEMPLATE = "home template"; + private const string LIBRARY_TEMPLATE = "library template"; + + private readonly string _testRootPath; + private readonly ThemeEngineOptionsDto _options; + private readonly ThemeService _sut; + private readonly ThemePackFixture _themePackFixture = new(); + private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeServiceTests() + { + _testRootPath = Path.Combine(Path.GetTempPath(), $"lumina-themes-{Guid.NewGuid():N}"); + Directory.CreateDirectory(_testRootPath); + _options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + _sut = CreateSut(_options); + } + + /// + /// Cleans up the temporary storage used by the tests. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_testRootPath)) + Directory.Delete(_testRootPath, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the per-test temp directory + } + catch (UnauthorizedAccessException) + { + // best effort cleanup of the per-test temp directory + } + } + + [Fact] + public void AllowThemeScripts_WhenConfiguredFalse_ShouldReturnFalse() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = false; + ThemeService sut = CreateSut(options); + + // Act + bool result = sut.AllowThemeScripts; + + // Assert + Assert.False(result); + } + + [Fact] + public void AllowThemeScripts_WhenConfiguredTrue_ShouldReturnTrue() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = true; + ThemeService sut = CreateSut(options); + + // Act + bool result = sut.AllowThemeScripts; + + // Assert + Assert.True(result); + } + + [Fact] + public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxArchiveBytes = 12345; + ThemeService sut = CreateSut(options); + + // Act + long result = sut.MaxArchiveBytes; + + // Assert + Assert.Equal(12345, result); + } + + [Fact] + public void DefaultThemeId_WhenConfigured_ShouldReturnConfiguredValue() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.DefaultThemeId = "custom-default"; + ThemeService sut = CreateSut(options); + + // Act + string result = sut.DefaultThemeId; + + // Assert + Assert.Equal("custom-default", result); + } + + [Fact] + public void GetBundledThemeArchivePaths_WhenBundledDirectoryDoesNotExist_ShouldReturnEmptyList() + { + // Arrange + // the bundled directory of the default options never exists + + // Act + IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void GetBundledThemeArchivePaths_WhenBundledDirectoryContainsZips_ShouldReturnSortedZipPaths() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "zeta.zip"), _themePackFixture.Create()); + File.WriteAllBytes(Path.Combine(bundledPath, "alpha.zip"), _themePackFixture.Create()); + File.WriteAllBytes(Path.Combine(bundledPath, "notes.txt"), Encoding.UTF8.GetBytes("not a theme archive")); + + // Act + IReadOnlyList result = _sut.GetBundledThemeArchivePaths(); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(Path.Combine(bundledPath, "alpha.zip"), result[0]); + Assert.Equal(Path.Combine(bundledPath, "zeta.zip"), result[1]); + } + + [Fact] + public async Task HasThemePack_WhenThemeIsInstalled_ShouldReturnTrue() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create()); + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.True(result); + } + + [Fact] + public void HasThemePack_WhenThemeIsNotInstalled_ShouldReturnFalse() + { + // Arrange + // nothing is installed + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.False(result); + } + + [Fact] + public void HasThemePack_WhenThemeDirectoryExistsButManifestIsMissing_ShouldReturnFalse() + { + // Arrange + Directory.CreateDirectory(Path.Combine(_options.StoragePath, "test-theme")); + + // Act + bool result = _sut.HasThemePack("test-theme"); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task InstallAsync_WhenArchiveIsValid_ShouldExtractThemeAndReturnManifest() + { + // Arrange + byte[] archive = _themePackFixture.Create(defaultTemplateContent: DEFAULT_TEMPLATE); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test-theme", result.Value.Id); + Assert.Equal("Test Theme", result.Value.Name); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "theme.json"))); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html"))); + Assert.True(File.Exists(Path.Combine(_options.StoragePath, "test-theme", "assets", "preview.png"))); + } + + [Fact] + public async Task InstallAsync_WhenThemeIsAlreadyInstalled_ShouldReplaceExistingThemeFiles() + { + // Arrange + byte[] firstArchive = _themePackFixture.Create(defaultTemplateContent: "first version"); + byte[] secondArchive = _themePackFixture.Create(defaultTemplateContent: "second version"); + + // Act + await InstallValidThemeAsync(firstArchive); + await InstallValidThemeAsync(secondArchive); + Result templateResult = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(templateResult.IsSuccess); + Assert.Equal("second version", templateResult.Value); + string[] themeDirectories = [.. Directory.GetDirectories(_options.StoragePath).Where(path => Path.GetFileName(path) != ".staging")]; + Assert.Single(themeDirectories); + Assert.Equal("test-theme", Path.GetFileName(themeDirectories[0])); + } + + [Fact] + public async Task InstallAsync_WhenArchiveExceedsMaxArchiveBytes_ShouldReturnArchiveTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxArchiveBytes = 128; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.TooLarge", result.FirstError.Code); + Assert.False(sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveStreamIsEmpty_ShouldReturnPackageInvalidError() + { + // Arrange + using MemoryStream emptyStream = new(); + + // Act + Result result = await _sut.InstallAsync(emptyStream, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("empty", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsNoEntries_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("no files", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() + { + // Arrange + byte[] archive = Encoding.UTF8.GetBytes("this is not a valid zip archive"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsPathTraversalEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("../evil.txt", "should not escape the package")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.False(_sut.HasThemePack("test-theme")); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsBackslashPathEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets\\..\\evil.txt", "should not escape the package")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenArchiveEntryIsOutsideAllowedLocations_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("notes/readme.txt", "files must live under templates or assets")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("outside the allowed", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsSymbolicLinkEntry_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("assets/link.png", "symlink target", UnixFileType: 0xA000)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("Symbolic links", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveContainsDuplicateEntryPaths_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", DEFAULT_TEMPLATE), + new("templates/default.html", "duplicate")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("duplicate path", result.FirstError.Description); + } + + [Fact] + public async Task InstallAsync_WhenArchiveExceedsMaxEntries_ShouldReturnTooManyEntriesError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxEntries = 2; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.TooManyEntries", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenArchiveFileExceedsMaxSingleFileBytes_ShouldReturnFileTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxSingleFileBytes = 10; + ThemeService sut = CreateSut(options); + string manifestJson = _themePackFixture.CreateManifestJson(); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("templates/default.html", new string('a', 64))); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.File.TooLarge", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenExpandedSizeExceedsMaxExpandedBytes_ShouldReturnExpandedTooLargeError() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.MaxSingleFileBytes = 400; + options.MaxExpandedBytes = 300; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.CreateArchive( + new("templates/default.html", new string('a', 200)), + new("templates/other.html", new string('b', 200))); + + // Act + Result result = await sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Archive.ExpandedTooLarge", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenSchemaVersionIsUnsupported_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(schemaVersion: 2); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "schemaVersion"); + } + + [Fact] + public async Task InstallAsync_WhenThemeIdIsNotKebabCase_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(themeId: "Test_Theme"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "kebab-case"); + } + + [Fact] + public async Task InstallAsync_WhenThemeIdIsTooLong_ShouldReturnPackageInvalidError() + { + // Arrange + string longThemeId = string.Join('-', Enumerable.Repeat("a", 33)); + byte[] archive = _themePackFixture.Create(themeId: longThemeId); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "kebab-case"); + } + + [Fact] + public async Task InstallAsync_WhenNameIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(name: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "name"); + } + + [Fact] + public async Task InstallAsync_WhenDescriptionIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(description: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "description"); + } + + [Fact] + public async Task InstallAsync_WhenAuthorIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(author: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "author"); + } + + [Fact] + public async Task InstallAsync_WhenVersionIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(version: string.Empty); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "version"); + } + + [Fact] + public async Task InstallAsync_WhenVersionIsNotSemanticVersion_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(version: "1.0"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "semantic version"); + } + + [Fact] + public async Task InstallAsync_WhenManifestDeclaresNoTemplates_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(templates: new Dictionary(StringComparer.OrdinalIgnoreCase)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "between 1 and 32"); + } + + [Fact] + public async Task InstallAsync_WhenManifestDeclaresTooManyTemplates_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary manyTemplates = new(StringComparer.OrdinalIgnoreCase); + for (int index = 0; index < 33; index++) + manyTemplates[$"template-{index}"] = $"templates/template-{index}.html"; + byte[] archive = _themePackFixture.Create(templates: manyTemplates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "between 1 and 32"); + } + + [Fact] + public async Task InstallAsync_WhenTemplateKeyIsInvalid_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html", + ["Bad Key"] = "templates/bad-key.html" + }; + byte[] archive = _themePackFixture.Create(templates: templates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "Template key"); + } + + [Fact] + public async Task InstallAsync_WhenTemplatePathIsOutsideTemplatesDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "assets/not-a-template.html" + }); + byte[] archive = _themePackFixture.CreateArchive( + new("theme.json", manifestJson), + new("assets/not-a-template.html", DEFAULT_TEMPLATE)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "under templates"); + } + + [Fact] + public async Task InstallAsync_WhenTemplateFileIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + string manifestJson = _themePackFixture.CreateManifestJson(templates: new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/missing.html" + }); + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", manifestJson)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "missing file"); + } + + [Fact] + public async Task InstallAsync_WhenManifestLacksDefaultTemplate_ShouldReturnPackageInvalidError() + { + // Arrange + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["home"] = "templates/home.html" + }; + byte[] archive = _themePackFixture.Create(templates: templates); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "default"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(preview: "templates/default.html"); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "preview"); + } + + [Fact] + public async Task InstallAsync_WhenPreviewFileIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(preview: "assets/missing.png", includePreviewAsset: false); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + AssertPackageInvalid(result, "preview"); + } + + [Fact] + public async Task InstallAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() + { + // Arrange + byte[] archive = _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "this is not json")); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + } + + [Fact] + public async Task InstallAsync_WhenManifestExceedsMaximumSize_ShouldReturnManifestTooLargeError() + { + // Arrange + byte[] archive = _themePackFixture.Create(description: new string('a', 70 * 1024)); + + // Act + Result result = await _sut.InstallAsync(new MemoryStream(archive), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.TooLarge", result.FirstError.Code); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveIsValid_ShouldReturnManifest() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "valid-theme.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.Create(themeId: "manifest-theme")); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("manifest-theme", result.Value.Id); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestEntryIsMissing_ShouldReturnPackageInvalidError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "no-manifest.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing theme.json", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenManifestIsNotValidJson_ShouldReturnInvalidJsonError() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "invalid-json.zip"); + File.WriteAllBytes(archivePath, _themePackFixture.CreateArchive(new ThemeArchiveEntry("theme.json", "not json"))); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Manifest.InvalidJson", result.FirstError.Code); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveIsNotAZip_ShouldReturnThemeArchiveNotReadable() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "not-a-zip.zip"); + File.WriteAllBytes(archivePath, Encoding.UTF8.GetBytes("plain text file")); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeArchiveNotReadable", result.FirstError.Description); + } + + [Fact] + public async Task ReadManifestFromArchiveAsync_WhenArchiveFileDoesNotExist_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string archivePath = Path.Combine(_testRootPath, "does-not-exist.zip"); + + // Act + Result result = await _sut.ReadManifestFromArchiveAsync(archivePath, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task DeleteAsync_WhenThemeIsInstalled_ShouldRemoveThemePack() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create()); + + // Act + Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.False(_sut.HasThemePack("test-theme")); + Assert.False(Directory.Exists(Path.Combine(_options.StoragePath, "test-theme"))); + } + + [Fact] + public async Task DeleteAsync_WhenThemeIsNotInstalled_ShouldReturnSuccess() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.DeleteAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.LoadManifestAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task LoadManifestAsync_WhenThemeIsInstalled_ShouldReturnManifest() + { + // Arrange + await InstallValidThemeAsync(_themePackFixture.Create(themeId: "loaded-theme")); + + // Act + Result result = await _sut.LoadManifestAsync("loaded-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("loaded-theme", result.Value.Id); + Assert.Equal("Test Theme", result.Value.Name); + } + + [Fact] + public async Task GetTemplateAsync_WhenPageKeyHasExplicitManifestTemplate_ShouldReturnExplicitTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(HOME_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenPageKeyHasNoExplicitTemplate_ShouldUseMirroredTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(LIBRARY_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenMirroredTemplateIsMissing_ShouldWalkUpToParentScope() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(LIBRARY_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenNoTemplateResolves_ShouldFallBackToDefaultTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(DEFAULT_TEMPLATE, result.Value); + } + + [Theory] + [InlineData("../secret")] // parent scope traversal attempt + [InlineData("/etc/passwd")] // rooted path attempt + [InlineData("templates//nested")] // empty segment attempt + public async Task GetTemplateAsync_WhenPageKeyAttemptsToEscapeTheThemePack_ShouldFallBackToDefaultTemplate(string pageKey) + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", pageKey, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(DEFAULT_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "home", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetTemplateAsync_WhenManifestTemplateFileWasRemoved_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "default.html")); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains("missing file", result.FirstError.Description); + } + + [Fact] + public async Task GetTemplateAsync_WhenMirroredTemplateFileWasRemoved_ShouldFallBackToDefaultTemplate() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + File.Delete(Path.Combine(_options.StoragePath, "test-theme", "templates", "library.html")); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "library/book", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(DEFAULT_TEMPLATE, result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenScriptsAreDisabled_ShouldStripScriptElements() + { + // Arrange + byte[] archive = _themePackFixture.Create(defaultTemplateContent: "

    safe content

    "); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("

    safe content

    ", result.Value); + } + + [Fact] + public async Task GetTemplateAsync_WhenScriptsAreEnabled_ShouldPreserveScriptElements() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = true; + ThemeService sut = CreateSut(options); + const string TEMPLATE_WITH_SCRIPT = "

    safe content

    "; + byte[] archive = _themePackFixture.Create(defaultTemplateContent: TEMPLATE_WITH_SCRIPT); + await InstallValidThemeAsync(archive, sut); + + // Act + Result result = await sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(TEMPLATE_WITH_SCRIPT, result.Value); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType() + { + // Arrange + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/style.css"] = "body { color: red; }" + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/style.css", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("text/css", result.Value.ContentType); + Assert.Equal("body { color: red; }", Encoding.UTF8.GetString(result.Value.Bytes)); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetPathIsOutsideAssetsDirectory_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = CreateThemeWithTemplates(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "templates/default.html", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetPathAttemptsTraversal_ShouldReturnPackageInvalidError() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "../secret.txt", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task GetAssetAsync_WhenAssetFileIsMissing_ShouldReturnThemeFilesUnreadable() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/missing.png", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetAssetAsync_WhenScriptsAreDisabledAndAssetIsJavaScript_ShouldReturnThemeFilesUnreadable() + { + // Arrange + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/app.js"] = "console.log('hello');" + }); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task GetAssetAsync_WhenScriptsAreEnabledAndAssetIsJavaScript_ShouldReturnJavaScriptContentType() + { + // Arrange + ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( + storagePath: Path.Combine(_testRootPath, "themes"), + bundledThemesPath: Path.Combine(_testRootPath, "bundled"), + defaultThemeId: "lumina-default", + maxArchiveBytes: 8 * 1024 * 1024, + maxExpandedBytes: 24 * 1024 * 1024, + maxSingleFileBytes: 6 * 1024 * 1024, + maxEntries: 250, + allowThemeScripts: false); + options.AllowThemeScripts = true; + ThemeService sut = CreateSut(options); + byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary + { + ["assets/app.js"] = "console.log('hello');" + }); + await InstallValidThemeAsync(archive, sut); + + // Act + Result result = await sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("application/javascript", result.Value.ContentType); + } + + [Fact] + public async Task BuildArchiveAsync_WhenThemeIsInstalled_ShouldReturnDownloadableZipArchive() + { + // Arrange + byte[] archive = _themePackFixture.Create(); + await InstallValidThemeAsync(archive); + + // Act + Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test-theme.zip", result.Value.FileName); + Assert.Equal("application/zip", result.Value.ContentType); + using MemoryStream stream = new(result.Value.Bytes); + using ZipArchive rebuiltArchive = new(stream, ZipArchiveMode.Read); + Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "theme.json"); + Assert.Contains(rebuiltArchive.Entries, entry => entry.FullName == "templates/default.html"); + } + + [Fact] + public async Task BuildArchiveAsync_WhenThemeIsNotInstalled_ShouldReturnThemeFilesUnreadable() + { + // Arrange + // nothing is installed + + // Act + Result result = await _sut.BuildArchiveAsync("test-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenBundledArchiveMatchesThemeId_ShouldInstallTheme() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "bundled-theme.zip"), _themePackFixture.Create(themeId: "bundled-theme")); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.True(_sut.HasThemePack("bundled-theme")); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenNoBundledArchiveMatches_ShouldReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "other-theme.zip"), _themePackFixture.Create(themeId: "other-theme")); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + } + + [Fact] + public async Task RestoreBundledThemeAsync_WhenBundledArchiveManifestIsInvalid_ShouldSkipArchiveAndReturnThemeFilesUnreadable() + { + // Arrange + string bundledPath = Path.Combine(_testRootPath, "bundled"); + Directory.CreateDirectory(bundledPath); + File.WriteAllBytes(Path.Combine(bundledPath, "broken.zip"), _themePackFixture.CreateArchive(new ThemeArchiveEntry("templates/default.html", DEFAULT_TEMPLATE))); + + // Act + Result result = await _sut.RestoreBundledThemeAsync("bundled-theme", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); + Assert.False(_sut.HasThemePack("bundled-theme")); + } + + /// + /// Creates a valid theme pack that declares the default, home and library templates and their files. + /// + /// The created theme pack ZIP archive. + private byte[] CreateThemeWithTemplates() + { + Dictionary templates = new(StringComparer.OrdinalIgnoreCase) + { + ["default"] = "templates/default.html", + ["home"] = "templates/home.html" + }; + + return _themePackFixture.Create( + templates: templates, + additionalFiles: new Dictionary + { + ["templates/library.html"] = LIBRARY_TEMPLATE + }); + } + + /// + /// Installs the provided theme archive using the provided service and asserts that the install succeeds. + /// + /// The theme pack ZIP archive to install. + /// The service to install with, defaults to the shared system under test. + /// The task representing the asynchronous operation. + private async Task InstallValidThemeAsync(byte[] archive, ThemeService? service = null) + { + ThemeService themeService = service ?? _sut; + using MemoryStream stream = new(archive); + Result result = await themeService.InstallAsync(stream, CancellationToken.None); + Assert.True(result.IsSuccess, result.Match( + success => string.Empty, + errors => $"Expected a successful install but got: {errors.First().Code}: {errors.First().Description}")); + } + + /// + /// Asserts that the result is a package invalid failure whose description contains the provided fragment. + /// + /// The result to assert on. + /// The fragment the error description must contain. + private static void AssertPackageInvalid(Result result, string expectedDescriptionFragment) + { + Assert.True(result.IsFailure); + Assert.Equal("Theme.Package.Invalid", result.FirstError.Code); + Assert.Contains(expectedDescriptionFragment, result.FirstError.Description); + } + + /// + /// Creates a instance using the provided options. + /// + /// The theme engine options to configure the service with. + /// The created service. + private static ThemeService CreateSut(ThemeEngineOptionsDto options) + { + ILogger logger = Substitute.For>(); + return new ThemeService(Options.Create(options), logger); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..18173544 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,202 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.DeleteTheme; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.DeleteTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly DeleteThemeEndpoint _sut; + private readonly DeleteThemeRequestFixture _deleteThemeRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContentResult() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsForbiddenError_ShouldReturnProblemResult() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.LastBundledThemeCannotBeDeleted; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Forbidden", problemDetailsBody.Title); + Assert.Equal("LastBundledThemeCannotBeDeleted", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteThemeCommandToHandler() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..65fe85bb --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,178 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.Themes.Management.Commands.InstallTheme; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.Extensions.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.InstallTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly InstallThemeEndpoint _sut; + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public InstallThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenArchiveUploaded_ShouldReturnOkResultWithInstalledTheme() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenArchiveUploaded_ShouldSendInstallThemeCommandWithUploadedStreamAndFileName() + { + // Arrange + byte[] content = [1, 2, 3, 4]; + string fileName = "theme-pack.zip"; + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeResponseFixture.Create())); + ConfigureFormWithArchive(content, fileName); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.FileName == fileName && + command.Archive != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldSendInstallThemeCommandWithNullArchiveAndFileName() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + ConfigureFormWithoutFiles(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Archive == null && + command.FileName == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeResponseFixture.Create()); + }, callInfo.Arg())); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + private void ConfigureFormWithArchive(byte[] content, string fileName) + { + // the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution + MemoryStream archiveStream = new(content); + IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName); + FormFileCollection files = [formFile]; + IFormCollection form = new FormCollection([], files); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + // a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the + // request machinery, which would bypass a mocked feature and parse the (empty) request body + _sut.HttpContext.Features.Set(new FormFeature(form)); + } + + private void ConfigureFormWithoutFiles() + { + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..301621b3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.SetCurrentTheme; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Management.SetCurrentTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly SetCurrentThemeEndpoint _sut; + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithActivatedTheme() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSetCurrentThemeCommandToHandler() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..e9cedbb9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetCurrentTheme; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetCurrentTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetCurrentThemeEndpoint _sut; + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetCurrentThemeEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCurrentTheme() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeResponse expectedResponse = _themeResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetCurrentThemeQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs new file mode 100644 index 00000000..97a35cd2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -0,0 +1,160 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeArchive; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeArchive; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeArchiveEndpoint _sut; + private readonly GetThemeArchiveRequestFixture _getThemeArchiveRequestFixture = new(); + private readonly ThemeArchiveResponseFixture _themeArchiveResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeArchiveEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnFileResultWithThemeArchive() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ThemeArchiveResponse expectedResponse = _themeArchiveResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult fileResult = Assert.IsType(result); + Assert.Equal(expectedResponse.Bytes, fileResult.FileContents.ToArray()); + Assert.Equal(expectedResponse.ContentType, fileResult.ContentType); + Assert.Equal(expectedResponse.FileName, fileResult.FileDownloadName); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeArchiveQueryToHandler() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeArchiveResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.ThemeId == request.ThemeId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeArchiveResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs new file mode 100644 index 00000000..66443e2f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeAsset; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeAsset; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeAssetEndpoint _sut; + private readonly GetThemeAssetRequestFixture _getThemeAssetRequestFixture = new(); + private readonly ThemeAssetResponseFixture _themeAssetResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeAssetEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnFileResultWithThemeAsset() + { + // Arrange + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ThemeAssetResponse expectedResponse = _themeAssetResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + FileContentHttpResult fileResult = Assert.IsType(result); + Assert.Equal(expectedResponse.Bytes, fileResult.FileContents.ToArray()); + Assert.Equal(expectedResponse.ContentType, fileResult.ContentType); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeAssetPathCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeAssetPathCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeAssetQueryToHandler() + { + // Arrange + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeAssetResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.ThemeId == request.ThemeId && + query.AssetPath == request.AssetPath), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeAssetResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs new file mode 100644 index 00000000..ab0e92d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeSettings; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeSettingsEndpoint _sut; + private readonly ThemeSettingsResponseFixture _themeSettingsResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeSettingsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemeSettings() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + ThemeSettingsResponse expectedResponse = _themeSettingsResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeSettingsQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeSettingsResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeSettingsResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs new file mode 100644 index 00000000..80a3de9e --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate; +using Lumina.Contracts.Fixtures.Core.Requests.Themes; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemeTemplate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetThemeTemplateEndpoint _sut; + private readonly GetThemeTemplateRequestFixture _getThemeTemplateRequestFixture = new(); + private readonly ThemeTemplateResponseFixture _themeTemplateResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemeTemplateEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemeTemplate() + { + // Arrange + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ThemeTemplateResponse expectedResponse = _themeTemplateResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ThemeIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeTemplateQueryToHandler() + { + // Arrange + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_themeTemplateResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.ThemeId == request.ThemeId && + query.PageKey == request.PageKey), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_themeTemplateResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..7af2cec2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Themes.Management.Queries.GetThemes; +using Lumina.Contracts.Fixtures.Core.Responses.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemes; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Themes.Queries.GetThemes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetThemesEndpoint _sut; + private readonly ThemeResponseFixture _themeResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemesEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithThemes() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _themeResponseFixture.CreateMany(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Themes.ThemeNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ThemeNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemesQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query != null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs new file mode 100644 index 00000000..8c588a76 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Services; +using Microsoft.Extensions.Caching.Hybrid; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeCachePreferenceServiceTests +{ + private readonly HybridCache _hybridCache; + private readonly ThemeCachePreferenceService _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeCachePreferenceServiceTests() + { + ServiceCollection services = new(); + services.AddHybridCache(); + _hybridCache = services.BuildServiceProvider().GetRequiredService(); + _sut = new ThemeCachePreferenceService(_hybridCache); + } + + [Fact] + public async Task GetAsync_WhenNoPreferenceStored_ShouldReturnDefaultValue() + { + // Arrange + Guid userId = Guid.NewGuid(); + + // Act + bool result = await _sut.GetAsync(userId, defaultValue: true, CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task GetAsync_WhenNoPreferenceStoredAndDefaultIsFalse_ShouldReturnFalse() + { + // Arrange + Guid userId = Guid.NewGuid(); + + // Act + bool result = await _sut.GetAsync(userId, defaultValue: false, CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task SetAsync_WhenPreferenceStored_ShouldReturnTheStoredValue() + { + // Arrange + Guid userId = Guid.NewGuid(); + + // Act + await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None); + bool result = await _sut.GetAsync(userId, defaultValue: false, CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task SetAsync_WhenPreferenceOverwritten_ShouldReturnTheNewValue() + { + // Arrange + Guid userId = Guid.NewGuid(); + + // Act + await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None); + await _sut.SetAsync(userId, isEnabled: false, CancellationToken.None); + bool result = await _sut.GetAsync(userId, defaultValue: true, CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task SetAsync_WhenStoredForOneUser_ShouldNotAffectAnotherUser() + { + // Arrange + Guid firstUserId = Guid.NewGuid(); + Guid secondUserId = Guid.NewGuid(); + + // Act + await _sut.SetAsync(firstUserId, isEnabled: true, CancellationToken.None); + bool firstUserResult = await _sut.GetAsync(firstUserId, defaultValue: false, CancellationToken.None); + bool secondUserResult = await _sut.GetAsync(secondUserId, defaultValue: false, CancellationToken.None); + + // Assert + Assert.True(firstUserResult); + Assert.False(secondUserResult); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..f659d122 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeleteThemeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldDeleteThemeAndReturnSuccessJson() + { + // Arrange + string themeId = "editorial-paper"; + + // Act + IResult result = await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body)) + { + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + } + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldDeleteThemeWithResolvedEndpoint() + { + // Arrange + string themeId = "editorial-paper"; + string expectedEndpoint = ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId); + + // Act + await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + } + + [Theory] + [InlineData(null)] // missing theme id + [InlineData("")] // empty theme id + [InlineData(" ")] // whitespace theme id + public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) + { + // Act + IResult result = await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs new file mode 100644 index 00000000..3176061a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DownloadThemeEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DownloadThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldReturnZipFileWithResolvedFileName() + { + // Arrange + string themeId = "editorial-paper"; + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(new BlobDataDto { Data = [0x50, 0x4B, 0x03, 0x04], ContentType = "application/zip" }); + + // Act + IResult result = await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None); + + // Assert + FileStreamHttpResult fileResult = Assert.IsType(result); + Assert.Equal("application/zip", fileResult.ContentType); + Assert.Equal($"{themeId}.zip", fileResult.FileDownloadName); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldFetchArchiveWithResolvedEndpoint() + { + // Arrange + string themeId = "editorial-paper"; + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId); + _mockApiHttpClient.GetBlobAsync(expectedEndpoint, Arg.Any()) + .Returns(new BlobDataDto { Data = [1, 2, 3], ContentType = "application/zip" }); + + // Act + await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); + } + + [Theory] + [InlineData(null)] // missing theme id + [InlineData("")] // empty theme id + [InlineData(" ")] // whitespace theme id + public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) + { + // Act + IResult result = await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().GetBlobAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..896dc807 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.GetThemes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetThemesEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetThemesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsThemes_ShouldReturnSuccessJsonWithThemeAdminData() + { + // Arrange + ThemeResponseDto[] themes = + [ + _themeResponseDtoFixture.Create(themeId: "editorial-paper"), + _themeResponseDtoFixture.Create(themeId: "lumina-default") + ]; + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default"); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns(themes); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(currentTheme); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) + .Returns(_themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using (JsonDocument jsonDocument = JsonDocument.Parse(body)) + { + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(2, data.GetProperty("themes").GetArrayLength()); + Assert.Equal("editorial-paper", data.GetProperty("themes")[0].GetProperty("id").GetString()); + Assert.Equal("lumina-default", data.GetProperty("currentThemeId").GetString()); + Assert.True(data.GetProperty("allowThemeScripts").GetBoolean()); + Assert.Equal(10 * 1024 * 1024, data.GetProperty("maxArchiveBytes").GetInt64()); + Assert.Equal(10.0, data.GetProperty("maxArchiveMegabytes").GetDouble()); + } + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldLoadThemesCurrentThemeAndSettings() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([.. _themeResponseDtoFixture.CreateMany(2)]); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) + .Returns(_themeSettingsResponseDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..b7678639 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.Extensions.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.InstallTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly InstallThemeEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public InstallThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenArchiveUploaded_ShouldInstallThemeAndReturnSuccessJson() + { + // Arrange + ThemeResponseDto installedTheme = _themeResponseDtoFixture.Create(themeId: "installed-theme"); + _mockApiHttpClient.PostMultipartAsync(ApiRoutes.Themes.INSTALL_THEME, Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(installedTheme); + ConfigureFormWithArchive([1, 2, 3, 4], "theme-pack.zip"); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using (JsonDocument jsonDocument = JsonDocument.Parse(body)) + { + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("installed-theme", jsonDocument.RootElement.GetProperty("data").GetProperty("id").GetString()); + } + + await _mockApiHttpClient.Received(1).PostMultipartAsync( + ApiRoutes.Themes.INSTALL_THEME, + Arg.Any(), + "theme-pack.zip", + "archive", + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenNoArchiveUploaded_ShouldReturnProblemWithBadRequest() + { + // Arrange + IFormFeature formFeature = Substitute.For(); + formFeature.Form.Returns(new FormCollection([])); + _sut.HttpContext.Features.Set(formFeature); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().PostMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + private void ConfigureFormWithArchive(byte[] content, string fileName) + { + // the stream stays open for the duration of the test, since the endpoint reads it through the form file during execution + MemoryStream archiveStream = new(content); + IFormFile formFile = new FormFile(archiveStream, 0, content.Length, "archive", fileName); + FormFileCollection files = [formFile]; + IFormCollection form = new FormCollection([], files); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + // a real FormFeature is used instead of a substitute, because the endpoint execution reads the form through the + // request machinery, which would bypass a mocked feature and parse the (empty) request body + _sut.HttpContext.Features.Set(new FormFeature(form)); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..667c03a7 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes.SetCurrentTheme; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly SetCurrentThemeEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetCurrentThemeEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeIdProvided_ShouldSetCurrentThemeAndReturnSuccessJson() + { + // Arrange + string themeId = "editorial-paper"; + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + IResult result = await _sut.ExecuteAsync(new SetCurrentThemeRequest(themeId), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body)) + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Themes.SET_CURRENT_THEME, + Arg.Is(payload => (payload.GetType().GetProperty("ThemeId")!.GetValue(payload) as string) == themeId), + Arg.Any()); + } + + [Theory] + [InlineData(null)] // missing theme id + [InlineData("")] // empty theme id + [InlineData(" ")] // whitespace theme id + public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) + { + // Act + IResult result = await _sut.ExecuteAsync(new SetCurrentThemeRequest(themeId), CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().PutAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs new file mode 100644 index 00000000..cabba6af --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Admin.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemesIndexViewEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemesIndexViewEndpoint _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemesIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = Factory.Create(themeService); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemesAvailable_ShouldReturnRazorViewResult() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([.. _themeResponseDtoFixture.CreateMany(2)]); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldLoadThemesAndCurrentThemeFromService() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([.. _themeResponseDtoFixture.CreateMany(2)]); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs new file mode 100644 index 00000000..f8d7080d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeLayoutRendererTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ICompositeViewEngine _mockViewEngine; + private readonly ITempDataProvider _mockTempDataProvider; + private readonly IServiceProvider _mockServiceProvider; + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly IUrlService _mockUrlService; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IView _mockHeadView; + private readonly IView _mockAudioPlayerView; + private readonly IView _mockScriptsView; + private readonly IView _mockNavMenuView; + private readonly ThemeLayoutRenderer _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeLayoutRendererTests() + { + _mockApiHttpClient = Substitute.For(); + _mockViewEngine = Substitute.For(); + _mockTempDataProvider = Substitute.For(); + _mockTempDataProvider.LoadTempData(Arg.Any()).Returns(new Dictionary()); + _mockServiceProvider = Substitute.For(); + _mockServiceProvider.GetService(typeof(IModelMetadataProvider)).Returns(new EmptyModelMetadataProvider()); + _mockHttpContextAccessor = Substitute.For(); + + _mockUrlService = Substitute.For(); + _mockUrlService.GetAbsoluteUrl(Arg.Any(), Arg.Any()).Returns("http://localhost/en-us"); + _mockStringLocalizer = CreateLocalizer(); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockAuthorizationService = Substitute.For(); + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + + _mockHeadView = CreateView(""); + _mockAudioPlayerView = CreateView(""); + _mockScriptsView = CreateView(""); + _mockNavMenuView = CreateView(""); + _mockViewEngine.FindView(Arg.Any(), "_ThemeLayoutHead", false).Returns(ViewEngineResult.Found("_ThemeLayoutHead", _mockHeadView)); + _mockViewEngine.FindView(Arg.Any(), "_AudioPlayer", false).Returns(ViewEngineResult.Found("_AudioPlayer", _mockAudioPlayerView)); + _mockViewEngine.FindView(Arg.Any(), "_ThemeLayoutScripts", false).Returns(ViewEngineResult.Found("_ThemeLayoutScripts", _mockScriptsView)); + _mockViewEngine.FindView(Arg.Any(), "_NavMenu", false).Returns(ViewEngineResult.Found("_NavMenu", _mockNavMenuView)); + + RazorViewToStringRenderer viewRenderer = new(_mockViewEngine, _mockTempDataProvider, _mockServiceProvider, _mockHttpContextAccessor); + ThemeNavBuilder navBuilder = new(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor); + ThemeService themeService = new(_mockApiHttpClient); + _sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, _mockHttpContextAccessor); + } + + [Fact] + public async Task RenderAsync_WhenUserIsAuthenticated_ShouldRenderLayoutWithAllPlaceholders() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}"); + ThemeLayoutPageDto page = new("My Page", "
    ", ""); + + // Act + Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("My Page|/theme-assets/editorial/assets||nav:Lumina|
    ||||", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenUserIsAnonymous_ShouldRenderEmptyAudioPlayerAndBottomMainStyle() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); + ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}"); + ThemeLayoutPageDto page = new("My Page", "
    ", ""); + + // Act + Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("My Page|/theme-assets/editorial/assets||nav:Lumina|
    ||||bottom: 0px;", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenNavTemplateCannotBeRendered_ShouldFallBackToApplicationNavMenu() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); + ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "{{#unclosed}}"); + ThemeLayoutPageDto page = new("My Page", "
    ", string.Empty); + + // Act + Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("My Page|", result.Value); + _mockViewEngine.Received(1).FindView(Arg.Any(), "_NavMenu", false); + } + + [Fact] + public async Task RenderAsync_WhenCalled_ShouldResolveLayoutAndNavDocumentsFromTheme() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); + ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + SetupRenderDocuments(theme, layoutTemplate: "{{title}}", navTemplate: "nav:{{siteName}}"); + ThemeLayoutPageDto page = new("My Page", "
    ", string.Empty); + string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "editorial") + .Replace("{*pageKey}", "shared/layout"); + string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "editorial") + .Replace("{*pageKey}", "shared/nav-menu"); + + // Act + await _sut.RenderAsync(page, "editorial", CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(layoutEndpoint, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(navEndpoint, Arg.Any()); + } + + private void SetupRenderDocuments(ThemeResponseDto theme, string layoutTemplate, string navTemplate) + { + string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", theme.ThemeId) + .Replace("{*pageKey}", "shared/layout"); + string navEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", theme.ThemeId) + .Replace("{*pageKey}", "shared/nav-menu"); + _mockApiHttpClient.GetAsync(layoutEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, layoutTemplate)); + _mockApiHttpClient.GetAsync(navEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, navTemplate)); + } + + private static IView CreateView(string markup) + { + IView view = Substitute.For(); + view.RenderAsync(Arg.Any()) + .Returns(callInfo => + { + callInfo.Arg().Writer.Write(markup); + return Task.CompletedTask; + }); + return view; + } + + private static IStringLocalizer CreateLocalizer() + { + IStringLocalizer localizer = Substitute.For(); + localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + return localizer; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs new file mode 100644 index 00000000..0ed4c0bc --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeNavBuilderTests.cs @@ -0,0 +1,251 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeNavBuilderTests +{ + private readonly IUrlService _mockUrlService; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly ThemeNavBuilder _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeNavBuilderTests() + { + _mockUrlService = Substitute.For(); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockAuthorizationService = Substitute.For(); + _mockHttpContextAccessor = Substitute.For(); + _sut = new ThemeNavBuilder(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor); + + StubSiteUrls(); + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(Arg.Any(), Arg.Any()).Returns(false); + } + + [Fact] + public async Task BuildAsync_WhenUserIsAnonymous_ShouldNotIncludeAdministratorLibraryOrToolsSections() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + Assert.Null(FindSection(result, "Localized-Administrator")); + Assert.Null(FindSection(result, "Localized-Library")); + Assert.Null(FindSection(result, "Localized-Tools")); + Assert.NotNull(FindSection(result, "Localized-Language")); + Assert.NotNull(FindSection(result, "Localized-Help")); + } + + [Fact] + public async Task BuildAsync_WhenUserIsAnonymous_ShouldIncludeLoginEntryInsteadOfLogoutEntry() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto accountSection = FindSection(result, "Localized-Account")!; + Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Login"); + Assert.DoesNotContain(accountSection.Items, entry => entry.Label == "Localized-Logout"); + Assert.Equal("http://localhost/en-us/auth/login", accountSection.Items.First(entry => entry.Label == "Localized-Login").Url); + } + + [Fact] + public async Task BuildAsync_WhenUserIsAuthenticated_ShouldIncludeAccountLinksAndLibrarySection() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto accountSection = FindSection(result, "Localized-Account")!; + Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Logout"); + Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Register"); + Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-ChangePassword"); + Assert.Contains(accountSection.Items, entry => entry.Label == "Localized-Profile"); + Assert.DoesNotContain(accountSection.Items, entry => entry.Label == "Localized-Login"); + + ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!; + Assert.Contains(librarySection.Items, entry => entry.Label == "Localized-ManageLibraries"); + Assert.DoesNotContain(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary"); + } + + [Fact] + public async Task BuildAsync_WhenUserIsAdmin_ShouldIncludeAdministratorSection() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(true); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto administratorSection = FindSection(result, "Localized-Administrator")!; + Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-ManageRoles" && entry.Url == "http://localhost/en-us/admin/manage-roles"); + Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-ManagePermissions" && entry.Url == "http://localhost/en-us/admin/manage-permissions"); + Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-Plugins" && entry.Url == "http://localhost/en-us/admin/manage-plugins"); + Assert.Contains(administratorSection.Items, entry => entry.Label == "Localized-Themes" && entry.Url == "http://localhost/en-us/admin/manage-themes"); + await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any()); + } + + [Fact] + public async Task BuildAsync_WhenUserCanCreateLibraries_ShouldIncludeAddNewLibraryEntry() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(true); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!; + Assert.Contains(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary" && entry.Url == "http://localhost/en-us/libraries/manage/item"); + await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()); + } + + [Fact] + public async Task BuildAsync_WhenUserCannotCreateLibraries_ShouldNotIncludeAddNewLibraryEntry() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!; + Assert.DoesNotContain(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary"); + } + + [Fact] + public async Task BuildAsync_WhenRequestHasPathAndQuery_ShouldKeepEscapedReturnUrlInLanguageEntries() + { + // Arrange + DefaultHttpContext httpContext = TestHttpContextFactory.Create(user: null); + httpContext.Request.Path = "/en-us"; + httpContext.Request.QueryString = new QueryString("?page=1"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto languageSection = FindSection(result, "Localized-Language")!; + Assert.Equal(9, languageSection.Items.Count); + Assert.All(languageSection.Items, entry => + { + Assert.Equal("lang-set", entry.CssClass); + Assert.Contains("returnUrl=%2Fen-us%3Fpage%3D1", entry.Url); + }); + Assert.Contains(languageSection.Items, entry => entry.Label == "English" && entry.Url!.StartsWith("http://localhost/en-us/tools/language/set-language?newCulture=en-us", StringComparison.Ordinal)); + } + + [Fact] + public async Task BuildAsync_WhenAuthenticated_ShouldIncludeSettingsEntryInDesktopToolsSection() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto toolsSection = FindSection(result, "Localized-Tools", isMobile: false)!; + Assert.Contains(toolsSection.Items, entry => entry.Label == "Localized-Settings" && entry.Url == "http://localhost/en-us/tools/settings"); + // the desktop tools section hosts the language submenu while the mobile menu has a dedicated language section + Assert.Contains(toolsSection.Items, entry => entry.Label == "Localized-Language" && entry.Children.Count == 9); + } + + [Fact] + public async Task BuildAsync_WhenCalled_ShouldCreateLocalizerForTheNavigationResources() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); + + // Act + await _sut.BuildAsync(CancellationToken.None); + + // Assert + _mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared._NavMenu", "Lumina.Presentation.Web"); + } + + [Fact] + public async Task BuildAsync_WhenAdminCreatesLibraries_ShouldAddAddNewLibraryEntryOnce() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); + _mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any()).Returns(true); + _mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any()).Returns(true); + + // Act + ThemeNavMenuDto result = await _sut.BuildAsync(CancellationToken.None); + + // Assert + ThemeNavSectionDto librarySection = FindSection(result, "Localized-Library")!; + Assert.Single(librarySection.Items, entry => entry.Label == "Localized-AddNewLibrary"); + } + + private void StubSiteUrls() + { + _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW).Returns("http://localhost/en-us/auth/login"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW).Returns("http://localhost/en-us/auth/recover-password"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT).Returns("http://localhost/en-us/auth/logout"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW).Returns("http://localhost/en-us/auth/change-password"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW).Returns("http://localhost/en-us/auth/profile"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES).Returns("http://localhost/en-us/admin/manage-roles"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS).Returns("http://localhost/en-us/admin/manage-permissions"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX).Returns("http://localhost/en-us/admin/manage-plugins"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_THEMES).Returns("http://localhost/en-us/admin/manage-themes"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX).Returns("http://localhost/en-us/libraries/manage"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY).Returns("http://localhost/en-us/libraries/manage/item"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX).Returns("http://localhost/en-us/tools/settings"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE).Returns("http://localhost/en-us/tools/language/set-language"); + } + + private static ThemeNavSectionDto? FindSection(ThemeNavMenuDto menu, string label, bool isMobile = true) + { + IReadOnlyList sections = isMobile ? menu.MobileSections : menu.MenubarSections; + return sections.FirstOrDefault(section => section.Label == label); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs new file mode 100644 index 00000000..4fc1b04b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageDataFactoryTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemePageDataFactoryTests +{ + private readonly IStringLocalizer _mockStringLocalizer; + + /// + /// Initializes a new instance of the class. + /// + public ThemePageDataFactoryTests() + { + _mockStringLocalizer = Substitute.For(); + } + + [Fact] + public void CreateLocalizedStrings_WhenLocalizerProvidesStrings_ShouldReturnDictionaryKeyedByName() + { + // Arrange + LocalizedString[] localizedStrings = + [ + new("Title", "The Title"), + new("Search", "Search") + ]; + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns(localizedStrings); + + // Act + Dictionary result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Title", result["Title"]); + Assert.Equal("Search", result["Search"]); + _mockStringLocalizer.Received(1).GetAllStrings(includeParentCultures: true); + } + + [Fact] + public void CreateLocalizedStrings_WhenLocalizerProvidesNoStrings_ShouldReturnEmptyDictionary() + { + // Arrange + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns([]); + + // Act + Dictionary result = ThemePageDataFactory.CreateLocalizedStrings(_mockStringLocalizer); + + // Assert + Assert.Empty(result); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs new file mode 100644 index 00000000..cc4282f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemePageRendererTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemePageRenderer _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemePageDtoFixture _themePageDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemePageRendererTests() + { + _mockApiHttpClient = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + _sut = new ThemePageRenderer(themeService, new ThemeTemplateEngine()); + } + + [Fact] + public async Task RenderAsync_WhenThemeIdProvided_ShouldRenderPageAndPopulateThemeMetadata() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper"); + string pageKey = "home/index"; + string template = "

    {{title}}

    {{#scripts}}{{/scripts}}"; + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "editorial-paper") + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, template)); + ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); + + // Act + Result result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("

    Home

    ", result.Value.Content); + Assert.Equal("", result.Value.Script); + Assert.Equal("editorial-paper", model.ThemeId); + Assert.Equal("/theme-assets/editorial-paper/assets", model.AssetBase); + Assert.StartsWith("script_", model.ScriptId); + await _mockApiHttpClient.DidNotReceive().GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + [Fact] + public async Task RenderAsync_WhenThemeIdMissing_ShouldResolveCurrentThemeBeforeRendering() + { + // Arrange + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default"); + string pageKey = "home/index"; + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "lumina-default") + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(currentTheme); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(currentTheme, "{{title}}")); + ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); + + // Act + Result result = await _sut.RenderAsync(model, null, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("lumina-default", model.ThemeId); + Assert.Equal("Home", result.Value.Content); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + [Fact] + public async Task RenderAsync_WhenTemplateRenderingFails_ShouldReturnFailure() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper"); + string pageKey = "home/index"; + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "editorial-paper") + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(new ThemeTemplateResponseDto(theme, "{{#unclosed}}")); + ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); + + // Act + Result result = await _sut.RenderAsync(model, "editorial-paper", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs new file mode 100644 index 00000000..c24c55f0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeServiceTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemeService _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new(); + private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeServiceTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = new ThemeService(_mockApiHttpClient); + } + + [Fact] + public async Task GetThemesAsync_WhenApiReturnsThemes_ShouldReturnMappedThemeInfoList() + { + // Arrange + ThemeResponseDto[] themes = + [ + _themeResponseDtoFixture.Create(themeId: "editorial-paper", name: "Editorial Paper", previewPath: "preview.png", includePreviewPath: true, installSource: ThemeInstallSource.Bundled), + _themeResponseDtoFixture.Create(themeId: "lumina-default", name: "Lumina Default", previewPath: "preview.png", includePreviewPath: true, installSource: ThemeInstallSource.Uploaded) + ]; + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns(themes); + + // Act + IReadOnlyList result = await _sut.GetThemesAsync(CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("editorial-paper", result[0].Id); + Assert.Equal("Editorial Paper", result[0].Name); + Assert.Equal(themes[0].Description, result[0].Description); + Assert.Equal(themes[0].Author, result[0].Author); + Assert.Equal(themes[0].Version, result[0].Version); + Assert.Equal("/theme-assets/editorial-paper/preview.png", result[0].PreviewUrl); + Assert.True(result[0].IsBundled); + Assert.False(result[1].IsBundled); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()); + } + + [Fact] + public async Task GetThemesAsync_WhenThemeHasNoPreviewPath_ShouldReturnPlaceholderPreviewUrl() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: null); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEMES, Arg.Any()) + .Returns([theme]); + + // Act + IReadOnlyList result = await _sut.GetThemesAsync(CancellationToken.None); + + // Assert + Assert.Equal("/admin/theme-placeholder.svg", result[0].PreviewUrl); + } + + [Fact] + public async Task GetCurrentThemeAsync_WhenApiReturnsCurrentTheme_ShouldReturnMappedThemeInfo() + { + // Arrange + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial-paper", previewPath: "preview.png", includePreviewPath: true); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(theme); + + // Act + ThemeInfoDto result = await _sut.GetCurrentThemeAsync(CancellationToken.None); + + // Assert + Assert.Equal("editorial-paper", result.Id); + Assert.Equal(theme.Name, result.Name); + Assert.Equal("/theme-assets/editorial-paper/preview.png", result.PreviewUrl); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + [Fact] + public async Task GetThemeSettingsAsync_WhenApiReturnsSettings_ShouldReturnSettings() + { + // Arrange + ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) + .Returns(settings); + + // Act + ThemeSettingsResponseDto result = await _sut.GetThemeSettingsAsync(CancellationToken.None); + + // Assert + Assert.Equal(settings, result); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()); + } + + [Fact] + public async Task SetCurrentThemeAsync_WhenCalled_ShouldSendThemeIdToApi() + { + // Arrange + string themeId = "editorial-paper"; + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_themeResponseDtoFixture.Create()); + + // Act + await _sut.SetCurrentThemeAsync(themeId, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Themes.SET_CURRENT_THEME, + Arg.Is(payload => payload.GetType().GetProperty("ThemeId")!.GetValue(payload)!.ToString()! == themeId), + Arg.Any()); + } + + [Fact] + public async Task InstallAsync_WhenCalled_ShouldUploadArchiveToInstallEndpoint() + { + // Arrange + ThemeResponseDto installedTheme = _themeResponseDtoFixture.Create(themeId: "installed-theme"); + using (MemoryStream archiveStream = new([1, 2, 3, 4])) + { + string fileName = "theme-pack.zip"; + _mockApiHttpClient.PostMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(installedTheme); + + // Act + ThemeInfoDto result = await _sut.InstallAsync(archiveStream, fileName, CancellationToken.None); + + // Assert + Assert.Equal("installed-theme", result.Id); + await _mockApiHttpClient.Received(1).PostMultipartAsync( + ApiRoutes.Themes.INSTALL_THEME, + archiveStream, + fileName, + "archive", + Arg.Any()); + } + } + + [Fact] + public async Task DeleteThemeAsync_WhenCalled_ShouldDeleteThemeWithResolvedEndpoint() + { + // Arrange + string themeId = "editorial-paper"; + string expectedEndpoint = ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId); + + // Act + await _sut.DeleteThemeAsync(themeId, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task GetRenderDocumentAsync_WhenThemeIdProvided_ShouldFetchTemplateWithResolvedRoute() + { + // Arrange + string themeId = "editorial-paper"; + string pageKey = "shared/layout"; + ThemeTemplateResponseDto templateResponse = _themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: "Hello {{title}}"); + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", themeId) + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(templateResponse); + + // Act + ThemeRenderDocumentDto result = await _sut.GetRenderDocumentAsync(pageKey, themeId, CancellationToken.None); + + // Assert + Assert.Equal(themeId, result.Theme.Id); + Assert.Equal("Hello {{title}}", result.Template); + await _mockApiHttpClient.DidNotReceive().GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task GetRenderDocumentAsync_WhenThemeIdMissing_ShouldResolveCurrentThemeFirst() + { + // Arrange + string pageKey = "home/index"; + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "lumina-default"); + ThemeTemplateResponseDto templateResponse = _themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: "lumina-default"), template: "Home"); + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", "lumina-default") + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) + .Returns(currentTheme); + _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) + .Returns(templateResponse); + + // Act + ThemeRenderDocumentDto result = await _sut.GetRenderDocumentAsync(pageKey, null, CancellationToken.None); + + // Assert + Assert.Equal("lumina-default", result.Theme.Id); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + } + + [Fact] + public async Task BuildArchiveAsync_WhenApiReturnsBlob_ShouldReturnZipArchiveWithResolvedFileName() + { + // Arrange + string themeId = "editorial-paper"; + byte[] data = [0x50, 0x4B, 0x03, 0x04]; + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .Returns(new BlobDataDto { Data = data, ContentType = "application/zip" }); + string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId); + + // Act + ThemeArchiveDto result = await _sut.BuildArchiveAsync(themeId, CancellationToken.None); + + // Assert + Assert.Equal($"{themeId}.zip", result.FileName); + using (MemoryStream content = new()) + { + await result.Content.CopyToAsync(content); + Assert.Equal(data, content.ToArray()); + } + + await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs new file mode 100644 index 00000000..e19b1753 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeTemplateEngineTests.cs @@ -0,0 +1,478 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Models; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeTemplateEngineTests +{ + private readonly ThemeTemplateEngine _sut; + private readonly SectionModelFixture _sectionModelFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeTemplateEngineTests() + { + _sut = new ThemeTemplateEngine(); + } + + [Fact] + public void RenderPage_WhenVariableValueContainsHtml_ShouldEscapeOutput() + { + // Arrange + Dictionary model = new() { ["value"] = "&\"quote\"" }; + string template = "{{value}}"; + + // Act + Result result = _sut.RenderPage(template, model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("<b>&"quote"", result.Value.Content); + Assert.Equal(string.Empty, result.Value.Script); + } + + [Fact] + public void RenderPage_WhenRawVariableTagUsed_ShouldNotEscapeOutput() + { + // Arrange + Dictionary model = new() { ["value"] = "raw" }; + + // Act + Result ampersandResult = _sut.RenderPage("{{&value}}", model); + Result tripleResult = _sut.RenderPage("{{{value}}}", model); + + // Assert + Assert.True(ampersandResult.IsSuccess); + Assert.Equal("raw", ampersandResult.Value.Content); + Assert.True(tripleResult.IsSuccess); + Assert.Equal("raw", tripleResult.Value.Content); + } + + [Fact] + public void RenderPage_WhenVariableMissing_ShouldRenderEmptyString() + { + // Arrange + Dictionary model = new() { ["title"] = "Present" }; + + // Act + Result result = _sut.RenderPage("{{title}}|{{missing}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("Present|", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenVariableIsBoolean_ShouldRenderLowercaseLiteral() + { + // Arrange + Dictionary model = new() { ["enabled"] = true, ["disabled"] = false }; + + // Act + Result result = _sut.RenderPage("{{enabled}}/{{disabled}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("true/false", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenDottedExpressionUsed_ShouldResolveNestedProperty() + { + // Arrange + Dictionary model = new() + { + ["user"] = new Dictionary { ["name"] = "Ada" } + }; + + // Act + Result result = _sut.RenderPage("Hello {{user.name}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("Hello Ada", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenCollectionCountRequested_ShouldRenderCollectionCount() + { + // Arrange + Dictionary model = new() { ["items"] = new List { "a", "b", "c" } }; + + // Act + Result result = _sut.RenderPage("{{items.Count}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("3", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenSectionIsTruthy_ShouldRenderChildren() + { + // Arrange + Dictionary model = new() { ["section"] = true, ["text"] = "inside" }; + + // Act + Result result = _sut.RenderPage("{{#section}}{{text}}{{/section}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("inside", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenSectionIsObject_ShouldRenderChildrenWithObjectScope() + { + // Arrange + Dictionary model = new() + { + ["section"] = _sectionModelFixture.Create(text: "scoped") + }; + + // Act + Result result = _sut.RenderPage("{{#section}}{{text}}{{/section}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("scoped", result.Value.Content); + } + + [Theory] + [InlineData(null)] // unresolved section + [InlineData(false)] // boolean false + [InlineData("")] // empty string + public void RenderPage_WhenSectionIsFalsy_ShouldSkipChildren(object? sectionValue) + { + // Arrange + Dictionary model = new() { ["section"] = sectionValue, ["text"] = "hidden" }; + + // Act + Result result = _sut.RenderPage("before{{#section}}{{text}}{{/section}}after", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("beforeafter", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenSectionIsEmptyCollection_ShouldSkipChildren() + { + // Arrange + Dictionary model = new() { ["section"] = new List() }; + + // Act + Result result = _sut.RenderPage("a{{#section}}x{{/section}}b", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("ab", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenSectionIsCollection_ShouldRenderChildrenPerItem() + { + // Arrange + Dictionary model = new() + { + ["items"] = new List + { + new Dictionary { ["name"] = "A" }, + new Dictionary { ["name"] = "B" } + } + }; + + // Act + Result result = _sut.RenderPage("{{#items}}[{{name}}]{{/items}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("[A][B]", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenSectionIteratesScalarItems_ShouldRenderCurrentScopeValue() + { + // Arrange + Dictionary model = new() { ["items"] = new List { "one", "two" } }; + + // Act + Result result = _sut.RenderPage("{{#items}}{{.}};{{/items}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("one;two;", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenParentTraversalUsed_ShouldResolveFromParentScope() + { + // Arrange + Dictionary model = new() + { + ["title"] = "Parent", + ["items"] = new List + { + new Dictionary { ["name"] = "A" }, + new Dictionary { ["name"] = "B" } + } + }; + + // Act + Result result = _sut.RenderPage("{{#items}}{{../title}}/{{name}};{{/items}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("Parent/A;Parent/B;", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenInvertedSectionIsFalsy_ShouldRenderChildren() + { + // Arrange + Dictionary model = new() { ["section"] = null }; + + // Act + Result result = _sut.RenderPage("{{^section}}fallback{{/section}}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("fallback", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenInvertedSectionIsTruthy_ShouldSkipChildren() + { + // Arrange + Dictionary model = new() { ["section"] = "present" }; + + // Act + Result result = _sut.RenderPage("a{{^section}}fallback{{/section}}b", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("ab", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenTopLevelScriptsSectionPresent_ShouldSeparateScriptFromContent() + { + // Arrange + Dictionary model = new() { ["title"] = "Page", ["script"] = "console.log('x');" }; + + // Act + Result result = _sut.RenderPage( + "

    {{title}}

    {{#scripts}}{{/scripts}}", + model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("

    Page

    ", result.Value.Content); + Assert.Equal("", result.Value.Script); + } + + [Fact] + public void RenderPage_WhenScriptsSectionIsNamedDifferentlyInCase_ShouldStillSplitIt() + { + // Arrange + Dictionary model = new() { ["title"] = "Page" }; + + // Act + Result result = _sut.RenderPage( + "content{{#SCRIPTS}}script{{/SCRIPTS}}", + model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("content", result.Value.Content); + Assert.Equal("script", result.Value.Script); + } + + [Fact] + public void RenderPage_WhenScriptsSectionIsNestedInsideAnotherSection_ShouldKeepItInContent() + { + // Arrange + Dictionary model = new() + { + ["items"] = new List + { + new Dictionary { ["name"] = "A", ["scripts"] = true, ["script"] = "x" } + } + }; + + // Act + Result result = _sut.RenderPage( + "{{#items}}{{name}}{{#scripts}}{{script}}{{/scripts}}{{/items}}", + model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("Ax", result.Value.Content); + } + + [Fact] + public void RenderPage_WhenTemplateContainsOnlyComments_ShouldReturnEmptyContent() + { + // Arrange + Dictionary model = new() { ["title"] = "Page" }; + + // Act + Result result = _sut.RenderPage("{{! this is a comment }}", model); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(string.Empty, result.Value.Content); + Assert.Equal(string.Empty, result.Value.Script); + } + + [Fact] + public void RenderPage_WhenSectionIsNotClosed_ShouldReturnTemplateError() + { + // Arrange + Dictionary model = new() { ["section"] = true }; + + // Act + Result result = _sut.RenderPage("{{#section}}content", model); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("not closed", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenClosingTagHasNoOpeningSection_ShouldReturnTemplateError() + { + // Act + Result result = _sut.RenderPage("{{/section}}", new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("no matching opening section", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenClosingTagMismatchesOpeningSection_ShouldReturnTemplateError() + { + // Act + Result result = _sut.RenderPage("{{#first}}x{{/second}}", new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("closed by", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenEmptyTagUsed_ShouldReturnTemplateError() + { + // Act + Result result = _sut.RenderPage("before{{}}after", new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("Empty template tags", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenTagIsNotClosed_ShouldReturnTemplateError() + { + // Act + Result result = _sut.RenderPage("before{{value", new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("not closed", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenRawTagIsNotClosed_ShouldReturnTemplateError() + { + // Act + Result result = _sut.RenderPage("before{{{value", new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("not closed", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenExpressionIsTooLong_ShouldReturnTemplateError() + { + // Arrange + string expression = new('a', 121); + string template = $"{{{{{expression}}}}}"; + + // Act + Result result = _sut.RenderPage(template, new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("too long", result.FirstError.Description); + } + + [Theory] + [InlineData("{{bad-name}}")] // hyphen is not a valid name part character + [InlineData("{{two words}}")] // whitespace inside the expression + [InlineData("{{a..b}}")] // empty name part + public void RenderPage_WhenExpressionIsInvalid_ShouldReturnTemplateError(string template) + { + // Act + Result result = _sut.RenderPage(template, new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("is invalid", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenSectionsAreNestedDeeperThanTheLimit_ShouldReturnTemplateError() + { + // Arrange + string template = string.Concat(Enumerable.Repeat("{{#section}}", 33)) + + string.Concat(Enumerable.Repeat("{{/section}}", 33)); + + // Act + Result result = _sut.RenderPage(template, new Dictionary()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("nested more than", result.FirstError.Description); + } + + [Fact] + public void RenderPage_WhenRenderedOutputExceedsTheSafetyLimit_ShouldReturnTemplateError() + { + // Arrange + int limit = 4 * 1024 * 1024; + Dictionary model = new() { ["text"] = new string('a', limit + 1) }; + + // Act + Result result = _sut.RenderPage("{{text}}", model); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + Assert.Contains("safety limit", result.FirstError.Description); + } +} From 02f27655f8c1c50208fa23939e9dd8ff35bc5eae Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:43:19 -0700 Subject: [PATCH 26/31] Adds the integration tests for the theming feature --- .../Common/Setup/ThemeTestHelpers.cs | 42 +++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 223 ++++++++++++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 237 +++++++++++++++++ .../SetCurrentThemeEndpointTests.cs | 244 ++++++++++++++++++ .../GetCurrentThemeEndpointTests.cs | 88 +++++++ .../GetThemeArchiveEndpointTests.cs | 111 ++++++++ .../GetThemeAssetEndpointTests.cs | 130 ++++++++++ .../GetThemeSettingsEndpointTests.cs | 84 ++++++ .../GetThemeTemplateEndpointTests.cs | 131 ++++++++++ .../GetThemes/GetThemesEndpointTests.cs | 95 +++++++ 10 files changed, 1385 insertions(+) create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs new file mode 100644 index 00000000..8dc3e89b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/ThemeTestHelpers.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using Xunit; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup; + +/// +/// Helpers shared by the theme integration tests. +/// +[ExcludeFromCodeCoverage] +public static class ThemeTestHelpers +{ + /// + /// Waits until the bundled 'editorial-paper' theme has been installed and activated by the theme detection job at startup. + /// + /// The shared API factory whose database is polled. + /// A task representing the asynchronous operation. + public static async Task WaitForBundledThemeAsync(AuthenticatedLuminaApiFactory apiFactory) + { + const int MAX_ATTEMPTS = 100; + const int DELAY_MILLISECONDS = 100; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) + { + using IServiceScope scope = apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + if (await dbContext.Themes.AnyAsync(theme => theme.ThemeId == "editorial-paper" && theme.IsCurrent == true)) + return; + + await Task.Delay(DELAY_MILLISECONDS); + } + + Assert.Fail("The bundled theme 'editorial-paper' was not installed and activated within the expected time."); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..539bf863 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.DeleteTheme; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Management.DeleteTheme; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithExistingTheme_ShouldDeleteTheme() + { + // Arrange + string themeId = await InstallThemeAsync(); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/themes/{themeId}"); + + // Assert + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + + // the theme row is removed from the database + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Null(await dbContext.Themes.FirstOrDefaultAsync(theme => theme.ThemeId == themeId)); + + // the theme no longer appears in GET /themes + HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes"); + List? themes = await listResponse.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(themes); + Assert.DoesNotContain(themes!, theme => theme.ThemeId == themeId); + } + + [Fact] + public async Task DeleteTheme_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + string themeId = "nonexistent-theme"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/themes/{themeId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task DeleteTheme_WhenTryingToDeleteTheLastBundledTheme_ShouldReturnForbiddenResult() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + + // Act + HttpResponseMessage response = await _client.DeleteAsync("/api/v1/themes/editorial-paper"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("LastBundledThemeCannotBeDeleted", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/editorial-paper", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync(); + + // Act + HttpResponseMessage response = await nonAdminClient.DeleteAsync("/api/v1/themes/editorial-paper"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/editorial-paper", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.DeleteAsync("/api/v1/themes/editorial-paper"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Installs a test theme through the API and returns its manifest id. + /// + /// The manifest id of the installed theme. + private async Task InstallThemeAsync() + { + string themeId = $"test-theme-{Guid.NewGuid():N}"; + byte[] archiveBytes = _themeArchiveFixture.Create(themeId); + + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + response.EnsureSuccessStatusCode(); + + _installedThemeIds.Add(themeId); + return themeId; + } + + /// + /// Disposes API factory resources, removing any test theme left installed by a failed deletion and clearing the authorization seed data of the admin test user. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + foreach (string themeId in _installedThemeIds) + { + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == themeId); + if (theme is not null) + dbContext.Themes.Remove(theme); + } + + await dbContext.SaveChangesAsync(); + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + foreach (string themeId in _installedThemeIds) + await themeService.DeleteAsync(themeId, CancellationToken.None); + + // the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..00b5214c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.InstallTheme; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Management.InstallTheme; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public InstallThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithValidArchive_ShouldInstallTheme() + { + // Arrange + string themeId = $"test-theme-{Guid.NewGuid():N}"; + byte[] archiveBytes = _themeArchiveFixture.Create(themeId); + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + // Act + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + ThemeResponse? result = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(result); + Assert.Equal(themeId, result!.ThemeId); + Assert.Equal("Test Theme", result.Name); + Assert.Equal(ThemeInstallSource.Uploaded, result.InstallSource); + Assert.Null(result.IsCurrent); + + // the installed theme is listed by GET /themes + HttpResponseMessage listResponse = await _client.GetAsync("/api/v1/themes"); + List? themes = await listResponse.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(themes); + Assert.Contains(themes!, theme => theme.ThemeId == themeId); + + // the installed theme is persisted in the database + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Themes.FirstOrDefaultAsync(theme => theme.ThemeId == themeId)); + + _installedThemeIds.Add(themeId); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithInvalidArchive_ShouldReturnProblemResult() + { + // Arrange + byte[] invalidArchive = Encoding.UTF8.GetBytes("this is not a valid zip archive"); + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(invalidArchive); + multipartContent.Add(fileContent, "file", "theme.zip"); + + // Act + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Failure", problemDetails["title"].GetString()); + Assert.Equal("ThemeArchiveNotReadable", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutArchive_ShouldReturnValidationProblem() + { + // Arrange + // a multipart form without any file part, only a regular form field, so the archive is missing + using MultipartFormDataContent multipartContent = []; + multipartContent.Add(new StringContent("value"), "field"); + + // Act + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("ThemeArchiveCannotBeNull", errors["General.Validation"]); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync(); + byte[] archiveBytes = _themeArchiveFixture.Create(); + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + // Act + HttpResponseMessage response = await nonAdminClient.PostAsync("/api/v1/themes", multipartContent); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + byte[] archiveBytes = _themeArchiveFixture.Create(); + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + // Act + HttpResponseMessage response = await anonymousClient.PostAsync("/api/v1/themes", multipartContent); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources, removing the installed test themes and the authorization seed data of the admin test user. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + foreach (string themeId in _installedThemeIds) + { + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == themeId); + if (theme is not null) + dbContext.Themes.Remove(theme); + } + + await dbContext.SaveChangesAsync(); + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + foreach (string themeId in _installedThemeIds) + await themeService.DeleteAsync(themeId, CancellationToken.None); + + // the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..9af4be62 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,244 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Contracts.Requests.Themes; +using Lumina.Contracts.Responses.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Management.SetCurrentTheme; +using Lumina.Presentation.Api.Fixtures.Core.Endpoints.Themes; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Management.SetCurrentTheme; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly TestThemeArchiveFixture _themeArchiveFixture = new(); + private readonly List _installedThemeIds = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetCurrentThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes an authenticated admin API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithExistingTheme_ShouldSetCurrentTheme() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + string themeId = await InstallThemeAsync(); + SetCurrentThemeRequest request = new(ThemeId: themeId); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + ThemeResponse? result = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(result); + Assert.Equal(themeId, result!.ThemeId); + Assert.True(result.IsCurrent); + + // the newly active theme is returned by GET /themes/current + HttpResponseMessage currentResponse = await _client.GetAsync("/api/v1/themes/current"); + ThemeResponse? current = await currentResponse.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(current); + Assert.Equal(themeId, current!.ThemeId); + Assert.True(current.IsCurrent); + } + + [Fact] + public async Task SetCurrentTheme_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + string themeId = "nonexistent-theme"; + SetCurrentThemeRequest request = new(ThemeId: themeId); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/current", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task SetCurrentTheme_WhenThemeIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + SetCurrentThemeRequest request = new(ThemeId: string.Empty); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("ThemeIdCannotBeEmpty", errors["General.Validation"]); + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithNonAdminAccount_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient nonAdminClient = await _apiFactory.CreateAuthenticatedClientAsync(); + SetCurrentThemeRequest request = new(ThemeId: "editorial-paper"); + + // Act + HttpResponseMessage response = await nonAdminClient.PutAsJsonAsync("/api/v1/themes/current", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/current", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + SetCurrentThemeRequest request = new(ThemeId: "editorial-paper"); + + // Act + HttpResponseMessage response = await anonymousClient.PutAsJsonAsync("/api/v1/themes/current", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Installs a test theme through the API and returns its manifest id. + /// + /// Optional manifest id of the theme to install. + /// The manifest id of the installed theme. + private async Task InstallThemeAsync(string? themeId = null) + { + string resolvedThemeId = themeId ?? $"test-theme-{Guid.NewGuid():N}"; + byte[] archiveBytes = _themeArchiveFixture.Create(resolvedThemeId); + + using MultipartFormDataContent multipartContent = []; + using ByteArrayContent fileContent = new(archiveBytes); + multipartContent.Add(fileContent, "file", "theme.zip"); + + HttpResponseMessage response = await _client.PostAsync("/api/v1/themes", multipartContent); + response.EnsureSuccessStatusCode(); + + _installedThemeIds.Add(resolvedThemeId); + return resolvedThemeId; + } + + /// + /// Disposes API factory resources, removing the installed test themes, restoring the bundled theme as the active one, and clearing the authorization seed data of the admin test user. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + foreach (string themeId in _installedThemeIds) + { + ThemeEntity? theme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == themeId); + if (theme is not null) + { + theme.IsCurrent = null; + dbContext.Themes.Remove(theme); + } + } + + // restore the bundled theme as the active one, so the following tests start from a clean state + ThemeEntity? bundledTheme = await dbContext.Themes.FirstOrDefaultAsync(t => t.ThemeId == "editorial-paper"); + if (bundledTheme is not null) + bundledTheme.IsCurrent = true; + + await dbContext.SaveChangesAsync(); + + IThemeService themeService = scope.ServiceProvider.GetRequiredService(); + foreach (string themeId in _installedThemeIds) + await themeService.DeleteAsync(themeId, CancellationToken.None); + + // the admin seeding performed by the factory is not idempotent, so the seed data must be cleared between tests + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..d4c9900c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Themes; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetCurrentTheme; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetCurrentTheme; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetCurrentThemeEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetCurrentTheme_WhenCalled_ShouldReturnTheCurrentTheme() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/current"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + ThemeResponse? theme = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(theme); + Assert.Equal("editorial-paper", theme!.ThemeId); + Assert.True(theme.IsCurrent); + } + + [Fact] + public async Task GetCurrentTheme_WhenCalledWithoutAuthentication_ShouldReturnTheCurrentTheme() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/current"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs new file mode 100644 index 00000000..c03e0f3c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -0,0 +1,111 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeArchive; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeArchive; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeArchiveEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetThemeArchive_WhenCalledWithExistingTheme_ShouldReturnArchiveFile() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/editorial-paper/archive"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/zip", response.Content.Headers.ContentType?.MediaType); + Assert.Equal("editorial-paper.zip", response.Content.Headers.ContentDisposition?.FileName); + + byte[] bytes = await response.Content.ReadAsByteArrayAsync(); + Assert.NotEmpty(bytes); + } + + [Fact] + public async Task GetThemeArchive_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + string themeId = "nonexistent-theme"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{themeId}/archive"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/archive", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task GetThemeArchive_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/archive"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs new file mode 100644 index 00000000..2a6d278b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeAsset; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeAsset; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointTests : IClassFixture, IAsyncLifetime +{ + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeAssetEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + /// + /// Performs no setup; the asset endpoint is accessed anonymously. + /// + /// A task representing the asynchronous operation. + public Task InitializeAsync() + { + return Task.CompletedTask; + } + + [Fact] + public async Task GetThemeAsset_WhenCalledWithExistingThemeAndAsset_ShouldReturnAssetFile() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + // the asset path is relative to the theme pack root and includes the assets/ prefix, so the URL is + // /themes/{themeId}/assets/assets/{assetPath} (the first assets/ segment is the route prefix) + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/assets/assets/theme.css"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/css", response.Content.Headers.ContentType?.MediaType); + + byte[] bytes = await response.Content.ReadAsByteArrayAsync(); + Assert.NotEmpty(bytes); + } + + [Fact] + public async Task GetThemeAsset_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + string themeId = "nonexistent-theme"; + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/assets/theme.css"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/assets/theme.css", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task GetThemeAsset_WhenAssetPathIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/assets/"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("ThemeAssetPathCannotBeEmpty", errors["General.Validation"]); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs new file mode 100644 index 00000000..5062e6f2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Themes; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeSettings; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeSettings; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetThemeSettings_WhenCalled_ShouldReturnTheThemeEngineSettings() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + ThemeSettingsResponse? settings = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(settings); + Assert.Equal(8 * 1024 * 1024, settings!.MaxArchiveBytes); + Assert.Equal("lumina-default", settings.DefaultThemeId); + } + + [Fact] + public async Task GetThemeSettings_WhenCalledWithoutAuthentication_ShouldReturnTheThemeEngineSettings() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/settings"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs new file mode 100644 index 00000000..5e235fc8 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Themes; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemeTemplate; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointTests : IClassFixture, IAsyncLifetime +{ + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeTemplateEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + /// + /// Performs no setup; the template endpoint is accessed anonymously. + /// + /// A task representing the asynchronous operation. + public Task InitializeAsync() + { + return Task.CompletedTask; + } + + [Fact] + public async Task GetThemeTemplate_WhenCalledWithExistingThemeAndPageKey_ShouldReturnTemplate() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/templates/shared/layout"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + ThemeTemplateResponse? result = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(result); + Assert.Equal("editorial-paper", result!.Theme.ThemeId); + Assert.False(string.IsNullOrWhiteSpace(result.Template)); + } + + [Fact] + public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnNotFound() + { + // Arrange + HttpClient anonymousClient = _apiFactory.CreateClient(); + string themeId = "nonexistent-theme"; + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync($"/api/v1/themes/{themeId}/templates/shared/layout"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/themes/{themeId}/templates/shared/layout", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task GetThemeTemplate_WhenPageKeyIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + HttpClient anonymousClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync("/api/v1/themes/editorial-paper/templates/"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains("PageKeyCannotBeEmpty", errors["General.Validation"]); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..69a1b9f5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Themes; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemes; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Themes.Queries.GetThemes; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetThemes_WhenCalled_ShouldReturnTheInstalledThemes() + { + // Arrange + await ThemeTestHelpers.WaitForBundledThemeAsync(_apiFactory); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + List? themes = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(themes); + + ThemeResponse? bundledTheme = themes!.FirstOrDefault(theme => theme.ThemeId == "editorial-paper"); + Assert.NotNull(bundledTheme); + Assert.NotEmpty(bundledTheme!.Name); + Assert.Equal(ThemeInstallSource.Bundled, bundledTheme.InstallSource); + Assert.True(bundledTheme.IsCurrent); + } + + [Fact] + public async Task GetThemes_WhenCalledWithoutAuthentication_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/themes"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} From 531450b3dbbc9c94abe817100d1ada0bf39c2364 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 09:43:27 -0700 Subject: [PATCH 27/31] Adds the security tests for the theming feature --- .../DeleteTheme/DeleteThemeEndpointTests.cs | 132 +++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 333 ++++++++++++++++++ .../SetCurrentThemeEndpointTests.cs | 130 +++++++ .../GetCurrentThemeEndpointTests.cs | 76 ++++ .../GetThemeArchiveEndpointTests.cs | 104 ++++++ .../GetThemeAssetEndpointTests.cs | 234 ++++++++++++ .../GetThemeSettingsEndpointTests.cs | 68 ++++ .../GetThemeTemplateEndpointTests.cs | 235 ++++++++++++ .../GetThemes/GetThemesEndpointTests.cs | 88 +++++ 9 files changed, 1400 insertions(+) create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..48fdcb60 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.DeleteTheme; + +/// +/// Contains security tests for the DELETE /api/v1/themes/{themeId} route. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteThemeEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task DeleteTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/themes/{Guid.NewGuid():N}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task DeleteTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateUserAsync(client); + string url = $"/api/v1/themes/{Guid.NewGuid():N}"; + + // Act + HttpResponseMessage response = await client.DeleteAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task DeleteTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + string url = $"/api/v1/themes/{maliciousThemeId}"; + + // Act + HttpResponseMessage response = await client.DeleteAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem + if (!string.IsNullOrWhiteSpace(content)) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + } + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..b93999b5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,333 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.IO.Compression; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.InstallTheme; + +/// +/// Contains security tests for the POST /api/v1/themes route. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture, IDisposable +{ + private const long MAX_ARCHIVE_BYTES = 8 * 1024 * 1024; + private const string VALID_MANIFEST_JSON = """ + { + "schemaVersion": 1, + "id": "valid-theme", + "name": "Valid Theme", + "description": "description", + "author": "author", + "version": "1.0.0", + "templates": { + "default": "templates/default.html" + } + } + """; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public InstallThemeEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task InstallTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/themes", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("/api/v1/themes", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task InstallTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateUserAsync(client); + + // Act + using MultipartFormDataContent form = CreateMultipartForm(Encoding.UTF8.GetBytes("not-a-zip"), "pack.zip", "application/zip"); + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes", problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task InstallTheme_WithNonZipBody_ShouldReturnCleanProblemDetails() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + using MultipartFormDataContent form = CreateMultipartForm(Encoding.UTF8.GetBytes("this is not a zip archive"), "pack.zip", "application/zip"); + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Failure", problemDetails["title"].GetString()); + Assert.Equal("ThemeArchiveNotReadable", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task InstallTheme_WithEmptyArchiveFile_ShouldReturnCleanPackageInvalidProblemDetails() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + // a multipart upload carrying a 0 byte archive reaches the theme service, which must reject it without crashing + using MultipartFormDataContent form = CreateMultipartForm([], "pack.zip", "application/zip"); + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.True(problemDetails["errors"].GetProperty("Theme.Package.Invalid").GetArrayLength() > 0); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task InstallTheme_WithOversizedArchive_ShouldReturnCleanProblemDetails() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + using MultipartFormDataContent form = CreateMultipartForm(new byte[MAX_ARCHIVE_BYTES + 1], "pack.zip", "application/zip"); + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.True(problemDetails["errors"].GetProperty("Theme.Archive.TooLarge").GetArrayLength() > 0); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task InstallTheme_WithZipContainingTraversalEntry_ShouldReturnCleanProblemDetails() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + byte[] zipBytes = CreateZipWithEntries(new Dictionary + { + ["theme.json"] = VALID_MANIFEST_JSON, + ["templates/default.html"] = "default", + [@"..\evil.txt"] = "evil" // path traversal entry inside the archive + }); + + // Act + using MultipartFormDataContent form = CreateMultipartForm(zipBytes, "pack.zip", "application/zip"); + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.True(problemDetails["errors"].GetProperty("Theme.Package.Invalid").GetArrayLength() > 0); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task InstallTheme_WithManifestDeclaringTraversalTemplate_ShouldReturnCleanProblemDetails() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + const string MALICIOUS_MANIFEST = """ + { + "schemaVersion": 1, + "id": "evil-theme", + "name": "Evil Theme", + "description": "description", + "author": "author", + "version": "1.0.0", + "templates": { + "default": "templates/default.html", + "admin": "../secret.html" + } + } + """; + byte[] zipBytes = CreateZipWithEntries(new Dictionary + { + ["theme.json"] = MALICIOUS_MANIFEST, + ["templates/default.html"] = "default" + }); + + // Act + using MultipartFormDataContent form = CreateMultipartForm(zipBytes, "pack.zip", "application/zip"); + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", form); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.True(problemDetails["errors"].GetProperty("Theme.Package.Invalid").GetArrayLength() > 0); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task InstallTheme_WithEmptyMultipartBody_ShouldReturnCleanValidationProblemDetails() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + using MultipartFormDataContent emptyForm = []; + + // Act + HttpResponseMessage response = await client.PostAsync("/api/v1/themes", emptyForm); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds a multipart form containing a single file part. + /// + /// The file content bytes. + /// The name of the uploaded file. + /// The content type of the uploaded file. + /// The multipart form content. + private static MultipartFormDataContent CreateMultipartForm(byte[] fileBytes, string fileName, string contentType) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new(fileBytes); + fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + form.Add(fileContent, "archive", fileName); + return form; + } + + /// + /// Builds an in-memory ZIP archive from the given entry paths and contents. + /// + /// The entry paths mapped to their contents. + /// The ZIP archive bytes. + private static byte[] CreateZipWithEntries(IReadOnlyDictionary entries) + { + using MemoryStream memoryStream = new(); + using (ZipArchive zipArchive = new(memoryStream, ZipArchiveMode.Create, leaveOpen: true)) + { + foreach ((string path, string content) in entries) + { + ZipArchiveEntry entry = zipArchive.CreateEntry(path); + using StreamWriter writer = new(entry.Open()); + writer.Write(content); + } + } + + return memoryStream.ToArray(); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..9f550895 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Themes; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Management.SetCurrentTheme; + +/// +/// Contains security tests for the PUT /api/v1/themes/current route. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetCurrentThemeEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task SetCurrentTheme_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + SetCurrentThemeRequest request = new("some-theme"); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/themes/current", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("/api/v1/themes/current", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task SetCurrentTheme_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateUserAsync(client); + SetCurrentThemeRequest request = new("some-theme"); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/themes/current", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/themes/current", problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("../evil")] // dot-dot path traversal + [InlineData("..\\..\\evil")] // backslash path traversal + [InlineData("/etc/passwd")] // absolute path traversal + [InlineData("C:\\windows\\system32")] // absolute windows path traversal + [InlineData("' OR '1'='1")] // SQL injection attempt + public async Task SetCurrentTheme_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + SetCurrentThemeRequest request = new(maliciousThemeId); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync("/api/v1/themes/current", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..2eee95fb --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetCurrentTheme; + +/// +/// Contains security tests for the /api/v1/themes/current route. +/// +[ExcludeFromCodeCoverage] +public class GetCurrentThemeEndpointTests : IClassFixture, IDisposable +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetCurrentThemeEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetCurrentTheme_WhenAnonymous_ShouldNotRequireAuthenticationOrLeakInternalDetails() + { + // Arrange + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/current"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the route is AllowAnonymous, so anonymous callers must never be challenged for credentials + Assert.NotEqual(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // when no active theme exists yet, the failure must be a clean, generic 404 that discloses nothing internal + if (response.StatusCode == HttpStatusCode.NotFound) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + } + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs new file mode 100644 index 00000000..4228c897 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeArchive; + +/// +/// Contains security tests for the /api/v1/themes/{themeId}/archive route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeArchiveEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetThemeArchive_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/themes/{Guid.NewGuid():N}/archive"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task GetThemeArchive_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + string url = $"/api/v1/themes/{maliciousThemeId}/archive"; + + // Act + HttpResponseMessage response = await client.GetAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem + if (!string.IsNullOrWhiteSpace(content)) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + } + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs new file mode 100644 index 00000000..0a3eadf2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeAsset; + +/// +/// Contains security tests for the /api/v1/themes/{themeId}/assets/{*assetPath} route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetEndpointTests : IClassFixture, IDisposable +{ + private const string DECOY_FILE_NAME = "decoy-secret.txt"; + private const string DECOY_CONTENT = "DECOY-SECRET-CONTENT"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly string _themeId; + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeAssetEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + _themeId = $"testtheme{Guid.NewGuid():N}"; + } + + [Fact] + public async Task GetThemeAsset_WhenThemeDoesNotExist_ShouldReturnCleanNotFoundProblemDetails() + { + // Arrange + string url = $"/api/v1/themes/does-not-exist/assets/logo.txt"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil.txt")] // encoded slash path traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil.txt")] // encoded dot-slash path traversal + [InlineData("..%5C..%5Cevil.txt")] // encoded backslash path traversal + [InlineData("assets%2F..%2F..%2Fevil.txt")] // traversal hiding behind the assets prefix + [InlineData("C:%5Cwindows%5Csystem32%5Cdrivers%5Cetc%5Chosts")] // absolute windows path + [InlineData("..%2F..%2F..%2F..%2Fdecoy-secret.txt")] // deep traversal targeting a decoy file outside the pack + public async Task GetThemeAsset_WithEncodedPathTraversalInAssetPath_ShouldReturnPackageInvalid(string maliciousAssetPath) + { + // Arrange + await SeedThemeAsync(); + EnsureThemePackOnDisk(); + EnsureDecoyFileOnDisk(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/assets/{maliciousAssetPath}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the encoded traversal is rejected either by the server before it reaches the handler (403) or by the theme service validation (422); + // in both cases it must be a clean client error that never serves or leaks the decoy + Assert.True(response.StatusCode >= HttpStatusCode.BadRequest && response.StatusCode < HttpStatusCode.InternalServerError, $"Unexpected status code {response.StatusCode}."); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task GetThemeAsset_WithRawPathTraversalInAssetPath_ShouldNotLeakOrServeOutsideThemePack() + { + // Arrange + await SeedThemeAsync(); + EnsureThemePackOnDisk(); + EnsureDecoyFileOnDisk(); + + // Act + // note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler + HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/assets/../evil.txt"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task GetThemeAsset_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + string url = $"/api/v1/themes/{maliciousThemeId}/assets/logo.txt"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem + if (!string.IsNullOrWhiteSpace(content)) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + } + } + + /// + /// Seeds a with the unique test theme id. + /// + /// A task representing the asynchronous operation. + private async Task SeedThemeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Writes a valid theme pack for the unique test theme into the server storage directory. + /// + private void EnsureThemePackOnDisk() + { + string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId); + Directory.CreateDirectory(Path.Combine(themeRoot, "templates")); + Directory.CreateDirectory(Path.Combine(themeRoot, "assets")); + string manifest = $$""" + { + "schemaVersion": 1, + "id": "{{_themeId}}", + "name": "Test Theme", + "description": "Test theme description", + "author": "Tester", + "version": "1.0.0", + "templates": { + "default": "templates/default.html", + "home": "templates/home.html" + } + } + """; + File.WriteAllText(Path.Combine(themeRoot, "theme.json"), manifest); + File.WriteAllText(Path.Combine(themeRoot, "templates", "default.html"), "default-template"); + File.WriteAllText(Path.Combine(themeRoot, "templates", "home.html"), "home-template"); + File.WriteAllText(Path.Combine(themeRoot, "assets", "logo.txt"), "logo-content"); + } + + /// + /// Writes a decoy file outside any theme pack, used to prove traversal payloads never escape the pack root. + /// + private static void EnsureDecoyFileOnDisk() + { + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME), DECOY_CONTENT); + } + + /// + /// Removes the seeded theme, its pack directory, and the decoy file. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId); + if (theme is not null) + { + dbContext.Themes.Remove(theme); + dbContext.SaveChanges(); + } + + string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId); + if (Directory.Exists(themeRoot)) + Directory.Delete(themeRoot, recursive: true); + + string decoyPath = Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME); + if (File.Exists(decoyPath)) + File.Delete(decoyPath); + + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs new file mode 100644 index 00000000..93c44b12 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeSettings; + +/// +/// Contains security tests for the /api/v1/themes/settings route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeSettingsEndpointTests : IClassFixture, IDisposable +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeSettingsEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetThemeSettings_WhenAnonymous_ShouldNotRequireAuthentication() + { + // Arrange + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings"); + + // Assert + // the route is AllowAnonymous, so anonymous callers must never be challenged for credentials + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task GetThemeSettings_WhenAnonymous_ShouldNotLeakSensitiveData() + { + // Arrange + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes/settings"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs new file mode 100644 index 00000000..cafced8f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -0,0 +1,235 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemeTemplate; + +/// +/// Contains security tests for the /api/v1/themes/{themeId}/templates/{*pageKey} route. +/// +[ExcludeFromCodeCoverage] +public class GetThemeTemplateEndpointTests : IClassFixture, IDisposable +{ + private const string DECOY_FILE_NAME = "decoy-secret.txt"; + private const string DECOY_CONTENT = "DECOY-SECRET-CONTENT"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly string _themeId; + private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemeTemplateEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + _themeId = $"testtheme{Guid.NewGuid():N}"; + } + + [Fact] + public async Task GetThemeTemplate_WhenThemeDoesNotExist_ShouldReturnCleanNotFoundProblemDetails() + { + // Arrange + string url = $"/api/v1/themes/does-not-exist/templates/home"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetString()); + Assert.True(problemDetails.ContainsKey("traceId")); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil.html")] // encoded slash path traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil.html")] // encoded dot-slash path traversal + [InlineData("..%5C..%5Cevil.html")] // encoded backslash path traversal + [InlineData("..%2F..%2F..%2F..%2Fdecoy-secret.txt")] // deep traversal targeting a decoy file outside the pack + public async Task GetThemeTemplate_WithEncodedPathTraversalInPageKey_ShouldOnlyServeInPackTemplates(string maliciousPageKey) + { + // Arrange + await SeedThemeAsync(); + EnsureThemePackOnDisk(); + EnsureDecoyFileOnDisk(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/templates/{maliciousPageKey}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // a successful render must only ever come from a template inside the theme pack + if (response.StatusCode == HttpStatusCode.OK) + Assert.Contains("default-template", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task GetThemeTemplate_WithRawPathTraversalInPageKey_ShouldNotLeakOrError() + { + // Arrange + await SeedThemeAsync(); + EnsureThemePackOnDisk(); + EnsureDecoyFileOnDisk(); + + // Act + // note: Kestrel normalizes literal dot-segments out of the raw path, so the request is re-routed or rejected before the handler + HttpResponseMessage response = await _client.GetAsync($"/api/v1/themes/{_themeId}/templates/../evil.html"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(DECOY_CONTENT, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task GetThemeTemplate_WithPathTraversalInThemeId_ShouldReturnCleanNotFoundProblemDetails(string maliciousThemeId) + { + // Arrange + string url = $"/api/v1/themes/{maliciousThemeId}/templates/home"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + + // note: some payloads are normalized away by the server before routing, producing an empty-body 404; + // when the value reaches the handler, the failure must still be the generic theme-not-found problem + if (!string.IsNullOrWhiteSpace(content)) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("ThemeNotFound", problemDetails["detail"].GetString()); + } + } + + /// + /// Seeds a with the unique test theme id. + /// + /// A task representing the asynchronous operation. + private async Task SeedThemeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Themes.Add(_themeEntityFixture.Create(themeId: _themeId, isDeleted: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Writes a valid theme pack for the unique test theme into the server storage directory. + /// + private void EnsureThemePackOnDisk() + { + string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId); + Directory.CreateDirectory(Path.Combine(themeRoot, "templates")); + Directory.CreateDirectory(Path.Combine(themeRoot, "assets")); + string manifest = $$""" + { + "schemaVersion": 1, + "id": "{{_themeId}}", + "name": "Test Theme", + "description": "Test theme description", + "author": "Tester", + "version": "1.0.0", + "templates": { + "default": "templates/default.html", + "home": "templates/home.html" + } + } + """; + File.WriteAllText(Path.Combine(themeRoot, "theme.json"), manifest); + File.WriteAllText(Path.Combine(themeRoot, "templates", "default.html"), "default-template"); + File.WriteAllText(Path.Combine(themeRoot, "templates", "home.html"), "home-template"); + File.WriteAllText(Path.Combine(themeRoot, "assets", "logo.txt"), "logo-content"); + } + + /// + /// Writes a decoy file outside any theme pack, used to prove traversal payloads never escape the pack root. + /// + private static void EnsureDecoyFileOnDisk() + { + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME), DECOY_CONTENT); + } + + /// + /// Removes the seeded theme, its pack directory, and the decoy file. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ThemeEntity? theme = dbContext.Themes.FirstOrDefault(candidate => candidate.ThemeId == _themeId); + if (theme is not null) + { + dbContext.Themes.Remove(theme); + dbContext.SaveChanges(); + } + + string themeRoot = Path.Combine(AppContext.BaseDirectory, "themes", _themeId); + if (Directory.Exists(themeRoot)) + Directory.Delete(themeRoot, recursive: true); + + string decoyPath = Path.Combine(AppContext.BaseDirectory, DECOY_FILE_NAME); + if (File.Exists(decoyPath)) + File.Delete(decoyPath); + + _client.Dispose(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..77dfddc4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Themes.Queries.GetThemes; + +/// +/// Contains security tests for the /api/v1/themes route. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetThemesEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // a unique X-Forwarded-For isolates rate limiting state per test + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetThemes_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/themes"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("/api/v1/themes", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetThemes_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync("/api/v1/themes"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} From 15945c2e5604601fdcb2e7bf2a7a7e4e6044a84b Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 11:47:16 -0700 Subject: [PATCH 28/31] Removes the option to disable theme scripts --- .../Infrastructure/Themes/IThemeService.cs | 5 - .../GetThemeSettingsQueryHandler.cs | 2 +- .../Responses/Themes/ThemeSettingsResponse.cs | 2 - .../Configuration/ThemeEngineOptionsDto.cs | 5 - .../Core/Themes/ThemeService.cs | 27 ---- .../appsettings.shared.json | 3 +- .../GetThemeSettingsEndpointSummary.cs | 3 +- .../Common/DTO/Themes/ThemeAdminDto.cs | 5 - .../DTO/Themes/ThemeSettingsResponseDto.cs | 2 - .../Themes/GetThemes/GetThemesEndpoint.cs | 1 - .../Themes/ThemeSettingsResponseFixture.cs | 3 - .../ThemeEngineOptionsDtoFixture.cs | 7 +- .../Themes/ThemeSettingsResponseDtoFixture.cs | 3 - .../GetThemeSettingsQueryHandlerTests.cs | 3 - .../Core/Themes/ThemeServiceTests.cs | 140 +----------------- .../GetThemes/GetThemesEndpointTests.cs | 3 +- .../Core/Themes/ThemeServiceTests.cs | 2 +- 17 files changed, 15 insertions(+), 201 deletions(-) diff --git a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs index 4ac5fae5..e9c2bd4a 100644 --- a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs @@ -14,11 +14,6 @@ namespace Lumina.Application.Common.Infrastructure.Themes; /// public interface IThemeService { - /// - /// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files. - /// - bool AllowThemeScripts { get; } - /// /// Gets the maximum allowed size of a theme archive, in bytes. /// diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs index 595c53b5..ea90c975 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandler.cs @@ -35,7 +35,7 @@ public class GetThemeSettingsQueryHandler : IQueryHandler public Task> HandleAsync(GetThemeSettingsQuery query, CancellationToken cancellationToken) { - ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.AllowThemeScripts, _themeService.DefaultThemeId); + ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.DefaultThemeId); return Task.FromResult(Result.From(response)); } } diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs index c21851cc..def03523 100644 --- a/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/Themes/ThemeSettingsResponse.cs @@ -9,11 +9,9 @@ namespace Lumina.Contracts.Responses.Themes; /// Represents a theme settings response. /// /// The maximum allowed size of a theme archive, in bytes. -/// Whether theme templates may contain script elements and theme assets may include script files. /// The identifier of the theme selected when no valid current theme is available. [DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")] public record ThemeSettingsResponse( long MaxArchiveBytes, - bool AllowThemeScripts, string DefaultThemeId ); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs index 1d2623b6..1a416220 100644 --- a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/ThemeEngineOptionsDto.cs @@ -46,9 +46,4 @@ public sealed class ThemeEngineOptionsDto /// Gets or sets the maximum allowed number of entries in a theme pack archive. /// public int MaxEntries { get; set; } = 250; - - /// - /// Gets or sets a value indicating whether script elements in theme templates and script files in theme assets are allowed to be served. - /// - public bool AllowThemeScripts { get; set; } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index aa90d83e..0a471cde 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -45,12 +45,6 @@ public sealed class ThemeService : IThemeService "^[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( - "]*>[\\s\\S]*?", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web) { PropertyNameCaseInsensitive = true, @@ -87,11 +81,6 @@ public sealed class ThemeService : IThemeService _mutationGate = s_storageGates.GetOrAdd(_storageRoot, static _ => new SemaphoreSlim(1, 1)); } - /// - /// Gets a value indicating whether theme templates may contain script elements and theme assets may include script files. - /// - public bool AllowThemeScripts => _options.AllowThemeScripts; - /// /// Gets the maximum allowed size of a theme archive, in bytes. /// @@ -280,8 +269,6 @@ public sealed class ThemeService : IThemeService return Errors.Themes.ThemeFilesUnreadable; string template = await File.ReadAllTextAsync(fullPathResult.Value, cancellationToken); - if (!AllowThemeScripts) - template = StripScriptElements(template); return template; } @@ -330,10 +317,6 @@ public sealed class ThemeService : IThemeService 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 fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), normalizedPath); if (fullPathResult.IsFailure) return fullPathResult.Errors; @@ -782,16 +765,6 @@ public sealed class ThemeService : IThemeService return Error.Validation(code: "Theme.Package.Invalid", description: description); } - /// - /// Removes every script element from a theme template, so that no script bundled in the theme runs when scripts are disabled. - /// - /// The template content to strip script elements from. - /// The template content without script elements. - private static string StripScriptElements(string template) - { - return s_scriptElementPattern.Replace(template, string.Empty); - } - /// /// Resolves the storage path of a theme pack directory for a theme identifier. /// diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 6ccc0db4..7790a2e1 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -13,8 +13,7 @@ "MaxArchiveBytes": 8388608, "MaxExpandedBytes": 25165824, "MaxSingleFileBytes": 6291456, - "MaxEntries": 250, - "AllowThemeScripts": true + "MaxEntries": 250 }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;User Id=;Password=;" diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs index 791d45f6..ad8c9349 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointSummary.cs @@ -19,12 +19,11 @@ public class GetThemeSettingsEndpointSummary : Summary public required string CurrentThemeId { get; init; } - /// - /// Gets or sets a value indicating whether theme templates may load script files. - /// - public required bool AllowThemeScripts { get; init; } - /// /// Gets or sets the maximum allowed size of a theme archive, in bytes. /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs index 636830db..8fe7ae73 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSettingsResponseDto.cs @@ -9,11 +9,9 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// Data transfer object for the theme engine settings returned by the remote API. /// /// The maximum allowed size of a theme archive, in bytes. -/// Whether theme templates may contain script elements and theme assets may include script files. /// The identifier of the theme selected when no valid current theme is available. [DebuggerDisplay("MaxArchiveBytes: {MaxArchiveBytes}")] public sealed record ThemeSettingsResponseDto( long MaxArchiveBytes, - bool AllowThemeScripts, string DefaultThemeId ); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs index d1fd73ee..0782a519 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpoint.cs @@ -58,7 +58,6 @@ public class GetThemesEndpoint : BaseEndpoint { Themes = themes, CurrentThemeId = currentTheme.Id, - AllowThemeScripts = settings.AllowThemeScripts, MaxArchiveBytes = settings.MaxArchiveBytes }; return JsonSuccess(themeAdmin); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs index 1a807539..2e091f3c 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeSettingsResponseFixture.cs @@ -20,17 +20,14 @@ public class ThemeSettingsResponseFixture /// Creates a random valid . /// /// Optional. The maximum allowed size of a theme archive, in bytes. - /// Optional. Whether theme templates may contain script elements. /// Optional. The identifier of the default theme. /// The created . public ThemeSettingsResponse Create( long? maxArchiveBytes = null, - bool? allowThemeScripts = null, string? defaultThemeId = null) { return new ThemeSettingsResponse( maxArchiveBytes ?? _faker.Random.Long(1_000_000, 100_000_000), - allowThemeScripts ?? _faker.Random.Bool(), defaultThemeId ?? _faker.Lorem.Slug(2)); } diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs index b61fbdd5..fa0c6533 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs @@ -25,7 +25,6 @@ public class ThemeEngineOptionsDtoFixture /// Optional maximum total size of an extracted theme pack, in bytes. /// Optional maximum size of a single file within a theme pack, in bytes. /// Optional maximum number of entries in a theme pack archive. - /// Optional value indicating whether script elements are allowed. /// A configured instance. public ThemeEngineOptionsDto Create( string? storagePath = null, @@ -34,8 +33,7 @@ public class ThemeEngineOptionsDtoFixture long? maxArchiveBytes = null, long? maxExpandedBytes = null, long? maxSingleFileBytes = null, - int? maxEntries = null, - bool? allowThemeScripts = null) + int? maxEntries = null) { Faker faker = new(); return new ThemeEngineOptionsDto @@ -46,8 +44,7 @@ public class ThemeEngineOptionsDtoFixture MaxArchiveBytes = maxArchiveBytes ?? faker.Random.Long(1_000_000, 100_000_000), MaxExpandedBytes = maxExpandedBytes ?? faker.Random.Long(10_000_000, 500_000_000), MaxSingleFileBytes = maxSingleFileBytes ?? faker.Random.Long(1_000_000, 50_000_000), - MaxEntries = maxEntries ?? faker.Random.Int(1, 1000), - AllowThemeScripts = allowThemeScripts ?? faker.Random.Bool() + MaxEntries = maxEntries ?? faker.Random.Int(1, 1000) }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs index fcb6ece5..03f0032e 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs @@ -18,18 +18,15 @@ public class ThemeSettingsResponseDtoFixture /// Creates a new instance with randomized test data. /// /// Optional maximum allowed archive size, in bytes. - /// Whether theme templates may load script files. /// Optional identifier of the fallback theme. /// A configured instance. public ThemeSettingsResponseDto Create( long? maxArchiveBytes = null, - bool? allowThemeScripts = null, string? defaultThemeId = null) { Faker faker = new(); return new ThemeSettingsResponseDto( MaxArchiveBytes: maxArchiveBytes ?? faker.Random.Long(1024 * 1024, 256 * 1024 * 1024), - AllowThemeScripts: allowThemeScripts ?? faker.Random.Bool(), DefaultThemeId: defaultThemeId ?? faker.Lorem.Word() ); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs index 64904a3d..4ff76e37 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeSettings/GetThemeSettingsQueryHandlerTests.cs @@ -37,10 +37,8 @@ public class GetThemeSettingsQueryHandlerTests // Arrange GetThemeSettingsQuery query = _getThemeSettingsQueryFixture.Create(); long maxArchiveBytes = 50_000_000; - bool allowThemeScripts = false; string defaultThemeId = "default-theme"; _mockThemeService.MaxArchiveBytes.Returns(maxArchiveBytes); - _mockThemeService.AllowThemeScripts.Returns(allowThemeScripts); _mockThemeService.DefaultThemeId.Returns(defaultThemeId); // Act @@ -49,7 +47,6 @@ public class GetThemeSettingsQueryHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(maxArchiveBytes, result.Value.MaxArchiveBytes); - Assert.Equal(allowThemeScripts, result.Value.AllowThemeScripts); Assert.Equal(defaultThemeId, result.Value.DefaultThemeId); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs index fd609d97..204d80d3 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -51,8 +51,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); _sut = CreateSut(_options); } @@ -76,52 +75,6 @@ public class ThemeServiceTests : IDisposable } } - [Fact] - public void AllowThemeScripts_WhenConfiguredFalse_ShouldReturnFalse() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); - options.AllowThemeScripts = false; - ThemeService sut = CreateSut(options); - - // Act - bool result = sut.AllowThemeScripts; - - // Assert - Assert.False(result); - } - - [Fact] - public void AllowThemeScripts_WhenConfiguredTrue_ShouldReturnTrue() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); - options.AllowThemeScripts = true; - ThemeService sut = CreateSut(options); - - // Act - bool result = sut.AllowThemeScripts; - - // Assert - Assert.True(result); - } - [Fact] public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue() { @@ -133,8 +86,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); options.MaxArchiveBytes = 12345; ThemeService sut = CreateSut(options); @@ -156,8 +108,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); options.DefaultThemeId = "custom-default"; ThemeService sut = CreateSut(options); @@ -288,8 +239,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); options.MaxArchiveBytes = 128; ThemeService sut = CreateSut(options); byte[] archive = _themePackFixture.Create(); @@ -453,8 +403,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); options.MaxEntries = 2; ThemeService sut = CreateSut(options); byte[] archive = _themePackFixture.Create(); @@ -478,8 +427,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); options.MaxSingleFileBytes = 10; ThemeService sut = CreateSut(options); string manifestJson = _themePackFixture.CreateManifestJson(); @@ -506,8 +454,7 @@ public class ThemeServiceTests : IDisposable maxArchiveBytes: 8 * 1024 * 1024, maxExpandedBytes: 24 * 1024 * 1024, maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); + maxEntries: 250); options.MaxSingleFileBytes = 400; options.MaxExpandedBytes = 300; ThemeService sut = CreateSut(options); @@ -1039,48 +986,6 @@ public class ThemeServiceTests : IDisposable Assert.Equal(DEFAULT_TEMPLATE, result.Value); } - [Fact] - public async Task GetTemplateAsync_WhenScriptsAreDisabled_ShouldStripScriptElements() - { - // Arrange - byte[] archive = _themePackFixture.Create(defaultTemplateContent: "

    safe content

    "); - await InstallValidThemeAsync(archive); - - // Act - Result result = await _sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal("

    safe content

    ", result.Value); - } - - [Fact] - public async Task GetTemplateAsync_WhenScriptsAreEnabled_ShouldPreserveScriptElements() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); - options.AllowThemeScripts = true; - ThemeService sut = CreateSut(options); - const string TEMPLATE_WITH_SCRIPT = "

    safe content

    "; - byte[] archive = _themePackFixture.Create(defaultTemplateContent: TEMPLATE_WITH_SCRIPT); - await InstallValidThemeAsync(archive, sut); - - // Act - Result result = await sut.GetTemplateAsync("test-theme", "unknown-page", CancellationToken.None); - - // Assert - Assert.True(result.IsSuccess); - Assert.Equal(TEMPLATE_WITH_SCRIPT, result.Value); - } - [Fact] public async Task GetAssetAsync_WhenAssetExists_ShouldReturnFileBytesAndContentType() { @@ -1146,7 +1051,7 @@ public class ThemeServiceTests : IDisposable } [Fact] - public async Task GetAssetAsync_WhenScriptsAreDisabledAndAssetIsJavaScript_ShouldReturnThemeFilesUnreadable() + public async Task GetAssetAsync_WhenAssetIsJavaScript_ShouldReturnJavaScriptContentType() { // Arrange byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary @@ -1158,35 +1063,6 @@ public class ThemeServiceTests : IDisposable // Act Result result = await _sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); - // Assert - Assert.True(result.IsFailure); - Assert.Equal("ThemeFilesUnreadable", result.FirstError.Description); - } - - [Fact] - public async Task GetAssetAsync_WhenScriptsAreEnabledAndAssetIsJavaScript_ShouldReturnJavaScriptContentType() - { - // Arrange - ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create( - storagePath: Path.Combine(_testRootPath, "themes"), - bundledThemesPath: Path.Combine(_testRootPath, "bundled"), - defaultThemeId: "lumina-default", - maxArchiveBytes: 8 * 1024 * 1024, - maxExpandedBytes: 24 * 1024 * 1024, - maxSingleFileBytes: 6 * 1024 * 1024, - maxEntries: 250, - allowThemeScripts: false); - options.AllowThemeScripts = true; - ThemeService sut = CreateSut(options); - byte[] archive = _themePackFixture.Create(additionalFiles: new Dictionary - { - ["assets/app.js"] = "console.log('hello');" - }); - await InstallValidThemeAsync(archive, sut); - - // Act - Result result = await sut.GetAssetAsync("test-theme", "assets/app.js", CancellationToken.None); - // Assert Assert.True(result.IsSuccess); Assert.Equal("application/javascript", result.Value.ContentType); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs index 896dc807..5f88ece1 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -53,7 +53,7 @@ public class GetThemesEndpointTests _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) .Returns(currentTheme); _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) - .Returns(_themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true)); + .Returns(_themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024)); // Act IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); @@ -67,7 +67,6 @@ public class GetThemesEndpointTests Assert.Equal(2, data.GetProperty("themes").GetArrayLength()); Assert.Equal("editorial-paper", data.GetProperty("themes")[0].GetProperty("id").GetString()); Assert.Equal("lumina-default", data.GetProperty("currentThemeId").GetString()); - Assert.True(data.GetProperty("allowThemeScripts").GetBoolean()); Assert.Equal(10 * 1024 * 1024, data.GetProperty("maxArchiveBytes").GetInt64()); Assert.Equal(10.0, data.GetProperty("maxArchiveMegabytes").GetDouble()); } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs index c24c55f0..0a306c3d 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -103,7 +103,7 @@ public class ThemeServiceTests public async Task GetThemeSettingsAsync_WhenApiReturnsSettings_ShouldReturnSettings() { // Arrange - ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024, allowThemeScripts: true); + ThemeSettingsResponseDto settings = _themeSettingsResponseDtoFixture.Create(maxArchiveBytes: 10 * 1024 * 1024); _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_THEME_SETTINGS, Arg.Any()) .Returns(settings); From 7e54c990ad9cb7a5abf99d55b7d8d7b517207763 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 21 Aug 2026 11:47:51 -0700 Subject: [PATCH 29/31] Adds a restore action for soft deleted bundled themes --- .../Themes/RestoreThemeRequestMapping.cs | 22 ++ .../Mapping/Themes/ThemeEntityMapping.cs | 3 +- .../RestoreTheme/RestoreThemeCommand.cs | 16 ++ .../RestoreThemeCommandHandler.cs | 106 ++++++++ .../RestoreThemeCommandValidator.cs | 24 ++ .../GetThemes/GetThemesQueryHandler.cs | 5 +- .../Requests/Themes/RestoreThemeRequest.cs | 15 ++ .../Responses/Themes/ThemeResponse.cs | 4 +- .../Common/Errors/Errors.Themes.cs | 1 + .../Common/Routes/Themes/ApiRoutes.Themes.cs | 1 + .../InstallThemeEndpointSummary.cs | 3 +- .../RestoreTheme/RestoreThemeEndpoint.cs | 53 ++++ .../RestoreThemeEndpointSummary.cs | 120 +++++++++ .../SetCurrentThemeEndpointSummary.cs | 3 +- .../GetCurrentThemeEndpointSummary.cs | 3 +- .../GetThemeTemplateEndpointSummary.cs | 3 +- .../GetThemes/GetThemesEndpointSummary.cs | 6 +- .../Common/DTO/Themes/ThemeInfoDto.cs | 4 +- .../Common/DTO/Themes/ThemeResponseDto.cs | 4 +- .../Requests/Themes/RestoreThemeRequest.cs | 14 + .../Common/Routes/ApiRoutes.Themes.cs | 1 + .../Common/Routes/WebRoutes.Themes.cs | 1 + .../RestoreTheme/RestoreThemeEndpoint.cs | 59 +++++ .../Resources/Views/Admin/Themes.de-DE.resx | 3 + .../Resources/Views/Admin/Themes.en-US.resx | 3 + .../Resources/Views/Admin/Themes.es-ES.resx | 3 + .../Resources/Views/Admin/Themes.fr-FR.resx | 3 + .../Resources/Views/Admin/Themes.it-IT.resx | 3 + .../Resources/Views/Admin/Themes.ja-JP.resx | 3 + .../Core/Resources/Views/Admin/Themes.resx | 3 + .../Resources/Views/Admin/Themes.ro-RO.resx | 3 + .../Resources/Views/Admin/Themes.ru-RU.resx | 3 + .../Resources/Views/Admin/Themes.zh-CN.resx | 3 + .../Core/Themes/ThemeService.cs | 12 +- .../Core/Views/Admin/Themes.cshtml | 30 ++- .../RestoreThemeCommandFixture.cs | 38 +++ .../Themes/RestoreThemeRequestFixture.cs | 38 +++ .../Responses/Themes/ThemeResponseFixture.cs | 7 +- .../Common/DTO/Themes/ThemeInfoDtoFixture.cs | 7 +- .../DTO/Themes/ThemeResponseDtoFixture.cs | 7 +- .../RestoreTheme/RestoreThemeEndpointTests.cs | 231 +++++++++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 193 ++++++++++++++ .../Themes/RestoreThemeRequestMappingTests.cs | 32 +++ .../Mapping/Themes/ThemeEntityMappingTests.cs | 1 + .../RestoreThemeCommandHandlerTests.cs | 241 ++++++++++++++++++ .../RestoreThemeCommandValidatorTests.cs | 61 +++++ .../GetThemes/GetThemesQueryHandlerTests.cs | 6 +- .../RestoreTheme/RestoreThemeEndpointTests.cs | 202 +++++++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 85 ++++++ 49 files changed, 1666 insertions(+), 26 deletions(-) create mode 100644 src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs create mode 100644 src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Themes/RestoreThemeRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Themes/RestoreThemeRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs diff --git a/src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs new file mode 100644 index 00000000..e4087116 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Themes/RestoreThemeRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using Lumina.Contracts.Requests.Themes; +#endregion + +namespace Lumina.Application.Common.Mapping.Themes; + +/// +/// Extension methods for converting . +/// +public static class RestoreThemeRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static RestoreThemeCommand ToCommand(this RestoreThemeRequest request) + { + return new RestoreThemeCommand(request.ThemeId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs index c6818b85..b3460bc2 100644 --- a/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Themes/ThemeEntityMapping.cs @@ -27,6 +27,7 @@ public static class ThemeEntityMapping theme.PreviewPath, theme.InstallSource, theme.IsCurrent, - theme.InstalledAtUtc); + theme.InstalledAtUtc, + theme.IsDeleted); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs new file mode 100644 index 00000000..642eb561 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Command for restoring a soft deleted bundled theme. +/// +/// The manifest id of the theme to restore. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record RestoreThemeCommand( + string? ThemeId +) : ICommand; diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs new file mode 100644 index 00000000..c092f1ac --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Themes; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Themes; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Handler for the command to restore a soft deleted bundled theme. +/// +public class RestoreThemeCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IThemeService _themeService; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for the server-side storage and serving of theme packs. + /// Injected service to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public RestoreThemeCommandHandler( + IUnitOfWork unitOfWork, + IThemeService themeService, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _themeService = themeService; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to restore a soft deleted bundled theme. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(RestoreThemeCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // only admins can restore themes + if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) + return ApplicationErrors.Authorization.NotAuthorized; + + Result getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false); + if (getThemeResult.IsFailure) + return getThemeResult.Errors; + + ThemeEntity? theme = getThemeResult.Value; + if (theme is null) + return DomainErrors.Themes.ThemeNotFound; + + // only bundled themes are soft deleted, so only a soft deleted bundled theme can be restored + if (!theme.IsDeleted || theme.InstallSource != ThemeInstallSource.Bundled) + return DomainErrors.Themes.ThemeCannotBeRestored; + + // restore the pack files from the shipped archive before reactivating the theme + Result restoreFilesResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); + if (restoreFilesResult.IsFailure) + return restoreFilesResult.Errors; + + theme.IsDeleted = false; + theme.IsCurrent = null; + theme.UpdatedOnUtc = DateTime.UtcNow; + theme.UpdatedBy = userId; + Result updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs new file mode 100644 index 00000000..d2b145a9 --- /dev/null +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandValidator.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Themes.Management.Commands.RestoreTheme; + +/// +/// Validates the needed validation rules for . +/// +public class RestoreThemeCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeCommandValidator() + { + RuleFor(command => command.ThemeId) + .NotEmpty() + .WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs index 90202b57..03eb9b5a 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemes/GetThemesQueryHandler.cs @@ -45,10 +45,11 @@ public class GetThemesQueryHandler : IQueryHandler>([.. getThemesResult.Value - .Where(theme => !theme.IsDeleted) + .OrderBy(theme => theme.IsDeleted) // the shipped bundled themes are listed before the user themes, so the defaults stay the most visible - .OrderByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) + .ThenByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase) .Select(theme => theme.ToResponse())]); } diff --git a/src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs b/src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs new file mode 100644 index 00000000..b0e07d08 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Themes/RestoreThemeRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Themes; + +/// +/// Represents a request to restore a soft deleted bundled theme. +/// +/// The manifest id of the theme to restore. Required. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record RestoreThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs b/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs index adda0c8c..b8aca76f 100644 --- a/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs +++ b/src/Lumina.Contracts/Responses/Themes/ThemeResponse.cs @@ -19,6 +19,7 @@ namespace Lumina.Contracts.Responses.Themes; /// The source the theme was installed from. /// Whether the theme is the currently active one. /// The UTC timestamp at which the theme was installed. +/// Whether the theme was deleted by the user, which is only possible for bundled themes. [DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")] public record ThemeResponse( Guid Id, @@ -30,5 +31,6 @@ public record ThemeResponse( string? PreviewPath, ThemeInstallSource InstallSource, bool? IsCurrent, - DateTime InstalledAtUtc + DateTime InstalledAtUtc, + bool IsDeleted ); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs index 81affa2e..3c32d711 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Themes.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Themes.cs @@ -18,6 +18,7 @@ public static partial class Errors public static Error ThemeArchiveCannotBeNull => Error.Validation(description: nameof(ThemeArchiveCannotBeNull)); public static Error LastBundledThemeCannotBeDeleted => Error.Forbidden(description: nameof(LastBundledThemeCannotBeDeleted)); public static Error ThemeCannotBeDeleted => Error.Forbidden(description: nameof(ThemeCannotBeDeleted)); + public static Error ThemeCannotBeRestored => Error.Forbidden(description: nameof(ThemeCannotBeRestored)); public static Error ThemeArchiveNotReadable => Error.Failure(description: nameof(ThemeArchiveNotReadable)); public static Error ThemeFilesUnreadable => Error.Failure(description: nameof(ThemeFilesUnreadable)); public static Error ThemeNotAvailable => Error.Failure(description: nameof(ThemeNotAvailable)); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs index f9e366ce..3c094d40 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs @@ -15,6 +15,7 @@ public static partial class ApiRoutes public const string GET_THEME_TEMPLATE = "/themes/{themeId}/templates/{*pageKey}"; public const string GET_THEME_ASSET = "/themes/{themeId}/assets/{*assetPath}"; public const string GET_THEME_ARCHIVE = "/themes/{themeId}/archive"; + public const string RESTORE_THEME = "/themes/{themeId}/restore"; public const string DELETE_THEME = "/themes/{themeId}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs index 9513198f..83bd9815 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/InstallTheme/InstallThemeEndpointSummary.cs @@ -34,7 +34,8 @@ public class InstallThemeEndpointSummary : Summary +/// API endpoint for the /themes/{themeId}/restore route. +/// +public class RestoreThemeEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _restoreThemeCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling restore theme commands. + public RestoreThemeEndpoint(ICommandHandler> restoreThemeCommandHandler) + { + _restoreThemeCommandHandler = restoreThemeCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Themes.RESTORE_THEME); + Version(1); + DontCatchExceptions(); + } + + /// + /// Restores the soft deleted bundled theme identified by . + /// + /// The request containing the theme to restore. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RestoreThemeRequest request, CancellationToken cancellationToken) + { + Result result = await _restoreThemeCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.NoContent(), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs new file mode 100644 index 00000000..e2592e87 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointSummary.cs @@ -0,0 +1,120 @@ +#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.RestoreTheme; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RestoreThemeEndpointSummary() + { + Summary = "Restores a deleted bundled theme."; + Description = "Restores the files and reactivates a bundled theme that was soft deleted by the user, restoring the pack from the shipped archive."; + + ExampleRequest = new RestoreThemeRequest( + ThemeId: "editorial-paper" + ); + + RequestParam(r => r.ThemeId, "The manifest id of the bundled theme to restore. Required."); + + Response(204, "The theme was successfully restored."); + + 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}/restore" + }, + 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}/restore" + }, + 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}/restore" + } + } + ); + + Response(403, "The request failed because the user is not an Admin or the theme is not a soft deleted bundled theme.", "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}/restore", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "ThemeCannotBeRestored", + instance = "/api/v1/themes/{themeId}/restore", + 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}/restore", + 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}/restore", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "ThemeIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs index a26d0331..b6bf6338 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointSummary.cs @@ -41,7 +41,8 @@ public class SetCurrentThemeEndpointSummary : Summary
    {{content}}
    " )); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs index f4d20771..2faaeadb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs @@ -34,7 +34,8 @@ public class GetThemesEndpointSummary : Summary PreviewPath: "preview.png", InstallSource: ThemeInstallSource.Bundled, IsCurrent: true, - InstalledAtUtc: DateTime.UtcNow + InstalledAtUtc: DateTime.UtcNow, + IsDeleted: false ), new ( Id: Guid.NewGuid(), @@ -46,7 +47,8 @@ public class GetThemesEndpointSummary : Summary PreviewPath: "preview.jpg", InstallSource: ThemeInstallSource.Uploaded, IsCurrent: null, - InstalledAtUtc: DateTime.UtcNow + InstalledAtUtc: DateTime.UtcNow, + IsDeleted: false ) }); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs index 3303271a..4dcf7cdb 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeInfoDto.cs @@ -14,6 +14,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// The version of the theme, using semantic version form. /// The URL of the theme preview image. /// Whether the theme ships with the application or noy. +/// Whether the theme was deleted by the user, which is only possible for bundled themes. [DebuggerDisplay("Id: {Id}, Name: {Name}")] public sealed record ThemeInfoDto( string Id, @@ -22,5 +23,6 @@ public sealed record ThemeInfoDto( string Author, string Version, string PreviewUrl, - bool IsBundled + bool IsBundled, + bool IsDeleted ); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs index 632cac46..fe46174c 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeResponseDto.cs @@ -19,6 +19,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// The source the theme was installed from. /// Whether the theme is the currently active one. /// The UTC timestamp at which the theme was installed. +/// Whether the theme was deleted by the user, which is only possible for bundled themes. [DebuggerDisplay("ThemeId: {ThemeId}, Name: {Name}")] public sealed record ThemeResponseDto( Guid Id, @@ -30,5 +31,6 @@ public sealed record ThemeResponseDto( string? PreviewPath, ThemeInstallSource InstallSource, bool? IsCurrent, - DateTime InstalledAtUtc + DateTime InstalledAtUtc, + bool IsDeleted ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs new file mode 100644 index 00000000..0ded5c46 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Themes/RestoreThemeRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Themes; + +/// +/// Represents a request to restore a soft deleted bundled theme. +/// +/// The manifest id of the bundled theme to restore. +[DebuggerDisplay("ThemeId: {ThemeId}")] +public record RestoreThemeRequest( + string? ThemeId +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs index c7f14c91..040bdf48 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs @@ -18,6 +18,7 @@ public static partial class ApiRoutes public const string GET_THEME_TEMPLATE = "themes/{themeId}/templates/{*pageKey}"; public const string GET_THEME_ASSET = "themes/{themeId}/assets/{*assetPath}"; public const string GET_THEME_ARCHIVE = "themes/{themeId}/archive"; + public const string RESTORE_THEME = "themes/{themeId}/restore"; public const string DELETE_THEME = "themes/{themeId}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs index 3ff06780..52ca707e 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Themes.cs @@ -13,6 +13,7 @@ public static partial class WebRoutes public const string GET_THEMES = "{culture}/admin/themes/api-get-themes"; public const string INSTALL_THEME = "{culture}/admin/themes/api-install-theme"; public const string SET_CURRENT_THEME = "{culture}/admin/themes/api-set-current-theme"; + public const string RESTORE_THEME = "{culture}/admin/themes/api-restore-theme/{themeId}"; public const string DELETE_THEME = "{culture}/admin/themes/api-delete-theme/{themeId}"; public const string DOWNLOAD_THEME = "{culture}/admin/themes/api-download-theme/{themeId}"; public const string THEME_ASSETS = "theme-assets/{themeId}/{*path}"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs new file mode 100644 index 00000000..0c53d557 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// API endpoint for the /{culture}/admin/themes/api-restore-theme/{themeId} route. +/// +public class RestoreThemeEndpoint : BaseEndpoint +{ + private readonly ThemeService _themeService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the remote theme endpoints. + public RestoreThemeEndpoint(ThemeService themeService) + { + _themeService = themeService; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Themes.RESTORE_THEME); + DontAutoTag(); + Options(options => options.WithTags("Themes")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + EnableAntiforgery(); + } + + /// + /// Restores the soft deleted bundled theme identified by . + /// + /// The request containing the theme to restore. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(RestoreThemeRequest request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(request.ThemeId)) + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id cannot be empty."); + + await _themeService.RestoreThemeAsync(request.ThemeId, cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx index 646913fe..732fbc9f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.de-DE.resx @@ -144,6 +144,9 @@ Herunterladen + + Wiederherstellen + Hochladen diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx index cdff40e2..6b067312 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.en-US.resx @@ -144,6 +144,9 @@ Download + + Restore + Upload diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx index dbd389c0..a09ab9b0 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.es-ES.resx @@ -144,6 +144,9 @@ Descargar + + Restaurar + Subir diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx index 86823228..16496ace 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.fr-FR.resx @@ -144,6 +144,9 @@ Télécharger + + Restaurer + Téléverser diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx index 8bf1478b..8bb93eaf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.it-IT.resx @@ -144,6 +144,9 @@ Scarica + + Ripristina + Carica diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx index 4cf2bc83..ed060625 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ja-JP.resx @@ -144,6 +144,9 @@ ダウンロード + + 復元 + アップロード diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx index cdff40e2..6b067312 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.resx @@ -144,6 +144,9 @@ Download + + Restore + Upload diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx index 502efbd1..27398dbb 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ro-RO.resx @@ -144,6 +144,9 @@ Descarcă + + Restaurează + Încarcă diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx index 720ec102..35abb21e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.ru-RU.resx @@ -144,6 +144,9 @@ Скачать + + Восстановить + Загрузить diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx index 3cb35acf..5fb9c608 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Admin/Themes.zh-CN.resx @@ -144,6 +144,9 @@ 下载 + + 恢复 + 上传 diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs index ebb5b27a..42ff8bb0 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -94,6 +94,16 @@ public sealed class ThemeService await _apiHttpClient.DeleteAsync(ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId), cancellationToken).ConfigureAwait(false); } + /// + /// Restores a soft deleted bundled theme from its shipped archive. + /// + /// The identifier of the bundled theme to restore. + /// Cancellation token that can be used to stop the execution. + public async Task RestoreThemeAsync(string themeId, CancellationToken cancellationToken = default) + { + await _apiHttpClient.PostAsync(ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId), new { }, cancellationToken).ConfigureAwait(false); + } + /// /// Gets the theme and raw template source selected for a page key. /// @@ -134,6 +144,6 @@ public sealed class ThemeService private static ThemeInfoDto ToThemeInfo(ThemeResponseDto theme) { string previewUrl = string.IsNullOrWhiteSpace(theme.PreviewPath) ? "/admin/theme-placeholder.svg" : $"/theme-assets/{theme.ThemeId}/{theme.PreviewPath}"; - return new ThemeInfoDto(theme.ThemeId, theme.Name, theme.Description, theme.Author, theme.Version, previewUrl, theme.InstallSource == ThemeInstallSource.Bundled); + return new ThemeInfoDto(theme.ThemeId, theme.Name, theme.Description, theme.Author, theme.Version, previewUrl, theme.InstallSource == ThemeInstallSource.Bundled, theme.IsDeleted); } } diff --git a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml index 6529ff80..7d2756f8 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Admin/Themes.cshtml @@ -5,6 +5,7 @@ @using Lumina.Presentation.Web.Common.DTO.Themes @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization +@using System.Linq @{ var themes = ViewData["themes"] as IReadOnlyList; @@ -14,7 +15,7 @@ int bundledThemeCount = 0; if (themes is not null) foreach (ThemeInfoDto theme in themes) - if (theme.IsBundled) + if (theme.IsBundled && !theme.IsDeleted) bundledThemeCount++; } @@ -109,7 +110,7 @@ @foreach (ThemeInfoDto theme in themes) { bool isCurrent = theme.Id == currentThemeId; - bool isLastRemaining = themes.Count <= 1 || (theme.IsBundled && bundledThemeCount == 1); + bool isLastRemaining = themes.Count(theme => !theme.IsDeleted) <= 1 || (theme.IsBundled && bundledThemeCount == 1);
    @(theme.IsBundled ? _localizer["Bundled"] : _localizer["UserProvided"])
    - - - + @if (theme.IsDeleted) + { + + } + else + { + + + + }