From 45dc3f5706301174cf5b7da297bddda4f6ab5552 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 00:16:58 -0700 Subject: [PATCH] Hard deletes user themes, restores damaged bundled themes and fixes the web theme service DI lifetime --- .../Repositories/Themes/IThemeRepository.cs | 6 +- .../Infrastructure/Themes/IThemeService.cs | 7 ++ .../DeleteTheme/DeleteThemeCommandHandler.cs | 21 ++++-- .../Repositories/Themes/ThemeRepository.cs | 18 +++++ .../Core/Themes/ThemeDetectionSyncJob.cs | 69 ++++++++++++++++++- .../Core/Themes/ThemeService.cs | 11 +++ .../PresentationWebLayerServices.cs | 4 +- 7 files changed, 126 insertions(+), 10 deletions(-) diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs index db094c7a..ae0d994b 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Themes/IThemeRepository.cs @@ -1,8 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Domain.Common.Primitives; +using System; using System.Threading; using System.Threading.Tasks; #endregion @@ -15,7 +16,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Themes; public interface IThemeRepository : IRepository, IGetAllRepositoryAction, IInsertRepositoryAction, - IUpdateRepositoryAction + IUpdateRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets a theme identified by its manifest from the storage medium. diff --git a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs index f9e00778..4ac5fae5 100644 --- a/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Themes/IThemeService.cs @@ -95,6 +95,13 @@ public interface IThemeService /// An representing either a successful operation, or an error. Task> RestoreBundledThemeAsync(string themeId, CancellationToken cancellationToken); + /// + /// Checks whether the stored pack files of a theme still exist. + /// + /// The manifest id of the theme. + /// when the theme pack files exist, otherwise. + bool HasThemePack(string themeId); + /// /// Gets the paths of the theme pack archives shipped with the application. /// diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs index e329555e..ec859146 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs @@ -112,11 +112,22 @@ public class DeleteThemeCommandHandler : ICommandHandler deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false); + if (deleteResult.IsFailure) + return deleteResult.Errors; + } await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs index 2dbc7def..330b06ce 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Microsoft.EntityFrameworkCore; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -84,6 +85,23 @@ internal sealed class ThemeRepository : IThemeRepository .FirstOrDefaultAsync(theme => theme.ThemeId == themeId, cancellationToken).ConfigureAwait(false); } + /// + /// Deletes a theme identified by from the storage medium. + /// + /// The id of the theme to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + ThemeEntity? foundTheme = await _luminaDbContext.Themes + .FirstOrDefaultAsync(theme => theme.Id == id, cancellationToken).ConfigureAwait(false); + if (foundTheme is null) + return Errors.Themes.ThemeNotFound; + + _luminaDbContext.Themes.Remove(foundTheme); + return Result.Deleted; + } + /// /// Gets the currently active theme from the storage medium. /// diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index c13ef49a..910d4112 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -57,7 +57,8 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService } // themes that were soft deleted by the user must not be reinstalled automatically - HashSet knownThemeIds = [.. getThemesResult.Value.Select(theme => theme.ThemeId)]; + List themes = [.. getThemesResult.Value]; + HashSet knownThemeIds = [.. themes.Select(theme => theme.ThemeId)]; foreach (string archivePath in _themeService.GetBundledThemeArchivePaths()) { @@ -100,6 +101,72 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService _logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description); } + await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken); + await unitOfWork.SaveChangesAsync(stoppingToken); } + + /// + /// Restores the files of the damaged bundled themes that were not deleted by the user, and removes the damaged themes whose files could not be recovered. + /// + /// The unit of work for interacting with the theme repository. + /// The installed themes read from the storage medium. + /// Cancellation token that can be used to stop the execution. + private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List themes, CancellationToken cancellationToken) + { + // a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored + // automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed + // externally, and is the only case where the files are restored + List brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; + if (brokenThemes.Count is 0) + return; + + foreach (ThemeEntity brokenTheme in brokenThemes) + { + if (brokenTheme.InstallSource == ThemeInstallSource.Bundled) + { + // the files of a bundled theme that was not deleted by the user are restored from its shipped archive + Result restoreResult = await _themeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, cancellationToken); + if (restoreResult.IsSuccess) + continue; + + _logger.LogWarning("Failed to restore the files of bundled theme '{ThemeId}': {Error}", brokenTheme.ThemeId, restoreResult.FirstError.Description); + + // a bundled theme whose files could not be recovered is soft deleted, so it is not shown anymore, but can be restored later + brokenTheme.IsDeleted = true; + brokenTheme.IsCurrent = null; + brokenTheme.UpdatedOnUtc = DateTime.UtcNow; + brokenTheme.UpdatedBy = default; + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(brokenTheme, cancellationToken); + if (updateResult.IsFailure) + _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, updateResult.FirstError.Description); + } + else + { + // a user theme has no shipped archive to restore from, so damage is permanent and the theme is removed entirely + _logger.LogWarning("The stored files of user theme '{ThemeId}' are missing, so the theme is deleted.", brokenTheme.ThemeId); + brokenTheme.IsCurrent = null; + Result deleteResult = await unitOfWork.ThemeRepository.DeleteByIdAsync(brokenTheme.Id, cancellationToken); + if (deleteResult.IsFailure) + _logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description); + } + } + + // if the deleted theme was the active one, switch to another available theme, preferring the configured default + if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) + return; + + ThemeEntity? replacementTheme = themes + .Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId)) + .OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(); + if (replacementTheme is null) + return; + + replacementTheme.IsCurrent = true; + replacementTheme.UpdatedOnUtc = DateTime.UtcNow; + replacementTheme.UpdatedBy = default; + await unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken); + } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index a2ad40b6..d9e64869 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -105,6 +105,17 @@ public sealed class ThemeService : IThemeService return [.. Directory.EnumerateFiles(_bundledRoot, "*.zip").OrderBy(path => path, StringComparer.OrdinalIgnoreCase)]; } + /// + /// Checks whether the stored pack files of a theme still exist. + /// + /// The manifest id of the theme. + /// when the theme pack files exist, otherwise. + public bool HasThemePack(string themeId) + { + string themePath = ResolveThemePath(themeId); + return Directory.Exists(themePath) && File.Exists(Path.Combine(themePath, MANIFEST_FILE_NAME)); + } + /// /// Installs a theme pack from the provided archive, replacing the files of an existing theme with the same manifest id. /// diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 23efe7b7..176cedab 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -301,9 +301,9 @@ public static class PresentationWebLayerServices services.AddHttpContextAccessor(); services.Configure(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024); - services.AddSingleton(); + services.AddScoped(); services.AddSingleton(); - services.AddSingleton(); + services.AddScoped(); services.AddScoped(); services.AddScoped();