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); } }