aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-08-27 07:52:32 -0500
committerGitHub <noreply@github.com>2021-08-27 07:52:32 -0500
commit5834a04885ad9f5159393d51da3ed3678f8ed6c3 (patch)
tree088e1558c39180135c86fec2ed1c44210d0c1e21 /src
parentdbf92255737057a7603366684456f90166a88045 (diff)
parent682d69c0bb6cbef7d0deb6027102db3cb26cf006 (diff)
downloadslskd-5834a04885ad9f5159393d51da3ed3678f8ed6c3.tar.gz
Merge pull request #169 from slskd/exclusions
Add the ability to filter shared files
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application/Application.cs7
-rw-r--r--src/slskd/Application/Search/Extensions.cs28
-rw-r--r--src/slskd/Application/Search/SearchService.cs6
-rw-r--r--src/slskd/Application/SharedFileCache.cs14
-rw-r--r--src/slskd/Common/Extensions.cs25
-rw-r--r--src/slskd/Options.cs42
-rw-r--r--src/slskd/Properties/slskd.yml19
7 files changed, 133 insertions, 8 deletions
diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs
index c317f467..3e054dc8 100644
--- a/src/slskd/Application/Application.cs
+++ b/src/slskd/Application/Application.cs
@@ -241,6 +241,13 @@ namespace slskd
Logger.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect.");
}
+ if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any()
+ || newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any())
+ {
+ StateMonitor.SetValue(state => state with { PendingShareRescan = true });
+ Logger.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect.");
+ }
+
// determine whether any Soulseek options changed. if so, we need to construct a patch
// and invoke ReconfigureOptionsAsync().
var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek);
diff --git a/src/slskd/Application/Search/Extensions.cs b/src/slskd/Application/Search/Extensions.cs
index d52975d2..149e0a14 100644
--- a/src/slskd/Application/Search/Extensions.cs
+++ b/src/slskd/Application/Search/Extensions.cs
@@ -71,6 +71,34 @@ namespace slskd.Search
}
/// <summary>
+ /// Returns a copy of the specified <paramref name="options"/> with the specified filter delegates overridden.
+ /// </summary>
+ /// <param name="options"></param>
+ /// <param name="responseFilter"></param>
+ /// <param name="fileFilter"></param>
+ /// <returns></returns>
+ public static SearchOptions WithFilters(
+ this SearchOptions options,
+ Func<SearchResponse, bool> responseFilter = null,
+ Func<Soulseek.File, bool> fileFilter = null)
+ {
+ return new SearchOptions(
+ options.SearchTimeout,
+ options.ResponseLimit,
+ filterResponses: options.FilterResponses || responseFilter != null || fileFilter != null,
+ options.MinimumResponseFileCount,
+ options.MinimumPeerFreeUploadSlots,
+ options.MaximumPeerQueueLength,
+ options.MinimumPeerUploadSpeed,
+ options.FileLimit,
+ options.RemoveSingleCharacterSearchTerms,
+ responseFilter,
+ fileFilter,
+ options.StateChanged,
+ options.ResponseReceived);
+ }
+
+ /// <summary>
/// Creates a projection over the specified <paramref name="query"/> which omits responses.
/// </summary>
/// <param name="query"></param>
diff --git a/src/slskd/Application/Search/SearchService.cs b/src/slskd/Application/Search/SearchService.cs
index 84cfd756..8de18977 100644
--- a/src/slskd/Application/Search/SearchService.cs
+++ b/src/slskd/Application/Search/SearchService.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Options;
+
namespace slskd.Search
{
using System;
@@ -41,14 +43,17 @@ namespace slskd.Search
/// <summary>
/// Initializes a new instance of the <see cref="SearchService"/> class.
/// </summary>
+ /// <param name="optionsMonitor"></param>
/// <param name="client">The client instance to use.</param>
/// <param name="contextFactory">The database context to use.</param>
/// <param name="log">The logger.</param>
public SearchService(
+ IOptionsMonitor<Options> optionsMonitor,
ISoulseekClient client,
IDbContextFactory<SearchDbContext> contextFactory,
ILogger<SearchService> log)
{
+ OptionsMonitor = optionsMonitor;
Client = client;
ContextFactory = contextFactory;
Log = log;
@@ -57,6 +62,7 @@ namespace slskd.Search
private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; }
= new ConcurrentDictionary<Guid, CancellationTokenSource>();
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
private ISoulseekClient Client { get; }
private IDbContextFactory<SearchDbContext> ContextFactory { get; }
private ILogger<SearchService> Log { get; set; }
diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs
index c2200daf..ee4e0c72 100644
--- a/src/slskd/Application/SharedFileCache.cs
+++ b/src/slskd/Application/SharedFileCache.cs
@@ -167,12 +167,16 @@ namespace slskd
unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet();
State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() });
- Log.Debug("Found {Directories} shared directories (and {Excluded} were filtered) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot);
+ Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot);
swSnapshot = sw.ElapsedMilliseconds;
+ var filters = OptionsMonitor.CurrentValue.Filters.Share
+ .Select(filter => new Regex(filter, RegexOptions.Compiled));
+
var files = new Dictionary<string, File>();
var maskedDirectories = new HashSet<string>();
var current = 0;
+ var filtered = 0;
foreach (var directory in unmaskedDirectories)
{
@@ -192,6 +196,12 @@ namespace slskd
// qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another.
foreach (var file in newFiles)
{
+ if (filters.Any(filter => filter.IsMatch(file.Key)))
+ {
+ filtered++;
+ continue;
+ }
+
if (files.ContainsKey(file.Key))
{
Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?).");
@@ -209,7 +219,7 @@ namespace slskd
State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count });
}
- Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot);
+ Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot);
swSnapshot = sw.ElapsedMilliseconds;
// potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
index 20620e44..077f5b17 100644
--- a/src/slskd/Common/Extensions.cs
+++ b/src/slskd/Common/Extensions.cs
@@ -23,6 +23,7 @@ namespace slskd
using System.Linq;
using System.Reflection;
using System.Text.Json;
+ using System.Text.RegularExpressions;
/// <summary>
/// Extensions.
@@ -118,6 +119,30 @@ namespace slskd
}
/// <summary>
+ /// Determines whether the string is a valid regular expression.
+ /// </summary>
+ /// <param name="pattern">The string to validate.</param>
+ /// <returns>A value indicating whether the string is a valid regular expression.</returns>
+ public static bool IsValidRegex(this string pattern)
+ {
+ if (string.IsNullOrWhiteSpace(pattern))
+ {
+ return false;
+ }
+
+ try
+ {
+ Regex.Match(string.Empty, pattern);
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ /// <summary>
/// Deeply compares this object with the specified object and returns a list of properties that are different.
/// </summary>
/// <param name="left">The left side of the comparison.</param>
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index ec1eab06..aac43c0a 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -188,6 +188,12 @@ namespace slskd
public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions();
/// <summary>
+ /// Gets filter options.
+ /// </summary>
+ [Validate]
+ public FiltersOptions Filters { get; private set; } = new FiltersOptions();
+
+ /// <summary>
/// Gets options for the web UI.
/// </summary>
[Validate]
@@ -255,7 +261,7 @@ namespace slskd
public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory;
/// <summary>
- /// Gets the path to shared files.
+ /// Gets the list of paths to shared files.
/// </summary>
[Argument('s', "shared")]
[EnvironmentVariable("SHARED_DIR")]
@@ -340,6 +346,40 @@ namespace slskd
}
/// <summary>
+ /// Filter options.
+ /// </summary>
+ public class FiltersOptions : IValidatableObject
+ {
+ /// <summary>
+ /// Gets the list of shared file filters.
+ /// </summary>
+ [Argument(default, "share-filter")]
+ [EnvironmentVariable("SHARE_FILTER")]
+ [Description("regular expressions to filter files from shares")]
+ public string[] Share { get; private set; } = Array.Empty<string>();
+
+ /// <summary>
+ /// Extended validation.
+ /// </summary>
+ /// <param name="validationContext"></param>
+ /// <returns></returns>
+ public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
+ {
+ var results = new List<ValidationResult>();
+
+ foreach (var filter in Share)
+ {
+ if (!filter.IsValidRegex())
+ {
+ results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression"));
+ }
+ }
+
+ return results;
+ }
+ }
+
+ /// <summary>
/// Logger options.
/// </summary>
public class LoggerOptions
diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml
index 938d2a70..4f25179c 100644
--- a/src/slskd/Properties/slskd.yml
+++ b/src/slskd/Properties/slskd.yml
@@ -1,6 +1,20 @@
# debug: false
# no_logo: false
+# no_start: false
+# no_connect: false
+# no_share_scan: false
# instance_name: default
+# directories:
+# app: ~
+# incomplete: ~
+# downloads: ~
+# shared:
+# - ~
+# filters:
+# share:
+# - \.ini$
+# - Thumbs.db$
+# - \.DS_Store$
# web:
# port: 5000
# https:
@@ -18,11 +32,6 @@
# jwt:
# key: ~
# ttl: 604800000
-# directories:
-# app: ~
-# incomplete: ~
-# downloads: ~
-# shared: ~
# logger:
# loki: ~
# feature: