New Scan Loop (#1447)
* Staging the code for the new scan loop. * Implemented a basic idea of changes on drives triggering scan loop. Issues: 1. Scan by folder does not work, 2. Queuing system is very hacky and needs a separate thread, 3. Performance degregation could be very real. * Started writing unit test for new loop code * Implemented a basic method to scan a folder path with ignore support (not implemented, code in place) * Added some code to the parser to build out the idea of processing series in batches based on some top level folder. * Scan Series now uses the new code (folder based parsing) and now handles the LocalizedSeries issue. * Got library scan working with the new folder-based scan loop. Updated code to set FolderPath (for improved scan times and partial scan support). * Wrote some notes on update library scan loop. * Removed migration for merge * Reapplied the SeriesFolder migration after merge * Refactored a check that used multiple db calls into one. * Made lots of progress on ignore support, but some confusion on underlying library. Ticket created. On hold till then. * Updated Scan Library and Scan Series to exit early if no changes are on the underlying folders that need to be scanned. * Implemented the ability to have .kavitaignore files within your directories and Kavita will parse them and ignore files and directories based on rules within them. * Fixed an issue where ignore files nested wouldn't stack with higher level ignores * Wrote out some basic code that showcases how we can scan series or library based on file events on the underlying system. Very buggy, needs lots of edge case testing and logging and dupplication checking. * Things are working kinda. I'm getting lost in my own code and complexity. I'm not sure it's worth it. * Refactored ScanFiles out to Directory Service. * Refactored more code out to keep the code clean. * More unit tests * Refactored the signature of ParsedSeries to use IList. Started writing unit tests and reworked the UpdateLibrary to work how it used to with new scan loop code (note: using async update library/series does not work). * Fixed the bug where processSeriesInfos was being invoked twice per series and made the code work very similar to old code (except loose leaf files dont work) but with folder based scanning. * Prep for unit tests (updating broken ones with new implementations) * Just some notes. Not sure I want to finish this work. * Refactored the LibraryWatcher with some comments and state variables. * Undid the migrations in case I don't move forward with this branch * Started to clean the code and prepare for finishing this work. * Fixed a bad merge * Updated signatures to cleanup the code and commit to the new strategy for scanning. * Swapped out the code with async processing of series on a small library * The new scan loop is working in both Sync and Async methods. The code is slow and not optimized. This represents a good point to start polling and applying optimizations. * Refactored UpdateSeries out of Scanner and into a dedicated file. * Refactored how ProcessTasks are awaited to allow more async * Fixed an issue where side nav item wouldn't show correct highlight and migrated to OnPush * Moved where we start to stopwatch to encapsulate the full scan * Cleaned up SignalR events to report correctly (still needs a redesign) * Remove the "remove" code until I figure it out * Put in extremely expensive series deletion code for library scan. * Have Genre and Tag update the DB immediately to avoid dup issues * Taking a break * Moving to a lock with People was successful. Need to apply to others. * Refactored code for series level and tag and genre with new locking strategy. * New scan loop works. Next up optimization * Swapped out the Kavita log with svg for faster load * Refactored metadata updates to occur when the series are being updated. * Code cleanup * Added a new type of generic message (Info) to inform the user. * Code cleanup * Implemented an optimization which prevents any I/O (other than an attribute lookup) for Library/Series Scan. This can bring a recently updated library on network storage (650 series) to fully process in 2 seconds. Fixed a bug where File Analysis was running everytime for each non-epub file. * Fixed ARM x64 builds not being able to view PDF cover images due to a bad update in DocNet. * Some code cleanup * Added experimental signalr update code to have a more natural refresh of library-detail page * Hooked in ability to send new series events to UI * Moved all scan (file scan only) tasks into Scan Queue. Made it so scheduled ScanLibraries will now check if any existing task is being run and reschedule for 3 hours, and 10 mins for scan series. * Implemented the info event in the events widget and added a clear all button to dismiss all infos and errors. Added --event-widget-info-bg-color * Remove --drawer-background-color since it's not used * When new series added, inject directly into the view. * Some debug code cleanup * Fixed up the unit tests * Ensure all config directories exist on startup * Disabled Library Watching (that will go in next build) * Ensure update for series is admin only * Lots of code changes, scan series kinda works, specials are splitting, optimizations are failing. Demotivated on this work again. * Removed SeriesFolder migration * Added the SeriesFolder migration * Added a new pipe for dates so we can provide some nicer defaults. Added folder path to the series detail. * The scan optimizations now work for NTFS systems. * Removed a TODO * Migrated all the times to use DateTime.Now and not Utc. * Refactored some repo calls to use the includes flag pattern * Implemented a check for the library scan optimization check to validate if the library was updated (type change, library rename, folder change, or series deleted) and let the optimization be bypassed. * Added another optimization which will use just folder attribute of last write time if the drive is not NTFS. * Fixed a unit test * Some code cleanup
This commit is contained in:
parent
8708b9ced5
commit
0eac193248
70 changed files with 4728 additions and 1187 deletions
|
|
@ -9,6 +9,7 @@ using System.Threading.Tasks;
|
|||
using API.DTOs.System;
|
||||
using API.Entities.Enums;
|
||||
using API.Extensions;
|
||||
using Kavita.Common.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace API.Services
|
||||
|
|
@ -57,6 +58,17 @@ namespace API.Services
|
|||
void RemoveNonImages(string directoryName);
|
||||
void Flatten(string directoryName);
|
||||
Task<bool> CheckWriteAccess(string directoryName);
|
||||
|
||||
IEnumerable<string> GetFilesWithCertainExtensions(string path,
|
||||
string searchPatternExpression = "",
|
||||
SearchOption searchOption = SearchOption.TopDirectoryOnly);
|
||||
|
||||
IEnumerable<string> GetDirectories(string folderPath);
|
||||
string GetParentDirectoryName(string fileOrFolder);
|
||||
#nullable enable
|
||||
IList<string> ScanFiles(string folderPath, GlobMatcher? matcher = null);
|
||||
DateTime GetLastWriteTime(string folderPath);
|
||||
#nullable disable
|
||||
}
|
||||
public class DirectoryService : IDirectoryService
|
||||
{
|
||||
|
|
@ -105,7 +117,7 @@ namespace API.Services
|
|||
/// <param name="searchPatternExpression">Regex version of search pattern (ie \.mp3|\.mp4). Defaults to * meaning all files.</param>
|
||||
/// <param name="searchOption">SearchOption to use, defaults to TopDirectoryOnly</param>
|
||||
/// <returns>List of file paths</returns>
|
||||
private IEnumerable<string> GetFilesWithCertainExtensions(string path,
|
||||
public IEnumerable<string> GetFilesWithCertainExtensions(string path,
|
||||
string searchPatternExpression = "",
|
||||
SearchOption searchOption = SearchOption.TopDirectoryOnly)
|
||||
{
|
||||
|
|
@ -507,10 +519,175 @@ namespace API.Services
|
|||
return dirs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a set of directories from the folder path. Automatically excludes directories that shouldn't be in scope.
|
||||
/// </summary>
|
||||
/// <param name="folderPath"></param>
|
||||
/// <returns>List of directory paths, empty if path doesn't exist</returns>
|
||||
public IEnumerable<string> GetDirectories(string folderPath)
|
||||
{
|
||||
if (!FileSystem.Directory.Exists(folderPath)) return ImmutableArray<string>.Empty;
|
||||
return FileSystem.Directory.GetDirectories(folderPath)
|
||||
.Where(path => ExcludeDirectories.Matches(path).Count == 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all directories, including subdirectories. Automatically excludes directories that shouldn't be in scope.
|
||||
/// </summary>
|
||||
/// <param name="folderPath"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<string> GetAllDirectories(string folderPath)
|
||||
{
|
||||
if (!FileSystem.Directory.Exists(folderPath)) return ImmutableArray<string>.Empty;
|
||||
var directories = new List<string>();
|
||||
|
||||
var foundDirs = GetDirectories(folderPath);
|
||||
foreach (var foundDir in foundDirs)
|
||||
{
|
||||
directories.Add(foundDir);
|
||||
directories.AddRange(GetAllDirectories(foundDir));
|
||||
}
|
||||
|
||||
return directories;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the parent directories name for a file or folder. Empty string is path is not valid.
|
||||
/// </summary>
|
||||
/// <remarks>This does touch I/O with an Attribute lookup</remarks>
|
||||
/// <param name="fileOrFolder"></param>
|
||||
/// <returns></returns>
|
||||
public string GetParentDirectoryName(string fileOrFolder)
|
||||
{
|
||||
// TODO: Write Unit tests
|
||||
try
|
||||
{
|
||||
var attr = File.GetAttributes(fileOrFolder);
|
||||
var isDirectory = attr.HasFlag(FileAttributes.Directory);
|
||||
if (isDirectory)
|
||||
{
|
||||
return Parser.Parser.NormalizePath(FileSystem.DirectoryInfo
|
||||
.FromDirectoryName(fileOrFolder).Parent
|
||||
.FullName);
|
||||
}
|
||||
|
||||
return Parser.Parser.NormalizePath(FileSystem.FileInfo
|
||||
.FromFileName(fileOrFolder).Directory.Parent
|
||||
.FullName);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scans a directory by utilizing a recursive folder search. If a .kavitaignore file is found, will ignore matching patterns
|
||||
/// </summary>
|
||||
/// <param name="folderPath"></param>
|
||||
/// <param name="matcher"></param>
|
||||
/// <returns></returns>
|
||||
public IList<string> ScanFiles(string folderPath, GlobMatcher? matcher = null)
|
||||
{
|
||||
_logger.LogDebug("[ScanFiles] called on {Path}", folderPath);
|
||||
var files = new List<string>();
|
||||
if (!Exists(folderPath)) return files;
|
||||
|
||||
var potentialIgnoreFile = FileSystem.Path.Join(folderPath, ".kavitaignore");
|
||||
if (matcher == null)
|
||||
{
|
||||
matcher = CreateMatcherFromFile(potentialIgnoreFile);
|
||||
}
|
||||
else
|
||||
{
|
||||
matcher.Merge(CreateMatcherFromFile(potentialIgnoreFile));
|
||||
}
|
||||
|
||||
|
||||
IEnumerable<string> directories;
|
||||
if (matcher == null)
|
||||
{
|
||||
directories = GetDirectories(folderPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
directories = GetDirectories(folderPath)
|
||||
.Where(folder => matcher != null &&
|
||||
!matcher.ExcludeMatches($"{FileSystem.DirectoryInfo.FromDirectoryName(folder).Name}{FileSystem.Path.AltDirectorySeparatorChar}"));
|
||||
}
|
||||
|
||||
foreach (var directory in directories)
|
||||
{
|
||||
files.AddRange(ScanFiles(directory, matcher));
|
||||
}
|
||||
|
||||
|
||||
// Get the matcher from either ignore or global (default setup)
|
||||
if (matcher == null)
|
||||
{
|
||||
files.AddRange(GetFilesWithCertainExtensions(folderPath, Parser.Parser.SupportedExtensions));
|
||||
}
|
||||
else
|
||||
{
|
||||
var foundFiles = GetFilesWithCertainExtensions(folderPath,
|
||||
Parser.Parser.SupportedExtensions)
|
||||
.Where(file => !matcher.ExcludeMatches(FileSystem.FileInfo.FromFileName(file).Name));
|
||||
files.AddRange(foundFiles);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively scans a folder and returns the max last write time on any folders
|
||||
/// </summary>
|
||||
/// <remarks>This is required vs just an attribute check as NTFS does not bubble up certain events from nested folders.
|
||||
/// This will also ignore recursive nature if the device is not NTFS</remarks>
|
||||
/// <param name="folderPath"></param>
|
||||
/// <returns>Max Last Write Time</returns>
|
||||
public DateTime GetLastWriteTime(string folderPath)
|
||||
{
|
||||
if (!FileSystem.Directory.Exists(folderPath)) throw new IOException($"{folderPath} does not exist");
|
||||
if (new DriveInfo(FileSystem.Path.GetPathRoot(folderPath)).DriveFormat != "NTFS")
|
||||
{
|
||||
return FileSystem.Directory.GetLastWriteTime(folderPath);
|
||||
}
|
||||
|
||||
var directories = GetAllDirectories(folderPath).ToList();
|
||||
if (directories.Count == 0) return FileSystem.Directory.GetLastWriteTime(folderPath);
|
||||
|
||||
return directories.Max(d => FileSystem.Directory.GetLastWriteTime(d));
|
||||
}
|
||||
|
||||
|
||||
private GlobMatcher CreateMatcherFromFile(string filePath)
|
||||
{
|
||||
if (!FileSystem.File.Exists(filePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read file in and add each line to Matcher
|
||||
var lines = FileSystem.File.ReadAllLines(filePath);
|
||||
if (lines.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
GlobMatcher matcher = new();
|
||||
foreach (var line in lines)
|
||||
{
|
||||
matcher.AddExclude(line);
|
||||
}
|
||||
|
||||
return matcher;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Recursively scans files and applies an action on them. This uses as many cores the underlying PC has to speed
|
||||
/// up processing.
|
||||
/// NOTE: This is no longer parallel due to user's machines locking up
|
||||
/// </summary>
|
||||
/// <param name="root">Directory to scan</param>
|
||||
/// <param name="action">Action to apply on file path</param>
|
||||
|
|
@ -538,18 +715,16 @@ namespace API.Services
|
|||
string[] files;
|
||||
|
||||
try {
|
||||
subDirs = FileSystem.Directory.GetDirectories(currentDir).Where(path => ExcludeDirectories.Matches(path).Count == 0);
|
||||
subDirs = GetDirectories(currentDir);
|
||||
}
|
||||
// Thrown if we do not have discovery permission on the directory.
|
||||
catch (UnauthorizedAccessException e) {
|
||||
Console.WriteLine(e.Message);
|
||||
logger.LogError(e, "Unauthorized access on {Directory}", currentDir);
|
||||
logger.LogCritical(e, "Unauthorized access on {Directory}", currentDir);
|
||||
continue;
|
||||
}
|
||||
// Thrown if another process has deleted the directory after we retrieved its name.
|
||||
catch (DirectoryNotFoundException e) {
|
||||
Console.WriteLine(e.Message);
|
||||
logger.LogError(e, "Directory not found on {Directory}", currentDir);
|
||||
logger.LogCritical(e, "Directory not found on {Directory}", currentDir);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -558,15 +733,15 @@ namespace API.Services
|
|||
.ToArray();
|
||||
}
|
||||
catch (UnauthorizedAccessException e) {
|
||||
Console.WriteLine(e.Message);
|
||||
logger.LogCritical(e, "Unauthorized access on a file in {Directory}", currentDir);
|
||||
continue;
|
||||
}
|
||||
catch (DirectoryNotFoundException e) {
|
||||
Console.WriteLine(e.Message);
|
||||
logger.LogCritical(e, "Directory not found on a file in {Directory}", currentDir);
|
||||
continue;
|
||||
}
|
||||
catch (IOException e) {
|
||||
Console.WriteLine(e.Message);
|
||||
logger.LogCritical(e, "IO exception on a file in {Directory}", currentDir);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -577,19 +752,16 @@ namespace API.Services
|
|||
foreach (var file in files) {
|
||||
action(file);
|
||||
fileCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (AggregateException ae) {
|
||||
ae.Handle((ex) => {
|
||||
if (ex is UnauthorizedAccessException) {
|
||||
// Here we just output a message and go on.
|
||||
Console.WriteLine(ex.Message);
|
||||
_logger.LogError(ex, "Unauthorized access on file");
|
||||
return true;
|
||||
}
|
||||
// Handle other exceptions here if necessary...
|
||||
if (ex is not UnauthorizedAccessException) return false;
|
||||
// Here we just output a message and go on.
|
||||
_logger.LogError(ex, "Unauthorized access on file");
|
||||
return true;
|
||||
// Handle other exceptions here if necessary...
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue