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

@@ -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>