mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Refreshes the bundled themes whose shipped version changes.
This commit is contained in:
1 parent
443f4612f8
commit
b29803ac77
4 files changed
+185
-11
No files matched your search
@@ -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<Updated> 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<Success> saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
@@ -189,8 +208,9 @@ internal static class ThemeSynchronizer
|
||||
/// <param name="themeService">Injected service for the server-side storage and serving of theme packs.</param>
|
||||
/// <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="logger">Injected logger used for logging.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
|
||||
private static async Task EnsureCurrentThemeExistsAsync(IThemeService themeService, IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> 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<Updated> 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);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
+156
-4
@@ -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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).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<CancellationToken>()).Returns(Result.From(manifest));
|
||||
@@ -111,6 +111,28 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).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<CancellationToken>()).Returns(Result.From(manifest));
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
|
||||
|
||||
// Act
|
||||
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.ThemeId == manifest.Id && theme.Version == "2.0.0"), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -420,6 +442,112 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).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<CancellationToken>()).Returns(Result.From(manifest));
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).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<ThemeEntity>(theme => theme.Id == installedTheme.Id && theme.Version == "3.0.0"),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).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<CancellationToken>()).Returns(Result.From(manifest));
|
||||
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
|
||||
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
|
||||
.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<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).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<CancellationToken>()).Returns(Result.From(manifest));
|
||||
|
||||
// Act
|
||||
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).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<CancellationToken>()).Returns(Result.From(manifest));
|
||||
|
||||
// Act
|
||||
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme()
|
||||
{
|
||||
@@ -467,6 +595,30 @@ public class ThemeSynchronizerTests : IDisposable
|
||||
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == defaultTheme.Id), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<ThemeEntity>(), Arg.Any<CancellationToken>())
|
||||
.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<ThemeEntity>(theme => theme.Id == defaultTheme.Id), Arg.Any<CancellationToken>());
|
||||
// A failed activation must not be silent, so it is logged instead of being discarded.
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Any<object>(),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a real archive file on disk so that <see cref="ThemeSynchronizer"/> can open it.
|
||||
/// </summary>
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user