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

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

No files matched your search

@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Command for deleting a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to delete.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record DeleteThemeCommand(
string? ThemeId
) : ICommand;
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Handler for the command to delete a theme.
/// </summary>
public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Result<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<DeleteThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteThemeCommandHandler(
IUnitOfWork unitOfWork,
IThemeService themeService,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<DeleteThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a theme.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
/// </returns>
public async Task<Result<Success>> HandleAsync(DeleteThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can delete themes
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<IEnumerable<ThemeEntity>> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getAllResult.IsFailure)
return getAllResult.Errors;
List<ThemeEntity> availableThemes = getAllResult.Value.Where(availableTheme => !availableTheme.IsDeleted).ToList();
// at least one bundled theme must always remain available, so the application never ends up without any theme
if (theme.InstallSource == ThemeInstallSource.Bundled)
{
int availableBundledThemes = availableThemes.Count(availableTheme => availableTheme.InstallSource == ThemeInstallSource.Bundled);
if (availableBundledThemes <= 1)
return DomainErrors.Themes.LastBundledThemeCannotBeDeleted;
}
// if the deleted theme was the active one, switch to another available theme, preferring the configured default
if (theme.IsCurrent == true)
{
ThemeEntity? replacementTheme = availableThemes
.Where(availableTheme => availableTheme.Id != theme.Id)
.OrderBy(availableTheme => string.Equals(availableTheme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(availableTheme => availableTheme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (replacementTheme is null)
return DomainErrors.Themes.ThemeCannotBeDeleted;
replacementTheme.IsCurrent = true;
await _unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken).ConfigureAwait(false);
}
theme.IsDeleted = true;
theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
Result<Success> deleteFilesResult = await _themeService.DeleteAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (deleteFilesResult.IsFailure)
return deleteFilesResult.Errors;
return Result.Success;
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.DeleteTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteThemeCommand"/>.
/// </summary>
public class DeleteThemeCommandValidator : AbstractValidator<DeleteThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteThemeCommandValidator"/> class.
/// </summary>
public DeleteThemeCommandValidator()
{
RuleFor(command => command.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
using System.IO;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Command for installing a theme pack, replacing the files of an existing theme with the same manifest id.
/// </summary>
/// <param name="Archive">The ZIP archive stream of the theme pack.</param>
/// <param name="FileName">The file name of the uploaded archive.</param>
[DebuggerDisplay("FileName: {FileName}")]
public record InstallThemeCommand(
Stream? Archive,
string? FileName
) : ICommand;
@@ -0,0 +1,148 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Handler for the command to install a theme pack.
/// </summary>
public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, Result<ThemeResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<InstallThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public InstallThemeCommandHandler(
IUnitOfWork unitOfWork,
IThemeService themeService,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<InstallThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to install a theme pack.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a successfully installed <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<ThemeResponse>> HandleAsync(InstallThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can install themes
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// store the theme pack files on the server, replacing the files of an existing theme with the same manifest id
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false);
if (installResult.IsFailure)
return installResult.Errors;
ThemeManifestDto manifest = installResult.Value;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity themeEntity;
if (getThemeResult.Value is not null)
{
ThemeEntity existingTheme = getThemeResult.Value;
themeEntity = new ThemeEntity
{
Id = existingTheme.Id,
ThemeId = manifest.Id,
Name = manifest.Name,
Description = manifest.Description,
Author = manifest.Author,
Version = manifest.Version,
PreviewPath = manifest.Preview,
InstallSource = existingTheme.InstallSource,
IsCurrent = existingTheme.IsCurrent,
IsDeleted = existingTheme.IsDeleted,
InstalledAtUtc = DateTime.UtcNow,
CreatedOnUtc = existingTheme.CreatedOnUtc,
CreatedBy = existingTheme.CreatedBy,
UpdatedOnUtc = DateTime.UtcNow,
UpdatedBy = userId
};
Result<Updated> updateResult = await _unitOfWork.ThemeRepository.UpdateAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (updateResult.IsFailure)
return updateResult.Errors;
}
else
{
themeEntity = new ThemeEntity
{
Id = Guid.NewGuid(),
ThemeId = manifest.Id,
Name = manifest.Name,
Description = manifest.Description,
Author = manifest.Author,
Version = manifest.Version,
PreviewPath = manifest.Preview,
InstallSource = ThemeInstallSource.Uploaded,
InstalledAtUtc = DateTime.UtcNow,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = userId,
UpdatedBy = userId
};
Result<Created> insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false);
if (insertResult.IsFailure)
{
// roll back the stored files so a failed install leaves no orphaned theme pack behind
await _themeService.DeleteAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
return insertResult.Errors;
}
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return themeEntity.ToResponse();
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="InstallThemeCommand"/>.
/// </summary>
public class InstallThemeCommandValidator : AbstractValidator<InstallThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="InstallThemeCommandValidator"/> class.
/// </summary>
public InstallThemeCommandValidator()
{
RuleFor(command => command.Archive)
.NotNull()
.WithError(DomainErrors.Themes.ThemeArchiveCannotBeNull);
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Command for setting the currently active theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme to activate.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record SetCurrentThemeCommand(
string? ThemeId
) : ICommand;
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Handler for the command to set the currently active theme.
/// </summary>
public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeCommand, Result<ThemeResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<SetCurrentThemeCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public SetCurrentThemeCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<SetCurrentThemeCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to set the currently active theme.
/// </summary>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the newly active <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<ThemeResponse>> HandleAsync(SetCurrentThemeCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can change the active theme
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
if (theme.IsCurrent == true)
return theme.ToResponse();
Result<ThemeEntity?> getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false);
if (getCurrentResult.IsFailure)
return getCurrentResult.Errors;
ThemeEntity? currentTheme = getCurrentResult.Value;
if (currentTheme is not null && currentTheme.Id != theme.Id)
{
currentTheme.IsCurrent = null;
await _unitOfWork.ThemeRepository.UpdateAsync(currentTheme, cancellationToken).ConfigureAwait(false);
}
theme.IsCurrent = true;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return theme.ToResponse();
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.SetCurrentTheme;
/// <summary>
/// Validates the needed validation rules for <see cref="SetCurrentThemeCommand"/>.
/// </summary>
public class SetCurrentThemeCommandValidator : AbstractValidator<SetCurrentThemeCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetCurrentThemeCommandValidator"/> class.
/// </summary>
public SetCurrentThemeCommandValidator()
{
RuleFor(command => command.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}