diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-09-25 14:36:31 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-09-25 14:36:31 -0500 |
| commit | cabbd9c2fcb30c6194d25045dd4a9f4bdf6d6e4f (patch) | |
| tree | 883663596f57ac644c8e23a520fea8219588a060 /src | |
| parent | 67bc4bed7726204bd373bd8e784dbb819cc2dadd (diff) | |
| parent | b6eebb3f6695c93bce44ceb17725b7342085ae16 (diff) | |
| download | slskd-cabbd9c2fcb30c6194d25045dd4a9f4bdf6d6e4f.tar.gz | |
Merge pull request #656 from slskd/cancel-scan
Add the ability to cancel a share scan
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 9 | ||||
| -rw-r--r-- | src/slskd/Common/ChannelReader.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Core/State.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 15 | ||||
| -rw-r--r-- | src/slskd/Shares/API/Controllers/SharesController.cs | 63 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareService.cs | 19 | ||||
| -rw-r--r-- | src/slskd/Shares/ISharedFileCache.cs | 32 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 32 | ||||
| -rw-r--r-- | src/slskd/Shares/SharedFileCache.cs | 256 | ||||
| -rw-r--r-- | src/web/src/components/System/Shares/index.js | 81 | ||||
| -rw-r--r-- | src/web/src/components/System/System.css | 5 | ||||
| -rw-r--r-- | src/web/src/lib/shares.js | 4 |
13 files changed, 385 insertions, 144 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 20735ead..f517850b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -94,6 +94,7 @@ namespace slskd Console.CancelKeyPress += (_, args) => { ShuttingDown = true; + Program.MasterCancellationTokenSource.Cancel(); Log.Warning("Received SIGINT"); }; @@ -102,6 +103,7 @@ namespace slskd PosixSignalRegistration.Create(signal, context => { ShuttingDown = true; + Program.MasterCancellationTokenSource.Cancel(); Log.Fatal("Received {Signal}", signal); }); } @@ -383,8 +385,7 @@ namespace slskd } else { - // todo: should this be forced prior to connection if the cache can't be loaded? - _ = Shares.StartScanAsync(); + await Shares.ScanAsync(); } } @@ -1023,7 +1024,7 @@ namespace slskd else if (!previous.Ready && current.Ready) { // the share transitioned into ready without completing a scan; it was loaded from disk - State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); + State.SetValue(state => state with { Shares = current with { ScanPending = false } }); Log.Information("Share cache loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files); _ = CacheBrowseResponse(); } @@ -1033,7 +1034,7 @@ namespace slskd var lastProgress = Math.Round(previous.ScanProgress * 100); var currentProgress = Math.Round(current.ScanProgress * 100); - if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 5d == 0) + if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 1d == 0) { State.SetValue(s => s with { Shares = current }); Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); diff --git a/src/slskd/Common/ChannelReader.cs b/src/slskd/Common/ChannelReader.cs index a6a8b9a3..49ebf0cf 100644 --- a/src/slskd/Common/ChannelReader.cs +++ b/src/slskd/Common/ChannelReader.cs @@ -68,8 +68,7 @@ namespace slskd.Shares Handler = handler; ExceptionHandler = exceptionHandler; - CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - CancellationToken = CancellationTokenSource.Token; + CancellationToken = cancellationToken; if (automaticallyStart) { @@ -91,7 +90,6 @@ namespace slskd.Shares private Action<T> Handler { get; } private Action<Exception> ExceptionHandler { get; } private TaskCompletionSource TaskCompletionSource { get; } = new TaskCompletionSource(); - private CancellationTokenSource CancellationTokenSource { get; } private CancellationToken CancellationToken { get; } private object SyncRoot { get; } = new object(); @@ -114,7 +112,7 @@ namespace slskd.Shares { try { - while (!CancellationTokenSource.Token.IsCancellationRequested && !Channel.Reader.Completion.IsCompleted) + while (!Channel.Reader.Completion.IsCompleted) { var item = await Channel.Reader.ReadAsync(CancellationToken); Handler(item); @@ -132,7 +130,7 @@ namespace slskd.Shares } finally { - TaskCompletionSource.SetResult(); + TaskCompletionSource.TrySetResult(); } } } diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index ac8be802..7fb914e9 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -72,6 +72,7 @@ namespace slskd.Core.API [Authorize] public IActionResult Shutdown() { + Program.MasterCancellationTokenSource.Cancel(); Lifetime.StopApplication(); Task.Run(async () => @@ -91,6 +92,7 @@ namespace slskd.Core.API [Authorize] public IActionResult Restart() { + Program.MasterCancellationTokenSource.Cancel(); Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); Lifetime.StopApplication(); diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 1b798ad3..519f5345 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -104,6 +104,7 @@ namespace slskd public bool Scanning { get; init; } public bool Ready { get; init; } public bool Faulted { get; init; } + public bool Cancelled { get; init; } public double ScanProgress { get; init; } public int Directories { get; init; } public int Files { get; init; } @@ -126,6 +127,8 @@ namespace slskd /// </summary> public bool Faulted { get; init; } = false; + public bool Cancelled { get; init; } = false; + /// <summary> /// Gets the current fill progress. /// </summary> diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e828f242..03870f0a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -30,6 +30,7 @@ namespace slskd using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json.Serialization; + using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -189,6 +190,16 @@ namespace slskd /// </summary> public static ConcurrentFixedSizeQueue<LogRecord> LogBuffer { get; } = new ConcurrentFixedSizeQueue<LogRecord>(size: 100); + /// <summary> + /// Gets the master cancellation token source for the program. + /// </summary> + /// <remarks> + /// The token from this source should be used (or linked) to any long-running asynchronous task, so that when the application + /// begins to shut down these tasks also shut down in a timely manner. Actions that control the lifecycle of the program + /// (POSIX signals, a restart from the API, etc) should cancel this source. + /// </remarks> + public static CancellationTokenSource MasterCancellationTokenSource { get; } = new CancellationTokenSource(); + private static IConfigurationRoot Configuration { get; set; } private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); @@ -329,8 +340,10 @@ namespace slskd Log.Warning($"Please report any issues here: {IssuesUrl}"); } + Log.Information("System: .NET {DotNet}, {OS}, {BitNess} bit, {ProcessorCount} processors", Environment.Version, Environment.OSVersion, Environment.Is64BitOperatingSystem ? 64 : 32, Environment.ProcessorCount); + Log.Information("Process ID: {ProcessId} ({BitNess} bit)", ProcessId, Environment.Is64BitProcess ? 64 : 32); + Log.Information("Invocation ID: {InvocationId}", InvocationId); - Log.Information("Process ID: {ProcessId}", ProcessId); Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); // SQLite must have specific capabilities to function properly. this shouldn't be a concern for shrinkwrapped diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 12a1c7b2..5f87f900 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -57,18 +57,13 @@ namespace slskd.Shares.API [ProducesResponseType(typeof(IEnumerable<SummarizedShare>), 200)] public async Task<IActionResult> List() { - var browse = await Shares.BrowseAsync(); + var shares = new List<SummarizedShare>(); - var summary = Shares.Shares.Select(share => + foreach (var share in Shares.Shares) { - var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); - var fileCount = directories.Aggregate(seed: 0, (sum, directory) => - { - sum += directory.FileCount; - return sum; - }); + var (directories, files) = await Shares.SummarizeShareAsync(share); - return new SummarizedShare() + shares.Add(new SummarizedShare() { Id = share.Id, Alias = share.Alias, @@ -76,12 +71,12 @@ namespace slskd.Shares.API LocalPath = share.LocalPath, Raw = share.Raw, RemotePath = share.RemotePath, - Directories = directories.Count(), - Files = fileCount, - }; - }); + Directories = directories, + Files = files, + }); + } - return Ok(summary); + return Ok(shares); } /// <summary> @@ -104,13 +99,7 @@ namespace slskd.Shares.API return NotFound(); } - var browse = await Shares.BrowseAsync(); - var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); - var fileCount = directories.Aggregate(seed: 0, (sum, directory) => - { - sum += directory.FileCount; - return sum; - }); + var (directories, files) = await Shares.SummarizeShareAsync(share); var summary = new SummarizedShare() { @@ -120,8 +109,8 @@ namespace slskd.Shares.API LocalPath = share.LocalPath, Raw = share.Raw, RemotePath = share.RemotePath, - Directories = directories.Count(), - Files = fileCount, + Directories = directories, + Files = files, }; return Ok(summary); @@ -159,8 +148,7 @@ namespace slskd.Shares.API return NotFound(); } - var contents = (await Shares.BrowseAsync()) - .Where(directory => directory.Name.StartsWith(share.RemotePath)); + var contents = await Shares.BrowseAsync(share); return Ok(contents); } @@ -176,11 +164,11 @@ namespace slskd.Shares.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(409)] - public async Task<IActionResult> RescanSharesAsync() + public IActionResult RescanSharesAsync() { try { - await Shares.StartScanAsync(); + _ = Shares.ScanAsync(); } catch (ShareScanInProgressException) { @@ -189,5 +177,26 @@ namespace slskd.Shares.API return Ok(); } + + /// <summary> + /// Cancels a share scan, if one is running. + /// </summary> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="409">A share scan was not in progress.</response> + [HttpDelete] + [Route("")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(404)] + public IActionResult CancelShareScan() + { + if (Shares.TryCancelScan()) + { + return StatusCode(204); + } + + return NotFound(); + } } } diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 962d4c1e..73f6a4ad 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -42,7 +42,7 @@ namespace slskd.Shares /// Returns the entire contents of the share. /// </summary> /// <returns>The entire contents of the share.</returns> - Task<IEnumerable<Directory>> BrowseAsync(); + Task<IEnumerable<Directory>> BrowseAsync(Share share = null); /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. @@ -70,11 +70,24 @@ namespace slskd.Shares Task<IEnumerable<File>> SearchAsync(SearchQuery query); /// <summary> - /// Starts a scan of the configured shares. + /// Scans the configured shares. /// </summary> /// <returns>The operation context.</returns> /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception> - Task StartScanAsync(); + Task ScanAsync(); + + /// <summary> + /// Gets summary information for the specified <paramref name="share"/>. + /// </summary> + /// <param name="share">The share to summarize.</param> + /// <returns>The summary information.</returns> + Task<(int Directories, int Files)> SummarizeShareAsync(Share share); + + /// <summary> + /// Cancels the currently running scan, if one is running. + /// </summary> + /// <returns>A value indicating whether a scan was cancelled.</returns> + bool TryCancelScan(); /// <summary> /// Attempt to load shares from disk. diff --git a/src/slskd/Shares/ISharedFileCache.cs b/src/slskd/Shares/ISharedFileCache.cs index 52c7783c..c59f5bba 100644 --- a/src/slskd/Shares/ISharedFileCache.cs +++ b/src/slskd/Shares/ISharedFileCache.cs @@ -19,7 +19,6 @@ namespace slskd.Shares { using System.Collections.Generic; using System.Text.RegularExpressions; - using System.Threading; using System.Threading.Tasks; using Soulseek; @@ -36,18 +35,31 @@ namespace slskd.Shares /// <summary> /// Returns the contents of the cache. /// </summary> + /// <param name="share">The optional share to which to limit the scope of the browse.</param> /// <returns>The contents of the cache.</returns> - IEnumerable<Directory> Browse(); + IEnumerable<Directory> Browse(Share share = null); + + /// <summary> + /// Returns the number of directories in the specified <paramref name="share"/>. + /// </summary> + /// <param name="share">The share for which the directories are to be counted.</param> + /// <returns>The number of directories.</returns> + int CountDirectories(Share share); + + /// <summary> + /// Returns the number of files in the specified <paramref name="share"/>. + /// </summary> + /// <param name="share">The share for which the files are to be counted.</param> + /// <returns>The number of files.</returns> + int CountFiles(Share share); /// <summary> /// Scans the configured shares and fills the cache. /// </summary> - /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks> /// <param name="shares">The list of shares from which to fill the cache.</param> /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> - /// <param name="cancellationToken">The optional cancellation token to monitor.</param> /// <returns>The operation context.</returns> - Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters, CancellationToken cancellationToken = default); + Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters); /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. @@ -62,7 +74,7 @@ namespace slskd.Shares /// </summary> /// <param name="filename">The fully qualified filename to unmask.</param> /// <returns>The unmasked filename.</returns> - public string Resolve(string filename); + string Resolve(string filename); /// <summary> /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. @@ -72,9 +84,15 @@ namespace slskd.Shares IEnumerable<File> Search(SearchQuery query); /// <summary> + /// Cancels the currently running fill operation, if one is running. + /// </summary> + /// <returns>A value indicating whether a fill operation was cancelled.</returns> + bool TryCancelFill(); + + /// <summary> /// Attempts to load the cache from disk. /// </summary> /// <returns>A value indicating whether the load was successful.</returns> bool TryLoad(); } -} +}
\ No newline at end of file diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 96ac4c1c..4307a98f 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -52,9 +52,10 @@ namespace slskd.Shares State.SetValue(state => state with { // scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending - ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending), + ScanPending = current.Faulted || current.Cancelled || (!(previous.Filling && !current.Filling) && state.ScanPending), Scanning = current.Filling, Faulted = current.Faulted, + Cancelled = current.Cancelled, Ready = current.Filled, ScanProgress = current.FillProgress, Directories = current.Directories, @@ -90,9 +91,9 @@ namespace slskd.Shares /// Returns the entire contents of the share. /// </summary> /// <returns>The entire contents of the share.</returns> - public Task<IEnumerable<Directory>> BrowseAsync() + public Task<IEnumerable<Directory>> BrowseAsync(Share share = null) { - var results = Cache.Browse(); + var results = Cache.Browse(share); var normalizedResults = results.Select(r => new Directory(r.Name.NormalizePath(), r.Files)); return Task.FromResult(normalizedResults); @@ -159,16 +160,37 @@ namespace slskd.Shares } /// <summary> - /// Starts a scan of the configured shares. + /// Scans the configured shares. /// </summary> /// <returns>The operation context.</returns> /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception> - public Task StartScanAsync() + public Task ScanAsync() { return Cache.FillAsync(Shares, FilterRegexes); } /// <summary> + /// Gets summary information for the specified <paramref name="share"/>. + /// </summary> + /// <param name="share">The share to summarize.</param> + /// <returns>The summary information.</returns> + public Task<(int Directories, int Files)> SummarizeShareAsync(Share share) + { + var dirs = Cache.CountDirectories(share); + var files = Cache.CountFiles(share); + return Task.FromResult((dirs, files)); + } + + /// <summary> + /// Cancels the currently running scan, if one is running. + /// </summary> + /// <returns>A value indicating whether a scan was cancelled.</returns> + public bool TryCancelScan() + { + return Cache.TryCancelFill(); + } + + /// <summary> /// Attempt to load shares from disk. /// </summary> /// <returns>A value indicating whether shares were loaded.</returns> diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index b9c09d7e..a10202e2 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -25,6 +25,7 @@ namespace slskd.Shares using System.Data; using System.Diagnostics; using System.Linq; + using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Channels; @@ -63,46 +64,35 @@ namespace slskd.Shares private ISoulseekFileFactory SoulseekFileFactory { get; } private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private Channel<string> DirectoryChannel { get; set; } + private CancellationTokenSource CancellationTokenSource { get; set; } /// <summary> /// Returns the contents of the cache. /// </summary> + /// <param name="share">The optional share to which to limit the scope of the browse.</param> /// <returns>The contents of the cache.</returns> - public IEnumerable<Directory> Browse() + public IEnumerable<Directory> Browse(Share share = null) { var directories = new ConcurrentDictionary<string, Directory>(); + string prefix = null; + + if (share != null) + { + prefix = share.RemotePath + Path.DirectorySeparatorChar; + } + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if // missing, files that are nested within directories which contain only directories (no files) are displayed as being // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the // files. if not they'll be left as is. - foreach (var directory in ListDirectories()) + foreach (var directory in ListDirectories(prefix)) { directories.TryAdd(directory, new Directory(directory)); } - var files = new List<File>(); - - using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files ORDER BY maskedFilename ASC;", conn); - var reader = cmd.ExecuteReader(); - - while (reader.Read()) - { - var filename = reader.GetString(0); - var code = reader.GetInt32(1); - var size = reader.GetInt64(2); - var extension = reader.GetString(3); - var attributeJson = reader.GetString(4); - - var attributeList = attributeJson.FromJson<List<FileAttribute>>(); - - var file = new File(code, filename, size, extension, attributeList); - - files.Add(file); - } + var files = ListFiles(prefix, includeFullPath: true); var groups = files .GroupBy(file => Path.GetDirectoryName(file.Filename)) @@ -127,13 +117,34 @@ namespace slskd.Shares } /// <summary> + /// Returns the number of directories in the specified <paramref name="share"/>. + /// </summary> + /// <param name="share">The share for which the directories are to be counted.</param> + /// <returns>The number of directories.</returns> + public int CountDirectories(Share share) + { + var path = share.RemotePath + Path.DirectorySeparatorChar; + return CountDirectories(path); + } + + /// <summary> + /// Returns the number of files in the specified <paramref name="share"/>. + /// </summary> + /// <param name="share">The share for which the files are to be counted.</param> + /// <returns>The number of files.</returns> + public int CountFiles(Share share) + { + var path = share.RemotePath + Path.DirectorySeparatorChar; + return CountFiles(path); + } + + /// <summary> /// Scans the configured shares and fills the cache. /// </summary> /// <param name="shares">The list of shares from which to fill the cache.</param> /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> - /// <param name="cancellationToken">The optional cancellation token to monitor for cancellation requests.</param> /// <returns>The operation context.</returns> - public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters, CancellationToken cancellationToken = default) + public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -142,12 +153,20 @@ namespace slskd.Shares throw new ShareScanInProgressException("Shared files are already being scanned."); } + CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(Program.MasterCancellationTokenSource.Token); + var cancellationToken = CancellationTokenSource.Token; + + // send control back to the calling context. if we don't do this, the caller will block until + // directories have been enumerated. + await Task.Yield(); + try { State.SetValue(state => state with { Filling = true, Filled = false, + Cancelled = false, FillProgress = 0, Directories = 0, Files = 0, @@ -165,8 +184,6 @@ namespace slskd.Shares Log.Debug("Starting shared file scan"); - await Task.Yield(); - var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var sw = new Stopwatch(); @@ -230,7 +247,7 @@ namespace slskd.Shares var filtered = 0; // set up a channel to fan out for directory scanning - DirectoryChannel = Channel.CreateBounded<string>(new BoundedChannelOptions(1000) + var channel = Channel.CreateBounded<string>(new BoundedChannelOptions(1000) { AllowSynchronousContinuations = false, FullMode = BoundedChannelFullMode.Wait, @@ -244,7 +261,7 @@ namespace slskd.Shares foreach (var id in Enumerable.Range(0, WorkerCount)) { workers.Add(new ChannelReader<string>( - channel: DirectoryChannel, + channel: channel, cancellationToken: cancellationToken, handler: (directory) => { @@ -299,16 +316,7 @@ namespace slskd.Shares cached += addedFiles; Log.Debug("Finished scanning {Directory}: {Added} files added and {Filtered} filtered", directory, addedFiles, filteredFiles); - - try - { - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to set cache state following scan of {Directory}: {Message}", directory, ex.Message); - throw; - } + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = cached }); })); } @@ -316,42 +324,66 @@ namespace slskd.Shares workers.ForEach(w => w.Start()); Log.Debug("All workers started"); - Log.Debug("Filling DirectoryChannel..."); - foreach (var directory in unmaskedDirectories) + try { - await DirectoryChannel.Writer.WriteAsync(directory); - } + try + { + Log.Debug("Filling DirectoryChannel..."); + foreach (var directory in unmaskedDirectories) + { + await channel.Writer.WriteAsync(directory, cancellationToken); + } - DirectoryChannel.Writer.Complete(); - Log.Debug("DirectoryChannel filled"); + Log.Debug("DirectoryChannel filled"); + } + catch (OperationCanceledException) + { + Log.Warning("Shared file scan cancellation requested"); + Log.Debug("DirectoryChannel fill aborted"); + } + finally + { + channel.Writer.Complete(); + } - Log.Debug("Waiting for workers to finish working..."); - await Task.WhenAll(workers.Select(w => w.Completed)); - Log.Debug("All workers finished"); + Log.Debug("Waiting for workers to finish working..."); + await Task.WhenAll(workers.Select(w => w.Completed)); + Log.Debug("All workers finished"); - Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; + Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; - var deletedFiles = DeleteStaleFiles(timestamp); - var deletedDirectories = DeleteStaleDirectories(timestamp); + var deletedFiles = DeleteStaleFiles(timestamp); + var deletedDirectories = DeleteStaleDirectories(timestamp); - Log.Information("Removed or renamed {Files} files and {Directories} directories in {Elapsed}ms", deletedFiles, deletedDirectories, sw.ElapsedMilliseconds - swSnapshot); + Log.Information("Removed or renamed {Files} files and {Directories} directories in {Elapsed}ms", deletedFiles, deletedDirectories, sw.ElapsedMilliseconds - swSnapshot); + } + catch (OperationCanceledException) + { + // important! don't try to delete stale files in this case; unscanned records will have a stale timestamp + Log.Warning("Shared file scan cancelled successfully"); + + State.SetValue(state => state with { Cancelled = true }); + } Log.Debug("Backing up shared file cache database..."); Backup(); Log.Debug("Shared file cache database backup complete"); + var directoryCount = CountDirectories(); + var fileCount = CountFiles(); + State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, - Directories = CountDirectories(), - Files = CountFiles(), + Directories = directoryCount, + Files = fileCount, }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {cached}"); + Log.Debug($"Shared file cache created or updated in {sw.ElapsedMilliseconds}ms. Directories: {directoryCount}, Files: {fileCount}"); } catch (Exception ex) { @@ -361,6 +393,7 @@ namespace slskd.Shares } finally { + CancellationTokenSource = null; SyncRoot.Release(); } } @@ -455,6 +488,21 @@ namespace slskd.Shares } /// <summary> + /// Cancels the currently running fill operation, if one is running. + /// </summary> + /// <returns>A value indicating whether a fill operation was cancelled.</returns> + public bool TryCancelFill() + { + if (CancellationTokenSource != null) + { + CancellationTokenSource.Cancel(); + return true; + } + + return false; + } + + /// <summary> /// Attempts to load the cache from disk. /// </summary> /// <returns>A value indicating whether the load was successful.</returns> @@ -587,22 +635,60 @@ namespace slskd.Shares sourceConn.BackupDatabase(backupConn); } - private int CountDirectories() + private int CountDirectories(string prefix = null) { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM directories;", conn); + } + else + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%'", conn); + cmd.Parameters.AddWithValue("prefix", prefix); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd.Dispose(); + } } - private int CountFiles() + private int CountFiles(string prefix = null) { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); - var reader = cmd.ExecuteReader(); - reader.Read(); - return reader.GetInt32(0); + + SqliteCommand cmd = default; + + try + { + if (string.IsNullOrEmpty(prefix)) + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM files;", conn); + } + else + { + cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%'", conn); + cmd.Parameters.AddWithValue("prefix", prefix); + } + + var reader = cmd.ExecuteReader(); + reader.Read(); + return reader.GetInt32(0); + } + finally + { + cmd.Dispose(); + } } private SqliteConnection GetConnection(string connectionString = null) @@ -674,24 +760,42 @@ namespace slskd.Shares return reader.GetInt64(0); } - private IEnumerable<string> ListDirectories() + private IEnumerable<string> ListDirectories(string prefix = null) { var results = new List<string>(); using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); - var reader = cmd.ExecuteReader(); + SqliteCommand cmd = default; - while (reader.Read()) + try { - results.Add(reader.GetString(0)); - } + if (string.IsNullOrEmpty(prefix)) + { + cmd = new SqliteCommand("SELECT name FROM directories ORDER BY name ASC;", conn); + } + else + { + cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ORDER BY name ASC;", conn); + cmd.Parameters.AddWithValue("prefix", prefix); + } + + var reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } - return results; + return results; + } + finally + { + cmd.Dispose(); + } } - private IEnumerable<File> ListFiles(string directory = null) + private IEnumerable<File> ListFiles(string directory = null, bool includeFullPath = false) { var results = new List<File>(); @@ -722,7 +826,9 @@ namespace slskd.Shares var attributeList = attributeJson.FromJson<List<FileAttribute>>(); - var file = new File(code, filename: Path.GetFileName(filename), size, extension, attributeList); + filename = includeFullPath ? filename : Path.GetFileName(filename); + + var file = new File(code, filename, size, extension, attributeList); results.Add(file); } diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index ceb5746c..6759ad6f 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -19,10 +19,11 @@ import ShareTable from './ShareTable'; const Index = ({ state = {} } = {}) => { const [loading, setLoading] = useState(true); + const [working, setWorking] = useState(false); const [shares, setShares] = useState([]); const [modal, setModal] = useState(false); - const { scanning, scanProgress, scanPending } = state; + const { scanning, scanProgress, scanPending, directories, files } = state; const scanned = !scanning; useEffect(() => { @@ -47,30 +48,76 @@ const Index = ({ state = {} } = {}) => { } }; + const rescan = async () => { + try { + setWorking(true); + await sharesLib.rescan(); + } catch (error) { + console.error(error); + toast.error(error?.response?.data ?? error?.message ?? error); + } finally { + setWorking(false); + } + }; + + const cancel = async () => { + try { + setWorking(true); + await sharesLib.cancel(); + } catch (error) { + console.error(error); + toast.error(error?.response?.data ?? error?.message ?? error ?? 'Failed to cancel the scan'); + } finally { + setWorking(false); + } + }; + + const ScanButton = () => <ShrinkableButton + primary={!scanPending} + color={scanPending ? 'yellow' : undefined} + icon='refresh' + loading={working} + disabled={working} + mediaQuery={'(max-width: 516px)'} + onClick={() => rescan()} + >Rescan Shares</ShrinkableButton>; + + const CancelButton = () => <ShrinkableButton + color='red' + icon='x' + disabled={working} + mediaQuery={'(max-width: 516px)'} + onClick={() => cancel()} + >Cancel Scan</ShrinkableButton>; + const shared = shares.filter(share => !share.isExcluded); const excluded = shares.filter(share => share.isExcluded); return ( <> - <div className="header-buttons"> - <ShrinkableButton - primary={!scanPending} - color={scanPending ? 'yellow' : undefined} - icon='refresh' - loading={scanning} - disabled={scanning || loading} - mediaQuery={'(max-width: 516px)'} - onClick={() => sharesLib.rescan()} - >{scanning ? 'Scanning shares' : 'Rescan Shares'}</ShrinkableButton> - </div> - <Divider/> <Switch - filling={(loading || scanning) && <LoaderSegment>{Math.round(scanProgress * 100)}%</LoaderSegment>} + loading={loading && <LoaderSegment/>} > - <ShareTable shares={shared} onClick={setModal}/> - <ExclusionTable exclusions={excluded}/> + <div className="header-buttons"> + <Switch + scanning={scanning && <CancelButton/>} + > + <ScanButton/> + </Switch> + </div> + <Divider/> + <Switch + filling={scanning && <LoaderSegment> + <div> + <div>{Math.round(scanProgress * 100)}%</div> + <div className='share-scan-detail'>Found {files} files in {directories} directories</div> + </div></LoaderSegment>} + > + <ShareTable shares={shared} onClick={setModal}/> + <ExclusionTable exclusions={excluded}/> + </Switch> + <ContentsModal share={modal} onClose={() => setModal(false)}/> </Switch> - <ContentsModal share={modal} onClose={() => setModal(false)}/> </> ); }; diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index a8e9cb8e..a463ab08 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -62,4 +62,9 @@ .share-count-column { width: 110px; +} + +.share-scan-detail { + margin-top: 10px; + font-size: 14px; }
\ No newline at end of file diff --git a/src/web/src/lib/shares.js b/src/web/src/lib/shares.js index 03fac7d6..c400e08e 100644 --- a/src/web/src/lib/shares.js +++ b/src/web/src/lib/shares.js @@ -20,4 +20,8 @@ export const browse = async ({ id } = {}) => { export const rescan = async () => { return (await api.put('/shares')).data; +}; + +export const cancel = async () => { + return (await api.delete('/shares')).data; };
\ No newline at end of file |
