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);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
/// <summary>
/// Query for retrieving the currently active theme.
/// </summary>
[DebuggerDisplay("GetCurrentThemeQuery")]
public record GetCurrentThemeQuery : IQuery;
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetCurrentTheme;
/// <summary>
/// Handler for the query to get the currently active theme.
/// </summary>
public class GetCurrentThemeQueryHandler : IQueryHandler<GetCurrentThemeQuery, Result<ThemeResponse>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetCurrentThemeQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetCurrentThemeQueryHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get the currently active theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the active <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<ThemeResponse>> HandleAsync(GetCurrentThemeQuery query, CancellationToken cancellationToken)
{
Result<ThemeEntity?> getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false);
if (getCurrentResult.IsFailure)
return getCurrentResult.Errors;
if (getCurrentResult.Value is null)
return DomainErrors.Themes.ThemeNotFound;
return getCurrentResult.Value.ToResponse();
}
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Query for retrieving the downloadable archive of a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme.</param>
[DebuggerDisplay("ThemeId: {ThemeId}")]
public record GetThemeArchiveQuery(
string? ThemeId
) : IQuery;
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Handler for the query to get the downloadable archive of a theme.
/// </summary>
public class GetThemeArchiveQueryHandler : IQueryHandler<GetThemeArchiveQuery, Result<ThemeArchiveResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeArchiveQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetThemeArchiveQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeArchiveQuery> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the downloadable archive of a theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the archive of the theme, or an error.
/// </returns>
public async Task<Result<ThemeArchiveResponse>> HandleAsync(GetThemeArchiveQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<ThemeArchiveDto> archiveResult = await _themeService.BuildArchiveAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (archiveResult.IsFailure)
return archiveResult.Errors;
return new ThemeArchiveResponse(archiveResult.Value.Bytes, archiveResult.Value.FileName, archiveResult.Value.ContentType);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive;
/// <summary>
/// Validates the needed validation rules for <see cref="GetThemeArchiveQuery"/>.
/// </summary>
public class GetThemeArchiveQueryValidator : AbstractValidator<GetThemeArchiveQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeArchiveQueryValidator"/> class.
/// </summary>
public GetThemeArchiveQueryValidator()
{
RuleFor(query => query.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Query for retrieving an asset file of a theme.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme.</param>
/// <param name="AssetPath">The asset path relative to the theme pack root.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, AssetPath: {AssetPath}")]
public record GetThemeAssetQuery(
string? ThemeId,
string? AssetPath
) : IQuery;
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Handler for the query to get an asset file of a theme.
/// </summary>
public class GetThemeAssetQueryHandler : IQueryHandler<GetThemeAssetQuery, Result<ThemeAssetResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeAssetQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetThemeAssetQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeAssetQuery> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
}
/// <summary>
/// Handles the query to get an asset file of a theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the asset of the theme, or an error.
/// </returns>
public async Task<Result<ThemeAssetResponse>> HandleAsync(GetThemeAssetQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<ThemeAssetDto> assetResult = await _themeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, cancellationToken).ConfigureAwait(false);
if (assetResult.IsFailure)
{
// the stored files of a bundled theme removed externally are restored, so its assets keep being served
if (theme.InstallSource == ThemeInstallSource.Bundled)
{
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (restoreResult.IsFailure)
return restoreResult.Errors;
assetResult = await _themeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, cancellationToken).ConfigureAwait(false);
}
if (assetResult.IsFailure)
return assetResult.Errors;
}
return new ThemeAssetResponse(assetResult.Value.Bytes, assetResult.Value.ContentType);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset;
/// <summary>
/// Validates the needed validation rules for <see cref="GetThemeAssetQuery"/>.
/// </summary>
public class GetThemeAssetQueryValidator : AbstractValidator<GetThemeAssetQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeAssetQueryValidator"/> class.
/// </summary>
public GetThemeAssetQueryValidator()
{
RuleFor(query => query.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
RuleFor(query => query.AssetPath)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeAssetPathCannotBeEmpty);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
/// <summary>
/// Query for retrieving the theme engine settings.
/// </summary>
[DebuggerDisplay("GetThemeSettingsQuery")]
public record GetThemeSettingsQuery : IQuery;
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeSettings;
/// <summary>
/// Handler for the query to get the theme engine settings.
/// </summary>
public class GetThemeSettingsQueryHandler : IQueryHandler<GetThemeSettingsQuery, Result<ThemeSettingsResponse>>
{
private readonly IThemeService _themeService;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeSettingsQueryHandler"/> class.
/// </summary>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
public GetThemeSettingsQueryHandler(IThemeService themeService)
{
_themeService = themeService;
}
/// <summary>
/// Handles the query to get the theme engine settings.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing the theme engine settings, or an error.
/// </returns>
public Task<Result<ThemeSettingsResponse>> HandleAsync(GetThemeSettingsQuery query, CancellationToken cancellationToken)
{
ThemeSettingsResponse response = new(_themeService.MaxArchiveBytes, _themeService.AllowThemeScripts, _themeService.DefaultThemeId);
return Task.FromResult(Result.From(response));
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Query for retrieving the template of a theme selected by a page key.
/// </summary>
/// <param name="ThemeId">The manifest id of the theme.</param>
/// <param name="PageKey">The page key that selects the template.</param>
[DebuggerDisplay("ThemeId: {ThemeId}, PageKey: {PageKey}")]
public record GetThemeTemplateQuery(
string? ThemeId,
string? PageKey
) : IQuery;
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Handler for the query to get the template of a theme.
/// </summary>
public class GetThemeTemplateQueryHandler : IQueryHandler<GetThemeTemplateQuery, Result<ThemeTemplateResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IThemeService _themeService;
private readonly IValidator<GetThemeTemplateQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetThemeTemplateQueryHandler(IUnitOfWork unitOfWork, IThemeService themeService, IValidator<GetThemeTemplateQuery> validator)
{
_unitOfWork = unitOfWork;
_themeService = themeService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the template of a theme.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the template of the theme, or an error.
/// </returns>
public async Task<Result<ThemeTemplateResponse>> HandleAsync(GetThemeTemplateQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false);
if (getThemeResult.IsFailure)
return getThemeResult.Errors;
ThemeEntity? theme = getThemeResult.Value;
if (theme is null || theme.IsDeleted)
return DomainErrors.Themes.ThemeNotFound;
Result<string> templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false);
if (templateResult.IsFailure)
{
// the stored files of a bundled theme removed externally are restored, and if the broken theme was the
// active one, the configured default theme is activated, so clients always have a renderable theme
if (theme.InstallSource == ThemeInstallSource.Bundled && await TryRestoreBundledThemeAsync(theme, cancellationToken).ConfigureAwait(false))
templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false);
if (templateResult.IsFailure)
return templateResult.Errors;
}
return new ThemeTemplateResponse(theme.ToResponse(), templateResult.Value);
}
/// <summary>
/// Restores the files of a bundled theme whose stored files were removed externally, and switches the active theme to the configured default when the broken theme was the active one.
/// </summary>
/// <param name="theme">The bundled theme to restore.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> when the theme was restored; <see langword="false"/> otherwise.</returns>
private async Task<bool> TryRestoreBundledThemeAsync(ThemeEntity theme, CancellationToken cancellationToken)
{
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
if (restoreResult.IsFailure)
return false;
if (theme.IsCurrent == true)
{
Result<ThemeEntity?> getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false);
if (getDefaultResult.IsFailure)
return true;
ThemeEntity? defaultTheme = getDefaultResult.Value;
if (defaultTheme is not null && !defaultTheme.IsDeleted && defaultTheme.Id != theme.Id)
{
theme.IsCurrent = null;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
defaultTheme.IsCurrent = true;
await _unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
}
return true;
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemeTemplate;
/// <summary>
/// Validates the needed validation rules for <see cref="GetThemeTemplateQuery"/>.
/// </summary>
public class GetThemeTemplateQueryValidator : AbstractValidator<GetThemeTemplateQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThemeTemplateQueryValidator"/> class.
/// </summary>
public GetThemeTemplateQueryValidator()
{
RuleFor(query => query.ThemeId)
.NotEmpty()
.WithError(DomainErrors.Themes.ThemeIdCannotBeEmpty);
RuleFor(query => query.PageKey)
.NotEmpty()
.WithError(DomainErrors.Themes.PageKeyCannotBeEmpty);
}
}
@@ -0,0 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemes;
/// <summary>
/// Query for retrieving all installed themes.
/// </summary>
[DebuggerDisplay("GetThemesQuery")]
public record GetThemesQuery : IQuery;
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.Themes;
using Lumina.Contracts.Responses.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.Themes.Management.Queries.GetThemes;
/// <summary>
/// Handler for the query to get all installed themes.
/// </summary>
public class GetThemesQueryHandler : IQueryHandler<GetThemesQuery, Result<IReadOnlyList<ThemeResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetThemesQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetThemesQueryHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to get all installed themes.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="ThemeResponse"/>, or an error.
/// </returns>
public async Task<Result<IReadOnlyList<ThemeResponse>>> HandleAsync(GetThemesQuery query, CancellationToken cancellationToken)
{
Result<IEnumerable<ThemeEntity>> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getThemesResult.IsFailure)
return getThemesResult.Errors;
return Result.From<IReadOnlyList<ThemeResponse>>([.. getThemesResult.Value
.Where(theme => !theme.IsDeleted)
.OrderByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled)
.ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase)
.Select(theme => theme.ToResponse())]);
}
}