aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Shares
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-09-25 14:36:31 -0500
committerGitHub <noreply@github.com>2022-09-25 14:36:31 -0500
commitcabbd9c2fcb30c6194d25045dd4a9f4bdf6d6e4f (patch)
tree883663596f57ac644c8e23a520fea8219588a060 /src/slskd/Shares
parent67bc4bed7726204bd373bd8e784dbb819cc2dadd (diff)
parentb6eebb3f6695c93bce44ceb17725b7342085ae16 (diff)
downloadslskd-cabbd9c2fcb30c6194d25045dd4a9f4bdf6d6e4f.tar.gz
Merge pull request #656 from slskd/cancel-scan
Add the ability to cancel a share scan
Diffstat (limited to 'src/slskd/Shares')
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs63
-rw-r--r--src/slskd/Shares/IShareService.cs19
-rw-r--r--src/slskd/Shares/ISharedFileCache.cs32
-rw-r--r--src/slskd/Shares/ShareService.cs32
-rw-r--r--src/slskd/Shares/SharedFileCache.cs256
5 files changed, 285 insertions, 117 deletions
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);
}