mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Moves the cancellation token to the last parameter position.
This commit is contained in:
1 parent
9a7a1dffb2
commit
006df1da3a
6 files changed
+741
-29
No files matched your search
+37
-2
@@ -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
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <param name="releaseTypeName">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.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null);
|
||||
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Stores the uploaded <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
|
||||
/// <param name="fileName">The name of the uploaded artwork file.</param>
|
||||
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, Stream artwork, string fileName, string? releaseTypeName, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork of the album from the internal media directory.
|
||||
@@ -50,6 +66,18 @@ public interface IMusicArtworkService
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, ArtworkDto artwork, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Stores the uploaded <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
|
||||
/// <param name="fileName">The name of the uploaded artwork file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
Task<Result<string>> SaveArtistArtworkAsync(Guid libraryId, string libraryName, string artistName, Stream artwork, string fileName, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork of the artist from the internal media directory.
|
||||
/// </summary>
|
||||
@@ -58,4 +86,11 @@ public interface IMusicArtworkService
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Result<Deleted> DeleteArtistArtwork(Guid libraryId, string libraryName, string artistName);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork file at <paramref name="artworkRelativePath"/> from the internal media directory, when it still exists.
|
||||
/// </summary>
|
||||
/// <param name="artworkRelativePath">The relative path of the stored artwork file.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Result<Deleted> DeleteStoredArtwork(string artworkRelativePath);
|
||||
}
|
||||
+128
-2
@@ -58,10 +58,10 @@ internal sealed class MusicArtworkService : IMusicArtworkService
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="artwork">The artwork to store.</param>
|
||||
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <param name="releaseTypeName">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.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
public async Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, CancellationToken cancellationToken, string? releaseTypeName = null)
|
||||
public async Task<Result<string>> SaveAlbumArtworkAsync(Guid libraryId, Guid albumId, string libraryName, string artistName, string albumTitle, ArtworkDto artwork, string? releaseTypeName, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the uploaded <paramref name="artwork"/> of the album into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
|
||||
/// <param name="albumId">The Id of the album.</param>
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
|
||||
/// <param name="fileName">The name of the uploaded artwork file.</param>
|
||||
/// <param name="releaseTypeName">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 <see langword="null"/>, no release type segment is added.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
public async Task<Result<string>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the uploaded <paramref name="artwork"/> of the artist into the internal media directory, and returns the relative path of the stored artwork.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <param name="artwork">The stream of the uploaded artwork to store.</param>
|
||||
/// <param name="fileName">The name of the uploaded artwork file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the relative path of the stored artwork, or an error.</returns>
|
||||
public async Task<Result<string>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="fileName">The name of the uploaded artwork file.</param>
|
||||
/// <returns>The file system path of the temporary file.</returns>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the uploaded <paramref name="artwork"/> stream into the temporary file at <paramref name="temporaryPath"/>.
|
||||
/// </summary>
|
||||
/// <param name="artwork">The stream of the uploaded artwork.</param>
|
||||
/// <param name="temporaryPath">The file system path of the temporary file.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the temporary file at <paramref name="temporaryPath"/>, ignoring the failures that must not mask the result of the operation.
|
||||
/// </summary>
|
||||
/// <param name="temporaryPath">The file system path of the temporary file.</param>
|
||||
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.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the local source of the <paramref name="artwork"/>, stores it into <paramref name="artworkDirectoryPath"/>, and cleans up the temporary download of a remote artwork.
|
||||
/// </summary>
|
||||
@@ -159,6 +259,32 @@ internal sealed class MusicArtworkService : IMusicArtworkService
|
||||
return DeleteArtworkInDirectory(artworkDirectoryPathResult.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the stored artwork file at <paramref name="artworkRelativePath"/> from the internal media directory, when it still exists.
|
||||
/// </summary>
|
||||
/// <param name="artworkRelativePath">The relative path of the stored artwork file.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Deleted> 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<FileSystemPathId> filePathIdResult = FileSystemPathId.Create(absolutePath);
|
||||
if (filePathIdResult.IsFailure)
|
||||
return filePathIdResult.Errors;
|
||||
|
||||
Result<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the files directly contained in <paramref name="artworkDirectoryPath"/>, leaving the subdirectories, such as the album directories of an artist, untouched.
|
||||
/// </summary>
|
||||
|
||||
+1
-1
@@ -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);
|
||||
|
||||
+236
-17
@@ -104,7 +104,7 @@ public class MusicArtworkServiceTests
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, type: artworkType, ordinal: ordinal), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName: " ", albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "https://coverartarchive.org/cover.jpg"), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistName, albumTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
await using MemoryStream artworkStream = new(uploadedBytes);
|
||||
try
|
||||
{
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.PNG));
|
||||
await using MemoryStream artworkStream = new(uploadedBytes);
|
||||
try
|
||||
{
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(File.Exists(callInfo.Arg<FileSystemPathId>().Path)));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
File.Delete(callInfo.Arg<FileSystemPathId>().Path);
|
||||
return Result.Deleted;
|
||||
});
|
||||
try
|
||||
{
|
||||
// Act
|
||||
Result<Deleted> 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<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[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<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath!);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().FileExists(Arg.Any<FileSystemPathId>());
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork storage pipeline performs real file system operations.
|
||||
/// </summary>
|
||||
/// <param name="onCopySource">Optional callback invoked with the source file of every file copy, used to observe the temporary upload.</param>
|
||||
private void MockRealFileSystemStubs(Action<FileSystemPathId>? onCopySource = null)
|
||||
{
|
||||
MockPathBuilding();
|
||||
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(File.Exists(callInfo.Arg<FileSystemPathId>().Path)));
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(Directory.Exists(callInfo.Arg<FileSystemPathId>().Path)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string createdDirectoryPath = Path.Combine(callInfo.ArgAt<FileSystemPathId>(0).Path, callInfo.ArgAt<string>(1));
|
||||
Directory.CreateDirectory(createdDirectoryPath);
|
||||
return Result.From(_fileSystemPathIdFixture.Create(createdDirectoryPath));
|
||||
});
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
FileSystemPathId sourcePathId = callInfo.ArgAt<FileSystemPathId>(0);
|
||||
FileSystemPathId destinationDirectoryPathId = callInfo.ArgAt<FileSystemPathId>(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<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
FileSystemPathId sourcePathId = callInfo.ArgAt<FileSystemPathId>(0);
|
||||
string newFileName = callInfo.ArgAt<string>(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<FileSystemPathId>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
File.Delete(callInfo.Arg<FileSystemPathId>().Path);
|
||||
return Result.Deleted;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path service so that building the artwork directory paths succeeds.
|
||||
/// </summary>
|
||||
@@ -708,6 +895,38 @@ public class MusicArtworkServiceTests
|
||||
$"{albumTitle}-{albumId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory of a music media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryName">The name of the media library.</param>
|
||||
/// <param name="libraryId">The Id of the media library.</param>
|
||||
/// <returns>The expected file system path of the music media library directory.</returns>
|
||||
private static string BuildLibraryDirectoryPath(string libraryName, Guid libraryId)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the artist is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>The expected file system path of the artist artwork directory.</returns>
|
||||
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}",
|
||||
artistName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temporary image file and returns its path.
|
||||
/// </summary>
|
||||
|
||||
+336
-4
@@ -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<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(), CancellationToken.None);
|
||||
Result<string> 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<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
Result<string> 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
|
||||
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg")));
|
||||
});
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
|
||||
await using MemoryStream artworkStream = new(uploadedBytes);
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), "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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
|
||||
await using MemoryStream artworkStream = new([1, 2, 3]);
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(),
|
||||
Arg.Is<FileSystemPathId>(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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
|
||||
});
|
||||
await using MemoryStream artworkStream = new([1, 2, 3, 4]);
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), Arg.Any<string>());
|
||||
}
|
||||
|
||||
[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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.img")));
|
||||
});
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
await using MemoryStream artworkStream = new([1, 2, 3]);
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.PNG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
|
||||
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.png")));
|
||||
});
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.png")
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
|
||||
await using MemoryStream artworkStream = new(uploadedBytes);
|
||||
|
||||
// Act
|
||||
Result<string> 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<FileSystemPathId>(), "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<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.PNG));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
|
||||
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
|
||||
});
|
||||
await using MemoryStream artworkStream = new([1, 2, 3]);
|
||||
|
||||
// Act
|
||||
Result<string> 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<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath!);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().FileExists(Arg.Any<FileSystemPathId>());
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenTheFileDoesNotExist_ShouldReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[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<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath))
|
||||
.Returns(Result.From(true));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenTheExistenceCheckFails_ShouldReturnTheError()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = "\\media\\music\\cover.jpg";
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal("FileSystem.Error", result.FirstError.Code);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnDeleted()
|
||||
{
|
||||
// Arrange
|
||||
string artworkRelativePath = "\\media\\music\\cover.jpg";
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
|
||||
.Returns(Error.Failure("FileSystem.Error", "Failed to delete the artwork file"));
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(Arg.Any<FileSystemPathId>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path service so that building the artwork directory paths succeeds.
|
||||
/// </summary>
|
||||
@@ -238,15 +540,45 @@ public class MusicArtworkServiceTests
|
||||
/// <param name="libraryName">The name of the media library the album belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="albumTitle">The title of the album.</param>
|
||||
/// <param name="releaseTypeName">Optional. The name of the release type directory the album is stored under.</param>
|
||||
/// <returns>The expected file system path of the album artwork directory.</returns>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the artist is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
|
||||
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
|
||||
/// <param name="artistName">The name of the artist.</param>
|
||||
/// <returns>The expected file system path of the artist artwork directory.</returns>
|
||||
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, string artistName)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"music",
|
||||
$"{libraryName}-{libraryId}",
|
||||
artistName);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -272,8 +272,8 @@ public class MusicMediaLibraryScanArtworkEnricherTests
|
||||
Arg.Any<string>(),
|
||||
album.Title,
|
||||
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
|
||||
Arg.Any<CancellationToken>(),
|
||||
Arg.Any<string?>());
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any<CancellationToken>());
|
||||
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
|
||||
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
|
||||
@@ -553,7 +553,7 @@ public class MusicMediaLibraryScanArtworkEnricherTests
|
||||
{
|
||||
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>(), Arg.Any<string?>())
|
||||
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From("/media/music/cover.jpg"));
|
||||
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>()).Returns(Result.Deleted);
|
||||
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
|
||||
|
||||
Reference in new issue
Block a user