Hard deletes user themes, restores damaged bundled themes and fixes the web theme service DI lifetime

This commit is contained in:
BinaryAlley committed 2026-08-20 00:16:58 -07:00
1 parent bf8faba24d
commit 45dc3f5706
7 files changed
+126 -10

No files matched your search

@@ -1,8 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Domain.Common.Primitives;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -15,7 +16,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Themes;
public interface IThemeRepository : IRepository<ThemeEntity>,
IGetAllRepositoryAction<ThemeEntity>,
IInsertRepositoryAction<ThemeEntity>,
IUpdateRepositoryAction<ThemeEntity>
IUpdateRepositoryAction<ThemeEntity>,
IDeleteByIdRepositoryAction<Guid>
{
/// <summary>
/// Gets a theme identified by its manifest <paramref name="themeId"/> from the storage medium.
@@ -95,6 +95,13 @@ public interface IThemeService
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
Task<Result<Success>> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken);
/// <summary>
/// Checks whether the stored pack files of a theme still exist.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <returns><see langword="true"/> when the theme pack files exist, <see langword="false"/> otherwise.</returns>
bool HasThemePack(string themeId);
/// <summary>
/// Gets the paths of the theme pack archives shipped with the application.
/// </summary>
@@ -112,11 +112,22 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
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);
if (theme.InstallSource == ThemeInstallSource.Bundled)
{
// bundled themes are soft deleted, so they can be restored automatically later, as long as the user did not delete them
theme.IsDeleted = true;
theme.IsCurrent = null;
theme.UpdatedOnUtc = DateTime.UtcNow;
theme.UpdatedBy = userId;
await _unitOfWork.ThemeRepository.UpdateAsync(theme, cancellationToken).ConfigureAwait(false);
}
else
{
// user themes are removed entirely, because their files are not shipped with the application and could never be restored
Result<Deleted> deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
}
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -84,6 +85,23 @@ internal sealed class ThemeRepository : IThemeRepository
.FirstOrDefaultAsync(theme => theme.ThemeId == themeId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a theme identified by <paramref name="id"/> from the storage medium.
/// </summary>
/// <param name="id">The id of the theme to delete.</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<Deleted>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
{
ThemeEntity? foundTheme = await _luminaDbContext.Themes
.FirstOrDefaultAsync(theme => theme.Id == id, cancellationToken).ConfigureAwait(false);
if (foundTheme is null)
return Errors.Themes.ThemeNotFound;
_luminaDbContext.Themes.Remove(foundTheme);
return Result.Deleted;
}
/// <summary>
/// Gets the currently active theme from the storage medium.
/// </summary>
@@ -57,7 +57,8 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
}
// themes that were soft deleted by the user must not be reinstalled automatically
HashSet<string> knownThemeIds = [.. getThemesResult.Value.Select(theme => theme.ThemeId)];
List<ThemeEntity> themes = [.. getThemesResult.Value];
HashSet<string> knownThemeIds = [.. themes.Select(theme => theme.ThemeId)];
foreach (string archivePath in _themeService.GetBundledThemeArchivePaths())
{
@@ -100,6 +101,72 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
}
await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken);
await unitOfWork.SaveChangesAsync(stoppingToken);
}
/// <summary>
/// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered.
/// </summary>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List<ThemeEntity> themes, CancellationToken cancellationToken)
{
// a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored
// automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed
// externally, and is the only case where the files are restored
List<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
if (brokenThemes.Count is 0)
return;
foreach (ThemeEntity brokenTheme in brokenThemes)
{
if (brokenTheme.InstallSource == ThemeInstallSource.Bundled)
{
// the files of a bundled theme that was not deleted by the user are restored from its shipped archive
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken);
if (restoreResult.IsSuccess)
continue;
_logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description);
// a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later
brokenTheme.IsDeleted = true;
brokenTheme.IsCurrent = null;
brokenTheme.UpdatedOnUtc = DateTime.UtcNow;
brokenTheme.UpdatedBy = default;
Result<Updated> updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken);
if (updateResult.IsFailure)
_logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description);
}
else
{
// a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely
_logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId);
brokenTheme.IsCurrent = null;
Result<Deleted> deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken);
if (deleteResult.IsFailure)
_logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
}
}
// if the deleted theme was the active one, switch to another available theme, preferring the configured default
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return;
ThemeEntity? replacementTheme = themes
.Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId))
.OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (replacementTheme is null)
return;
replacementTheme.IsCurrent = true;
replacementTheme.UpdatedOnUtc = DateTime.UtcNow;
replacementTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken);
}
}
@@ -105,6 +105,17 @@ public sealed class ThemeService : IThemeService
return [.. Directory.EnumerateFiles(_bundledRoot, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Checks whether the stored pack files of a theme still exist.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <returns><see langword="true"/> when the theme pack files exist, <see langword="false"/> otherwise.</returns>
public bool HasThemePack(string themeId)
{
string themePath = ResolveThemePath(themeId);
return Directory.Exists(themePath) && File.Exists(Path.Combine(themePath, MANIFEST_FILE_NAME));
}
/// <summary>
/// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id.
/// </summary>
@@ -301,9 +301,9 @@ public static class PresentationWebLayerServices
services.AddHttpContextAccessor();
services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024);
services.AddSingleton<ThemeService>();
services.AddScoped<ThemeService>();
services.AddSingleton<ThemeTemplateEngine>();
services.AddSingleton<ThemePageRenderer>();
services.AddScoped<ThemePageRenderer>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddScoped<IAuthorizationHandler, RoleAuthorizationHandler>();