From 54d829d5d3f657fc6506e187c60668b2418a756b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 12 Aug 2021 09:12:49 -0500 Subject: digest aliases --- src/slskd/Application/SharedFileCache.cs | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 558cf46b..71a579d2 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -25,6 +25,7 @@ namespace slskd using System.Collections.Generic; using System.Diagnostics; using System.Linq; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Sqlite; @@ -101,6 +102,41 @@ namespace slskd return directories.Values; } + private (Dictionary Aliases, IEnumerable Shares) DigestAliases(IEnumerable shares) + { + var aliases = new Dictionary(); + var cleanedShares = new HashSet(); + + foreach (var share in shares) + { + var matches = Regex.Matches(share, @"^(\[.*\])(.*)$"); + + if (matches.Any()) + { + var alias = matches[0].Groups[1].Value; + var unaliasedShare = matches[0].Groups[2].Value; + var parent = System.IO.Directory.GetParent(unaliasedShare).FullName; + + cleanedShares.Add(unaliasedShare); + + if (aliases.ContainsKey(parent)) + { + aliases[parent] = alias; + } + else + { + aliases.Add(parent, alias); + } + } + else + { + cleanedShares.Add(share); + } + } + + return (aliases, cleanedShares); + } + /// /// Scans the configured shares and fills the cache. /// @@ -133,10 +169,16 @@ namespace slskd var shares = configuredShares.Where(s => !s.StartsWith('!') && !s.StartsWith('-')); var exclusions = configuredShares.Except(shares).Select(s => s[1..]); + var (aliases, unaliasedShares) = DigestAliases(shares); + shares = unaliasedShares; + var masks = new Dictionary(shares .Select(s => System.IO.Directory.GetParent(s).FullName) .Select(s => new KeyValuePair(Compute.MaskHash(s), s)).ToHashSet()); + Console.WriteLine(masks.ToJson()); + Console.WriteLine(aliases.ToJson()); + Log.Debug("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; -- cgit v1.2.3 From 818ffb0244d2fbfc97304df49bc8f2a94e1779fc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 12 Aug 2021 09:45:12 -0500 Subject: derive aliased path --- src/slskd/Application/SharedFileCache.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 71a579d2..4b196b68 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -115,17 +115,16 @@ namespace slskd { var alias = matches[0].Groups[1].Value; var unaliasedShare = matches[0].Groups[2].Value; - var parent = System.IO.Directory.GetParent(unaliasedShare).FullName; cleanedShares.Add(unaliasedShare); - if (aliases.ContainsKey(parent)) + if (aliases.ContainsKey(unaliasedShare)) { - aliases[parent] = alias; + aliases[alias] = unaliasedShare; } else { - aliases.Add(parent, alias); + aliases.Add(alias, unaliasedShare); } } else @@ -203,6 +202,17 @@ namespace slskd foreach (var directory in unmaskedDirectories) { var mask = masks.First(m => directory.StartsWith(m.Value)); + var alias = aliases.FirstOrDefault(a => directory.StartsWith(a.Value)); + + var masked = directory.ReplaceFirst(mask.Value, mask.Key); + + if (alias.Key != null) + { + var target = masked.Split(new[] { '\\', '/' }).Skip(1).First(); + Console.WriteLine($"Directory {target} is aliased to {alias.Key}"); + masked = masked.ReplaceFirst(target, alias.Key); + Console.WriteLine(masked); + } maskedDirectories.Add(directory.ReplaceFirst(mask.Value, mask.Key)); -- cgit v1.2.3 From cd2b93fb8c75ca41fd31126bf41dadf9c1668400 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 13 Aug 2021 09:40:12 -0500 Subject: implement alias replacement --- src/slskd/Application/SharedFileCache.cs | 124 ++++++++++++++++--------------- 1 file changed, 64 insertions(+), 60 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 4b196b68..5f385e9d 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -102,40 +102,6 @@ namespace slskd return directories.Values; } - private (Dictionary Aliases, IEnumerable Shares) DigestAliases(IEnumerable shares) - { - var aliases = new Dictionary(); - var cleanedShares = new HashSet(); - - foreach (var share in shares) - { - var matches = Regex.Matches(share, @"^(\[.*\])(.*)$"); - - if (matches.Any()) - { - var alias = matches[0].Groups[1].Value; - var unaliasedShare = matches[0].Groups[2].Value; - - cleanedShares.Add(unaliasedShare); - - if (aliases.ContainsKey(unaliasedShare)) - { - aliases[alias] = unaliasedShare; - } - else - { - aliases.Add(alias, unaliasedShare); - } - } - else - { - cleanedShares.Add(share); - } - } - - return (aliases, cleanedShares); - } - /// /// Scans the configured shares and fills the cache. /// @@ -165,18 +131,9 @@ namespace slskd sw.Start(); var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared.ToList(); // copy it so it can't change as we scan - var shares = configuredShares.Where(s => !s.StartsWith('!') && !s.StartsWith('-')); - var exclusions = configuredShares.Except(shares).Select(s => s[1..]); - - var (aliases, unaliasedShares) = DigestAliases(shares); - shares = unaliasedShares; - - var masks = new Dictionary(shares - .Select(s => System.IO.Directory.GetParent(s).FullName) - .Select(s => new KeyValuePair(Compute.MaskHash(s), s)).ToHashSet()); - - Console.WriteLine(masks.ToJson()); - Console.WriteLine(aliases.ToJson()); + var (aliases, unaliasedShares) = DigestAliases(configuredShares); + var (shares, exclusions) = DigestExclusions(unaliasedShares); + var masks = ComputeMasks(shares); Log.Debug("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; @@ -202,25 +159,17 @@ namespace slskd foreach (var directory in unmaskedDirectories) { var mask = masks.First(m => directory.StartsWith(m.Value)); - var alias = aliases.FirstOrDefault(a => directory.StartsWith(a.Value)); + var alias = aliases + .OrderByDescending(a => a.Value.Length) // ensure that nested aliases are matched first + .FirstOrDefault(a => directory.StartsWith(a.Value)); - var masked = directory.ReplaceFirst(mask.Value, mask.Key); - - if (alias.Key != null) - { - var target = masked.Split(new[] { '\\', '/' }).Skip(1).First(); - Console.WriteLine($"Directory {target} is aliased to {alias.Key}"); - masked = masked.ReplaceFirst(target, alias.Key); - Console.WriteLine(masked); - } - - maskedDirectories.Add(directory.ReplaceFirst(mask.Value, mask.Key)); + maskedDirectories.Add(TransformPath(directory, mask, alias)); // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized // filename and with a value of a Soulseek.File object var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(mask.Value, mask.Key), new FileInfo(f).Length, Path.GetExtension(f))) - .ToDictionary(f => f.Filename.ReplaceFirst(mask.Value, mask.Key), f => f); + .Select(f => new File(1, TransformPath(f.Replace("/", @"\"), mask, alias), new FileInfo(f).Length, Path.GetExtension(f))) + .ToDictionary(f => f.Filename, f => f); // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. @@ -324,6 +273,13 @@ namespace slskd } } + private Dictionary ComputeMasks(IEnumerable shares) + { + return new Dictionary(shares + .Select(s => System.IO.Directory.GetParent(s).FullName) + .Select(s => new KeyValuePair(Compute.MaskHash(s), s)).ToHashSet()); + } + private void CreateTable() { if (SQLite != null) @@ -338,6 +294,41 @@ namespace slskd cmd.ExecuteNonQuery(); } + private (Dictionary Aliases, IEnumerable UnaliasedShares) DigestAliases(IEnumerable shares) + { + var aliases = new ConcurrentDictionary(); + var unaliasedShares = new HashSet(); + + foreach (var share in shares) + { + var matches = Regex.Matches(share, @"^(-?)\[(.*)\](.*)$"); + + if (matches.Any()) + { + var groups = matches[0].Groups; + var alias = groups[2].Value; + var unaliasedShare = groups[1].Value + groups[3].Value; + + unaliasedShares.Add(unaliasedShare); + aliases.AddOrUpdate(alias, unaliasedShare, (k, v) => unaliasedShare); + } + else + { + unaliasedShares.Add(share); + } + } + + return (new Dictionary(aliases), unaliasedShares); + } + + private (IEnumerable Shares, IEnumerable Exclusions) DigestExclusions(IEnumerable shares) + { + var included = shares.Where(s => !s.StartsWith('!') && !s.StartsWith('-')); + var exclusions = shares.Except(included).Select(s => s[1..]); + + return (included, exclusions); + } + private void InsertFilename(string filename) { using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); @@ -353,5 +344,18 @@ namespace slskd Files = new Dictionary(); State.SetValue(state => state with { Directories = 0, Files = 0 }); } + + private string TransformPath(string path, KeyValuePair mask, KeyValuePair alias) + { + var maskedPath = path.ReplaceFirst(mask.Value, mask.Key); + + if (alias.Key != null) + { + var relativeAlias = alias.Value[(mask.Value.Length + 1)..]; + return maskedPath.ReplaceFirst(relativeAlias, alias.Key); + } + + return path.ReplaceFirst(mask.Value, mask.Key); + } } } \ No newline at end of file -- cgit v1.2.3 From b0b776f21d9f5813a31f49b209242eaecd66311e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Aug 2021 12:36:16 -0500 Subject: resolve aliases --- src/slskd/Application/SharedFileCache.cs | 34 +++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 5f385e9d..4cea3780 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -56,6 +56,7 @@ namespace slskd private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } private Dictionary Masks { get; set; } = new Dictionary(); + private Dictionary Aliases { get; set; } = new Dictionary(); private IOptionsMonitor OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); @@ -130,7 +131,7 @@ namespace slskd var swSnapshot = 0L; sw.Start(); - var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared.ToList(); // copy it so it can't change as we scan + var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared.ToHashSet().ToList(); // copy it so it can't change as we scan var (aliases, unaliasedShares) = DigestAliases(configuredShares); var (shares, exclusions) = DigestExclusions(unaliasedShares); var masks = ComputeMasks(shares); @@ -201,6 +202,7 @@ namespace slskd UnmaskedDirectories = unmaskedDirectories; MaskedDirectories = maskedDirectories; Masks = masks; + Aliases = aliases; Files = files; State.SetValue(state => state with { Filling = false, Faulted = false, FillProgress = 1, Directories = UnmaskedDirectories.Count, Files = Files.Count }); @@ -226,14 +228,30 @@ namespace slskd /// The unmasked filename. public string Resolve(string filename) { - var mask = filename.Split(new[] { '/', '\\' }).FirstOrDefault(); + var resolved = filename; - if (Masks.ContainsKey(mask)) + var parts = filename.Split(new[] { '/', '\\' }); + + if (parts.Length < 2) + { + return resolved; + } + + var mask = parts[0]; + var root = parts[1]; + + if (Masks.TryGetValue(mask, out var maskedPath)) { - return filename.ReplaceFirst(mask, Masks[mask]); + resolved = resolved.ReplaceFirst(mask, maskedPath); + + if (Aliases.TryGetValue(root, out var aliasedPath)) + { + var relativeAlias = aliasedPath[(maskedPath.Length + 1)..]; + resolved = resolved.ReplaceFirst(root, relativeAlias); + } } - return filename; + return resolved; } /// @@ -307,6 +325,12 @@ namespace slskd { var groups = matches[0].Groups; var alias = groups[2].Value; + + if (alias.Contains('\\') || alias.Contains('/')) + { + throw new ShareAliasException($"Share aliases must not contain path separators '/' or '\\' (provided: {alias})"); + } + var unaliasedShare = groups[1].Value + groups[3].Value; unaliasedShares.Add(unaliasedShare); -- cgit v1.2.3 From 8f1083955ff018b4b463e5b5a103d6526748261b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Aug 2021 21:06:41 -0500 Subject: force ordering --- src/slskd/Application/SharedFileCache.cs | 46 +++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 15 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 4cea3780..f842dec3 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -100,7 +100,7 @@ namespace slskd directories.AddOrUpdate(group.Name, group, (_, _) => group); } - return directories.Values; + return directories.Values.OrderBy(f => f.Name[8..]); } /// @@ -131,7 +131,11 @@ namespace slskd var swSnapshot = 0L; sw.Start(); - var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared.ToHashSet().ToList(); // copy it so it can't change as we scan + var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared + .ToHashSet() // remove duplicates + .OrderBy(s => DigestShare(s).Share.Length) // ensure root directories are first + .ToList(); // copy it so it can't change as we scan + var (aliases, unaliasedShares) = DigestAliases(configuredShares); var (shares, exclusions) = DigestExclusions(unaliasedShares); var masks = ComputeMasks(shares); @@ -319,20 +323,10 @@ namespace slskd foreach (var share in shares) { - var matches = Regex.Matches(share, @"^(-?)\[(.*)\](.*)$"); + var (alias, unaliasedShare) = DigestShare(share); - if (matches.Any()) + if (!string.IsNullOrEmpty(share)) { - var groups = matches[0].Groups; - var alias = groups[2].Value; - - if (alias.Contains('\\') || alias.Contains('/')) - { - throw new ShareAliasException($"Share aliases must not contain path separators '/' or '\\' (provided: {alias})"); - } - - var unaliasedShare = groups[1].Value + groups[3].Value; - unaliasedShares.Add(unaliasedShare); aliases.AddOrUpdate(alias, unaliasedShare, (k, v) => unaliasedShare); } @@ -345,6 +339,28 @@ namespace slskd return (new Dictionary(aliases), unaliasedShares); } + private (string Alias, string Share) DigestShare(string share) + { + var matches = Regex.Matches(share, @"^(-?)\[(.*)\](.*)$"); + + if (matches.Any()) + { + var groups = matches[0].Groups; + var alias = groups[2].Value; + + if (alias.Contains('\\') || alias.Contains('/')) + { + throw new ShareAliasException($"Share aliases must not contain path separators '/' or '\\' (provided: {alias})"); + } + + var unaliasedShare = groups[1].Value + groups[3].Value; + + return (alias, unaliasedShare); + } + + return (string.Empty, share); + } + private (IEnumerable Shares, IEnumerable Exclusions) DigestExclusions(IEnumerable shares) { var included = shares.Where(s => !s.StartsWith('!') && !s.StartsWith('-')); @@ -373,7 +389,7 @@ namespace slskd { var maskedPath = path.ReplaceFirst(mask.Value, mask.Key); - if (alias.Key != null) + if (!string.IsNullOrEmpty(alias.Key) && alias.Value != mask.Value) { var relativeAlias = alias.Value[(mask.Value.Length + 1)..]; return maskedPath.ReplaceFirst(relativeAlias, alias.Key); -- cgit v1.2.3 From 5563c62ec10fcf1cd0e90072d76f6c924100c56e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Aug 2021 09:54:21 -0500 Subject: simplify masking/alias logic --- src/slskd/Application/SharedFileCache.cs | 185 ++++++++++++++----------------- 1 file changed, 85 insertions(+), 100 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index f842dec3..4e996bf7 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -55,12 +55,11 @@ namespace slskd private Dictionary Files { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } - private Dictionary Masks { get; set; } = new Dictionary(); - private Dictionary Aliases { get; set; } = new Dictionary(); private IOptionsMonitor OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private HashSet UnmaskedDirectories { get; set; } + private List Shares { get; set; } /// /// Returns the contents of the cache. @@ -131,25 +130,33 @@ namespace slskd var swSnapshot = 0L; sw.Start(); - var configuredShares = OptionsMonitor.CurrentValue.Directories.Shared + Shares = OptionsMonitor.CurrentValue.Directories.Shared .ToHashSet() // remove duplicates - .OrderBy(s => DigestShare(s).Share.Length) // ensure root directories are first - .ToList(); // copy it so it can't change as we scan + .Select(share => new Share(share)) // convert to Shares + .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent + .ToList(); - var (aliases, unaliasedShares) = DigestAliases(configuredShares); - var (shares, exclusions) = DigestExclusions(unaliasedShares); - var masks = ComputeMasks(shares); + // check for and warn about duplicates + var duplicates = Shares.GroupBy(share => share.Mask + share.Alias).Where(group => group.Count() > 1); + + if (duplicates.Any()) + { + foreach (var dupe in duplicates) + { + Log.Warning($"Overlapping shares: {string.Join(", ", dupe.Select(s => s.Raw))}. Use different alias(es) to disambiguate; downloads from these shares will most likely fail."); + } + } Log.Debug("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; - var unmaskedDirectories = shares - .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) - .Concat(shares) - .ToHashSet(); + var unmaskedDirectories = Shares + .SelectMany(share => System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories)) + .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .ToHashSet(); // remove duplicates (in case shares overlap) var excludedDirectories = unmaskedDirectories - .Where(share => exclusions.Any(exclusions => share.StartsWith(exclusions))); + .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); @@ -163,17 +170,14 @@ namespace slskd foreach (var directory in unmaskedDirectories) { - var mask = masks.First(m => directory.StartsWith(m.Value)); - var alias = aliases - .OrderByDescending(a => a.Value.Length) // ensure that nested aliases are matched first - .FirstOrDefault(a => directory.StartsWith(a.Value)); + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - maskedDirectories.Add(TransformPath(directory, mask, alias)); + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized // filename and with a value of a Soulseek.File object var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(f => new File(1, TransformPath(f.Replace("/", @"\"), mask, alias), new FileInfo(f).Length, Path.GetExtension(f))) + .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f))) .ToDictionary(f => f.Filename, f => f); // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully @@ -205,8 +209,6 @@ namespace slskd UnmaskedDirectories = unmaskedDirectories; MaskedDirectories = maskedDirectories; - Masks = masks; - Aliases = aliases; Files = files; State.SetValue(state => state with { Filling = false, Faulted = false, FillProgress = 1, Directories = UnmaskedDirectories.Count, Files = Files.Count }); @@ -234,6 +236,8 @@ namespace slskd { var resolved = filename; + // a well-formed path will consist of a mask, either an alias or a local directory, and a + // fully qualified path to a file. split the requested filename so we can examine the first two segments var parts = filename.Split(new[] { '/', '\\' }); if (parts.Length < 2) @@ -241,21 +245,15 @@ namespace slskd return resolved; } - var mask = parts[0]; - var root = parts[1]; + // find the share with a matching mask and alias/local directory + var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); - if (Masks.TryGetValue(mask, out var maskedPath)) + if (share == default) { - resolved = resolved.ReplaceFirst(mask, maskedPath); - - if (Aliases.TryGetValue(root, out var aliasedPath)) - { - var relativeAlias = aliasedPath[(maskedPath.Length + 1)..]; - resolved = resolved.ReplaceFirst(root, relativeAlias); - } + return resolved; } - return resolved; + return resolved.ReplaceFirst(share.RemotePath, share.LocalPath); } /// @@ -295,13 +293,6 @@ namespace slskd } } - private Dictionary ComputeMasks(IEnumerable shares) - { - return new Dictionary(shares - .Select(s => System.IO.Directory.GetParent(s).FullName) - .Select(s => new KeyValuePair(Compute.MaskHash(s), s)).ToHashSet()); - } - private void CreateTable() { if (SQLite != null) @@ -316,59 +307,6 @@ namespace slskd cmd.ExecuteNonQuery(); } - private (Dictionary Aliases, IEnumerable UnaliasedShares) DigestAliases(IEnumerable shares) - { - var aliases = new ConcurrentDictionary(); - var unaliasedShares = new HashSet(); - - foreach (var share in shares) - { - var (alias, unaliasedShare) = DigestShare(share); - - if (!string.IsNullOrEmpty(share)) - { - unaliasedShares.Add(unaliasedShare); - aliases.AddOrUpdate(alias, unaliasedShare, (k, v) => unaliasedShare); - } - else - { - unaliasedShares.Add(share); - } - } - - return (new Dictionary(aliases), unaliasedShares); - } - - private (string Alias, string Share) DigestShare(string share) - { - var matches = Regex.Matches(share, @"^(-?)\[(.*)\](.*)$"); - - if (matches.Any()) - { - var groups = matches[0].Groups; - var alias = groups[2].Value; - - if (alias.Contains('\\') || alias.Contains('/')) - { - throw new ShareAliasException($"Share aliases must not contain path separators '/' or '\\' (provided: {alias})"); - } - - var unaliasedShare = groups[1].Value + groups[3].Value; - - return (alias, unaliasedShare); - } - - return (string.Empty, share); - } - - private (IEnumerable Shares, IEnumerable Exclusions) DigestExclusions(IEnumerable shares) - { - var included = shares.Where(s => !s.StartsWith('!') && !s.StartsWith('-')); - var exclusions = shares.Except(included).Select(s => s[1..]); - - return (included, exclusions); - } - private void InsertFilename(string filename) { using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); @@ -380,22 +318,69 @@ namespace slskd CreateTable(); UnmaskedDirectories = new HashSet(); MaskedDirectories = new HashSet(); - Masks = new Dictionary(); Files = new Dictionary(); State.SetValue(state => state with { Directories = 0, Files = 0 }); } - private string TransformPath(string path, KeyValuePair mask, KeyValuePair alias) + private class Share { - var maskedPath = path.ReplaceFirst(mask.Value, mask.Key); - - if (!string.IsNullOrEmpty(alias.Key) && alias.Value != mask.Value) + public Share(string share) { - var relativeAlias = alias.Value[(mask.Value.Length + 1)..]; - return maskedPath.ReplaceFirst(relativeAlias, alias.Key); + Raw = share; + IsExcluded = share.StartsWith('-') || share.StartsWith('!'); + + if (IsExcluded) + { + share = share[1..]; + } + + // test to see whether an alias has been specified + var matches = Regex.Matches(share, @"^\[(.*)\](.*)$"); + + if (matches.Any()) + { + // split the alias from the path, and validate the alias + var groups = matches[0].Groups; + Alias = groups[1].Value; + + if (string.IsNullOrWhiteSpace(Alias)) + { + throw new ShareAliasException($"Share aliases must not be null, empty or contain only whitespace (provided: {Alias})"); + } + else if (Alias.Contains('\\') || Alias.Contains('/')) + { + throw new ShareAliasException($"Share aliases must not contain path separators '/' or '\\' (provided: {Alias})"); + } + + LocalPath = groups[2].Value; + } + else + { + Alias = new Uri(share).Segments.Last(); + LocalPath = share; + } + + Mask = Compute.MaskHash(System.IO.Directory.GetParent(LocalPath).FullName); + + var maskedPath = LocalPath.ReplaceFirst(System.IO.Directory.GetParent(LocalPath).FullName, Mask); + + if (!string.IsNullOrEmpty(Alias)) + { + var aliasedSegment = LocalPath[(System.IO.Directory.GetParent(LocalPath).FullName.Length + 1)..]; + RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias); + } + else + { + RemotePath = LocalPath.ReplaceFirst(System.IO.Directory.GetParent(LocalPath).FullName, Mask); + } } - return path.ReplaceFirst(mask.Value, mask.Key); + public string Raw { get; init; } + public string Alias { get; init; } + public string LocalPath { get; init; } + public string RemotePath { get; init; } + public string Mask { get; init; } + public bool IsExcluded { get; init; } } } } \ No newline at end of file -- cgit v1.2.3 From 7637336a076a2da712b7f42fb322d1ef011a156f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Aug 2021 10:00:19 -0500 Subject: clarify duplicate warning --- src/slskd/Application/SharedFileCache.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 4e996bf7..338e187b 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -56,10 +56,10 @@ namespace slskd private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } + private List Shares { get; set; } private SqliteConnection SQLite { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private HashSet UnmaskedDirectories { get; set; } - private List Shares { get; set; } /// /// Returns the contents of the cache. @@ -143,7 +143,7 @@ namespace slskd { foreach (var dupe in duplicates) { - Log.Warning($"Overlapping shares: {string.Join(", ", dupe.Select(s => s.Raw))}. Use different alias(es) to disambiguate; downloads from these shares will most likely fail."); + Log.Warning($"Overlapping shares: {string.Join(", ", dupe.Select(s => s.Raw))}. Use different alias(es) to disambiguate; downloads from one of these shares will fail."); } } @@ -236,8 +236,8 @@ namespace slskd { var resolved = filename; - // a well-formed path will consist of a mask, either an alias or a local directory, and a - // fully qualified path to a file. split the requested filename so we can examine the first two segments + // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a + // file. split the requested filename so we can examine the first two segments var parts = filename.Split(new[] { '/', '\\' }); if (parts.Length < 2) @@ -375,12 +375,12 @@ namespace slskd } } - public string Raw { get; init; } public string Alias { get; init; } + public bool IsExcluded { get; init; } public string LocalPath { get; init; } - public string RemotePath { get; init; } public string Mask { get; init; } - public bool IsExcluded { get; init; } + public string Raw { get; init; } + public string RemotePath { get; init; } } } } \ No newline at end of file -- cgit v1.2.3 From 741889f40bdc6af47e8fddc5ebcc786cb51e71cf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Aug 2021 10:08:39 -0500 Subject: don't fail on missing directories --- src/slskd/Application/SharedFileCache.cs | 44 +++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 12 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 338e187b..76abf77e 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -151,8 +151,20 @@ namespace slskd swSnapshot = sw.ElapsedMilliseconds; var unmaskedDirectories = Shares - .SelectMany(share => System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories)) + .SelectMany(share => + { + try + { + return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + return Array.Empty(); + } + }) .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. .ToHashSet(); // remove duplicates (in case shares overlap) var excludedDirectories = unmaskedDirectories @@ -176,21 +188,29 @@ namespace slskd // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized // filename and with a value of a Soulseek.File object - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f))) - .ToDictionary(f => f.Filename, f => f); - - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully - // 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) + try { - if (files.ContainsKey(file.Key)) + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(f => new File(1, f.Replace("/", @"\").ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f))) + .ToDictionary(f => f.Filename, f => f); + + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // 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) { - 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?)."); - } + 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?)."); + } - files[file.Key] = file.Value; + files[file.Key] = file.Value; + } } + catch (Exception ex) + { + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); + } + current++; State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); -- cgit v1.2.3 From b02375273faa8ebfc81a681e9c07f0e1624b7bbf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Aug 2021 17:44:28 -0500 Subject: remove redundant checking for duplicates and bad aliases --- src/slskd/Application/SharedFileCache.cs | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) (limited to 'src/slskd/Application/SharedFileCache.cs') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 76abf77e..3f050086 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -131,22 +131,12 @@ namespace slskd sw.Start(); Shares = OptionsMonitor.CurrentValue.Directories.Shared + .Select(share => Path.TrimEndingDirectorySeparator(share)) .ToHashSet() // remove duplicates .Select(share => new Share(share)) // convert to Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); - // check for and warn about duplicates - var duplicates = Shares.GroupBy(share => share.Mask + share.Alias).Where(group => group.Count() > 1); - - if (duplicates.Any()) - { - foreach (var dupe in duplicates) - { - Log.Warning($"Overlapping shares: {string.Join(", ", dupe.Select(s => s.Raw))}. Use different alias(es) to disambiguate; downloads from one of these shares will fail."); - } - } - Log.Debug("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; @@ -362,16 +352,6 @@ namespace slskd // split the alias from the path, and validate the alias var groups = matches[0].Groups; Alias = groups[1].Value; - - if (string.IsNullOrWhiteSpace(Alias)) - { - throw new ShareAliasException($"Share aliases must not be null, empty or contain only whitespace (provided: {Alias})"); - } - else if (Alias.Contains('\\') || Alias.Contains('/')) - { - throw new ShareAliasException($"Share aliases must not contain path separators '/' or '\\' (provided: {Alias})"); - } - LocalPath = groups[2].Value; } else -- cgit v1.2.3