Adds a per-library option to skip hidden files and directories during scans

This commit is contained in:
BinaryAlley committed 2026-11-27 09:52:40 +02:00
1 parent 0bb795dca5
commit 0e8d61b215
67 files changed
+4624 -19

No files matched your search

@@ -33,6 +33,7 @@ public class LibraryEntityFixture
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Whether hidden files and directories should be skipped during a scan or not.</param>
/// <param name="isContentOnSsd">Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Whether the consumption progress of the media library items is tracked.</param>
/// <param name="completionThresholdPercentage">The percentage of a media library item that must be consumed for its session to be considered completed.</param>
@@ -53,6 +54,7 @@ public class LibraryEntityFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = true,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false,
bool isContentOnSsd = false,
bool shouldTrackConsumptionProgress = false,
int? completionThresholdPercentage = null,
@@ -77,6 +79,7 @@ public class LibraryEntityFixture
CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb,
ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories,
ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan,
ShouldSkipHiddenFilesAndDirectoriesDuringScan = shouldSkipHiddenFilesAndDirectoriesDuringScan,
IsContentOnSsd = isContentOnSsd,
ShouldTrackConsumptionProgress = shouldTrackConsumptionProgress,
CompletionThresholdPercentage = completionThresholdPercentage,
@@ -28,6 +28,7 @@ public class AddLibraryCommandFixture
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Optional. Whether hidden files and directories should be skipped during a scan or not. When absent, the default is off.</param>
/// <param name="isContentOnSsd">Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
@@ -46,6 +47,7 @@ public class AddLibraryCommandFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = true,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool? shouldSkipHiddenFilesAndDirectoriesDuringScan = null,
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
@@ -65,6 +67,7 @@ public class AddLibraryCommandFixture
true,
true,
false,
null,
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
@@ -82,6 +85,7 @@ public class AddLibraryCommandFixture
.RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb)
.RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories)
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.ShouldSkipHiddenFilesAndDirectoriesDuringScan, shouldSkipHiddenFilesAndDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
.RuleFor(x => x.MetadataProviders, metadataProviders)
@@ -30,6 +30,7 @@ public class UpdateLibraryCommandFixture
/// <param name="canDownloadMetadataFromWeb">Whether the media library should download metadata from the web or not.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether the metadata should be saved in the media directories or not.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Optional. Whether hidden files and directories should be skipped during a scan or not. When absent, the stored value is kept.</param>
/// <param name="isContentOnSsd">Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
@@ -49,6 +50,7 @@ public class UpdateLibraryCommandFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = true,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool? shouldSkipHiddenFilesAndDirectoriesDuringScan = null,
bool isContentOnSsd = false,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
@@ -69,6 +71,7 @@ public class UpdateLibraryCommandFixture
true,
true,
false,
null,
false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
@@ -87,6 +90,7 @@ public class UpdateLibraryCommandFixture
.RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb)
.RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories)
.RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan)
.RuleFor(x => x.ShouldSkipHiddenFilesAndDirectoriesDuringScan, shouldSkipHiddenFilesAndDirectoriesDuringScan)
.RuleFor(x => x.IsContentOnSsd, isContentOnSsd)
.RuleFor(x => x.PathTemplateParts, pathTemplateParts)
.RuleFor(x => x.MetadataProviders, metadataProviders)
@@ -28,6 +28,7 @@ public class AddLibraryRequestFixture
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Optional. Whether hidden files and directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Optional. Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
@@ -46,6 +47,7 @@ public class AddLibraryRequestFixture
bool? canDownloadMetadataFromWeb = null,
bool? shouldSaveMetadataInMediaDirectories = null,
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
bool? shouldSkipHiddenFilesAndDirectoriesDuringScan = null,
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
@@ -64,6 +66,7 @@ public class AddLibraryRequestFixture
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
shouldSkipHiddenFilesAndDirectoriesDuringScan ?? _faker.Random.Bool(),
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
@@ -30,6 +30,7 @@ public class UpdateLibraryRequestFixture
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Optional. Whether hidden files and directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Optional. Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items should be tracked, or not.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
@@ -49,6 +50,7 @@ public class UpdateLibraryRequestFixture
bool? canDownloadMetadataFromWeb = null,
bool? shouldSaveMetadataInMediaDirectories = null,
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
bool? shouldSkipHiddenFilesAndDirectoriesDuringScan = null,
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
@@ -68,6 +70,7 @@ public class UpdateLibraryRequestFixture
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
shouldSkipHiddenFilesAndDirectoriesDuringScan ?? _faker.Random.Bool(),
isContentOnSsd ?? false,
shouldTrackConsumptionProgress,
completionThresholdPercentage,
@@ -32,6 +32,7 @@ public class LibraryResponseFixture
/// <param name="canDownloadMetadataFromWeb">Optional. Whether metadata should be downloaded from the web.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Optional. Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Optional. Whether unchanged directories should be skipped during scan.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Optional. Whether hidden files and directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Optional. Whether the content of the media library is stored on a solid state drive.</param>
/// <param name="shouldTrackConsumptionProgress">Optional. Whether the consumption progress of the media library items is tracked.</param>
/// <param name="completionThresholdPercentage">Optional. The percentage of a media library item that must be consumed for its session to be considered completed.</param>
@@ -51,6 +52,7 @@ public class LibraryResponseFixture
bool? canDownloadMetadataFromWeb = null,
bool? shouldSaveMetadataInMediaDirectories = null,
bool? shouldSkipUnchangedDirectoriesDuringScan = null,
bool? shouldSkipHiddenFilesAndDirectoriesDuringScan = null,
bool? isContentOnSsd = null,
bool? shouldTrackConsumptionProgress = null,
int? completionThresholdPercentage = null,
@@ -72,6 +74,7 @@ public class LibraryResponseFixture
canDownloadMetadataFromWeb ?? _faker.Random.Bool(),
shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(),
shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(),
shouldSkipHiddenFilesAndDirectoriesDuringScan ?? _faker.Random.Bool(),
isContentOnSsd ?? false,
resolvedShouldTrackConsumptionProgress,
resolvedCompletionThresholdPercentage,
@@ -43,6 +43,7 @@ public class LibraryFixture
/// <param name="canDownloadMetadataFromWeb">Whether metadata download from the web is enabled.</param>
/// <param name="shouldSaveMetadataInMediaDirectories">Whether metadata should be saved in the media directories.</param>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during scan.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Whether hidden files and directories should be skipped during scan.</param>
/// <param name="isContentOnSsd">Whether the content of the library is stored on a solid state drive.</param>
/// <param name="consumptionSettings">Optional. The consumption settings of the library.</param>
/// <param name="scanIds">Optional. The scan Ids associated with the library.</param>
@@ -61,6 +62,7 @@ public class LibraryFixture
bool canDownloadMetadataFromWeb = true,
bool shouldSaveMetadataInMediaDirectories = false,
bool shouldSkipUnchangedDirectoriesDuringScan = false,
bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false,
bool isContentOnSsd = false,
LibraryConsumptionSettings? consumptionSettings = null,
IEnumerable<Guid>? scanIds = null,
@@ -93,6 +95,7 @@ public class LibraryFixture
canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
shouldSkipHiddenFilesAndDirectoriesDuringScan,
isContentOnSsd,
resolvedConsumptionSettings,
pathTemplate ?? LibraryPathTemplate.Empty(),
@@ -110,6 +113,7 @@ public class LibraryFixture
canDownloadMetadataFromWeb,
shouldSaveMetadataInMediaDirectories,
shouldSkipUnchangedDirectoriesDuringScan,
shouldSkipHiddenFilesAndDirectoriesDuringScan,
isContentOnSsd,
resolvedConsumptionSettings,
pathTemplate ?? LibraryPathTemplate.Empty(),
@@ -25,8 +25,15 @@ public class LibraryDtoFixture
/// <param name="libraryType">Optional type of the library.</param>
/// <param name="isEnabled">Whether the media library is enabled or not.</param>
/// <param name="contentLocations">Optional collection of directories that contain the library files.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Optional. Whether hidden files and directories should be skipped during the scan, or not.</param>
/// <returns>A configured <see cref="LibraryDto"/> instance.</returns>
public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List<string>? contentLocations = null)
public LibraryDto Create(
Guid? id = null,
string? title = null,
string? libraryType = null,
bool? isEnabled = null,
List<string>? contentLocations = null,
bool? shouldSkipHiddenFilesAndDirectoriesDuringScan = null)
{
return new LibraryDto
{
@@ -35,7 +42,8 @@ public class LibraryDtoFixture
LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"),
CoverImage = _faker.Image.PicsumUrl(),
ContentLocations = contentLocations ?? [_faker.System.DirectoryPath()],
IsEnabled = isEnabled ?? _faker.Random.Bool()
IsEnabled = isEnabled ?? _faker.Random.Bool(),
ShouldSkipHiddenFilesAndDirectoriesDuringScan = shouldSkipHiddenFilesAndDirectoriesDuringScan ?? _faker.Random.Bool()
};
}
@@ -95,6 +95,48 @@ public class DirectoryScanFingerprintRepositoryTests : IDisposable
Assert.Empty(result.Value);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldDeleteOnlyTheFingerprintsOfThatLibrary()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
UserEntity otherUser = _userEntityFixture.Create();
_context.Users.Add(otherUser);
Guid otherLibraryId = Guid.NewGuid();
LibraryEntity otherLibrary = _libraryEntityFixture.Create(id: otherLibraryId, userId: otherUser.Id);
_context.Libraries.Add(otherLibrary);
DirectoryScanFingerprintEntity firstFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1");
DirectoryScanFingerprintEntity secondFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2");
DirectoryScanFingerprintEntity fingerprintOfOtherLibrary = _directoryScanFingerprintEntityFixture.Create(libraryId: otherLibraryId, path: "/dir3");
_context.DirectoryScanFingerprints.AddRange(firstFingerprint, secondFingerprint, fingerprintOfOtherLibrary);
await _context.SaveChangesAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
DirectoryScanFingerprintEntity remainingFingerprint = await _context.DirectoryScanFingerprints.AsNoTracking().SingleAsync();
Assert.Equal(fingerprintOfOtherLibrary.Id, remainingFingerprint.Id);
}
[Fact]
public async Task DeleteByLibraryIdAsync_WhenNoFingerprintsExist_ShouldReturnDeleted()
{
// Arrange
(Guid libraryId, _) = await SeedLibraryGraphAsync();
// Act
Result<Deleted> result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
Assert.False(await _context.DirectoryScanFingerprints.AnyAsync());
}
[Fact]
public async Task UpsertRangeAsync_WhenCalledWithNewFingerprints_ShouldInsertThemAndReturnUpdated()
{
@@ -96,8 +96,13 @@ public class BooksFileSystemDiscoveryJobTests
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("book1.pdf", "book content");
temporaryLibraryDirectory.CreateFile("notes.log", "not a book");
temporaryLibraryDirectory.CreateFile(".hidden.pdf", "hidden book content");
SetHiddenAttribute(Path.Combine(temporaryLibraryDirectory.Path, ".hidden.pdf"));
string subdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("sub");
File.WriteAllText(Path.Combine(subdirectoryPath, "book2.epub"), "another book content");
string hiddenSubdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory(".hidden");
SetHiddenAttribute(hiddenSubdirectoryPath);
File.WriteAllText(Path.Combine(hiddenSubdirectoryPath, "hidden.epub"), "hidden book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
@@ -125,12 +130,53 @@ public class BooksFileSystemDiscoveryJobTests
.FirstOrDefault();
Assert.True(actualEntities is not null, $"InsertRangeAsync was not called. Received: {string.Join(", ", _mockStagingResultsRepository.ReceivedCalls().Select(call => call.GetMethodInfo().Name))}");
Assert.Equal(
["book1.pdf", "book2.epub"],
[".hidden.pdf", "book1.pdf", "book2.epub", "hidden.epub"],
actualEntities!.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal));
await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenHiddenFilesAndDirectoriesAreSkipped_ShouldNotDiscoverThem()
{
// Arrange
using TemporaryLibraryDirectory temporaryLibraryDirectory = new();
temporaryLibraryDirectory.CreateFile("visible.pdf", "visible book content");
temporaryLibraryDirectory.CreateFile(".hidden.pdf", "hidden book content");
string hiddenFileName = Path.Combine(temporaryLibraryDirectory.Path, ".hidden.pdf");
SetHiddenAttribute(hiddenFileName);
string visibleSubdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("visible");
File.WriteAllText(Path.Combine(visibleSubdirectoryPath, "nested.epub"), "nested book content");
string hiddenSubdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory(".hidden");
SetHiddenAttribute(hiddenSubdirectoryPath);
File.WriteAllText(Path.Combine(hiddenSubdirectoryPath, "secret.epub"), "secret book content");
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: [temporaryLibraryDirectory.Path],
shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities =>
entities.Count == 2
&& entities.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal).SequenceEqual(new[] { "nested.epub", "visible.pdf" })),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenFastSkipIsEnabledAndDirectoryDidNotChange_ShouldSkipTheDirectoryAndUpsertOnlyChangedFingerprints()
{
@@ -310,6 +356,16 @@ public class BooksFileSystemDiscoveryJobTests
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
}
/// <summary>
/// Marks the file system entry at <paramref name="path"/> as hidden on Windows, where the dot prefix alone is not enough.
/// </summary>
/// <param name="path">The path of the file or directory to mark as hidden.</param>
private static void SetHiddenAttribute(string path)
{
if (OperatingSystem.IsWindows())
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
}
/// <summary>
/// Test helper managing a temporary library directory, deleted when the test finishes.
/// </summary>
@@ -71,7 +71,8 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true
);
// Act
@@ -83,12 +84,14 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Assert.NotNull(library);
Assert.Equal("New Library", library!.Title);
Assert.Equal(LibraryType.EBook, library.LibraryType);
Assert.True(library.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.Equal("New Library", storedLibrary!.Title);
Assert.True(storedLibrary.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
}
[Fact]
@@ -41,6 +41,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
@@ -69,6 +70,12 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title");
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.DirectoryScanFingerprints.Add(_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/fingerprint"));
await seedDbContext.SaveChangesAsync();
}
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
title: "Updated Title",
@@ -79,7 +86,8 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true
);
// Act
@@ -91,12 +99,66 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.Equal("Updated Title", library!.Title);
Assert.True(library.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.Equal("Updated Title", storedLibrary!.Title);
Assert.True(storedLibrary.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.False(await dbContext.DirectoryScanFingerprints.AnyAsync(fingerprint => fingerprint.LibraryId == libraryId));
}
[Fact]
public async Task UpdateLibrary_WhenHiddenFilesSettingIsAbsent_ShouldKeepTheStoredValue()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
using (IServiceScope seedScope = _apiFactory.Services.CreateScope())
{
LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService<LuminaDbContext>();
seedDbContext.DirectoryScanFingerprints.Add(_directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/fingerprint"));
await seedDbContext.SaveChangesAsync();
}
Dictionary<string, object?> request = new()
{
["id"] = libraryId,
["title"] = "Updated Title",
["libraryType"] = "EBook",
["contentLocations"] = new[] { "C:/Media" },
["coverImage"] = null,
["isEnabled"] = true,
["isLocked"] = false,
["canDownloadMetadataFromWeb"] = true,
["shouldSaveMetadataInMediaDirectories"] = false,
["shouldSkipUnchangedDirectoriesDuringScan"] = false,
["isContentOnSsd"] = false,
["shouldTrackConsumptionProgress"] = null,
["completionThresholdPercentage"] = null,
["pathTemplateParts"] = null,
["metadataProviders"] = null,
["artworkProviders"] = null,
["bookReaders"] = null
};
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
response.EnsureSuccessStatusCode();
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.True(library!.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.True(await dbContext.DirectoryScanFingerprints.AnyAsync(fingerprint => fingerprint.LibraryId == libraryId));
}
[Fact]
@@ -473,7 +535,8 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Guid userId,
string title,
bool shouldTrackConsumptionProgress = false,
int? completionThresholdPercentage = null)
int? completionThresholdPercentage = null,
bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
@@ -483,6 +546,7 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
title: title,
libraryType: LibraryType.EBook,
contentLocations: [],
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan,
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
completionThresholdPercentage: completionThresholdPercentage));
await dbContext.SaveChangesAsync();
@@ -11,6 +11,7 @@ using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
#endregion
@@ -56,6 +57,36 @@ public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EditLibraryView_WhenLibraryHasHiddenFilesSetting_ShouldRenderTheCheckboxWithItsStoredState(bool shouldSkipHiddenFilesAndDirectoriesDuringScan)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryDto expectedLibrary = _libraryDtoFixture.Create(
id: libraryId,
title: "Books",
libraryType: "Book",
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan);
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
// Act
HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}");
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
string? checkboxTag = GetCheckboxTag(content, "ShouldSkipHiddenFilesAndDirectoriesDuringScan");
Assert.NotNull(checkboxTag);
if (shouldSkipHiddenFilesAndDirectoriesDuringScan)
Assert.Contains("checked", checkboxTag, StringComparison.OrdinalIgnoreCase);
else
Assert.DoesNotContain("checked", checkboxTag, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task EditLibraryView_WhenThemeProvidesFileSystemBrowserTemplates_ShouldRenderThemedComponent()
{
@@ -104,6 +135,18 @@ public class EditLibraryViewEndpointTests : IClassFixture<LuminaWebFactory>
Assert.Contains("initFileSystemBrowser(", content);
}
/// <summary>
/// Gets the rendered checkbox input tag with the provided name, or <see langword="null"/> when it is not present.
/// </summary>
/// <param name="content">The rendered HTML content.</param>
/// <param name="name">The name of the checkbox input.</param>
/// <returns>The rendered checkbox input tag, or <see langword="null"/>.</returns>
private static string? GetCheckboxTag(string content, string name)
{
Match match = Regex.Match(content, $@"<input[^>]*name=""{Regex.Escape(name)}""[^>]*>");
return match.Success ? match.Value : null;
}
/// <summary>
/// Registers the theme template response returned for the specified page key of the given theme.
/// </summary>
@@ -36,6 +36,7 @@ public class AddMediaLibraryRequestMappingTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 90
@@ -54,6 +55,7 @@ public class AddMediaLibraryRequestMappingTests
Assert.Equal(request.IsLocked, result.IsLocked);
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(request.ShouldSkipHiddenFilesAndDirectoriesDuringScan, result.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.Equal(request.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(request.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(request.CompletionThresholdPercentage, result.CompletionThresholdPercentage);
@@ -33,6 +33,7 @@ public class LibraryEntityMappingTests
libraryType: LibraryType.Book,
contentLocations: ["C:/Books", "D:/Media/Books"],
coverImage: "D:/myPoster.jpg",
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true);
// Act
@@ -46,6 +47,7 @@ public class LibraryEntityMappingTests
Assert.Equal(entity.LibraryType, result.LibraryType);
Assert.Equal(entity.ContentLocations.Select(l => l.Path), result.ContentLocations);
Assert.Equal(entity.CoverImage, result.CoverImage);
Assert.Equal(entity.ShouldSkipHiddenFilesAndDirectoriesDuringScan, result.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.Equal(entity.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(entity.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(entity.CompletionThresholdPercentage, result.CompletionThresholdPercentage);
@@ -190,6 +192,7 @@ public class LibraryEntityMappingTests
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
coverImage: "D:/cover.jpg",
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
pathTemplateParts: [firstPart, secondPart]);
@@ -203,6 +206,7 @@ public class LibraryEntityMappingTests
Assert.Equal(entity.Title, result.Value.Title);
Assert.Equal(entity.LibraryType, result.Value.LibraryType);
Assert.Equal("D:/cover.jpg", result.Value.CoverImage.Value);
Assert.Equal(entity.ShouldSkipHiddenFilesAndDirectoriesDuringScan, result.Value.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.Equal(entity.IsContentOnSsd, result.Value.IsContentOnSsd);
Assert.Equal(entity.ShouldTrackConsumptionProgress, result.Value.ConsumptionSettings.ShouldTrackConsumptionProgress);
Assert.Equal(entity.CompletionThresholdPercentage, result.Value.ConsumptionSettings.CompletionThresholdPercentage.HasValue ? result.Value.ConsumptionSettings.CompletionThresholdPercentage.Value : null);
@@ -41,6 +41,7 @@ public class LibraryMappingTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
scanIds: [Guid.NewGuid()]);
// Act
@@ -60,6 +61,7 @@ public class LibraryMappingTests
Assert.False(result.IsLocked);
Assert.True(result.CanDownloadMetadataFromWeb);
Assert.False(result.ShouldSaveMetadataInMediaDirectories);
Assert.True(result.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.Equal(library.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(library.ConsumptionSettings.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(library.ConsumptionSettings.CompletionThresholdPercentage.HasValue ? library.ConsumptionSettings.CompletionThresholdPercentage.Value : null, result.CompletionThresholdPercentage);
@@ -36,6 +36,7 @@ public class UpdateLibraryRequestMappingTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 90);
@@ -54,6 +55,7 @@ public class UpdateLibraryRequestMappingTests
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan);
Assert.Equal(request.ShouldSkipHiddenFilesAndDirectoriesDuringScan, result.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.Equal(request.IsContentOnSsd, result.IsContentOnSsd);
Assert.Equal(request.ShouldTrackConsumptionProgress, result.ShouldTrackConsumptionProgress);
Assert.Equal(request.CompletionThresholdPercentage, result.CompletionThresholdPercentage);
@@ -114,6 +114,25 @@ public class AddLibraryCommandHandlerTests
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
[Fact]
public async Task HandleAsync_WhenHiddenFilesSettingIsAbsent_ShouldDefaultToNotSkippingHiddenFiles()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(shouldSkipHiddenFilesAndDirectoriesDuringScan: null);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library => !library.ShouldSkipHiddenFilesAndDirectoriesDuringScan),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThresholdIsSuppliedWhileEffectiveTrackingIsOff_ShouldReturnThresholdMustBeNullError()
{
@@ -45,6 +45,7 @@ public class UpdateLibraryCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IDirectoryScanFingerprintRepository _mockDirectoryScanFingerprintRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IDomainEventsQueue _mockDomainEventsQueue;
@@ -70,6 +71,10 @@ public class UpdateLibraryCommandHandlerTests
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockDirectoryScanFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
_mockDirectoryScanFingerprintRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockDirectoryScanFingerprintRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockDomainEventsQueue = Substitute.For<IDomainEventsQueue>();
@@ -121,6 +126,101 @@ public class UpdateLibraryCommandHandlerTests
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
[Theory]
[InlineData(true, false, false, false)] // Only the skip unchanged directories setting changes.
[InlineData(false, true, false, false)] // Only the skip hidden files and directories setting changes.
public async Task HandleAsync_WhenAScanScopeSettingChanges_ShouldDeleteTheDirectoryScanFingerprints(
bool commandShouldSkipUnchangedDirectories,
bool commandShouldSkipHiddenFilesAndDirectories,
bool existingShouldSkipUnchangedDirectories,
bool existingShouldSkipHiddenFilesAndDirectories)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
shouldSkipUnchangedDirectoriesDuringScan: commandShouldSkipUnchangedDirectories,
shouldSkipHiddenFilesAndDirectoriesDuringScan: commandShouldSkipHiddenFilesAndDirectories);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: _userId,
shouldSkipUnchangedDirectoriesDuringScan: existingShouldSkipUnchangedDirectories,
shouldSkipHiddenFilesAndDirectoriesDuringScan: existingShouldSkipHiddenFilesAndDirectories);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockDirectoryScanFingerprintRepository.Received(1).DeleteByLibraryIdAsync(command.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenHiddenFilesSettingIsAbsent_ShouldKeepTheStoredValue()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(shouldSkipHiddenFilesAndDirectoriesDuringScan: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: _userId,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library => library.ShouldSkipHiddenFilesAndDirectoriesDuringScan),
Arg.Any<CancellationToken>());
await _mockDirectoryScanFingerprintRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenScanScopeSettingsAreUnchanged_ShouldNotDeleteTheDirectoryScanFingerprints()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockDirectoryScanFingerprintRepository.DidNotReceive().DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenDeletingTheDirectoryScanFingerprintsFails_ShouldReturnTheErrorAndNotSave()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
Error deleteError = Error.Failure("Database.Error", "Failed to delete the directory scan fingerprints");
_mockDirectoryScanFingerprintRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(deleteError);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(deleteError, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThresholdIsSuppliedWhileStoredTrackingIsOff_ShouldReturnThresholdMustBeNullError()
{
@@ -56,6 +56,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: false,
shouldSaveMetadataInMediaDirectories: true,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
consumptionSettings,
LibraryPathTemplate.Empty(),
@@ -74,6 +75,7 @@ public class LibraryTests
Assert.False(result.Value.CanDownloadMetadataFromWeb);
Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories);
Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan);
Assert.True(result.Value.ShouldSkipHiddenFilesAndDirectoriesDuringScan);
Assert.True(result.Value.IsContentOnSsd);
Assert.Equal(consumptionSettings, result.Value.ConsumptionSettings);
Assert.Equal(scanIds, result.Value.ScanIds);
@@ -99,6 +101,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
@@ -128,6 +131,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
@@ -166,6 +170,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
@@ -196,6 +201,7 @@ public class LibraryTests
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
shouldSkipHiddenFilesAndDirectoriesDuringScan: false,
isContentOnSsd: false,
_libraryConsumptionSettingsFixture.Create(),
LibraryPathTemplate.Empty(),
@@ -179,6 +179,8 @@ public class MusicFileSystemDiscoveryJobTests
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
_mockFileProviderService.Received(1).GetFilePaths(Arg.Any<FileSystemPathId>(), true);
_mockDirectoryProviderService.Received(1).GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), true);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1
&& entities.First().Path == AUDIO_FILE_PATH
@@ -227,6 +229,25 @@ public class MusicFileSystemDiscoveryJobTests
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task ExecuteAsync_WhenHiddenFilesAndDirectoriesAreSkipped_ShouldAskTheProvidersToExcludeThem()
{
// Arrange
SetupLibrary(shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: [], shouldIncludeHiddenElements: false);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
_mockFileProviderService.Received(1).GetFilePaths(Arg.Any<FileSystemPathId>(), false);
_mockDirectoryProviderService.Received(1).GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), false);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && entities.First().Path == AUDIO_FILE_PATH),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt()
{
@@ -403,14 +424,16 @@ public class MusicFileSystemDiscoveryJobTests
/// Stubs the media library reader with a library whose single content location is the test root path.
/// </summary>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether the library skips the directories that have not changed since the last scan.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Whether the library skips hidden files and directories.</param>
/// <param name="isContentOnSsd">Whether the content of the library is stored on a solid state drive.</param>
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false, bool isContentOnSsd = false)
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false, bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false, bool isContentOnSsd = false)
{
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [ROOT_PATH],
shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan,
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan,
isContentOnSsd: isContentOnSsd);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
@@ -422,11 +445,12 @@ public class MusicFileSystemDiscoveryJobTests
/// <param name="directory">The file system path of the directory.</param>
/// <param name="files">The file system paths of the files of the directory.</param>
/// <param name="subdirectories">The file system paths of the subdirectories of the directory.</param>
private void SetupDirectory(string directory, string[] files, string[] subdirectories)
/// <param name="shouldIncludeHiddenElements">Whether the providers are expected to include hidden elements.</param>
private void SetupDirectory(string directory, string[] files, string[] subdirectories, bool shouldIncludeHiddenElements = true)
{
_mockFileProviderService.GetFilePaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), true)
_mockFileProviderService.GetFilePaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), shouldIncludeHiddenElements)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. files.Select(file => PathId(file))]));
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), true)
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), shouldIncludeHiddenElements)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. subdirectories.Select(subdirectoryPath => PathId(subdirectoryPath))]));
}
@@ -87,6 +87,7 @@ public class AddLibraryEndpointTests
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
@@ -109,6 +110,7 @@ public class AddLibraryEndpointTests
command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb &&
command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories &&
command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan &&
command.ShouldSkipHiddenFilesAndDirectoriesDuringScan == request.ShouldSkipHiddenFilesAndDirectoriesDuringScan &&
command.IsContentOnSsd == request.IsContentOnSsd &&
command.ShouldTrackConsumptionProgress == request.ShouldTrackConsumptionProgress &&
command.CompletionThresholdPercentage == request.CompletionThresholdPercentage),
@@ -87,6 +87,7 @@ public class UpdateLibraryEndpointTests
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
shouldSkipHiddenFilesAndDirectoriesDuringScan: true,
isContentOnSsd: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
@@ -110,6 +111,7 @@ public class UpdateLibraryEndpointTests
command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb &&
command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories &&
command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan &&
command.ShouldSkipHiddenFilesAndDirectoriesDuringScan == request.ShouldSkipHiddenFilesAndDirectoriesDuringScan &&
command.IsContentOnSsd == request.IsContentOnSsd &&
command.ShouldTrackConsumptionProgress == request.ShouldTrackConsumptionProgress &&
command.CompletionThresholdPercentage == request.CompletionThresholdPercentage),