Merge pull request #292 from BinaryAlley/bugfix/honor-music-artwork-deletion-results

Honors music artwork deletion results and keeps stored artwork records consistent
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-11-16 23:42:52 +02:00
commit b056dbd28f
4 files changed
+61 -4

No files matched your search

@@ -292,6 +292,7 @@ internal sealed class MusicArtworkService : IMusicArtworkService
/// <summary>
/// Deletes the files directly contained in <paramref name="artworkDirectoryPath"/>, leaving the subdirectories, such as the album directories of an artist, untouched.
/// The deletion stops at the first file that cannot be deleted, returning its error, so that a locked or read-only file is never silently ignored.
/// </summary>
/// <param name="artworkDirectoryPath">The file system path of the directory whose files are deleted.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
@@ -313,7 +314,12 @@ internal sealed class MusicArtworkService : IMusicArtworkService
return getFilesResult.Errors;
foreach (FileSystemPathId filePathId in getFilesResult.Value)
_environmentContext.FileProviderService.DeleteFile(filePathId);
{
// The bulk path stops at the first failure, because the artwork enricher only observes the bulk result: reporting the failure lets it retry the owner instead of storing new artwork over a file that could not be cleared.
Result<Deleted> deleteFileResult = _environmentContext.FileProviderService.DeleteFile(filePathId);
if (deleteFileResult.IsFailure)
return deleteFileResult.Errors;
}
return Result.Deleted;
}
@@ -415,6 +415,18 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr
if (deleteStoredArtworkResult.IsFailure)
{
_logger.LogWarning("Failed to clear the stored artwork files of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
// Some files may have been deleted before the failure, so the stored records are dropped and the owner is marked as failed,
// keeping it eligible for a retry without serving the paths of the files that no longer exist.
Result<Deleted> deleteFailedEntitiesResult = await unitOfWork.MusicArtworkRepository.DeleteByOwnerAsync(ownerType, ownerId, cancellationToken).ConfigureAwait(false);
if (deleteFailedEntitiesResult.IsFailure)
_logger.LogWarning("Failed to clear the stored artwork records of the {OwnerType} '{OwnerDescription}'.", ownerType, ownerDescription);
else
{
List<MusicArtworkEntity> failedArtworkEntities = [CreateArtworkEntity(ownerId, ownerType, ArtworkType.Cover, 0, null, 0, ArtworkStatus.Failed, null)];
await PersistArtworkAsync(unitOfWork, failedArtworkEntities, cancellationToken).ConfigureAwait(false);
}
DeleteTemporaryArtworks(resolution.Artworks.Select(resolvedArtwork => resolvedArtwork.Artwork));
return false;
}
@@ -170,6 +170,37 @@ public class MusicArtworkServiceTests
_mockFileProviderService.Received(1).DeleteFile(bookletFileId);
}
[Fact]
public void DeleteAlbumArtwork_WhenDeletingAFileFails_ShouldReturnTheErrorAndStopDeletingTheRemainingFiles()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg"));
Error deleteError = Errors.FileSystemManagement.FileDeleteError;
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
_mockFileProviderService.DeleteFile(coverFileId).Returns(deleteError);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(deleteError, result.FirstError);
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
_mockFileProviderService.DidNotReceive().DeleteFile(bookletFileId);
}
[Fact]
public void DeleteAlbumArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
{
@@ -343,7 +343,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
}
[Fact]
public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldLeaveTheArtistUnresolved()
public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldClearTheStoredArtworkRecordsAndMarkTheArtistFailed()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
@@ -356,8 +356,16 @@ public class MusicMediaLibraryScanArtworkEnricherTests
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkRepository.DidNotReceive().DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
&& entities.First().OwnerType == MusicArtworkOwnerType.Artist
&& entities.First().OwnerId == artist.Id
&& entities.First().Status == ArtworkStatus.Failed
&& entities.First().FileName == null),
Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
}
[Fact]