diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs index 278e3175..3ce050ad 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -53,9 +53,17 @@ internal static class ThemeSynchronizer ThemeEntity? existingTheme = themes.Where(theme => theme.ThemeId == manifestResult.Value.Id).FirstOrDefault(); - // A theme that was soft deleted by the user must not be reinstalled automatically; an installed bundled theme - // whose files are present is already in sync, so only a bundled theme whose files went missing gets its files reinstalled. - if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled || themeService.HasThemePack(existingTheme.ThemeId))) + // A theme that was soft deleted by the user must not be reinstalled automatically, and a theme installed from + // another source (like an uploaded pack) is never replaced by a bundled archive. + if (existingTheme is not null && (existingTheme.IsDeleted || existingTheme.InstallSource != ThemeInstallSource.Bundled)) + continue; + + // A bundled theme that is already installed is reinstalled when its files went missing, or when the shipped + // archive carries a new version, so that content updates of the bundled themes reach the installed packs. + bool isBundledThemeOutOfDate = existingTheme is not null + && (!themeService.HasThemePack(existingTheme.ThemeId) + || !string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal)); + if (existingTheme is not null && !isBundledThemeOutOfDate) continue; // Installing a bundled theme at startup is best effort: a file system failure here must never crash the host, because the default @@ -70,9 +78,20 @@ internal static class ThemeSynchronizer continue; } - // A known theme only gets its missing files reinstalled, so no new row is inserted. + // A known theme is refreshed in place, so its row is updated with the shipped version instead of a new row being inserted. if (existingTheme is not null) + { + if (!string.Equals(existingTheme.Version, manifestResult.Value.Version, StringComparison.Ordinal)) + { + existingTheme.Version = manifestResult.Value.Version; + existingTheme.UpdatedOnUtc = DateTime.UtcNow; + existingTheme.UpdatedBy = default; + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(existingTheme, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + logger.LogWarning("Failed to update the version of theme '{ThemeId}': {Error}", existingTheme.ThemeId, updateResult.FirstError.Description); + } continue; + } ThemeEntity themeEntity = new() { @@ -107,7 +126,7 @@ internal static class ThemeSynchronizer } await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); - await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false); + await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (saveChangesResult.IsFailure) @@ -189,8 +208,9 @@ internal static class ThemeSynchronizer /// Injected service for the server-side storage and serving of theme packs. /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. + /// Injected logger used for logging. /// Cancellation token that can be used to stop the execution. - private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, CancellationToken cancellationToken) + private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList themes, ILogger logger, CancellationToken cancellationToken) { if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true)) return; @@ -209,6 +229,8 @@ internal static class ThemeSynchronizer defaultTheme.IsCurrent = true; defaultTheme.UpdatedOnUtc = DateTime.UtcNow; defaultTheme.UpdatedBy = default; - await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); + Result updateResult = await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + logger.LogWarning("Failed to activate theme '{ThemeId}': {Error}", defaultTheme.ThemeId, updateResult.FirstError.Description); } } diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index d7b349d1..7fd8df7e 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index 5d6dfbf4..86127920 100644 Binary files a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip and b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip differ diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs index 4dc26415..57715c76 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -96,11 +96,11 @@ public class ThemeSynchronizerTests : IDisposable } [Fact] - public async Task SynchronizeAsync_WhenTheBundledThemeIsAlreadyInstalled_ShouldNotReinstallIt() + public async Task SynchronizeAsync_WhenTheBundledThemeIsAlreadyInstalledAtTheSameVersion_ShouldNotReinstallIt() { // Arrange - ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); - ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.2.3"); + ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.2.3", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); @@ -111,6 +111,28 @@ public class ThemeSynchronizerTests : IDisposable // Assert await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenTheBundledThemeCarriesANewerVersion_ShouldReinstallItAndUpdateTheVersion() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0"); + ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.Received(1).InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.ThemeId == manifest.Id && theme.Version == "2.0.0"), Arg.Any()); } [Fact] @@ -420,6 +442,112 @@ public class ThemeSynchronizerTests : IDisposable await Assert.ThrowsAsync(Act); } + [Fact] + public async Task SynchronizeAsync_WhenTheBundledThemeVersionDiffers_ShouldRefreshTheVersionTimestampAndUpdater() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0"); + ThemeEntity installedTheme = _themeEntityFixture.Create( + themeId: manifest.Id, + version: "1.0.0", + installSource: ThemeInstallSource.Bundled, + isDeleted: false, + includeIsCurrent: true, + isCurrent: true, + includeUpdatedOnUtc: true, + updatedOnUtc: DateTime.UtcNow.AddDays(-1), + includeUpdatedBy: true, + updatedBy: Guid.NewGuid()); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + Assert.Equal("3.0.0", installedTheme.Version); + Assert.NotNull(installedTheme.UpdatedOnUtc); + Assert.Null(installedTheme.UpdatedBy); + await _mockThemeRepository.Received(1).UpdateAsync( + Arg.Is(theme => theme.Id == installedTheme.Id && theme.Version == "3.0.0"), + Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenRefreshingTheInstalledThemeVersionFails_ShouldLogAndContinueWithoutThrowing() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0"); + ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + _mockThemeService.InstallAsync(Arg.Any(), Arg.Any()).Returns(Result.From(manifest)); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Themes.UpdateFailed", "Failed to update the theme")); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenAThemeWithTheSameIdWasInstalledFromAnotherSource_ShouldSkipTheBundledArchive() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0"); + ThemeEntity uploadedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); + _mockThemeService.HasThemePack(uploadedTheme.ThemeId).Returns(true); + _mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SynchronizeAsync_WhenABundledThemeIsAlreadyInstalledAndUpToDate_ShouldSkipIt() + { + // Arrange + ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.5.0"); + ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.5.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1))); + string archivePath = CreateArchiveFile(); + _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); + _mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true); + _mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any()).Returns(Result.From(manifest)); + + // Act + await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); + + // Assert + await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + [Fact] public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme() { @@ -467,6 +595,30 @@ public class ThemeSynchronizerTests : IDisposable await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any()); } + [Fact] + public async Task EnsureCurrentThemeExistsAsync_WhenActivatingTheDefaultThemeFails_ShouldLogAndNotThrow() + { + // Arrange + ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "lumina-default", installSource: ThemeInstallSource.Bundled, isDeleted: false); + _mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true); + _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure("Themes.UpdateFailed", "Failed to activate the theme")); + + // Act + await InvokeEnsureCurrentThemeExistsAsync([defaultTheme]); + + // Assert + Assert.True(defaultTheme.IsCurrent); + await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is(theme => theme.Id == defaultTheme.Id), Arg.Any()); + // A failed activation must not be silent, so it is logged instead of being discarded. + _mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + /// /// Creates a real archive file on disk so that can open it. /// @@ -487,7 +639,7 @@ public class ThemeSynchronizerTests : IDisposable { MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic) ?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer."); - Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, CancellationToken.None])!; + Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, _mockLogger, CancellationToken.None])!; await task.ConfigureAwait(false); }