mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Fixes library cover image handling on save
Validates the cover image only when a new one is chosen, so an unchanged stored cover does not block saving unrelated changes, and keeps the cover already copied to the internal media directory instead of re-copying the stored relative path, which was treated as an absolute file system path.
This commit is contained in:
1 parent
00dcf3d471
commit
ccefb65c83
4 files changed
+101
-12
No files matched your search
+10
-9
@@ -93,8 +93,16 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// make sure the file is an actual supported image
|
||||
if (command.CoverImage is not null)
|
||||
// get a library repository and retrieve the library to update
|
||||
Result<LibraryEntity?> 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<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
|
||||
if (fileSystemPathIdResult.IsFailure)
|
||||
@@ -107,13 +115,6 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
||||
return DomainErrors.Library.CoverFileMustBeAnImage;
|
||||
}
|
||||
|
||||
// get a library repository and retrieve the library to update
|
||||
Result<LibraryEntity?> 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<ILibraryOwnershipPolicy>(
|
||||
|
||||
+29
@@ -107,6 +107,22 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
return libraryPathResult.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="IPathService.CombinePath"/>, because that method
|
||||
/// treats the combined name as a directory segment and appends a trailing separator, which would make the file path invalid.
|
||||
/// </summary>
|
||||
/// <param name="relativePath">The path relative to the application base directory, with a leading path separator.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing the absolute path, or an error.</returns>
|
||||
private Result<FileSystemPathId> ResolveInternalMediaPathId(string relativePath)
|
||||
{
|
||||
string absolutePath = AppContext.BaseDirectory.TrimEnd(_pathService.PathSeparator)
|
||||
+ _pathService.PathSeparator
|
||||
+ relativePath.TrimStart(_pathService.PathSeparator);
|
||||
return FileSystemPathId.Create(absolutePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the cover image of a media library to the internal media directory.
|
||||
/// </summary>
|
||||
@@ -125,8 +141,21 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler<LibrarySavedDo
|
||||
Result<bool> 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<FileSystemPathId> internalImagePathIdResult = ResolveInternalMediaPathId(imagePath);
|
||||
if (internalImagePathIdResult.IsFailure)
|
||||
return internalImagePathIdResult.Errors;
|
||||
Result<bool> 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<ImageType> imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+38
-3
@@ -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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(existingLibrary));
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(existingLibrary));
|
||||
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(existingLibrary));
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> 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<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<CancellationToken>())
|
||||
.Returns(Result.From<LibraryEntity?>(existingLibrary));
|
||||
|
||||
// Act
|
||||
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockEnvironmentContext.FileTypeService.DidNotReceive()
|
||||
.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError()
|
||||
{
|
||||
|
||||
+24
@@ -156,6 +156,30 @@ public class LibrarySavedDomainEventHandlerTests
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[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<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1)) + '/'));
|
||||
string internalImagePath = $"{AppContext.BaseDirectory.TrimEnd('/')}/Media/Libraries/guid/cover.png";
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(callInfo.Arg<FileSystemPathId>().Path == internalImagePath));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(domainEvent, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage);
|
||||
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), Arg.Any<bool>());
|
||||
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCoverSourceFileDoesNotExist_ShouldThrowEventualConsistencyException()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user