From 006df1da3a2f8c4454965ed8a7556c441cbfe582 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 12 Oct 2026 23:02:05 +0300 Subject: [PATCH] Moves the cancellation token to the last parameter position. --- .../Artwork/IMusicArtworkService.cs | 39 +- .../Artwork/MusicArtworkService.cs | 130 ++++++- .../MusicMediaLibraryScanArtworkEnricher.cs | 2 +- .../Artwork/MusicArtworkServiceTests.cs | 253 ++++++++++++- .../Artwork/MusicArtworkServiceTests.cs | 340 +++++++++++++++++- ...sicMediaLibraryScanArtworkEnricherTests.cs | 6 +- 6 files changed, 741 insertions(+), 29 deletions(-) diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs index 1754343c..3c1690e6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/IMusicArtworkService.cs @@ -2,6 +2,7 @@ using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.Primitives; using System; +using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -22,10 +23,25 @@ public interface IMusicArtworkService /// The name of the artist of the album. /// The title of the album. /// The artwork to store. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. /// Cancellation token that can be used to stop the execution. - /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. /// An containing either the relative path of the stored artwork, or an error. - Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null); + Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken); + + /// + /// Stores the uploaded of the album into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The stream of the uploaded artwork to store. + /// The name of the uploaded artwork file. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken); /// /// Deletes the stored artwork of the album from the internal media directory. @@ -50,6 +66,18 @@ public interface IMusicArtworkService /// An containing either the relative path of the stored artwork, or an error. Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken); + /// + /// Stores the uploaded of the artist into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The stream of the uploaded artwork to store. + /// The name of the uploaded artwork file. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken); + /// /// Deletes the stored artwork of the artist from the internal media directory. /// @@ -58,4 +86,11 @@ public interface IMusicArtworkService /// The name of the artist. /// An representing either a successful operation, or an error. Result DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName); + + /// + /// Deletes the stored artwork file at from the internal media directory, when it still exists. + /// + /// The relative path of the stored artwork file. + /// An representing either a successful operation, or an error. + Result DeleteStoredArtwork(string artworkRelativePath); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs index 28ccb723..a2c4866a 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkService.cs @@ -58,10 +58,10 @@ internal sealed class MusicArtworkService : IMusicArtworkService /// The name of the artist of the album. /// The title of the album. /// The artwork to store. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. /// Cancellation token that can be used to stop the execution. - /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When omitted, no release type segment is added. /// An containing either the relative path of the stored artwork, or an error. - public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null) + public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken) { Result artworkDirectoryPathResult = BuildAlbumArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); if (artworkDirectoryPathResult.IsFailure) @@ -86,6 +86,106 @@ internal sealed class MusicArtworkService : IMusicArtworkService return await SaveArtworkAsync(artworkDirectoryPathResult.Value, artwork, cancellationToken).ConfigureAwait(false); } + /// + /// Stores the uploaded of the album into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the album belongs to. + /// The Id of the album. + /// The name of the media library the album belongs to. + /// The name of the artist of the album. + /// The title of the album. + /// The stream of the uploaded artwork to store. + /// The name of the uploaded artwork file. + /// The name of the release type directory the album is stored under on disk, used to group the artwork of the different releases of an artist. When , no release type segment is added. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken) + { + // The uploaded bytes are persisted to a temporary file first, so that the storage pipeline can treat the upload like any other local artwork source and clean it up afterwards. + string temporaryPath = BuildTemporaryUploadPath(fileName); + try + { + await WriteUploadedArtworkAsync(artwork, temporaryPath, cancellationToken).ConfigureAwait(false); + return await SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), releaseTypeName, cancellationToken).ConfigureAwait(false); + } + finally + { + DeleteTemporaryFile(temporaryPath); + } + } + + /// + /// Stores the uploaded of the artist into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The stream of the uploaded artwork to store. + /// The name of the uploaded artwork file. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken) + { + // The uploaded bytes are persisted to a temporary file first, so that the storage pipeline can treat the upload like any other local artwork source and clean it up afterwards. + string temporaryPath = BuildTemporaryUploadPath(fileName); + try + { + await WriteUploadedArtworkAsync(artwork, temporaryPath, cancellationToken).ConfigureAwait(false); + return await SaveArtistArtworkAsync(libraryId, libraryName, artistName, new ArtworkDto(ArtworkType.Cover, 0, temporaryPath, null, IsTemporary: true), cancellationToken).ConfigureAwait(false); + } + finally + { + DeleteTemporaryFile(temporaryPath); + } + } + + /// + /// Builds the path of the temporary file an uploaded artwork is buffered into, keeping the extension of the uploaded file so that its content can be probed by name. + /// + /// The name of the uploaded artwork file. + /// The file system path of the temporary file. + private static string BuildTemporaryUploadPath(string fileName) + { + string extension = Path.GetExtension(fileName); + if (string.IsNullOrWhiteSpace(extension)) + extension = ".img"; + return Path.Combine(Path.GetTempPath(), $"lumina-upload-{Guid.NewGuid():N}{extension}"); + } + + /// + /// Copies the uploaded stream into the temporary file at . + /// + /// The stream of the uploaded artwork. + /// The file system path of the temporary file. + /// Cancellation token that can be used to stop the execution. + private static async Task WriteUploadedArtworkAsync(Stream artwork, string temporaryPath, CancellationToken cancellationToken) + { + await using FileStream fileStream = new(temporaryPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true); + await artwork.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes the temporary file at , ignoring the failures that must not mask the result of the operation. + /// + /// The file system path of the temporary file. + private static void DeleteTemporaryFile(string temporaryPath) + { + if (!File.Exists(temporaryPath)) + return; + try + { + File.Delete(temporaryPath); + } + catch (IOException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + catch (UnauthorizedAccessException) + { + // A failed cleanup of the temporary file must not mask the result of the operation. + } + } + /// /// Resolves the local source of the , stores it into , and cleans up the temporary download of a remote artwork. /// @@ -159,6 +259,32 @@ internal sealed class MusicArtworkService : IMusicArtworkService return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value); } + /// + /// Deletes the stored artwork file at from the internal media directory, when it still exists. + /// + /// The relative path of the stored artwork file. + /// An representing either a successful operation, or an error. + public Result DeleteStoredArtwork(string artworkRelativePath) + { + if (string.IsNullOrWhiteSpace(artworkRelativePath)) + return Result.Deleted; + + // The stored path is relative to the application's base directory, so it is rooted back to the absolute path of the file to delete. + string absolutePath = Path.Combine(AppContext.BaseDirectory, artworkRelativePath.TrimStart(_pathService.PathSeparator)); + Result filePathIdResult = FileSystemPathId.Create(absolutePath); + if (filePathIdResult.IsFailure) + return filePathIdResult.Errors; + + Result fileExistsResult = _environmentContext.FileProviderService.FileExists(filePathIdResult.Value); + if (fileExistsResult.IsFailure) + return fileExistsResult.Errors; + if (!fileExistsResult.Value) + return Result.Deleted; + + _environmentContext.FileProviderService.DeleteFile(filePathIdResult.Value); + return Result.Deleted; + } + /// /// Deletes the files directly contained in , leaving the subdirectories, such as the album directories of an artist, untouched. /// diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs index 17ff4a58..1a4e4c05 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricher.cs @@ -381,7 +381,7 @@ internal sealed class MusicMediaLibraryScanArtworkEnricher : IMediaLibraryScanAr musicArtworkService, fileHashService, () => musicArtworkService!.DeleteAlbumArtwork(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, releaseTypeName), - (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, token, releaseTypeName), + (artwork, token) => musicArtworkService!.SaveAlbumArtworkAsync(albumEntity.LibraryId, albumEntity.Id, libraryName, artistName, albumEntity.Title, artwork, releaseTypeName, token), shouldAggregateArtworkWhenMissing, unitOfWork, cancellationToken).ConfigureAwait(false); diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs index 50f9f53d..16dcb9c1 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -104,7 +104,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(renamedFileId)); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -150,7 +150,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, expectedFileName)))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -187,7 +187,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -218,7 +218,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -246,7 +246,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -272,7 +272,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -309,7 +309,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -327,7 +327,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -342,7 +342,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -375,7 +375,7 @@ public class MusicArtworkServiceTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), null, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -402,7 +402,7 @@ public class MusicArtworkServiceTests // Act async Task Act() { - await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), cancellationTokenSource.Token); + await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), null, cancellationTokenSource.Token); } // Assert @@ -422,7 +422,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -458,7 +458,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("Directory.Error", "Failed to create the artwork directory")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -494,7 +494,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("Directory.Error", "Failed to check the artwork directory")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -530,7 +530,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("FileSystem.Error", "Failed to copy the artwork")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -568,7 +568,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("FileSystem.Error", "Failed to rename the artwork")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -613,7 +613,7 @@ public class MusicArtworkServiceTests }); // Act - Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -654,6 +654,193 @@ public class MusicArtworkServiceTests _mockFileProviderService.Received(1).DeleteFile(bookletFileId); } + [Fact] + public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreTheFileOnDiskAndDeleteTheTemporaryUpload() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + byte[] uploadedBytes = [10, 20, 30, 40, 50]; + string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId); + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.jpg"); + string? temporaryUploadPath = null; + MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + await using MemoryStream artworkStream = new(uploadedBytes); + try + { + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedStoredPath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + Assert.True(File.Exists(expectedStoredPath)); + Assert.Equal(uploadedBytes, File.ReadAllBytes(expectedStoredPath)); + Assert.NotNull(temporaryUploadPath); + Assert.StartsWith(Path.GetTempPath(), temporaryUploadPath); + Assert.EndsWith(".jpg", temporaryUploadPath); + Assert.False(File.Exists(temporaryUploadPath)); + } + finally + { + if (Directory.Exists(libraryDirectoryPath)) + Directory.Delete(libraryDirectoryPath, recursive: true); + } + } + + [Fact] + public async Task SaveArtistArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreTheFileOnDiskAndDeleteTheTemporaryUpload() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + byte[] uploadedBytes = [60, 70, 80, 90]; + string libraryDirectoryPath = BuildLibraryDirectoryPath(libraryName, libraryId); + string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + string expectedStoredPath = Path.Combine(artworkDirectoryPath, "cover.png"); + string? temporaryUploadPath = null; + MockRealFileSystemStubs(pathId => temporaryUploadPath = pathId.Path); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + await using MemoryStream artworkStream = new(uploadedBytes); + try + { + // Act + Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedStoredPath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + Assert.True(File.Exists(expectedStoredPath)); + Assert.Equal(uploadedBytes, File.ReadAllBytes(expectedStoredPath)); + Assert.NotNull(temporaryUploadPath); + Assert.StartsWith(Path.GetTempPath(), temporaryUploadPath); + Assert.EndsWith(".png", temporaryUploadPath); + Assert.False(File.Exists(temporaryUploadPath)); + } + finally + { + if (Directory.Exists(libraryDirectoryPath)) + Directory.Delete(libraryDirectoryPath, recursive: true); + } + } + + [Fact] + public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteTheRealFile() + { + // Arrange + string libraryDirectoryPath = Path.Combine(AppContext.BaseDirectory, "media", "music", $"delete-{Guid.NewGuid():N}"); + Directory.CreateDirectory(libraryDirectoryPath); + string artworkPath = Path.Combine(libraryDirectoryPath, "cover.jpg"); + File.WriteAllBytes(artworkPath, [1, 2, 3]); + string artworkRelativePath = artworkPath[AppContext.BaseDirectory.Length..].Insert(0, "\\"); + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(callInfo => Result.From(File.Exists(callInfo.Arg().Path))); + _mockFileProviderService.DeleteFile(Arg.Any()) + .Returns(callInfo => + { + File.Delete(callInfo.Arg().Path); + return Result.Deleted; + }); + try + { + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath); + + // Assert + Assert.False(result.IsFailure); + Assert.False(File.Exists(artworkPath)); + } + finally + { + if (Directory.Exists(libraryDirectoryPath)) + Directory.Delete(libraryDirectoryPath, recursive: true); + } + } + + [Fact] + public void DeleteStoredArtwork_WhenTheFileIsMissing_ShouldReturnDeleted() + { + // Arrange + string artworkRelativePath = $"\\media\\music\\missing-{Guid.NewGuid():N}.jpg"; + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Theory] + [InlineData(null)] // a null path is a no-op + [InlineData("")] // an empty path is a no-op + [InlineData(" ")] // a whitespace path is a no-op + public void DeleteStoredArtwork_WhenThePathIsMissing_ShouldReturnDeletedWithoutTouchingTheFileSystem(string? artworkRelativePath) + { + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath!); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.DidNotReceive().FileExists(Arg.Any()); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + /// + /// Stubs the path and file system services so that the artwork storage pipeline performs real file system operations. + /// + /// Optional callback invoked with the source file of every file copy, used to observe the temporary upload. + private void MockRealFileSystemStubs(Action? onCopySource = null) + { + MockPathBuilding(); + + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(callInfo => Result.From(File.Exists(callInfo.Arg().Path))); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(Directory.Exists(callInfo.Arg().Path))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + string createdDirectoryPath = Path.Combine(callInfo.ArgAt(0).Path, callInfo.ArgAt(1)); + Directory.CreateDirectory(createdDirectoryPath); + return Result.From(_fileSystemPathIdFixture.Create(createdDirectoryPath)); + }); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(callInfo => + { + FileSystemPathId sourcePathId = callInfo.ArgAt(0); + FileSystemPathId destinationDirectoryPathId = callInfo.ArgAt(1); + onCopySource?.Invoke(sourcePathId); + string destinationFilePath = Path.Combine(destinationDirectoryPathId.Path, Path.GetFileName(sourcePathId.Path)); + File.Copy(sourcePathId.Path, destinationFilePath, overwrite: true); + return Result.From(_fileSystemPathIdFixture.Create(destinationFilePath)); + }); + _mockFileProviderService.RenameFile(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + FileSystemPathId sourcePathId = callInfo.ArgAt(0); + string newFileName = callInfo.ArgAt(1); + string renamedFilePath = Path.Combine(Path.GetDirectoryName(sourcePathId.Path)!, newFileName); + File.Move(sourcePathId.Path, renamedFilePath); + return Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)); + }); + _mockFileProviderService.DeleteFile(Arg.Any()) + .Returns(callInfo => + { + File.Delete(callInfo.Arg().Path); + return Result.Deleted; + }); + } + /// /// Stubs the path service so that building the artwork directory paths succeeds. /// @@ -708,6 +895,38 @@ public class MusicArtworkServiceTests $"{albumTitle}-{albumId}"); } + /// + /// Builds the file system path of the directory of a music media library. + /// + /// The name of the media library. + /// The Id of the media library. + /// The expected file system path of the music media library directory. + private static string BuildLibraryDirectoryPath(string libraryName, Guid libraryId) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}"); + } + + /// + /// Builds the file system path of the directory that the artwork of the artist is stored into. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The expected file system path of the artist artwork directory. + private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName); + } + /// /// Creates a temporary image file and returns its path. /// diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs index f79aef01..9ca8eaa9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artwork/MusicArtworkServiceTests.cs @@ -8,6 +8,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork; using Microsoft.Extensions.Options; using NSubstitute; @@ -75,7 +76,7 @@ public class MusicArtworkServiceTests _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -90,7 +91,7 @@ public class MusicArtworkServiceTests MockPathBuilding(); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -107,7 +108,7 @@ public class MusicArtworkServiceTests .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); // Act - Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + Result result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -196,6 +197,307 @@ public class MusicArtworkServiceTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + [Fact] + public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + byte[] uploadedBytes = [1, 2, 3, 4, 5, 6, 7, 8]; + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); + string? capturedTemporaryPath = null; + byte[]? capturedBytes = null; + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(callInfo => + { + capturedTemporaryPath = callInfo.ArgAt(0).Path; + capturedBytes = File.ReadAllBytes(capturedTemporaryPath); + return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg"))); + }); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath))); + await using MemoryStream artworkStream = new(uploadedBytes); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + Assert.NotNull(capturedTemporaryPath); + Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath); + Assert.EndsWith(".jpg", capturedTemporaryPath); + Assert.Equal(uploadedBytes, capturedBytes); + Assert.False(File.Exists(capturedTemporaryPath)); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpg"); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploadedWithAReleaseType_ShouldStoreTheArtworkUnderTheReleaseTypeDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + string releaseTypeName = "Single"; + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle, releaseTypeName); + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg"); + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath))); + await using MemoryStream artworkStream = new([1, 2, 3]); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).CopyFile( + Arg.Any(), + Arg.Is(pathId => pathId.Path == artworkDirectoryPath), + true); + } + + [Fact] + public async Task SaveAlbumArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string? capturedTemporaryPath = null; + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(callInfo => + { + capturedTemporaryPath = callInfo.ArgAt(0).Path; + return Error.Failure("FileSystem.Error", "Failed to copy the artwork"); + }); + await using MemoryStream artworkStream = new([1, 2, 3, 4]); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + Assert.NotNull(capturedTemporaryPath); + Assert.False(File.Exists(capturedTemporaryPath)); + _mockFileProviderService.DidNotReceive().RenameFile(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("cover")] // a name without an extension falls back to the .img extension + [InlineData("")] // an empty name falls back to the .img extension + [InlineData(null)] // a null name falls back to the .img extension + public async Task SaveAlbumArtworkAsync_WhenTheUploadedFileNameHasNoExtension_ShouldBufferTheUploadWithTheImgExtension(string? fileName) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string albumTitle = "Test Album"; + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistName, albumTitle); + string? capturedTemporaryPath = null; + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(callInfo => + { + capturedTemporaryPath = callInfo.ArgAt(0).Path; + return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.img"))); + }); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + await using MemoryStream artworkStream = new([1, 2, 3]); + + // Act + Result result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(capturedTemporaryPath); + Assert.EndsWith(".img", capturedTemporaryPath); + } + + [Fact] + public async Task SaveArtistArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + byte[] uploadedBytes = [9, 8, 7, 6, 5]; + string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.png"); + string? capturedTemporaryPath = null; + byte[]? capturedBytes = null; + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(callInfo => + { + capturedTemporaryPath = callInfo.ArgAt(0).Path; + capturedBytes = File.ReadAllBytes(capturedTemporaryPath); + return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.png"))); + }); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.png") + .Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath))); + await using MemoryStream artworkStream = new(uploadedBytes); + + // Act + Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + Assert.NotNull(capturedTemporaryPath); + Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath); + Assert.EndsWith(".png", capturedTemporaryPath); + Assert.Equal(uploadedBytes, capturedBytes); + Assert.False(File.Exists(capturedTemporaryPath)); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.png"); + } + + [Fact] + public async Task SaveArtistArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + string libraryName = "Test Library"; + string artistName = "Test Artist"; + string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistName); + string? capturedTemporaryPath = null; + MockArtworkDirectoryStubs(artworkDirectoryPath); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(callInfo => + { + capturedTemporaryPath = callInfo.ArgAt(0).Path; + return Error.Failure("FileSystem.Error", "Failed to copy the artwork"); + }); + await using MemoryStream artworkStream = new([1, 2, 3]); + + // Act + Result result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistName, artworkStream, "cover.png", CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + Assert.NotNull(capturedTemporaryPath); + Assert.False(File.Exists(capturedTemporaryPath)); + } + + [Theory] + [InlineData(null)] // a null path is a no-op + [InlineData("")] // an empty path is a no-op + [InlineData(" ")] // a whitespace path is a no-op + public void DeleteStoredArtwork_WhenThePathIsMissing_ShouldReturnDeletedWithoutTouchingTheFileSystem(string? artworkRelativePath) + { + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath!); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.DidNotReceive().FileExists(Arg.Any()); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Fact] + public void DeleteStoredArtwork_WhenTheFileDoesNotExist_ShouldReturnDeleted() + { + // Arrange + string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg"; + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Fact] + public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteItAndReturnDeleted() + { + // Arrange + string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg"; + string expectedAbsolutePath = Path.Combine(AppContext.BaseDirectory, artworkRelativePath.TrimStart('\\')); + _mockFileProviderService.FileExists(Arg.Is(pathId => pathId.Path == expectedAbsolutePath)) + .Returns(Result.From(true)); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(Arg.Is(pathId => pathId.Path == expectedAbsolutePath)); + } + + [Fact] + public void DeleteStoredArtwork_WhenTheExistenceCheckFails_ShouldReturnTheError() + { + // Arrange + string artworkRelativePath = "\\media\\music\\cover.jpg"; + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file")); + + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("FileSystem.Error", result.FirstError.Code); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Fact] + public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnDeleted() + { + // Arrange + string artworkRelativePath = "\\media\\music\\cover.jpg"; + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileProviderService.DeleteFile(Arg.Any()) + .Returns(Error.Failure("FileSystem.Error", "Failed to delete the artwork file")); + + // Act + Result result = _sut.DeleteStoredArtwork(artworkRelativePath); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(Arg.Any()); + } + /// /// Stubs the path service so that building the artwork directory paths succeeds. /// @@ -238,15 +540,45 @@ public class MusicArtworkServiceTests /// The name of the media library the album belongs to. /// The name of the artist of the album. /// The title of the album. + /// Optional. The name of the release type directory the album is stored under. /// The expected file system path of the album artwork directory. - private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle) + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, string? releaseTypeName = null) { + if (string.IsNullOrWhiteSpace(releaseTypeName)) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName, + $"{albumTitle}-{albumId}"); + } + return Path.Combine( AppContext.BaseDirectory, "media", "music", $"{libraryName}-{libraryId}", artistName, + releaseTypeName, $"{albumTitle}-{albumId}"); } + + /// + /// Builds the file system path of the directory that the artwork of the artist is stored into. + /// + /// The Id of the media library the artist belongs to. + /// The name of the media library the artist belongs to. + /// The name of the artist. + /// The expected file system path of the artist artwork directory. + private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "music", + $"{libraryName}-{libraryId}", + artistName); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs index 3c5e645b..a70367fc 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Audio/Music/MusicMediaLibraryScanArtworkEnricherTests.cs @@ -272,8 +272,8 @@ public class MusicMediaLibraryScanArtworkEnricherTests Arg.Any(), album.Title, Arg.Is(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0), - Arg.Any(), - Arg.Any()); + Arg.Any(), + Arg.Any()); await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any()); await _mockMusicArtworkRepository.Received(1).InsertRangeAsync( Arg.Is>(entities => entities.Count == 1 @@ -553,7 +553,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests { _mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From("/media/music/cover.jpg")); - _mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From("/media/music/cover.jpg")); _mockMusicArtworkService.DeleteArtistArtwork(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted); _mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Deleted);