diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 7f4f1017..52de01c6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -93,8 +93,16 @@ public class UpdateLibraryCommandHandler : ICommandHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + else if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is + // relative to the application base directory and is already validated, so it must not block saving unrelated changes + if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage) { Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); if (fileSystemPathIdResult.IsFailure) @@ -107,13 +115,6 @@ public class UpdateLibraryCommandHandler : ICommandHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure) - return getLibraryResult.Errors; - else if (getLibraryResult.Value is null) - return DomainErrors.Library.LibraryNotFound; - // admins or users with the permission to manage media libraries can update any library; other users can only update the libraries they own bool hasManagePermission = await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false); bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index d1a8f916..9772737d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -107,6 +107,22 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler + /// Resolves a media file path stored relative to the application base directory into an absolute file system path. + /// The stored path was created by removing the base directory from the copied file path, so it is resolved by prepending the + /// base directory back. The path is built directly instead of using , because that method + /// treats the combined name as a directory segment and appends a trailing separator, which would make the file path invalid. + /// + /// The path relative to the application base directory, with a leading path separator. + /// An containing the absolute path, or an error. + private Result ResolveInternalMediaPathId(string relativePath) + { + string absolutePath = AppContext.BaseDirectory.TrimEnd(_pathService.PathSeparator) + + _pathService.PathSeparator + + relativePath.TrimStart(_pathService.PathSeparator); + return FileSystemPathId.Create(absolutePath); + } + /// /// Saves the cover image of a media library to the internal media directory. /// @@ -125,8 +141,21 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler fileExistsResult = _environmentContext.FileProviderService.FileExists(fileSystemPathIdResult.Value); if (fileExistsResult.IsFailure) return fileExistsResult.Errors; + + // when the library is saved without changing its cover, the stored cover image path is already the internal media directory + // path, relative to the application base directory; resolve it against the base directory and keep it when the file is found if (!fileExistsResult.Value) + { + Result internalImagePathIdResult = ResolveInternalMediaPathId(imagePath); + if (internalImagePathIdResult.IsFailure) + return internalImagePathIdResult.Errors; + Result internalFileExistsResult = _environmentContext.FileProviderService.FileExists(internalImagePathIdResult.Value); + if (internalFileExistsResult.IsFailure) + return internalFileExistsResult.Errors; + if (internalFileExistsResult.Value) + return imagePath; return Errors.FileSystemManagement.FileNotFound; + } // make sure the file is an actual supported image Result imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index 8b4b5ead..075425c5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -168,6 +168,11 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = "C:/Users/user/cover.jpg" }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.None)); @@ -177,7 +182,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -186,6 +191,11 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = "C:/Users/user/cover.jpg" }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to determine image type")); @@ -194,7 +204,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -204,6 +214,10 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = " " }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -211,10 +225,31 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenCoverImageIsUnchanged_ShouldSkipImageTypeCheck() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = command.CoverImage; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockEnvironmentContext.FileTypeService.DidNotReceive() + .GetImageTypeAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs index a7c49d0f..267c59ec 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -156,6 +156,30 @@ public class LibrarySavedDomainEventHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenCoverImageIsAlreadyInMediaDirectory_ShouldKeepItWithoutRecopying() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "/Media/Libraries/guid/cover.png"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + // mirror the real CombinePath behavior, which treats the combined name as a directory segment and appends a trailing + // separator; the internal cover path resolution must still yield the file path without that trailing separator + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt(0), callInfo.ArgAt(1)) + '/')); + string internalImagePath = $"{AppContext.BaseDirectory.TrimEnd('/')}/Media/Libraries/guid/cover.png"; + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(callInfo => Result.From(callInfo.Arg().Path == internalImagePath)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCoverSourceFileDoesNotExist_ShouldThrowEventualConsistencyException() {