From 181fca7ded7dd797fdb1e7b58b7d5508559425bd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Jul 2021 23:19:27 -0500 Subject: add Browse() --- src/slskd/Application/ISharedFileCache.cs | 1 + src/slskd/Application/SharedFileCache.cs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) (limited to 'src') diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs index 97133e40..0744be9f 100644 --- a/src/slskd/Application/ISharedFileCache.cs +++ b/src/slskd/Application/ISharedFileCache.cs @@ -32,5 +32,6 @@ namespace slskd void Fill(); IEnumerable Search(SearchQuery query); + IEnumerable Browse(); } } \ No newline at end of file diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 45a810fc..aeb2022a 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -132,6 +132,23 @@ namespace slskd return QueryTable(query.Query); } + public IEnumerable Browse() + { + var directories = Files + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Soulseek.Directory(g.Key, g.Select(g => { + var f = g.Value; + return new Soulseek.File( + f.Code, + Path.GetFileName(f.Filename), + f.Size, + f.Extension, + f.Attributes); + }))); + + return directories; + } + private void CreateTable() { SQLite = new SqliteConnection("Data Source=:memory:"); -- cgit v1.2.3 From d42d679a056b15d6c29f08e8d219dea89ef61ced Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Jul 2021 23:19:42 -0500 Subject: browse from cache, fill cache on start --- src/slskd/Application/Service.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index ef47cf24..cdd0cc6b 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -137,6 +137,7 @@ namespace slskd SoulseekClient = Client; + SharedFileCache.Fill(); SharedFileCache.Refreshed += SharedFileCache_Refreshed; } @@ -326,16 +327,7 @@ namespace slskd /// A Task resolving an IEnumerable of Soulseek.Directory. private Task BrowseResponseResolver(string username, IPEndPoint endpoint) { - var shares = OptionsMonitor.CurrentValue.Directories.Shared; - var directories = new List(); - - foreach (var share in shares) - { - directories.AddRange(System.IO.Directory - .GetDirectories(share, "*", SearchOption.AllDirectories) - .Select(dir => new Soulseek.Directory(dir.Replace("/", @"\"), System.IO.Directory.GetFiles(dir) - .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))))); - } + var directories = SharedFileCache.Browse(); return Task.FromResult(new BrowseResponse(directories)); } -- cgit v1.2.3 From 0568ed9d11ecd63e0386ebe5e16927d2273c0468 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 31 Jul 2021 23:36:25 -0500 Subject: add some logs --- src/slskd/Application/SharedFileCache.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index aeb2022a..1ebe76c6 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -73,6 +73,8 @@ namespace slskd foreach (var directory in Directories) { + Console.WriteLine(directory); + directories += System.IO.Directory.GetDirectories(directory, "*", SearchOption.AllDirectories).Length; // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized @@ -86,6 +88,7 @@ namespace slskd // the only time this *should* cause problems is if one of the shares is a subdirectory of another. foreach (var file in newFiles) { + Console.WriteLine(file.Key); if (files.ContainsKey(file.Key)) { Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); -- cgit v1.2.3 From 0a45d7efba977869d9a81701a33d8dab103b9fe2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 12:50:22 -0500 Subject: fix missing directories in browse response --- src/slskd/Application/ISharedFileCache.cs | 2 +- src/slskd/Application/Service.cs | 2 + src/slskd/Application/SharedFileCache.cs | 89 +++++++++++++++++++------------ 3 files changed, 59 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs index 0744be9f..47b16997 100644 --- a/src/slskd/Application/ISharedFileCache.cs +++ b/src/slskd/Application/ISharedFileCache.cs @@ -25,7 +25,7 @@ namespace slskd { event EventHandler<(int Directories, int Files)> Refreshed; - IEnumerable Directories { get; } + IEnumerable Shares { get; } DateTime? LastFill { get; } long TTL { get; } diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index cdd0cc6b..3874b494 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -329,6 +329,8 @@ namespace slskd { var directories = SharedFileCache.Browse(); + System.IO.File.WriteAllText(@"C:\Users\JP.WHATNET\Desktop\Soulseek\files.json", directories.ToJson()); + return Task.FromResult(new BrowseResponse(directories)); } diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 1ebe76c6..729fe167 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -18,6 +18,7 @@ namespace slskd { using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -34,17 +35,17 @@ namespace slskd /// /// Initializes a new instance of the class. /// - /// + /// /// - public SharedFileCache(IEnumerable directories, long ttl) + public SharedFileCache(IEnumerable shares, long ttl) { - Directories = directories; + Shares = shares; TTL = ttl; } public event EventHandler<(int Directories, int Files)> Refreshed; - public IEnumerable Directories { get; } + public IEnumerable Shares { get; } public DateTime? LastFill { get; set; } public long TTL { get; } @@ -52,8 +53,10 @@ namespace slskd private SqliteConnection SQLite { get; set; } private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + private HashSet Directories { get; set; } + /// - /// Scans the configured and fills the cache. + /// Scans the configured and fills the cache. /// public void Fill() { @@ -67,34 +70,33 @@ namespace slskd try { CreateTable(); - - var directories = 0; + var directories = new HashSet(); var files = new Dictionary(); - foreach (var directory in Directories) + foreach (var share in Shares) { - Console.WriteLine(directory); - - directories += System.IO.Directory.GetDirectories(directory, "*", SearchOption.AllDirectories).Length; - - // 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.AllDirectories) - .Select(f => new Soulseek.File(1, f.Replace("/", @"\"), 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) + foreach (var directory in System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) { - Console.WriteLine(file.Key); - if (files.ContainsKey(file.Key)) + directories.Add(directory); + + // 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 Soulseek.File(1, f.Replace("/", @"\"), 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) { - Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); - } + if (files.ContainsKey(file.Key)) + { + Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); + } - files[file.Key] = file.Value; + files[file.Key] = file.Value; + } } } @@ -105,9 +107,9 @@ namespace slskd InsertFilename(file.Key); } + Directories = directories; Files = files; - - Refreshed?.Invoke(this, (directories, Files.Count)); + Refreshed?.Invoke(this, (directories.Count, Files.Count)); } finally { @@ -137,19 +139,40 @@ namespace slskd public IEnumerable Browse() { - var directories = Files + var directories = new ConcurrentDictionary(); + + // 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 Directories) + { + directories.TryAdd(directory, new Soulseek.Directory(directory)); + } + + var groups = Files .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Soulseek.Directory(g.Key, g.Select(g => { + .Select(g => new Soulseek.Directory(g.Key, g.Select(g => + { var f = g.Value; return new Soulseek.File( f.Code, - Path.GetFileName(f.Filename), + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. f.Size, f.Extension, f.Attributes); }))); - return directories; + // merge the dictionary containing all directories with the Soulseek.Directory instances + // containing their files. entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values; } private void CreateTable() -- cgit v1.2.3 From d2cd2c484def2074dde3f5eb0cec0e473bdb7aad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 22:46:11 -0500 Subject: add Shares namespace --- src/slskd/Application/Shares/ISharesService.cs | 32 ++++ src/slskd/Application/Shares/SharesService.cs | 243 +++++++++++++++++++++++++ src/slskd/Application/Shares/SharesState.cs | 30 +++ 3 files changed, 305 insertions(+) create mode 100644 src/slskd/Application/Shares/ISharesService.cs create mode 100644 src/slskd/Application/Shares/SharesService.cs create mode 100644 src/slskd/Application/Shares/SharesState.cs (limited to 'src') diff --git a/src/slskd/Application/Shares/ISharesService.cs b/src/slskd/Application/Shares/ISharesService.cs new file mode 100644 index 00000000..78fe3e12 --- /dev/null +++ b/src/slskd/Application/Shares/ISharesService.cs @@ -0,0 +1,32 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Soulseek; + + public interface ISharesService + { + IEnumerable Browse(); + + Task FillAsync(); + + Task> SearchAsync(SearchQuery query); + } +} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharesService.cs b/src/slskd/Application/Shares/SharesService.cs new file mode 100644 index 00000000..1dac5089 --- /dev/null +++ b/src/slskd/Application/Shares/SharesService.cs @@ -0,0 +1,243 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Shares +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Soulseek; + + /// + /// Caches shared files. + /// + public class SharesService : ISharesService + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SharesService( + IStateMonitor stateMonitor, + IOptionsMonitor optionsMonitor) + { + StateMonitor = stateMonitor; + OptionsMonitor = optionsMonitor; + + State = new SharesState() { Ready = false, FillProgress = 0 }; + } + + public IEnumerable Shares => OptionsMonitor.CurrentValue.Directories.Shared; + public SharesState State { get; } + + private HashSet Directories { get; set; } + private Dictionary Files { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private SqliteConnection SQLite { get; set; } + private IStateMonitor StateMonitor { get; set; } + private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + + public IEnumerable Browse() + { + if (!State.Ready) + { + return Enumerable.Empty(); + } + + var directories = new ConcurrentDictionary(); + + // 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 Directories) + { + directories.TryAdd(directory, new Soulseek.Directory(directory)); + } + + var groups = Files + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Soulseek.Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new Soulseek.File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values; + } + + /// + /// Scans the configured and fills the cache. + /// + /// + public async Task FillAsync() + { + await Task.Yield(); + + var sw = new Stopwatch(); + sw.Start(); + + SyncRoot.EnterWriteLock(); + + try + { + StateMonitor.Set(state => state with { Ready = false, FillProgress = 0 }); + + CreateTable(); + + var directories = Shares + .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) + .ToHashSet(); + + var files = new Dictionary(); + var current = 0; + var total = directories.Count; + + foreach (var directory in directories.Take(100)) + { + // 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 Soulseek.File(1, f.Replace("/", @"\"), 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) + { + if (files.ContainsKey(file.Key)) + { + Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); + } + + files[file.Key] = file.Value; + } + + current++; + StateMonitor.Set(state => state with { Ready = false, FillProgress = current / (double)total, Directories = current, Files = files.Count }); + } + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Directories = directories; + Files = files; + + StateMonitor.Set(state => state with { Ready = true, FillProgress = 1, Directories = directories.Count, Files = files.Count }); + } + finally + { + SyncRoot.ExitWriteLock(); + } + + sw.Stop(); + } + + /// + /// Searches the cache for files matching the specified . + /// + /// + /// + public async Task> SearchAsync(SearchQuery query) + { + if (!State.Ready) + { + return Enumerable.Empty(); + } + + // sanitize the query string. there's probably more to it than this. + var text = query.Query + .Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " "); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; + + SyncRoot.EnterReadLock(); + + try + { + using var cmd = new SqliteCommand(sql, SQLite); + var results = new List(); + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results.Select(r => Files[r.Replace("''", "'")]); + } + catch (Exception ex) + { + // temporary error trap to refine substitution rules + Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); + return Enumerable.Empty(); + } + finally + { + SyncRoot.ExitReadLock(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=:memory:"); + SQLite.Open(); + + using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharesState.cs b/src/slskd/Application/Shares/SharesState.cs new file mode 100644 index 00000000..bea4b308 --- /dev/null +++ b/src/slskd/Application/Shares/SharesState.cs @@ -0,0 +1,30 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + /// + /// Share cache state. + /// + public record SharesState() + { + public bool Ready { get; init; } = true; + public double FillProgress { get; init; } = 1; + public int Directories { get; init; } + public int Files { get; init; } + } +} -- cgit v1.2.3 From d1db63a44827d928121be84479e5a22864107881 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 22:46:25 -0500 Subject: deprecate SharedFileCache --- src/slskd/Application/ISharedFileCache.cs | 37 ----- src/slskd/Application/SharedFileCache.cs | 231 ------------------------------ 2 files changed, 268 deletions(-) delete mode 100644 src/slskd/Application/ISharedFileCache.cs delete mode 100644 src/slskd/Application/SharedFileCache.cs (limited to 'src') diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs deleted file mode 100644 index 47b16997..00000000 --- a/src/slskd/Application/ISharedFileCache.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using Soulseek; - - public interface ISharedFileCache - { - event EventHandler<(int Directories, int Files)> Refreshed; - - IEnumerable Shares { get; } - DateTime? LastFill { get; } - long TTL { get; } - - void Fill(); - - IEnumerable Search(SearchQuery query); - IEnumerable Browse(); - } -} \ No newline at end of file diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs deleted file mode 100644 index 729fe167..00000000 --- a/src/slskd/Application/SharedFileCache.cs +++ /dev/null @@ -1,231 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Linq; - using System.Threading; - using Microsoft.Data.Sqlite; - using Soulseek; - - /// - /// Caches shared files. - /// - public class SharedFileCache : ISharedFileCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SharedFileCache(IEnumerable shares, long ttl) - { - Shares = shares; - TTL = ttl; - } - - public event EventHandler<(int Directories, int Files)> Refreshed; - - public IEnumerable Shares { get; } - public DateTime? LastFill { get; set; } - public long TTL { get; } - - private Dictionary Files { get; set; } - private SqliteConnection SQLite { get; set; } - private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); - - private HashSet Directories { get; set; } - - /// - /// Scans the configured and fills the cache. - /// - public void Fill() - { - var sw = new Stopwatch(); - sw.Start(); - - Console.WriteLine($"[SHARED FILE CACHE]: Refreshing..."); - - SyncRoot.EnterWriteLock(); - - try - { - CreateTable(); - var directories = new HashSet(); - var files = new Dictionary(); - - foreach (var share in Shares) - { - foreach (var directory in System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) - { - directories.Add(directory); - - // 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 Soulseek.File(1, f.Replace("/", @"\"), 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) - { - if (files.ContainsKey(file.Key)) - { - Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); - } - - files[file.Key] = file.Value; - } - } - } - - // potentially optimize with multi-valued insert - // https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Directories = directories; - Files = files; - Refreshed?.Invoke(this, (directories.Count, Files.Count)); - } - finally - { - SyncRoot.ExitWriteLock(); - } - - sw.Stop(); - - Console.WriteLine($"[SHARED FILE CACHE]: Refreshed in {sw.ElapsedMilliseconds}ms. Found {Files.Count} files."); - LastFill = DateTime.UtcNow; - } - - /// - /// Searches the cache for files matching the specified . - /// - /// - /// - public IEnumerable Search(SearchQuery query) - { - if (!LastFill.HasValue || LastFill.Value.AddMilliseconds(TTL) < DateTime.UtcNow) - { - Fill(); - } - - return QueryTable(query.Query); - } - - public IEnumerable Browse() - { - var directories = new ConcurrentDictionary(); - - // 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 Directories) - { - directories.TryAdd(directory, new Soulseek.Directory(directory)); - } - - var groups = Files - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Soulseek.Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new Soulseek.File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances - // containing their files. entries with no files will remain untouched. - foreach (var group in groups) - { - directories.AddOrUpdate(group.Name, group, (_, _) => group); - } - - return directories.Values; - } - - private void CreateTable() - { - SQLite = new SqliteConnection("Data Source=:memory:"); - SQLite.Open(); - - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); - cmd.ExecuteNonQuery(); - } - - private IEnumerable QueryTable(string text) - { - // sanitize the query string. there's probably more to it than this. - text = text - .Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " "); - - var query = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - - SyncRoot.EnterReadLock(); - - try - { - using var cmd = new SqliteCommand(query, SQLite); - var results = new List(); - var reader = cmd.ExecuteReader(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - - return results.Select(r => Files[r.Replace("''", "'")]); - } - catch (Exception ex) - { - // temporary error trap to refine substitution rules - Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); - return Enumerable.Empty(); - } - finally - { - SyncRoot.ExitReadLock(); - } - } - } -} \ No newline at end of file -- cgit v1.2.3 From a0176d5ae8c03624b5dbbf2d9689993db6878def Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 22:46:52 -0500 Subject: make StateMonitor generic --- src/slskd/Application/IStateMonitor.cs | 10 +++++----- src/slskd/Application/StateMonitor.cs | 26 +++++++++++++------------- 2 files changed, 18 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/IStateMonitor.cs b/src/slskd/Application/IStateMonitor.cs index e4c8fc26..e36d083d 100644 --- a/src/slskd/Application/IStateMonitor.cs +++ b/src/slskd/Application/IStateMonitor.cs @@ -22,25 +22,25 @@ namespace slskd /// /// Used for notifications when changes. /// - public interface IStateMonitor + public interface IStateMonitor { /// /// Gets the current application state. /// - State Current { get; } + T Current { get; } /// - /// Registers a listener to be called whenever changes. + /// Registers a listener to be called whenever changes. /// /// Registers a listener to be called whenver state changes. /// An which should be disposed to stop listening for changes. - IDisposable OnChange(Action<(State Previous, State Current)> listener); + IDisposable OnChange(Action<(T Previous, T Current)> listener); /// /// Replaces the current state with the value resolved by the . /// /// Given the current state, resolves a new state value. /// The updated state. - State Set(Func setter); + T Set(Func setter); } } diff --git a/src/slskd/Application/StateMonitor.cs b/src/slskd/Application/StateMonitor.cs index 5c9d90e3..b8328776 100644 --- a/src/slskd/Application/StateMonitor.cs +++ b/src/slskd/Application/StateMonitor.cs @@ -22,23 +22,23 @@ namespace slskd /// /// Used for notifications when changes. /// - public class StateMonitor : IStateMonitor + public class StateMonitor : IStateMonitor { - private event Action<(State, State)> Changed; + private event Action<(T, T)> Changed; /// /// Gets the current application state. /// - public State Current { get; private set; } = new State(); + public T Current { get; private set; } = (T)Activator.CreateInstance(typeof(T)); /// - /// Registers a listener to be called whenever changes. + /// Registers a listener to be called whenever changes. /// /// Registers a listener to be called whenver state changes. /// An which should be disposed to stop listening for changes. - public IDisposable OnChange(Action<(State Previous, State Current)> listener) + public IDisposable OnChange(Action<(T Previous, T Current)> listener) { - var disposable = new StateTrackerDisposable(this, listener); + var disposable = new StateTrackerDisposable(this, listener); Changed += disposable.OnChange; return disposable; } @@ -48,26 +48,26 @@ namespace slskd /// /// Given the current state, resolves a new state value. /// The updated state. - public State Set(Func setter) + public T Set(Func setter) { - var previous = Current.ToJson().ToObject(); + var previous = Current.ToJson().ToObject(); Current = setter(Current); Changed?.Invoke((previous, Current)); return Current; } - private class StateTrackerDisposable : IDisposable + private class StateTrackerDisposable : IDisposable { - public StateTrackerDisposable(StateMonitor stateMonitor, Action<(State Previous, State Current)> listener) + public StateTrackerDisposable(StateMonitor stateMonitor, Action<(T Previous, T Current)> listener) { StateMonitor = stateMonitor; Listener = listener; } private bool Disposed { get; set; } - private Action<(State Previous, State Current)> Listener { get; } - private StateMonitor StateMonitor { get; } + private Action<(T Previous, T Current)> Listener { get; } + private StateMonitor StateMonitor { get; } public void Dispose() { @@ -75,7 +75,7 @@ namespace slskd GC.SuppressFinalize(this); } - public void OnChange((State Previous, State Current) args) => Listener.Invoke(args); + public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); protected virtual void Dispose(bool disposing) { -- cgit v1.2.3 From d98787a54b5b6c02f696263fcf9e8ac190846f91 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 22:47:20 -0500 Subject: refactor State to make it new-able --- src/slskd/Application/State.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/State.cs index 75d46dec..83b801f3 100644 --- a/src/slskd/Application/State.cs +++ b/src/slskd/Application/State.cs @@ -20,5 +20,9 @@ namespace slskd /// /// Application state. /// - public record State(bool PendingReconnect = false, bool PendingRestart = false); + public record State() + { + public bool PendingReconnect { get; init; } + public bool PendingRestart { get; init; } + } } \ No newline at end of file -- cgit v1.2.3 From fe120319288649e2141f0c40e44e446111542fbd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 22:47:58 -0500 Subject: add Shares stuff to DI --- src/slskd/Startup.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index dcbf0a16..d30d717e 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -41,6 +41,7 @@ namespace slskd using slskd.Messaging; using slskd.Peer; using slskd.Search; + using slskd.Shares; using slskd.Transfer; using slskd.Validation; @@ -104,9 +105,11 @@ namespace slskd return true; }); - // add IStateMonitor to DI, to track application state in an observable way. similar to IOptionsMonitor, - // but state is managed by the application itself. Usage is roughly the same. - services.AddSingleton(); + // add IStateMonitor instances to DI, to track application state in an observable way. + // imilar to IOptionsMonitor, but state is managed by the application itself. + // Usage is roughly the same. + services.AddSingleton, StateMonitor>(); + services.AddSingleton, StateMonitor>(); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); @@ -205,9 +208,8 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton(_ => - new SharedFileCache(OptionsAtStartup.Directories.Shared, 3600000)); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 0a0d9f70cfeeb9c362403bb950d31398a7246801 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Aug 2021 22:58:28 -0500 Subject: logging --- src/slskd/Application/Service.cs | 75 +++++++++++++++++++-------- src/slskd/Application/Shares/SharesService.cs | 2 +- 2 files changed, 54 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 3874b494..1ee8ea20 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -35,6 +35,7 @@ namespace slskd using slskd.Messaging; using slskd.Peer; using slskd.Search; + using slskd.Shares; using slskd.Transfer; using Soulseek; using Soulseek.Diagnostics; @@ -48,12 +49,13 @@ namespace slskd public Service( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, - IStateMonitor stateMonitor, + IStateMonitor stateMonitor, + IStateMonitor sharesStateMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, - ISharedFileCache sharedFileCache, + ISharesService sharesService, IPushbulletService pushbulletService) { OptionsAtStartup = optionsAtStartup; @@ -66,11 +68,14 @@ namespace slskd StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); + SharesStateMonitor = sharesStateMonitor; + SharesStateMonitor.OnChange(state => SharesStateMonitor_OnChange(state)); + TransferTracker = transferTracker; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; RoomTracker = roomTracker; - SharedFileCache = sharedFileCache; + SharesService = sharesService; Pushbullet = pushbulletService; ProxyOptions proxyOptions = default; @@ -136,9 +141,6 @@ namespace slskd Client.LoggedIn += Client_LoggedIn; SoulseekClient = Client; - - SharedFileCache.Fill(); - SharedFileCache.Refreshed += SharedFileCache_Refreshed; } public static ISoulseekClient SoulseekClient { get; private set; } @@ -152,14 +154,19 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private Options PreviousOptions { get; set; } private IRoomTracker RoomTracker { get; set; } - private IStateMonitor StateMonitor { get; set; } - private ISharedFileCache SharedFileCache { get; set; } + private IStateMonitor StateMonitor { get; set; } + private IStateMonitor SharesStateMonitor { get; set; } + private ISharesService SharesService { get; set; } private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); + private (int Directories, int Files) SharedCounts { get; set; } = (0, 0); + private DateTime SharesRefreshStarted { get; set; } public async Task StartAsync(CancellationToken cancellationToken) { + _ = SharesService.FillAsync(); + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); @@ -310,12 +317,34 @@ namespace slskd Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); } - private void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e) + private void SharesStateMonitor_OnChange((SharesState Previous, SharesState Current) state) { - if (sharedCounts != e) + if (state.Previous.Ready && !state.Current.Ready) { - _ = SoulseekClient.SetSharedCountsAsync(e.Directories, e.Files); - sharedCounts = e; + Logger.Information("Refreshing shares"); + SharesRefreshStarted = DateTime.UtcNow; + } + + var lastProgress = Math.Round(state.Previous.FillProgress * 100); + var currentProgress = Math.Round(state.Current.FillProgress * 100); + + if (lastProgress != currentProgress) + { + Logger.Debug("Processed {Percent}%", currentProgress); + } + + if (!state.Previous.Ready && state.Current.Ready) + { + SharedCounts = (state.Current.Directories, state.Current.Files); + + Logger.Information("Shares refreshed successfully. Found {Directories} directories and {Files} files in {Duration}ms", SharedCounts.Directories, SharedCounts.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + + SharesRefreshStarted = default; + + if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) + { + _ = SoulseekClient.SetSharedCountsAsync(SharedCounts.Directories, SharedCounts.Files); + } } } @@ -327,7 +356,7 @@ namespace slskd /// A Task resolving an IEnumerable of Soulseek.Directory. private Task BrowseResponseResolver(string username, IPEndPoint endpoint) { - var directories = SharedFileCache.Browse(); + var directories = SharesService.Browse(); System.IO.File.WriteAllText(@"C:\Users\JP.WHATNET\Desktop\Soulseek\files.json", directories.ToJson()); @@ -363,6 +392,10 @@ namespace slskd private void Client_LoggedIn(object sender, EventArgs e) { Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); + + // send whatever counts we have currently. we'll probably connect before the cache is primed, + // so these will be zero initially, but we'll update them when the cache is filled. + _ = SoulseekClient.SetSharedCountsAsync(SharedCounts.Directories, SharedCounts.Files); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) @@ -581,41 +614,39 @@ namespace slskd /// The search token. /// The search query. /// A Task resolving a SearchResponse, or null. - private Task SearchResponseResolver(string username, int token, SearchQuery query) + private async Task SearchResponseResolver(string username, int token, SearchQuery query) { - var defaultResponse = Task.FromResult(null); - // some bots continually query for very common strings. blacklist known names here. var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; if (blacklist.Contains(username)) { - return defaultResponse; + return null; } // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. if (query.Query.Length < 3) { - return defaultResponse; + return null; } - var results = SharedFileCache.Search(query); + var results = await SharesService.SearchAsync(query); if (results.Any()) { Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - return Task.FromResult(new Soulseek.SearchResponse( + return new Soulseek.SearchResponse( SoulseekClient.Username, token, freeUploadSlots: 1, uploadSpeed: 0, queueLength: 0, - fileList: results)); + fileList: results); } // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no // response will be sent to the requestor. - return Task.FromResult(null); + return null; } /// diff --git a/src/slskd/Application/Shares/SharesService.cs b/src/slskd/Application/Shares/SharesService.cs index 1dac5089..f5fbb88d 100644 --- a/src/slskd/Application/Shares/SharesService.cs +++ b/src/slskd/Application/Shares/SharesService.cs @@ -129,7 +129,7 @@ namespace slskd.Shares var current = 0; var total = directories.Count; - foreach (var directory in directories.Take(100)) + foreach (var directory in directories) { // 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 -- cgit v1.2.3 From f84e4067f872ae568574d389b71794608c9c8498 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Aug 2021 07:27:10 -0500 Subject: synchronize state updates --- src/slskd/Application/StateMonitor.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/StateMonitor.cs b/src/slskd/Application/StateMonitor.cs index b8328776..b7d13f6a 100644 --- a/src/slskd/Application/StateMonitor.cs +++ b/src/slskd/Application/StateMonitor.cs @@ -31,6 +31,8 @@ namespace slskd /// public T Current { get; private set; } = (T)Activator.CreateInstance(typeof(T)); + private object Lock { get; } = new object(); + /// /// Registers a listener to be called whenever changes. /// @@ -50,11 +52,14 @@ namespace slskd /// The updated state. public T Set(Func setter) { - var previous = Current.ToJson().ToObject(); - Current = setter(Current); + lock (Lock) + { + var previous = Current.ToJson().ToObject(); + Current = setter(Current); - Changed?.Invoke((previous, Current)); - return Current; + Changed?.Invoke((previous, Current)); + return Current; + } } private class StateTrackerDisposable : IDisposable -- cgit v1.2.3 From ad8b3dabef05aa9c7edba5fbb22e071baa3e95e1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Aug 2021 08:13:31 -0500 Subject: move StateMonitor to common --- src/slskd/Application/IStateMonitor.cs | 46 --------------- src/slskd/Application/StateMonitor.cs | 99 -------------------------------- src/slskd/Common/IStateMonitor.cs | 47 +++++++++++++++ src/slskd/Common/StateMonitor.cs | 102 +++++++++++++++++++++++++++++++++ 4 files changed, 149 insertions(+), 145 deletions(-) delete mode 100644 src/slskd/Application/IStateMonitor.cs delete mode 100644 src/slskd/Application/StateMonitor.cs create mode 100644 src/slskd/Common/IStateMonitor.cs create mode 100644 src/slskd/Common/StateMonitor.cs (limited to 'src') diff --git a/src/slskd/Application/IStateMonitor.cs b/src/slskd/Application/IStateMonitor.cs deleted file mode 100644 index e36d083d..00000000 --- a/src/slskd/Application/IStateMonitor.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - - /// - /// Used for notifications when changes. - /// - public interface IStateMonitor - { - /// - /// Gets the current application state. - /// - T Current { get; } - - /// - /// Registers a listener to be called whenever changes. - /// - /// Registers a listener to be called whenver state changes. - /// An which should be disposed to stop listening for changes. - IDisposable OnChange(Action<(T Previous, T Current)> listener); - - /// - /// Replaces the current state with the value resolved by the . - /// - /// Given the current state, resolves a new state value. - /// The updated state. - T Set(Func setter); - } -} diff --git a/src/slskd/Application/StateMonitor.cs b/src/slskd/Application/StateMonitor.cs deleted file mode 100644 index b7d13f6a..00000000 --- a/src/slskd/Application/StateMonitor.cs +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - - /// - /// Used for notifications when changes. - /// - public class StateMonitor : IStateMonitor - { - private event Action<(T, T)> Changed; - - /// - /// Gets the current application state. - /// - public T Current { get; private set; } = (T)Activator.CreateInstance(typeof(T)); - - private object Lock { get; } = new object(); - - /// - /// Registers a listener to be called whenever changes. - /// - /// Registers a listener to be called whenver state changes. - /// An which should be disposed to stop listening for changes. - public IDisposable OnChange(Action<(T Previous, T Current)> listener) - { - var disposable = new StateTrackerDisposable(this, listener); - Changed += disposable.OnChange; - return disposable; - } - - /// - /// Replaces the current state with the value resolved by the . - /// - /// Given the current state, resolves a new state value. - /// The updated state. - public T Set(Func setter) - { - lock (Lock) - { - var previous = Current.ToJson().ToObject(); - Current = setter(Current); - - Changed?.Invoke((previous, Current)); - return Current; - } - } - - private class StateTrackerDisposable : IDisposable - { - public StateTrackerDisposable(StateMonitor stateMonitor, Action<(T Previous, T Current)> listener) - { - StateMonitor = stateMonitor; - Listener = listener; - } - - private bool Disposed { get; set; } - private Action<(T Previous, T Current)> Listener { get; } - private StateMonitor StateMonitor { get; } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); - - protected virtual void Dispose(bool disposing) - { - if (!Disposed) - { - if (disposing) - { - StateMonitor.Changed -= OnChange; - } - - Disposed = true; - } - } - } - } -} diff --git a/src/slskd/Common/IStateMonitor.cs b/src/slskd/Common/IStateMonitor.cs new file mode 100644 index 00000000..b2286aac --- /dev/null +++ b/src/slskd/Common/IStateMonitor.cs @@ -0,0 +1,47 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + + /// + /// Used for notifications when changes. + /// + /// The type of the tracked state object. + public interface IStateMonitor + { + /// + /// Gets the current application state. + /// + T CurrentValue { get; } + + /// + /// Registers a listener to be called whenever the tracked state changes. + /// + /// Registers a listener to be called whenver state changes. + /// An which should be disposed to stop listening for changes. + IDisposable OnChange(Action<(T Previous, T Current)> listener); + + /// + /// Replaces the current state with the value resolved by the . + /// + /// Given the current state, resolves a new state value. + /// The updated state. + T SetValue(Func setter); + } +} diff --git a/src/slskd/Common/StateMonitor.cs b/src/slskd/Common/StateMonitor.cs new file mode 100644 index 00000000..22704398 --- /dev/null +++ b/src/slskd/Common/StateMonitor.cs @@ -0,0 +1,102 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + + /// + /// Used for notifications when changes. + /// + /// The type of the tracked state object. + public class StateMonitor : IStateMonitor + { + private event Action<(T, T)> Changed; + + /// + /// Gets the current application state. + /// + public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); + + private object Lock { get; } = new object(); + + /// + /// Registers a listener to be called whenever the stracked state changes. + /// + /// Registers a listener to be called whenver state changes. + /// An which should be disposed to stop listening for changes. + public IDisposable OnChange(Action<(T Previous, T Current)> listener) + { + var disposable = new StateTrackerDisposable(this, listener); + Changed += disposable.OnChange; + return disposable; + } + + /// + /// Replaces the current state with the value resolved by the . + /// + /// Given the current state, resolves a new state value. + /// The updated state. + public T SetValue(Func setter) + { + lock (Lock) + { + var previous = CurrentValue.ToJson().ToObject(); + CurrentValue = setter(CurrentValue); + + Changed?.Invoke((previous, CurrentValue)); + return CurrentValue; + } + } + +#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type + private class StateTrackerDisposable : IDisposable +#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type + { + public StateTrackerDisposable(StateMonitor stateMonitor, Action<(T Previous, T Current)> listener) + { + StateMonitor = stateMonitor; + Listener = listener; + } + + private bool Disposed { get; set; } + private Action<(T Previous, T Current)> Listener { get; } + private StateMonitor StateMonitor { get; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + StateMonitor.Changed -= OnChange; + } + + Disposed = true; + } + } + } + } +} -- cgit v1.2.3 From a2ce1945f76f4a6f54483436cae7d3539a91be38 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Aug 2021 08:13:48 -0500 Subject: rename stuff --- src/slskd/Application/Service.cs | 31 ++- src/slskd/Application/ServiceState.cs | 28 +++ src/slskd/Application/Shares/ISharedFileCache.cs | 48 ++++ src/slskd/Application/Shares/ISharesService.cs | 32 --- src/slskd/Application/Shares/SharedFileCache.cs | 242 ++++++++++++++++++++ .../Application/Shares/SharedFileCacheState.cs | 52 +++++ src/slskd/Application/Shares/SharesService.cs | 243 --------------------- src/slskd/Application/Shares/SharesState.cs | 30 --- src/slskd/Application/State.cs | 28 --- src/slskd/Startup.cs | 7 +- 10 files changed, 388 insertions(+), 353 deletions(-) create mode 100644 src/slskd/Application/ServiceState.cs create mode 100644 src/slskd/Application/Shares/ISharedFileCache.cs delete mode 100644 src/slskd/Application/Shares/ISharesService.cs create mode 100644 src/slskd/Application/Shares/SharedFileCache.cs create mode 100644 src/slskd/Application/Shares/SharedFileCacheState.cs delete mode 100644 src/slskd/Application/Shares/SharesService.cs delete mode 100644 src/slskd/Application/Shares/SharesState.cs delete mode 100644 src/slskd/Application/State.cs (limited to 'src') diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 1ee8ea20..3d019dd3 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -19,7 +19,6 @@ namespace slskd { using System; using System.Collections.Concurrent; - using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; @@ -44,18 +43,16 @@ namespace slskd { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes - private (int Directories, int Files) sharedCounts = (0, 0); - public Service( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, - IStateMonitor stateMonitor, - IStateMonitor sharesStateMonitor, + IStateMonitor stateMonitor, + IStateMonitor sharedFileCacheStateMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, - ISharesService sharesService, + ISharedFileCache sharesService, IPushbulletService pushbulletService) { OptionsAtStartup = optionsAtStartup; @@ -68,8 +65,8 @@ namespace slskd StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); - SharesStateMonitor = sharesStateMonitor; - SharesStateMonitor.OnChange(state => SharesStateMonitor_OnChange(state)); + SharedFileCacheStateMonitor = sharedFileCacheStateMonitor; + SharedFileCacheStateMonitor.OnChange(state => SharedFileCacheStateMonitor_OnChange(state)); TransferTracker = transferTracker; BrowseTracker = browseTracker; @@ -154,9 +151,9 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private Options PreviousOptions { get; set; } private IRoomTracker RoomTracker { get; set; } - private IStateMonitor StateMonitor { get; set; } - private IStateMonitor SharesStateMonitor { get; set; } - private ISharesService SharesService { get; set; } + private IStateMonitor StateMonitor { get; set; } + private IStateMonitor SharedFileCacheStateMonitor { get; set; } + private ISharedFileCache SharesService { get; set; } private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); @@ -289,13 +286,13 @@ namespace slskd // OR if the call to reconfigure the client requires a reconnect if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect) { - StateMonitor.Set(state => state with { PendingReconnect = true }); + StateMonitor.SetValue(state => state with { PendingReconnect = true }); Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect."); } if (pendingRestart) { - StateMonitor.Set(state => state with { PendingRestart = true }); + StateMonitor.SetValue(state => state with { PendingRestart = true }); Logger.Information("One or more updated options requires an application restart to take effect."); } @@ -312,12 +309,12 @@ namespace slskd } } - private void StateMonitor_OnChange((State Previous, State Current) state) + private void StateMonitor_OnChange((ServiceState Previous, ServiceState Current) state) { Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); } - private void SharesStateMonitor_OnChange((SharesState Previous, SharesState Current) state) + private void SharedFileCacheStateMonitor_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) { if (state.Previous.Ready && !state.Current.Ready) { @@ -400,9 +397,9 @@ namespace slskd private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { - if (StateMonitor.Current.PendingReconnect) + if (StateMonitor.CurrentValue.PendingReconnect) { - StateMonitor.Set(state => state with { PendingReconnect = false }); + StateMonitor.SetValue(state => state with { PendingReconnect = false }); } if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) diff --git a/src/slskd/Application/ServiceState.cs b/src/slskd/Application/ServiceState.cs new file mode 100644 index 00000000..67671947 --- /dev/null +++ b/src/slskd/Application/ServiceState.cs @@ -0,0 +1,28 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Application service state. + /// + public record ServiceState() + { + public bool PendingReconnect { get; init; } + public bool PendingRestart { get; init; } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Shares/ISharedFileCache.cs b/src/slskd/Application/Shares/ISharedFileCache.cs new file mode 100644 index 00000000..22667a7a --- /dev/null +++ b/src/slskd/Application/Shares/ISharedFileCache.cs @@ -0,0 +1,48 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface ISharedFileCache + { + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Drops and re-creates the cache from disk. + /// + /// The operation context. + Task FillAsync(); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } +} \ No newline at end of file diff --git a/src/slskd/Application/Shares/ISharesService.cs b/src/slskd/Application/Shares/ISharesService.cs deleted file mode 100644 index 78fe3e12..00000000 --- a/src/slskd/Application/Shares/ISharesService.cs +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System.Collections.Generic; - using System.Threading.Tasks; - using Soulseek; - - public interface ISharesService - { - IEnumerable Browse(); - - Task FillAsync(); - - Task> SearchAsync(SearchQuery query); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs new file mode 100644 index 00000000..efc43a17 --- /dev/null +++ b/src/slskd/Application/Shares/SharedFileCache.cs @@ -0,0 +1,242 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Shares +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Soulseek; + + /// + /// Shared file cache. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SharedFileCache( + IStateMonitor stateMonitor, + IOptionsMonitor optionsMonitor) + { + StateMonitor = stateMonitor; + OptionsMonitor = optionsMonitor; + } + + private HashSet Directories { get; set; } + private Dictionary Files { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private SqliteConnection SQLite { get; set; } + private IStateMonitor StateMonitor { get; set; } + private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + if (!StateMonitor.CurrentValue.Ready) + { + return Enumerable.Empty(); + } + + var directories = new ConcurrentDictionary(); + + // 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 Directories) + { + directories.TryAdd(directory, new Soulseek.Directory(directory)); + } + + var groups = Files + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Soulseek.Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new Soulseek.File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values; + } + + /// + /// Scans the configured and fills the cache. + /// + /// + public async Task FillAsync() + { + await Task.Yield(); + + var sw = new Stopwatch(); + sw.Start(); + + SyncRoot.EnterWriteLock(); + + try + { + StateMonitor.SetValue(state => state with { Ready = false, FillProgress = 0 }); + + CreateTable(); + + var directories = OptionsMonitor.CurrentValue.Directories.Shared + .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) + .ToHashSet(); + + var files = new Dictionary(); + var current = 0; + var total = directories.Count; + + foreach (var directory in directories) + { + // 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 Soulseek.File(1, f.Replace("/", @"\"), 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) + { + if (files.ContainsKey(file.Key)) + { + Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); + } + + files[file.Key] = file.Value; + } + + current++; + StateMonitor.SetValue(state => state with { Ready = false, FillProgress = current / (double)total, Directories = current, Files = files.Count }); + } + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Directories = directories; + Files = files; + + StateMonitor.SetValue(state => state with { Ready = true, FillProgress = 1, Directories = directories.Count, Files = files.Count }); + } + finally + { + SyncRoot.ExitWriteLock(); + } + + sw.Stop(); + } + + /// + /// Searches the cache for files matching the specified . + /// + /// + /// + public async Task> SearchAsync(SearchQuery query) + { + if (!StateMonitor.CurrentValue.Ready) + { + return Enumerable.Empty(); + } + + // sanitize the query string. there's probably more to it than this. + var text = query.Query + .Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " "); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; + + SyncRoot.EnterReadLock(); + + try + { + using var cmd = new SqliteCommand(sql, SQLite); + var results = new List(); + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results.Select(r => Files[r.Replace("''", "'")]); + } + catch (Exception ex) + { + // temporary error trap to refine substitution rules + Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); + return Enumerable.Empty(); + } + finally + { + SyncRoot.ExitReadLock(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=:memory:"); + SQLite.Open(); + + using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCacheState.cs b/src/slskd/Application/Shares/SharedFileCacheState.cs new file mode 100644 index 00000000..4bda9d7b --- /dev/null +++ b/src/slskd/Application/Shares/SharedFileCacheState.cs @@ -0,0 +1,52 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + using System; + + /// + /// Share cache state. + /// + public record SharedFileCacheState() + { + /// + /// Gets a value indicating whether the cache is ready to be used. + /// + public bool Ready { get; init; } = true; + + /// + /// Gets the current fill progress. + /// + public double FillProgress { get; init; } = 1; + + /// + /// Gets the number of cached directories. + /// + public int Directories { get; init; } + + /// + /// Gets the number of cached files. + /// + public int Files { get; init; } + + /// + /// Gets the UTC timestamp of the last fill. + /// + public DateTime? LastFilled { get; init; } + } +} diff --git a/src/slskd/Application/Shares/SharesService.cs b/src/slskd/Application/Shares/SharesService.cs deleted file mode 100644 index f5fbb88d..00000000 --- a/src/slskd/Application/Shares/SharesService.cs +++ /dev/null @@ -1,243 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Shares -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Soulseek; - - /// - /// Caches shared files. - /// - public class SharesService : ISharesService - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SharesService( - IStateMonitor stateMonitor, - IOptionsMonitor optionsMonitor) - { - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; - - State = new SharesState() { Ready = false, FillProgress = 0 }; - } - - public IEnumerable Shares => OptionsMonitor.CurrentValue.Directories.Shared; - public SharesState State { get; } - - private HashSet Directories { get; set; } - private Dictionary Files { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private SqliteConnection SQLite { get; set; } - private IStateMonitor StateMonitor { get; set; } - private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); - - public IEnumerable Browse() - { - if (!State.Ready) - { - return Enumerable.Empty(); - } - - var directories = new ConcurrentDictionary(); - - // 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 Directories) - { - directories.TryAdd(directory, new Soulseek.Directory(directory)); - } - - var groups = Files - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Soulseek.Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new Soulseek.File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. - // entries with no files will remain untouched. - foreach (var group in groups) - { - directories.AddOrUpdate(group.Name, group, (_, _) => group); - } - - return directories.Values; - } - - /// - /// Scans the configured and fills the cache. - /// - /// - public async Task FillAsync() - { - await Task.Yield(); - - var sw = new Stopwatch(); - sw.Start(); - - SyncRoot.EnterWriteLock(); - - try - { - StateMonitor.Set(state => state with { Ready = false, FillProgress = 0 }); - - CreateTable(); - - var directories = Shares - .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) - .ToHashSet(); - - var files = new Dictionary(); - var current = 0; - var total = directories.Count; - - foreach (var directory in directories) - { - // 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 Soulseek.File(1, f.Replace("/", @"\"), 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) - { - if (files.ContainsKey(file.Key)) - { - Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); - } - - files[file.Key] = file.Value; - } - - current++; - StateMonitor.Set(state => state with { Ready = false, FillProgress = current / (double)total, Directories = current, Files = files.Count }); - } - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Directories = directories; - Files = files; - - StateMonitor.Set(state => state with { Ready = true, FillProgress = 1, Directories = directories.Count, Files = files.Count }); - } - finally - { - SyncRoot.ExitWriteLock(); - } - - sw.Stop(); - } - - /// - /// Searches the cache for files matching the specified . - /// - /// - /// - public async Task> SearchAsync(SearchQuery query) - { - if (!State.Ready) - { - return Enumerable.Empty(); - } - - // sanitize the query string. there's probably more to it than this. - var text = query.Query - .Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " "); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - - SyncRoot.EnterReadLock(); - - try - { - using var cmd = new SqliteCommand(sql, SQLite); - var results = new List(); - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - - return results.Select(r => Files[r.Replace("''", "'")]); - } - catch (Exception ex) - { - // temporary error trap to refine substitution rules - Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); - return Enumerable.Empty(); - } - finally - { - SyncRoot.ExitReadLock(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection("Data Source=:memory:"); - SQLite.Open(); - - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); - cmd.ExecuteNonQuery(); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharesState.cs b/src/slskd/Application/Shares/SharesState.cs deleted file mode 100644 index bea4b308..00000000 --- a/src/slskd/Application/Shares/SharesState.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - /// - /// Share cache state. - /// - public record SharesState() - { - public bool Ready { get; init; } = true; - public double FillProgress { get; init; } = 1; - public int Directories { get; init; } - public int Files { get; init; } - } -} diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/State.cs deleted file mode 100644 index 83b801f3..00000000 --- a/src/slskd/Application/State.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - /// - /// Application state. - /// - public record State() - { - public bool PendingReconnect { get; init; } - public bool PendingRestart { get; init; } - } -} \ No newline at end of file diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index d30d717e..c15e9f8a 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -108,8 +108,8 @@ namespace slskd // add IStateMonitor instances to DI, to track application state in an observable way. // imilar to IOptionsMonitor, but state is managed by the application itself. // Usage is roughly the same. - services.AddSingleton, StateMonitor>(); - services.AddSingleton, StateMonitor>(); + services.AddSingleton, StateMonitor>(); + services.AddSingleton, StateMonitor>(); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); @@ -209,7 +209,8 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 30aa9546a91d8ce0d3db672f8297dad4ad64556b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Aug 2021 09:18:04 -0500 Subject: don't fill if already filling --- src/slskd/Application/Shares/ISharedFileCache.cs | 2 +- src/slskd/Application/Shares/SharedFileCache.cs | 44 ++++++++++++++---------- 2 files changed, 27 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Shares/ISharedFileCache.cs b/src/slskd/Application/Shares/ISharedFileCache.cs index 22667a7a..163f4eea 100644 --- a/src/slskd/Application/Shares/ISharedFileCache.cs +++ b/src/slskd/Application/Shares/ISharedFileCache.cs @@ -33,7 +33,7 @@ namespace slskd.Shares IEnumerable Browse(); /// - /// Drops and re-creates the cache from disk. + /// Scans the configured shares and fills the cache. /// /// The operation context. Task FillAsync(); diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs index efc43a17..a06e86f6 100644 --- a/src/slskd/Application/Shares/SharedFileCache.cs +++ b/src/slskd/Application/Shares/SharedFileCache.cs @@ -15,6 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using System.IO; using Microsoft.Extensions.Options; namespace slskd.Shares @@ -23,11 +24,11 @@ namespace slskd.Shares using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; - using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Sqlite; + using Serilog; using Soulseek; /// @@ -49,24 +50,25 @@ namespace slskd.Shares } private HashSet Directories { get; set; } - private Dictionary Files { get; set; } + private Dictionary Files { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } private IStateMonitor StateMonitor { get; set; } private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Returns the contents of the cache. /// /// The contents of the cache. - public IEnumerable Browse() + public IEnumerable Browse() { if (!StateMonitor.CurrentValue.Ready) { - return Enumerable.Empty(); + return Enumerable.Empty(); } - var directories = new ConcurrentDictionary(); + var directories = new ConcurrentDictionary(); // 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 @@ -75,15 +77,15 @@ namespace slskd.Shares // files. if not they'll be left as is. foreach (var directory in Directories) { - directories.TryAdd(directory, new Soulseek.Directory(directory)); + directories.TryAdd(directory, new Directory(directory)); } var groups = Files .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Soulseek.Directory(g.Key, g.Select(g => + .Select(g => new Directory(g.Key, g.Select(g => { var f = g.Value; - return new Soulseek.File( + return new File( f.Code, Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. f.Size, @@ -102,11 +104,17 @@ namespace slskd.Shares } /// - /// Scans the configured and fills the cache. + /// Scans the configured shares and fills the cache. /// - /// + /// The operation context. public async Task FillAsync() { + if (!StateMonitor.CurrentValue.Ready) + { + Log.Warning("Cache fill rejected; cache is already filling."); + return; + } + await Task.Yield(); var sw = new Stopwatch(); @@ -124,7 +132,7 @@ namespace slskd.Shares .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) .ToHashSet(); - var files = new Dictionary(); + var files = new Dictionary(); var current = 0; var total = directories.Count; @@ -133,7 +141,7 @@ namespace slskd.Shares // 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 Soulseek.File(1, f.Replace("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f))) + .Select(f => new File(1, f.Replace("/", @"\"), 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 @@ -172,15 +180,15 @@ namespace slskd.Shares } /// - /// Searches the cache for files matching the specified . + /// Searches the cache for the specified and returns the matching files. /// - /// - /// - public async Task> SearchAsync(SearchQuery query) + /// The query for which to search. + /// The matching files. + public async Task> SearchAsync(SearchQuery query) { if (!StateMonitor.CurrentValue.Ready) { - return Enumerable.Empty(); + return Enumerable.Empty(); } // sanitize the query string. there's probably more to it than this. @@ -211,7 +219,7 @@ namespace slskd.Shares { // temporary error trap to refine substitution rules Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); - return Enumerable.Empty(); + return Enumerable.Empty(); } finally { -- cgit v1.2.3 From 71815c51cb305ba97a7732be52509eb64fcd4aa3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Aug 2021 09:39:39 -0500 Subject: detect changes to shared config and set PendingRescan flag if changed --- src/slskd/Application/Service.cs | 7 +++++++ src/slskd/Application/ServiceState.cs | 1 + 2 files changed, 8 insertions(+) (limited to 'src') diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 3d019dd3..8b88e8ff 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -226,6 +226,13 @@ namespace slskd pendingReconnect |= requiresReconnect; } + if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() + || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) + { + StateMonitor.SetValue(state => state with { PendingReconnect = true }); + Logger.Information("Shared directory 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/ServiceState.cs b/src/slskd/Application/ServiceState.cs index 67671947..a1339d40 100644 --- a/src/slskd/Application/ServiceState.cs +++ b/src/slskd/Application/ServiceState.cs @@ -24,5 +24,6 @@ namespace slskd { public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } + public bool PendingRescan { get; init; } } } \ No newline at end of file -- cgit v1.2.3 From 43f3bf2d128dc7e44043a8ef2199d75cdb0d3d4b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 Aug 2021 09:25:10 -0500 Subject: add plumbing to rescan shares via API --- .../Exceptions/ShareScanInProgressException.cs | 72 ++++++++++++++++++++ .../API/Controllers/ApplicationController.cs | 18 +++-- .../API/Controllers/ConfigurationController.cs | 76 ++++++++++++++++++++++ .../Application/Management/API/DTO/ServerState.cs | 33 ++++++++++ .../Application/Management/Domain/ServerState.cs | 33 ---------- .../Application/Management/IManagementService.cs | 12 ++++ .../Application/Management/ManagementService.cs | 38 +++++++---- src/slskd/Application/Shares/SharedFileCache.cs | 18 ++--- 8 files changed, 243 insertions(+), 57 deletions(-) create mode 100644 src/slskd/Application/Exceptions/ShareScanInProgressException.cs create mode 100644 src/slskd/Application/Management/API/Controllers/ConfigurationController.cs create mode 100644 src/slskd/Application/Management/API/DTO/ServerState.cs delete mode 100644 src/slskd/Application/Management/Domain/ServerState.cs (limited to 'src') diff --git a/src/slskd/Application/Exceptions/ShareScanInProgressException.cs b/src/slskd/Application/Exceptions/ShareScanInProgressException.cs new file mode 100644 index 00000000..2e548930 --- /dev/null +++ b/src/slskd/Application/Exceptions/ShareScanInProgressException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareScanInProgressException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ShareScanInProgressException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ShareScanInProgressException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public ShareScanInProgressException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected ShareScanInProgressException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs index ddac832a..43029aa5 100644 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs @@ -22,7 +22,6 @@ namespace slskd.Management.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; - using Soulseek; /// /// Application. @@ -34,15 +33,26 @@ namespace slskd.Management.API [Consumes("application/json")] public class ApplicationController : ControllerBase { - public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime) + public ApplicationController(IManagementService managementService, IHostApplicationLifetime lifetime) { - Client = client; + Management = managementService; Lifetime = lifetime; } - private ISoulseekClient Client { get; } + private IManagementService Management { get; } private IHostApplicationLifetime Lifetime { get; } + /// + /// Gets the current state of the application. + /// + /// + [HttpGet] + [Authorize] + public IActionResult State() + { + return Ok(Management.GetServiceState()); + } + /// /// Stops the application. /// diff --git a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs new file mode 100644 index 00000000..26ce6c52 --- /dev/null +++ b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs @@ -0,0 +1,76 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Application.Management.API +{ + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using slskd.Management; + using slskd.Shares; + + /// + /// Configuration. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConfigurationController : ControllerBase + { + public ConfigurationController( + IOptionsSnapshot optionsShapshot, + IStateMonitor sharedFileCacheMonitor, + IManagementService managementService) + { + OptionsShapshot = optionsShapshot; + SharedFileCacheMonitor = sharedFileCacheMonitor; + ManagementService = managementService; + } + + private IManagementService ManagementService { get; } + private IOptionsSnapshot OptionsShapshot { get; } + private IStateMonitor SharedFileCacheMonitor { get; } + + [HttpGet] + [Authorize] + public IActionResult GetOptions() + { + // todo: sanitize this to remove passwords + return Ok(OptionsShapshot.Value); + } + + [HttpPut] + [Authorize] + public async Task RescanSharesAsync() + { + try + { + await ManagementService.RescanSharesAsync(); + } + catch (ShareScanInProgressException ex) + { + return Conflict(ex.Message); + } + + return Ok(); + } + } +} diff --git a/src/slskd/Application/Management/API/DTO/ServerState.cs b/src/slskd/Application/Management/API/DTO/ServerState.cs new file mode 100644 index 00000000..80c1e856 --- /dev/null +++ b/src/slskd/Application/Management/API/DTO/ServerState.cs @@ -0,0 +1,33 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Management +{ + using System.Net; + using Soulseek; + + public class ServerState + { + public string Address { get; set; } + public IPEndPoint IPEndPoint { get; set; } + public SoulseekClientStates State { get; set; } + public string Username { get; set; } + public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); + public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); + public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); + } +} diff --git a/src/slskd/Application/Management/Domain/ServerState.cs b/src/slskd/Application/Management/Domain/ServerState.cs deleted file mode 100644 index 80c1e856..00000000 --- a/src/slskd/Application/Management/Domain/ServerState.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Management -{ - using System.Net; - using Soulseek; - - public class ServerState - { - public string Address { get; set; } - public IPEndPoint IPEndPoint { get; set; } - public SoulseekClientStates State { get; set; } - public string Username { get; set; } - public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); - public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); - public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); - } -} diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index b3e13477..6c5f3784 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -43,5 +43,17 @@ namespace slskd.Management /// /// The current server state. ServerState GetServerState(); + + /// + /// Gets the current state of the slskd service. + /// + /// + ServiceState GetServiceState(); + + /// + /// Re-scans shared directories. + /// + /// The operation context. + Task RescanSharesAsync(); } } \ No newline at end of file diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 66ed2b97..2f79f496 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -1,18 +1,13 @@ // // Copyright (c) slskd Team. All rights reserved. // -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. +// This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public +// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. // -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. +// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty +// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. // -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. +// You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/. // using Microsoft.Extensions.Options; @@ -21,6 +16,7 @@ namespace slskd.Management { using System; using System.Threading.Tasks; + using slskd.Shares; using Soulseek; /// @@ -32,18 +28,26 @@ namespace slskd.Management /// Initializes a new instance of the class. /// /// The options monitor used to derive application options. + /// The state monitor for application service state. /// The Soulseek client. + /// The shared file cache. public ManagementService( IOptionsMonitor optionsMonitor, - ISoulseekClient soulseekClient) + IStateMonitor serviceStateMonitor, + ISoulseekClient soulseekClient, + ISharedFileCache sharedFileCache) { OptionsMonitor = optionsMonitor; + ServiceStateMonitor = serviceStateMonitor; Client = soulseekClient; + SharedFileCache = sharedFileCache; } private ISoulseekClient Client { get; } private Options Options => OptionsMonitor.CurrentValue; private IOptionsMonitor OptionsMonitor { get; } + private IStateMonitor ServiceStateMonitor { get; } + private ISharedFileCache SharedFileCache { get; } /// /// Connects the Soulseek client to the server using the configured username and password. @@ -72,5 +76,17 @@ namespace slskd.Management State = Client.State, Username = Client.Username, }; + + /// + /// Gets the current state of the slskd service. + /// + /// + public ServiceState GetServiceState() => ServiceStateMonitor.CurrentValue; + + /// + /// Re-scans shared directories. + /// + /// The operation context. + public Task RescanSharesAsync() => SharedFileCache.FillAsync(); } } \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs index a06e86f6..439e5eb8 100644 --- a/src/slskd/Application/Shares/SharedFileCache.cs +++ b/src/slskd/Application/Shares/SharedFileCache.cs @@ -109,21 +109,21 @@ namespace slskd.Shares /// The operation context. public async Task FillAsync() { - if (!StateMonitor.CurrentValue.Ready) + if (SyncRoot.TryEnterWriteLock(0)) { - Log.Warning("Cache fill rejected; cache is already filling."); - return; + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); } await Task.Yield(); - var sw = new Stopwatch(); - sw.Start(); - SyncRoot.EnterWriteLock(); try { + var sw = new Stopwatch(); + sw.Start(); + StateMonitor.SetValue(state => state with { Ready = false, FillProgress = 0 }); CreateTable(); @@ -150,7 +150,7 @@ namespace slskd.Shares { if (files.ContainsKey(file.Key)) { - Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); + 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; @@ -170,13 +170,13 @@ namespace slskd.Shares Files = files; StateMonitor.SetValue(state => state with { Ready = true, FillProgress = 1, Directories = directories.Count, Files = files.Count }); + + Log.Information($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); } finally { SyncRoot.ExitWriteLock(); } - - sw.Stop(); } /// -- cgit v1.2.3 From 0aaf9ff434e07097b9c7844a9c00dc3517479203 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 08:52:39 -0500 Subject: add NoConnect option --- src/slskd/Application/Service.cs | 25 +++++++++++++------------ src/slskd/Options.cs | 6 ++++++ 2 files changed, 19 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 8b88e8ff..ae17da33 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -52,7 +52,7 @@ namespace slskd IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, - ISharedFileCache sharesService, + ISharedFileCache sharedFileCache, IPushbulletService pushbulletService) { OptionsAtStartup = optionsAtStartup; @@ -72,7 +72,7 @@ namespace slskd BrowseTracker = browseTracker; ConversationTracker = conversationTracker; RoomTracker = roomTracker; - SharesService = sharesService; + SharedFileCache = sharedFileCache; Pushbullet = pushbulletService; ProxyOptions proxyOptions = default; @@ -153,7 +153,7 @@ namespace slskd private IRoomTracker RoomTracker { get; set; } private IStateMonitor StateMonitor { get; set; } private IStateMonitor SharedFileCacheStateMonitor { get; set; } - private ISharedFileCache SharesService { get; set; } + private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); @@ -162,7 +162,7 @@ namespace slskd public async Task StartAsync(CancellationToken cancellationToken) { - _ = SharesService.FillAsync(); + _ = SharedFileCache.FillAsync(); if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { @@ -172,7 +172,11 @@ namespace slskd Logger.Information("Client started"); Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); - if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) + if (OptionsAtStartup.NoConnect) + { + Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); + } + else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) { Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } @@ -360,10 +364,7 @@ namespace slskd /// A Task resolving an IEnumerable of Soulseek.Directory. private Task BrowseResponseResolver(string username, IPEndPoint endpoint) { - var directories = SharesService.Browse(); - - System.IO.File.WriteAllText(@"C:\Users\JP.WHATNET\Desktop\Soulseek\files.json", directories.ToJson()); - + var directories = SharedFileCache.Browse(); return Task.FromResult(new BrowseResponse(directories)); } @@ -618,7 +619,7 @@ namespace slskd /// The search token. /// The search query. /// A Task resolving a SearchResponse, or null. - private async Task SearchResponseResolver(string username, int token, SearchQuery query) + private async Task SearchResponseResolver(string username, int token, SearchQuery query) { // some bots continually query for very common strings. blacklist known names here. var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; @@ -633,13 +634,13 @@ namespace slskd return null; } - var results = await SharesService.SearchAsync(query); + var results = await SharedFileCache.SearchAsync(query); if (results.Any()) { Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - return new Soulseek.SearchResponse( + return new SearchResponse( SoulseekClient.Username, token, freeUploadSlots: 1, diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index ff791f39..793ab1d8 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -150,6 +150,12 @@ namespace slskd [RequiresRestart] public bool NoStart { get; private set; } = false; + [Argument(default, "no-connect")] + [EnvironmentVariable("NO_CONNECT")] + [Description("do not connect to the Soulseek network on startup")] + [RequiresRestart] + public bool NoConnect { get; private set; } = false; + /// /// Gets the unique name for this instance. /// -- cgit v1.2.3 From 3cb5eedb1834859dfee1257bb3d71737cc375912 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 10:29:16 -0500 Subject: add NoShareScan option --- src/slskd/Options.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 793ab1d8..93895a2e 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -150,12 +150,24 @@ namespace slskd [RequiresRestart] public bool NoStart { get; private set; } = false; + /// + /// Gets a value indicating whether the application should connect to the Soulseek network on startup. + /// [Argument(default, "no-connect")] [EnvironmentVariable("NO_CONNECT")] [Description("do not connect to the Soulseek network on startup")] [RequiresRestart] public bool NoConnect { get; private set; } = false; + /// + /// Gets a value indicating whether the application should scan shared directories on startup. + /// + [Argument(default, "no-share-scan")] + [EnvironmentVariable("NO_SHARE_SCAN")] + [Description("do not scan shares on startup")] + [RequiresRestart] + public bool NoShareScan { get; private set; } = true; + /// /// Gets the unique name for this instance. /// @@ -245,7 +257,6 @@ namespace slskd [Argument('s', "shared")] [EnvironmentVariable("SHARED_DIR")] [Description("path to shared files")] - [RequiresRestart] public string[] Shared { get; private set; } = new[] { Program.DefaultSharedDirectory }; } -- cgit v1.2.3 From c17197f30ba6339431e743bf3244b58ef7361115 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 10:30:09 -0500 Subject: return 409 if share scan is in progress --- .../Management/API/Controllers/ConfigurationController.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs index 26ce6c52..c44cf2f2 100644 --- a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs @@ -19,7 +19,6 @@ using Microsoft.Extensions.Options; namespace slskd.Application.Management.API { - using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using slskd.Management; @@ -50,6 +49,7 @@ namespace slskd.Application.Management.API private IStateMonitor SharedFileCacheMonitor { get; } [HttpGet] + [Route("")] [Authorize] public IActionResult GetOptions() { @@ -58,18 +58,17 @@ namespace slskd.Application.Management.API } [HttpPut] + [Route("shares")] [Authorize] - public async Task RescanSharesAsync() + public IActionResult RescanSharesAsync() { - try + if (SharedFileCacheMonitor.CurrentValue.Filling) { - await ManagementService.RescanSharesAsync(); - } - catch (ShareScanInProgressException ex) - { - return Conflict(ex.Message); + return Conflict("A share scan is already in progress."); } + _ = ManagementService.RescanSharesAsync(); + return Ok(); } } -- cgit v1.2.3 From a09df6485dea51732fbe9966822bbf91bc4ebda0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 10:30:39 -0500 Subject: Ready > !Filling, add Faulted --- src/slskd/Application/Shares/SharedFileCacheState.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Shares/SharedFileCacheState.cs b/src/slskd/Application/Shares/SharedFileCacheState.cs index 4bda9d7b..37ac9f86 100644 --- a/src/slskd/Application/Shares/SharedFileCacheState.cs +++ b/src/slskd/Application/Shares/SharedFileCacheState.cs @@ -25,14 +25,19 @@ namespace slskd.Shares public record SharedFileCacheState() { /// - /// Gets a value indicating whether the cache is ready to be used. + /// Gets a value indicating whether the cache is being filled. /// - public bool Ready { get; init; } = true; + public bool Filling { get; init; } = false; + + /// + /// Gets a value indicating whether the cache is faulted. + /// + public bool Faulted { get; init; } = false; /// /// Gets the current fill progress. /// - public double FillProgress { get; init; } = 1; + public double FillProgress { get; init; } /// /// Gets the number of cached directories. @@ -49,4 +54,4 @@ namespace slskd.Shares /// public DateTime? LastFilled { get; init; } } -} +} \ No newline at end of file -- cgit v1.2.3 From 134333ac34716d539c4bd9ba438c0c829c23c810 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 10:31:09 -0500 Subject: use a semaphore instead of a lock. add state changes and logging --- src/slskd/Application/Shares/SharedFileCache.cs | 74 ++++++++++++++++--------- 1 file changed, 48 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs index 439e5eb8..e9bddb09 100644 --- a/src/slskd/Application/Shares/SharedFileCache.cs +++ b/src/slskd/Application/Shares/SharedFileCache.cs @@ -54,7 +54,7 @@ namespace slskd.Shares private IOptionsMonitor OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } private IStateMonitor StateMonitor { get; set; } - private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private ILogger Log { get; } = Serilog.Log.ForContext(); /// @@ -63,11 +63,6 @@ namespace slskd.Shares /// The contents of the cache. public IEnumerable Browse() { - if (!StateMonitor.CurrentValue.Ready) - { - return Enumerable.Empty(); - } - var directories = new ConcurrentDictionary(); // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if @@ -109,7 +104,7 @@ namespace slskd.Shares /// The operation context. public async Task FillAsync() { - if (SyncRoot.TryEnterWriteLock(0)) + if (SyncRoot.CurrentCount == 0) { Log.Warning("Shared file scan rejected; scan is already in progress."); throw new ShareScanInProgressException("Shared files are already being scanned."); @@ -117,24 +112,38 @@ namespace slskd.Shares await Task.Yield(); - SyncRoot.EnterWriteLock(); + await SyncRoot.WaitAsync(); try { + StateMonitor.SetValue(state => state with { Filling = true, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + var sw = new Stopwatch(); sw.Start(); + var swSnapshot = 0L; - StateMonitor.SetValue(state => state with { Ready = false, FillProgress = 0 }); - + // this destroys the old table and creates a new one. empty the other cached fields to reflect this + // todo: use an A/B style table naming schema so that the cache remains available while it is filling CreateTable(); + Directories = new HashSet(); + Files = new Dictionary(); + StateMonitor.SetValue(state => state with { Directories = 0, Files = 0 }); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; var directories = OptionsMonitor.CurrentValue.Directories.Shared .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) .ToHashSet(); + StateMonitor.SetValue(state => state with { Directories = directories.Count }); + + Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting recursive scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); + swSnapshot = sw.ElapsedMilliseconds; + var files = new Dictionary(); var current = 0; - var total = directories.Count; foreach (var directory in directories) { @@ -157,25 +166,49 @@ namespace slskd.Shares } current++; - StateMonitor.SetValue(state => state with { Ready = false, FillProgress = current / (double)total, Directories = current, Files = files.Count }); + StateMonitor.SetValue(state => state with { FillProgress = current / (double)directories.Count, Files = files.Count }); } + Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite foreach (var file in files) { InsertFilename(file.Key); } + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + Directories = directories; Files = files; - StateMonitor.SetValue(state => state with { Ready = true, FillProgress = 1, Directories = directories.Count, Files = files.Count }); + StateMonitor.SetValue(state => state with + { + Filling = false, + Faulted = false, + FillProgress = 1, + Directories = Directories.Count, + Files = Files.Count, + }); + + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + StateMonitor.SetValue(state => state with + { + Filling = false, + Faulted = true, + FillProgress = 0, + }); - Log.Information($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; } finally { - SyncRoot.ExitWriteLock(); + SyncRoot.Release(); } } @@ -186,11 +219,6 @@ namespace slskd.Shares /// The matching files. public async Task> SearchAsync(SearchQuery query) { - if (!StateMonitor.CurrentValue.Ready) - { - return Enumerable.Empty(); - } - // sanitize the query string. there's probably more to it than this. var text = query.Query .Replace("/", " ") @@ -200,8 +228,6 @@ namespace slskd.Shares var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - SyncRoot.EnterReadLock(); - try { using var cmd = new SqliteCommand(sql, SQLite); @@ -221,10 +247,6 @@ namespace slskd.Shares Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); return Enumerable.Empty(); } - finally - { - SyncRoot.ExitReadLock(); - } } private void CreateTable() -- cgit v1.2.3 From f8d84e60b9476c6cda24824a871f92861ec7f1b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 10:31:24 -0500 Subject: add shared counts to service state --- src/slskd/Application/ServiceState.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/ServiceState.cs b/src/slskd/Application/ServiceState.cs index a1339d40..3f3eda05 100644 --- a/src/slskd/Application/ServiceState.cs +++ b/src/slskd/Application/ServiceState.cs @@ -24,6 +24,7 @@ namespace slskd { public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } - public bool PendingRescan { get; init; } + public bool PendingShareRescan { get; init; } + public (int Directories, int Files) SharedCounts { get; init; } = (0, 0); } } \ No newline at end of file -- cgit v1.2.3 From 86aeebf6a900e44461aa0094b8bf3cf1d81adcbe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 Aug 2021 20:48:01 -0500 Subject: refine handling of share scanning --- src/slskd/Application/Service.cs | 58 +++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index ae17da33..469d4227 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -148,21 +148,29 @@ namespace slskd private ILogger Logger { get; set; } = Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; set; } + private Options Options => OptionsMonitor.CurrentValue; private OptionsAtStartup OptionsAtStartup { get; set; } private Options PreviousOptions { get; set; } private IRoomTracker RoomTracker { get; set; } private IStateMonitor StateMonitor { get; set; } + private ServiceState State => StateMonitor.CurrentValue; private IStateMonitor SharedFileCacheStateMonitor { get; set; } private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); - private (int Directories, int Files) SharedCounts { get; set; } = (0, 0); private DateTime SharesRefreshStarted { get; set; } public async Task StartAsync(CancellationToken cancellationToken) { - _ = SharedFileCache.FillAsync(); + if (OptionsAtStartup.NoShareScan) + { + Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); + } + else + { + _ = SharedFileCache.FillAsync(); + } if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { @@ -233,7 +241,7 @@ namespace slskd if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) { - StateMonitor.SetValue(state => state with { PendingReconnect = true }); + StateMonitor.SetValue(state => state with { PendingShareRescan = true }); Logger.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect."); } @@ -327,31 +335,39 @@ namespace slskd private void SharedFileCacheStateMonitor_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) { - if (state.Previous.Ready && !state.Current.Ready) + if (!state.Previous.Filling && state.Current.Filling) { - Logger.Information("Refreshing shares"); SharesRefreshStarted = DateTime.UtcNow; + Logger.Information("Scanning shares"); } var lastProgress = Math.Round(state.Previous.FillProgress * 100); var currentProgress = Math.Round(state.Current.FillProgress * 100); - if (lastProgress != currentProgress) + if (lastProgress != currentProgress && currentProgress % 10 == 0) { - Logger.Debug("Processed {Percent}%", currentProgress); + Logger.Debug("Share scan progress {Percent}%", currentProgress); } - if (!state.Previous.Ready && state.Current.Ready) + if (state.Previous.Filling && !state.Current.Filling) { - SharedCounts = (state.Current.Directories, state.Current.Files); + StateMonitor.SetValue(s => s with { SharedCounts = (state.Current.Directories, state.Current.Files) }); - Logger.Information("Shares refreshed successfully. Found {Directories} directories and {Files} files in {Duration}ms", SharedCounts.Directories, SharedCounts.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + if (state.Current.Faulted) + { + Logger.Error("Failed to scan shares."); + } + else + { + StateMonitor.SetValue(s => s with { PendingShareRescan = false }); + Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", State.SharedCounts.Directories, State.SharedCounts.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); - SharesRefreshStarted = default; + SharesRefreshStarted = default; - if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) - { - _ = SoulseekClient.SetSharedCountsAsync(SharedCounts.Directories, SharedCounts.Files); + if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) + { + _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); + } } } } @@ -400,12 +416,12 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, // so these will be zero initially, but we'll update them when the cache is filled. - _ = SoulseekClient.SetSharedCountsAsync(SharedCounts.Directories, SharedCounts.Files); + _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { - if (StateMonitor.CurrentValue.PendingReconnect) + if (State.PendingReconnect) { StateMonitor.SetValue(state => state with { PendingReconnect = false }); } @@ -430,7 +446,7 @@ namespace slskd { Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - if (string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Username) || string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Password)) + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) { Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); return; @@ -454,7 +470,7 @@ namespace slskd { // reconnect with the latest configuration values we have for username and password, instead of the options that were // captured at startup. if a user has updated these values prior to the disconnect, the changes will take effect now. - await Client.ConnectAsync(OptionsMonitor.CurrentValue.Soulseek.Username, OptionsMonitor.CurrentValue.Soulseek.Password); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); break; } catch (Exception ex) @@ -470,7 +486,7 @@ namespace slskd { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && !args.Replayed) + if (Options.Integration.Pushbullet.Enabled && !args.Replayed) { Console.WriteLine("Pushing..."); _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); @@ -481,7 +497,7 @@ namespace slskd { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); } @@ -506,7 +522,7 @@ namespace slskd var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); - if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); } -- cgit v1.2.3 From a56bfb47abe33d259ba9d12d492123ab4baa3739 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 Aug 2021 07:53:24 -0500 Subject: rename more stuff --- src/slskd/Application/Application.cs | 687 ++++++++++++++++++++ src/slskd/Application/ApplicationState.cs | 30 + src/slskd/Application/ISharedFileCache.cs | 53 ++ .../API/Controllers/ApplicationController.cs | 2 +- .../API/Controllers/ConfigurationController.cs | 8 +- .../Management/API/Controllers/ServerController.cs | 6 +- .../Application/Management/IManagementService.cs | 27 +- .../Application/Management/ManagementService.cs | 61 +- src/slskd/Application/Service.cs | 691 --------------------- src/slskd/Application/ServiceState.cs | 30 - src/slskd/Application/SharedFileCache.cs | 273 ++++++++ src/slskd/Application/SharedFileCacheState.cs | 52 ++ src/slskd/Application/Shares/ISharedFileCache.cs | 48 -- src/slskd/Application/Shares/SharedFileCache.cs | 272 -------- .../Application/Shares/SharedFileCacheState.cs | 57 -- src/slskd/Common/IStateMonitor.cs | 2 +- src/slskd/Common/StateMonitor.cs | 2 +- src/slskd/Startup.cs | 12 +- 18 files changed, 1157 insertions(+), 1156 deletions(-) create mode 100644 src/slskd/Application/Application.cs create mode 100644 src/slskd/Application/ApplicationState.cs create mode 100644 src/slskd/Application/ISharedFileCache.cs delete mode 100644 src/slskd/Application/Service.cs delete mode 100644 src/slskd/Application/ServiceState.cs create mode 100644 src/slskd/Application/SharedFileCache.cs create mode 100644 src/slskd/Application/SharedFileCacheState.cs delete mode 100644 src/slskd/Application/Shares/ISharedFileCache.cs delete mode 100644 src/slskd/Application/Shares/SharedFileCache.cs delete mode 100644 src/slskd/Application/Shares/SharedFileCacheState.cs (limited to 'src') diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs new file mode 100644 index 00000000..fc359b43 --- /dev/null +++ b/src/slskd/Application/Application.cs @@ -0,0 +1,687 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Collections.Concurrent; + using System.IO; + using System.Linq; + using System.Net; + using System.Reflection; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Options; + using Serilog; + using Serilog.Events; + using slskd.Configuration; + using slskd.Integrations.Pushbullet; + using slskd.Messaging; + using slskd.Peer; + using slskd.Search; + using slskd.Transfer; + using Soulseek; + using Soulseek.Diagnostics; + + public class Application : IHostedService + { + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + + public Application( + OptionsAtStartup optionsAtStartup, + IOptionsMonitor optionsMonitor, + IStateMonitor stateMonitor, + ITransferTracker transferTracker, + IBrowseTracker browseTracker, + IConversationTracker conversationTracker, + IRoomTracker roomTracker, + ISharedFileCache sharedFileCache, + IPushbulletService pushbulletService) + { + OptionsAtStartup = optionsAtStartup; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + + PreviousOptions = OptionsMonitor.CurrentValue; + + StateMonitor = stateMonitor; + StateMonitor.OnChange(state => StateMonitor_OnChange(state)); + + SharedFileCache = sharedFileCache; + SharedFileCache.State.OnChange(state => SharedFileCacheState_OnChange(state)); + + TransferTracker = transferTracker; + BrowseTracker = browseTracker; + ConversationTracker = conversationTracker; + RoomTracker = roomTracker; + Pushbullet = pushbulletService; + + ProxyOptions proxyOptions = default; + + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) + { + proxyOptions = new ProxyOptions( + address: OptionsAtStartup.Soulseek.Connection.Proxy.Address, + port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value, + username: OptionsAtStartup.Soulseek.Connection.Proxy.Username, + password: OptionsAtStartup.Soulseek.Connection.Proxy.Password); + } + + var connectionOptions = new ConnectionOptions( + readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read, + writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write, + connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, + proxyOptions: proxyOptions); + + var clientOptions = new SoulseekClientOptions( + listenPort: OptionsAtStartup.Soulseek.ListenPort, + enableListener: true, + userEndPointCache: new UserEndPointCache(), + distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel, + autoAcknowledgePrivateMessages: false, + acceptPrivateRoomInvitations: true, + serverConnectionOptions: connectionOptions, + peerConnectionOptions: connectionOptions, + transferConnectionOptions: connectionOptions, + distributedConnectionOptions: connectionOptions, + userInfoResponseResolver: UserInfoResponseResolver, + browseResponseResolver: BrowseResponseResolver, + directoryContentsResponseResolver: DirectoryContentsResponseResolver, + enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + searchResponseCache: new SearchResponseCache(), + searchResponseResolver: SearchResponseResolver); + + Client = new SoulseekClient(options: clientOptions); + + Client.DiagnosticGenerated += Client_DiagnosticGenerated; + + Client.TransferStateChanged += Client_TransferStateChanged; + Client.TransferProgressUpdated += Client_TransferProgressUpdated; + + Client.BrowseProgressUpdated += Client_BrowseProgressUpdated; + Client.UserStatusChanged += Client_UserStatusChanged; + Client.PrivateMessageReceived += Client_PrivateMessageRecieved; + + Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); + Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); + Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); + Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); + + Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; + Client.RoomMessageReceived += Client_RoomMessageReceived; + Client.RoomJoined += Client_RoomJoined; + Client.RoomLeft += Client_RoomLeft; + Client.Disconnected += Client_Disconnected; + Client.Connected += Client_Connected; + Client.LoggedIn += Client_LoggedIn; + + SoulseekClient = Client; + } + + public static ISoulseekClient SoulseekClient { get; private set; } + + private IBrowseTracker BrowseTracker { get; set; } + private ISoulseekClient Client { get; set; } + private IConversationTracker ConversationTracker { get; set; } + private ILogger Logger { get; set; } = Log.ForContext(); + private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); + private IOptionsMonitor OptionsMonitor { get; set; } + private Options Options => OptionsMonitor.CurrentValue; + private OptionsAtStartup OptionsAtStartup { get; set; } + private Options PreviousOptions { get; set; } + private IRoomTracker RoomTracker { get; set; } + private IStateMonitor StateMonitor { get; set; } + private ApplicationState State => StateMonitor.CurrentValue; + private ISharedFileCache SharedFileCache { get; set; } + private ITransferTracker TransferTracker { get; set; } + private IPushbulletService Pushbullet { get; } + private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); + private DateTime SharesRefreshStarted { get; set; } + + public async Task StartAsync(CancellationToken cancellationToken) + { + if (OptionsAtStartup.NoShareScan) + { + Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); + } + else + { + _ = SharedFileCache.FillAsync(); + } + + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) + { + Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); + } + + Logger.Information("Client started"); + Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); + + if (OptionsAtStartup.NoConnect) + { + Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); + } + else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) + { + Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); + } + else + { + await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); + } + } + + public Task StopAsync(CancellationToken cancellationToken) + { + Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); + Client.Dispose(); + Logger.Information("Client stopped"); + return Task.CompletedTask; + } + + private async Task OptionsMonitor_OnChange(Options newOptions) + { + // this code is known to fire more than once per update. i'm not sure + // whether these might be executed concurrently. lock to be safe, because + // we need to accurately track the last value of Options for diffing purposes. + // threading shenanigans here could lead to missed updates. + OptionsSyncRoot.EnterWriteLock(); + + try + { + var pendingRestart = false; + var pendingReconnect = false; + var soulseekRequiresReconnect = false; + + var diff = PreviousOptions.DiffWith(newOptions); + + // don't react to duplicate/no-change events + // https://github.com/slskd/slskd/issues/126 + if (!diff.Any()) + { + return; + } + + foreach (var (property, fqn, left, right) in diff) + { + static bool HasAttribute(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + + var requiresRestart = HasAttribute(property); + var requiresReconnect = HasAttribute(property); + + Logger.Debug($"{fqn} changed from '{left.ToJson() ?? ""}' to '{right.ToJson() ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); + + pendingRestart |= requiresRestart; + pendingReconnect |= requiresReconnect; + } + + if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() + || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) + { + StateMonitor.SetValue(state => state with { PendingShareRescan = true }); + Logger.Information("Shared directory 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); + + if (slskDiff.Any()) + { + var old = PreviousOptions.Soulseek; + var update = newOptions.Soulseek; + + Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); + + // determine whether any Connection options changed. if so, replace the whole object. + // Soulseek.NET doesn't offer a way to patch parts of connection options. the updates only affect + // new connections, so a partial patch doesn't make a lot of sense anyway. + var connectionDiff = old.Connection.DiffWith(update.Connection); + + ConnectionOptions connectionPatch = null; + + if (connectionDiff.Any()) + { + var connection = update.Connection; + + ProxyOptions proxyPatch = null; + + if (connection.Proxy.Enabled) + { + proxyPatch = new ProxyOptions( + connection.Proxy.Address, + connection.Proxy.Port.Value, + connection.Proxy.Username, + connection.Proxy.Password); + } + + connectionPatch = new ConnectionOptions( + connection.Buffer.Read, + connection.Buffer.Write, + connection.Timeout.Connect, + connection.Timeout.Inactivity, + proxyOptions: proxyPatch); + } + + var patch = new SoulseekClientOptionsPatch( + listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort, + enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, + distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, + serverConnectionOptions: connectionPatch, + peerConnectionOptions: connectionPatch, + transferConnectionOptions: connectionPatch, + incomingConnectionOptions: connectionPatch, + distributedConnectionOptions: connectionPatch); + + Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); + + soulseekRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); + } + + // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed, + // OR if the call to reconfigure the client requires a reconnect + if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect) + { + StateMonitor.SetValue(state => state with { PendingReconnect = true }); + Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect."); + } + + if (pendingRestart) + { + StateMonitor.SetValue(state => state with { PendingRestart = true }); + Logger.Information("One or more updated options requires an application restart to take effect."); + } + + Logger.Information("Options updated successfully."); + } + catch (Exception ex) + { + Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); + } + finally + { + PreviousOptions = OptionsMonitor.CurrentValue; + OptionsSyncRoot.ExitWriteLock(); + } + } + + private void StateMonitor_OnChange((ApplicationState Previous, ApplicationState Current) state) + { + Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); + } + + private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) + { + if (!state.Previous.Filling && state.Current.Filling) + { + SharesRefreshStarted = DateTime.UtcNow; + Logger.Information("Scanning shares"); + } + + var lastProgress = Math.Round(state.Previous.FillProgress * 100); + var currentProgress = Math.Round(state.Current.FillProgress * 100); + + if (lastProgress != currentProgress && currentProgress % 10 == 0) + { + Logger.Debug("Share scan progress {Percent}%", currentProgress); + } + + if (state.Previous.Filling && !state.Current.Filling) + { + StateMonitor.SetValue(s => s with { SharedCounts = (state.Current.Directories, state.Current.Files) }); + + if (state.Current.Faulted) + { + Logger.Error("Failed to scan shares."); + } + else + { + StateMonitor.SetValue(s => s with { PendingShareRescan = false }); + Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", State.SharedCounts.Directories, State.SharedCounts.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + + SharesRefreshStarted = default; + + if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) + { + _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); + } + } + } + } + + /// + /// Creates and returns an instances of in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving an IEnumerable of Soulseek.Directory. + private Task BrowseResponseResolver(string username, IPEndPoint endpoint) + { + var directories = SharedFileCache.Browse(); + return Task.FromResult(new BrowseResponse(directories)); + } + + private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) + { + BrowseTracker.AddOrUpdate(args.Username, args); + } + + private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) + { + static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch + { + DiagnosticLevel.Debug => LogEventLevel.Debug, + DiagnosticLevel.Info => LogEventLevel.Information, + DiagnosticLevel.Warning => LogEventLevel.Warning, + DiagnosticLevel.None => default, + _ => default, + }; + + var logger = Loggers.GetOrAdd(sender.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", sender.GetType().FullName)); + + logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); + } + + private void Client_Connected(object sender, EventArgs e) + { + Logger.Information("Connected to the Soulseek server"); + } + + private void Client_LoggedIn(object sender, EventArgs e) + { + Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); + + // send whatever counts we have currently. we'll probably connect before the cache is primed, + // so these will be zero initially, but we'll update them when the cache is filled. + _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); + } + + private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + { + if (State.PendingReconnect) + { + StateMonitor.SetValue(state => state with { PendingReconnect = false }); + } + + if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) + { + Logger.Information("Disconnected from the Soulseek server: the client is shutting down"); + } + else if (args.Exception is IntentionalDisconnectException) + { + Logger.Information("Disconnected from the Soulseek server: disconnected by the user"); + } + else if (args.Exception is LoginRejectedException) + { + Logger.Error("Disconnected from the Soulseek server: invalid username or password"); + } + else if (args.Exception is KickedFromServerException) + { + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); + } + else + { + Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); + + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + { + Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); + return; + } + + var attempts = 1; + + while (true) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Logger.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + await Task.Delay(delay + jitter); + + Logger.Information($"Attempting to reconnect (#{attempts})...", attempts); + + try + { + // reconnect with the latest configuration values we have for username and password, instead of the options that were + // captured at startup. if a user has updated these values prior to the disconnect, the changes will take effect now. + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + break; + } + catch (Exception ex) + { + attempts++; + Logger.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } + } + + private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) + { + ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); + + if (Options.Integration.Pushbullet.Enabled && !args.Replayed) + { + Console.WriteLine("Pushing..."); + _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); + } + } + + private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) + { + Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); + + if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + { + _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); + } + } + + private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) + { + // this will fire when we join a room; track that through the join operation. + if (args.Username != Client.Username) + { + RoomTracker.TryAddUser(args.RoomName, args.UserData); + } + } + + private void Client_RoomLeft(object sender, RoomLeftEventArgs args) + { + RoomTracker.TryRemoveUser(args.RoomName, args.Username); + } + + private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) + { + var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); + RoomTracker.AddOrUpdateMessage(args.RoomName, message); + + if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + { + _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); + } + } + + private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) + { + // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] + // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] + // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); + } + + private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) + { + var xfer = args.Transfer; + var direction = xfer.Direction.ToString().ToUpper(); + var user = xfer.Username; + var file = Path.GetFileName(xfer.Filename); + var oldState = args.PreviousState; + var state = xfer.State; + + var completed = xfer.State.HasFlag(TransferStates.Completed); + + Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); + + if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded)) + { + _ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed); + } + } + + private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) + { + Console.WriteLine($"[USER] {args.Username}: {args.Status}"); + } + + /// + /// Creates and returns a in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The unique token for the request, supplied by the requesting user. + /// The requested directory. + /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. + private Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + { + var result = new Soulseek.Directory(directory.Replace("/", @"\"), System.IO.Directory.GetFiles(directory) + .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))); + + return Task.FromResult(result); + } + + /// + /// Invoked upon a remote request to download a file. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// The filename of the requested file. + /// (for example purposes) the ITransferTracker used to track progress. + /// A Task representing the asynchronous operation. + /// + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// + /// + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for + /// security reasons. + /// + private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) + { + _ = endpoint; + var localFilename = filename.ToLocalOSPath(); + var fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + throw new DownloadEnqueueException($"File not shared."); + } + + if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) + { + // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse + Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); + return Task.CompletedTask; + } + + // create a new cancellation token source so that we can cancel the upload from the UI. + var cts = new CancellationTokenSource(); + var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); + + // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and + // uploads would be handled separately. + Task.Run(async () => + { + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + await Client.UploadAsync(username, filename, fileInfo.Length, stream, options: topts, cancellationToken: cts.Token); + }).ContinueWith(t => + { + Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget + + // return a completed task so that the invoking code can respond to the remote client. + return Task.CompletedTask; + } + + /// + /// Creates and returns a in response to the given . + /// + /// The username of the requesting user. + /// The search token. + /// The search query. + /// A Task resolving a SearchResponse, or null. + private async Task SearchResponseResolver(string username, int token, SearchQuery query) + { + // some bots continually query for very common strings. blacklist known names here. + var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; + if (blacklist.Contains(username)) + { + return null; + } + + // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. + if (query.Query.Length < 3) + { + return null; + } + + var results = await SharedFileCache.SearchAsync(query); + + if (results.Any()) + { + Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); + + return new SearchResponse( + SoulseekClient.Username, + token, + freeUploadSlots: 1, + uploadSpeed: 0, + queueLength: 0, + fileList: results); + } + + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. + return null; + } + + /// + /// Creates and returns a object in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving the UserInfo instance. + private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) + { + var info = new UserInfo( + description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", + picture: Array.Empty(), + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); + + return Task.FromResult(info); + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/ApplicationState.cs b/src/slskd/Application/ApplicationState.cs new file mode 100644 index 00000000..2e3f627f --- /dev/null +++ b/src/slskd/Application/ApplicationState.cs @@ -0,0 +1,30 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Application service state. + /// + public record ApplicationState() + { + public bool PendingReconnect { get; init; } + public bool PendingRestart { get; init; } + public bool PendingShareRescan { get; init; } + public (int Directories, int Files) SharedCounts { get; init; } = (0, 0); + } +} \ No newline at end of file diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs new file mode 100644 index 00000000..291d78e4 --- /dev/null +++ b/src/slskd/Application/ISharedFileCache.cs @@ -0,0 +1,53 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface ISharedFileCache + { + /// + /// Gets the cache state. + /// + IStateMonitor State { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + Task FillAsync(); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } +} \ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs index 43029aa5..dd115786 100644 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs @@ -50,7 +50,7 @@ namespace slskd.Management.API [Authorize] public IActionResult State() { - return Ok(Management.GetServiceState()); + return Ok(Management.ApplicationState); } /// diff --git a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs index c44cf2f2..f2b90718 100644 --- a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs @@ -17,12 +17,11 @@ using Microsoft.Extensions.Options; -namespace slskd.Application.Management.API +namespace slskd.Management.API { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using slskd.Management; - using slskd.Shares; /// /// Configuration. @@ -36,17 +35,14 @@ namespace slskd.Application.Management.API { public ConfigurationController( IOptionsSnapshot optionsShapshot, - IStateMonitor sharedFileCacheMonitor, IManagementService managementService) { OptionsShapshot = optionsShapshot; - SharedFileCacheMonitor = sharedFileCacheMonitor; ManagementService = managementService; } private IManagementService ManagementService { get; } private IOptionsSnapshot OptionsShapshot { get; } - private IStateMonitor SharedFileCacheMonitor { get; } [HttpGet] [Route("")] @@ -62,7 +58,7 @@ namespace slskd.Application.Management.API [Authorize] public IActionResult RescanSharesAsync() { - if (SharedFileCacheMonitor.CurrentValue.Filling) + if (ManagementService.SharedFileCacheState.Filling) { return Conflict("A share scan is already in progress."); } diff --git a/src/slskd/Application/Management/API/Controllers/ServerController.cs b/src/slskd/Application/Management/API/Controllers/ServerController.cs index 6468063c..fc47f475 100644 --- a/src/slskd/Application/Management/API/Controllers/ServerController.cs +++ b/src/slskd/Application/Management/API/Controllers/ServerController.cs @@ -50,7 +50,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public async Task Connect() { - if (!Management.GetServerState().IsConnected) + if (!Management.ServerState.IsConnected) { await Management.ConnectServerAsync(); } @@ -70,7 +70,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public IActionResult Disconnect([FromBody] string message) { - if (Management.GetServerState().IsConnected) + if (Management.ServerState.IsConnected) { Management.DisconnectServer(message); } @@ -90,7 +90,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public IActionResult Get() { - return Ok(Management.GetServerState()); + return Ok(Management.ServerState); } } } \ No newline at end of file diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index 6c5f3784..9a06d961 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -25,6 +25,21 @@ namespace slskd.Management /// public interface IManagementService { + /// + /// Gets the current state of the slskd service. + /// + ApplicationState ApplicationState { get; } + + /// + /// Gets the current state of the connection to the Soulseek server. + /// + ServerState ServerState { get; } + + /// + /// Gets the current state of the shared file cache. + /// + SharedFileCacheState SharedFileCacheState { get; } + /// /// Connects the Soulseek client to the server using the configured username and password. /// @@ -38,18 +53,6 @@ namespace slskd.Management /// An optional Exception to associate with the disconnect. void DisconnectServer(string message = null, Exception exception = null); - /// - /// Gets the current state of the connection to the Soulseek server. - /// - /// The current server state. - ServerState GetServerState(); - - /// - /// Gets the current state of the slskd service. - /// - /// - ServiceState GetServiceState(); - /// /// Re-scans shared directories. /// diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 2f79f496..3d7bd442 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -1,13 +1,18 @@ // // Copyright (c) slskd Team. All rights reserved. // -// This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public -// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. // -// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty -// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. // -// You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/. +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. // using Microsoft.Extensions.Options; @@ -16,7 +21,6 @@ namespace slskd.Management { using System; using System.Threading.Tasks; - using slskd.Shares; using Soulseek; /// @@ -33,7 +37,7 @@ namespace slskd.Management /// The shared file cache. public ManagementService( IOptionsMonitor optionsMonitor, - IStateMonitor serviceStateMonitor, + IStateMonitor serviceStateMonitor, ISoulseekClient soulseekClient, ISharedFileCache sharedFileCache) { @@ -43,10 +47,32 @@ namespace slskd.Management SharedFileCache = sharedFileCache; } + /// + /// Gets the current state of the slskd service. + /// + public ApplicationState ApplicationState => ServiceStateMonitor.CurrentValue; + + /// + /// Gets the current state of the connection to the Soulseek server. + /// + public ServerState ServerState => + new ServerState() + { + Address = Client.Address, + IPEndPoint = Client.IPEndPoint, + State = Client.State, + Username = Client.Username, + }; + + /// + /// Gets the current state of the connection to the Soulseek server. + /// + public SharedFileCacheState SharedFileCacheState => SharedFileCache.State.CurrentValue; + private ISoulseekClient Client { get; } private Options Options => OptionsMonitor.CurrentValue; private IOptionsMonitor OptionsMonitor { get; } - private IStateMonitor ServiceStateMonitor { get; } + private IStateMonitor ServiceStateMonitor { get; } private ISharedFileCache SharedFileCache { get; } /// @@ -64,25 +90,6 @@ namespace slskd.Management public void DisconnectServer(string message = null, Exception exception = null) => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); - /// - /// Gets the current state of the connection to the Soulseek server. - /// - /// The current server state. - public ServerState GetServerState() => - new ServerState() - { - Address = Client.Address, - IPEndPoint = Client.IPEndPoint, - State = Client.State, - Username = Client.Username, - }; - - /// - /// Gets the current state of the slskd service. - /// - /// - public ServiceState GetServiceState() => ServiceStateMonitor.CurrentValue; - /// /// Re-scans shared directories. /// diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs deleted file mode 100644 index 469d4227..00000000 --- a/src/slskd/Application/Service.cs +++ /dev/null @@ -1,691 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Concurrent; - using System.IO; - using System.Linq; - using System.Net; - using System.Reflection; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Options; - using Serilog; - using Serilog.Events; - using slskd.Configuration; - using slskd.Integrations.Pushbullet; - using slskd.Messaging; - using slskd.Peer; - using slskd.Search; - using slskd.Shares; - using slskd.Transfer; - using Soulseek; - using Soulseek.Diagnostics; - - public class Service : IHostedService - { - private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes - - public Service( - OptionsAtStartup optionsAtStartup, - IOptionsMonitor optionsMonitor, - IStateMonitor stateMonitor, - IStateMonitor sharedFileCacheStateMonitor, - ITransferTracker transferTracker, - IBrowseTracker browseTracker, - IConversationTracker conversationTracker, - IRoomTracker roomTracker, - ISharedFileCache sharedFileCache, - IPushbulletService pushbulletService) - { - OptionsAtStartup = optionsAtStartup; - - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); - - PreviousOptions = OptionsMonitor.CurrentValue; - - StateMonitor = stateMonitor; - StateMonitor.OnChange(state => StateMonitor_OnChange(state)); - - SharedFileCacheStateMonitor = sharedFileCacheStateMonitor; - SharedFileCacheStateMonitor.OnChange(state => SharedFileCacheStateMonitor_OnChange(state)); - - TransferTracker = transferTracker; - BrowseTracker = browseTracker; - ConversationTracker = conversationTracker; - RoomTracker = roomTracker; - SharedFileCache = sharedFileCache; - Pushbullet = pushbulletService; - - ProxyOptions proxyOptions = default; - - if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) - { - proxyOptions = new ProxyOptions( - address: OptionsAtStartup.Soulseek.Connection.Proxy.Address, - port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value, - username: OptionsAtStartup.Soulseek.Connection.Proxy.Username, - password: OptionsAtStartup.Soulseek.Connection.Proxy.Password); - } - - var connectionOptions = new ConnectionOptions( - readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read, - writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write, - connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect, - inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, - proxyOptions: proxyOptions); - - var clientOptions = new SoulseekClientOptions( - listenPort: OptionsAtStartup.Soulseek.ListenPort, - enableListener: true, - userEndPointCache: new UserEndPointCache(), - distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel, - autoAcknowledgePrivateMessages: false, - acceptPrivateRoomInvitations: true, - serverConnectionOptions: connectionOptions, - peerConnectionOptions: connectionOptions, - transferConnectionOptions: connectionOptions, - distributedConnectionOptions: connectionOptions, - userInfoResponseResolver: UserInfoResponseResolver, - browseResponseResolver: BrowseResponseResolver, - directoryContentsResponseResolver: DirectoryContentsResponseResolver, - enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), - searchResponseCache: new SearchResponseCache(), - searchResponseResolver: SearchResponseResolver); - - Client = new SoulseekClient(options: clientOptions); - - Client.DiagnosticGenerated += Client_DiagnosticGenerated; - - Client.TransferStateChanged += Client_TransferStateChanged; - Client.TransferProgressUpdated += Client_TransferProgressUpdated; - - Client.BrowseProgressUpdated += Client_BrowseProgressUpdated; - Client.UserStatusChanged += Client_UserStatusChanged; - Client.PrivateMessageReceived += Client_PrivateMessageRecieved; - - Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); - Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); - Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); - Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); - - Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; - Client.RoomMessageReceived += Client_RoomMessageReceived; - Client.RoomJoined += Client_RoomJoined; - Client.RoomLeft += Client_RoomLeft; - Client.Disconnected += Client_Disconnected; - Client.Connected += Client_Connected; - Client.LoggedIn += Client_LoggedIn; - - SoulseekClient = Client; - } - - public static ISoulseekClient SoulseekClient { get; private set; } - - private IBrowseTracker BrowseTracker { get; set; } - private ISoulseekClient Client { get; set; } - private IConversationTracker ConversationTracker { get; set; } - private ILogger Logger { get; set; } = Log.ForContext(); - private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); - private IOptionsMonitor OptionsMonitor { get; set; } - private Options Options => OptionsMonitor.CurrentValue; - private OptionsAtStartup OptionsAtStartup { get; set; } - private Options PreviousOptions { get; set; } - private IRoomTracker RoomTracker { get; set; } - private IStateMonitor StateMonitor { get; set; } - private ServiceState State => StateMonitor.CurrentValue; - private IStateMonitor SharedFileCacheStateMonitor { get; set; } - private ISharedFileCache SharedFileCache { get; set; } - private ITransferTracker TransferTracker { get; set; } - private IPushbulletService Pushbullet { get; } - private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); - private DateTime SharesRefreshStarted { get; set; } - - public async Task StartAsync(CancellationToken cancellationToken) - { - if (OptionsAtStartup.NoShareScan) - { - Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); - } - else - { - _ = SharedFileCache.FillAsync(); - } - - if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) - { - Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); - } - - Logger.Information("Client started"); - Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); - - if (OptionsAtStartup.NoConnect) - { - Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); - } - else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) - { - Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); - } - else - { - await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); - } - } - - public Task StopAsync(CancellationToken cancellationToken) - { - Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); - Client.Dispose(); - Logger.Information("Client stopped"); - return Task.CompletedTask; - } - - private async Task OptionsMonitor_OnChange(Options newOptions) - { - // this code is known to fire more than once per update. i'm not sure - // whether these might be executed concurrently. lock to be safe, because - // we need to accurately track the last value of Options for diffing purposes. - // threading shenanigans here could lead to missed updates. - OptionsSyncRoot.EnterWriteLock(); - - try - { - var pendingRestart = false; - var pendingReconnect = false; - var soulseekRequiresReconnect = false; - - var diff = PreviousOptions.DiffWith(newOptions); - - // don't react to duplicate/no-change events - // https://github.com/slskd/slskd/issues/126 - if (!diff.Any()) - { - return; - } - - foreach (var (property, fqn, left, right) in diff) - { - static bool HasAttribute(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); - - var requiresRestart = HasAttribute(property); - var requiresReconnect = HasAttribute(property); - - Logger.Debug($"{fqn} changed from '{left.ToJson() ?? ""}' to '{right.ToJson() ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); - - pendingRestart |= requiresRestart; - pendingReconnect |= requiresReconnect; - } - - if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() - || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) - { - StateMonitor.SetValue(state => state with { PendingShareRescan = true }); - Logger.Information("Shared directory 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); - - if (slskDiff.Any()) - { - var old = PreviousOptions.Soulseek; - var update = newOptions.Soulseek; - - Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); - - // determine whether any Connection options changed. if so, replace the whole object. - // Soulseek.NET doesn't offer a way to patch parts of connection options. the updates only affect - // new connections, so a partial patch doesn't make a lot of sense anyway. - var connectionDiff = old.Connection.DiffWith(update.Connection); - - ConnectionOptions connectionPatch = null; - - if (connectionDiff.Any()) - { - var connection = update.Connection; - - ProxyOptions proxyPatch = null; - - if (connection.Proxy.Enabled) - { - proxyPatch = new ProxyOptions( - connection.Proxy.Address, - connection.Proxy.Port.Value, - connection.Proxy.Username, - connection.Proxy.Password); - } - - connectionPatch = new ConnectionOptions( - connection.Buffer.Read, - connection.Buffer.Write, - connection.Timeout.Connect, - connection.Timeout.Inactivity, - proxyOptions: proxyPatch); - } - - var patch = new SoulseekClientOptionsPatch( - listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort, - enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, - distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, - serverConnectionOptions: connectionPatch, - peerConnectionOptions: connectionPatch, - transferConnectionOptions: connectionPatch, - incomingConnectionOptions: connectionPatch, - distributedConnectionOptions: connectionPatch); - - Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); - - soulseekRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); - } - - // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed, - // OR if the call to reconfigure the client requires a reconnect - if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect) - { - StateMonitor.SetValue(state => state with { PendingReconnect = true }); - Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect."); - } - - if (pendingRestart) - { - StateMonitor.SetValue(state => state with { PendingRestart = true }); - Logger.Information("One or more updated options requires an application restart to take effect."); - } - - Logger.Information("Options updated successfully."); - } - catch (Exception ex) - { - Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); - } - finally - { - PreviousOptions = OptionsMonitor.CurrentValue; - OptionsSyncRoot.ExitWriteLock(); - } - } - - private void StateMonitor_OnChange((ServiceState Previous, ServiceState Current) state) - { - Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); - } - - private void SharedFileCacheStateMonitor_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) - { - if (!state.Previous.Filling && state.Current.Filling) - { - SharesRefreshStarted = DateTime.UtcNow; - Logger.Information("Scanning shares"); - } - - var lastProgress = Math.Round(state.Previous.FillProgress * 100); - var currentProgress = Math.Round(state.Current.FillProgress * 100); - - if (lastProgress != currentProgress && currentProgress % 10 == 0) - { - Logger.Debug("Share scan progress {Percent}%", currentProgress); - } - - if (state.Previous.Filling && !state.Current.Filling) - { - StateMonitor.SetValue(s => s with { SharedCounts = (state.Current.Directories, state.Current.Files) }); - - if (state.Current.Faulted) - { - Logger.Error("Failed to scan shares."); - } - else - { - StateMonitor.SetValue(s => s with { PendingShareRescan = false }); - Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", State.SharedCounts.Directories, State.SharedCounts.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); - - SharesRefreshStarted = default; - - if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) - { - _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); - } - } - } - } - - /// - /// Creates and returns an instances of in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// A Task resolving an IEnumerable of Soulseek.Directory. - private Task BrowseResponseResolver(string username, IPEndPoint endpoint) - { - var directories = SharedFileCache.Browse(); - return Task.FromResult(new BrowseResponse(directories)); - } - - private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) - { - BrowseTracker.AddOrUpdate(args.Username, args); - } - - private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args) - { - static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch - { - DiagnosticLevel.Debug => LogEventLevel.Debug, - DiagnosticLevel.Info => LogEventLevel.Information, - DiagnosticLevel.Warning => LogEventLevel.Warning, - DiagnosticLevel.None => default, - _ => default, - }; - - var logger = Loggers.GetOrAdd(sender.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", sender.GetType().FullName)); - - logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); - } - - private void Client_Connected(object sender, EventArgs e) - { - Logger.Information("Connected to the Soulseek server"); - } - - private void Client_LoggedIn(object sender, EventArgs e) - { - Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); - - // send whatever counts we have currently. we'll probably connect before the cache is primed, - // so these will be zero initially, but we'll update them when the cache is filled. - _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); - } - - private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) - { - if (State.PendingReconnect) - { - StateMonitor.SetValue(state => state with { PendingReconnect = false }); - } - - if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) - { - Logger.Information("Disconnected from the Soulseek server: the client is shutting down"); - } - else if (args.Exception is IntentionalDisconnectException) - { - Logger.Information("Disconnected from the Soulseek server: disconnected by the user"); - } - else if (args.Exception is LoginRejectedException) - { - Logger.Error("Disconnected from the Soulseek server: invalid username or password"); - } - else if (args.Exception is KickedFromServerException) - { - Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); - } - else - { - Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) - { - Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); - return; - } - - var attempts = 1; - - while (true) - { - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: attempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - - var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); - Logger.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); - await Task.Delay(delay + jitter); - - Logger.Information($"Attempting to reconnect (#{attempts})...", attempts); - - try - { - // reconnect with the latest configuration values we have for username and password, instead of the options that were - // captured at startup. if a user has updated these values prior to the disconnect, the changes will take effect now. - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - break; - } - catch (Exception ex) - { - attempts++; - Logger.Error("Failed to reconnect: {Message}", ex.Message); - } - } - } - } - - private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) - { - ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - - if (Options.Integration.Pushbullet.Enabled && !args.Replayed) - { - Console.WriteLine("Pushing..."); - _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); - } - } - - private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) - { - Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - - if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) - { - _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); - } - } - - private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) - { - // this will fire when we join a room; track that through the join operation. - if (args.Username != Client.Username) - { - RoomTracker.TryAddUser(args.RoomName, args.UserData); - } - } - - private void Client_RoomLeft(object sender, RoomLeftEventArgs args) - { - RoomTracker.TryRemoveUser(args.RoomName, args.Username); - } - - private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args) - { - var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); - RoomTracker.AddOrUpdateMessage(args.RoomName, message); - - if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) - { - _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); - } - } - - private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) - { - // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] - // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] - // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); - } - - private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) - { - var xfer = args.Transfer; - var direction = xfer.Direction.ToString().ToUpper(); - var user = xfer.Username; - var file = Path.GetFileName(xfer.Filename); - var oldState = args.PreviousState; - var state = xfer.State; - - var completed = xfer.State.HasFlag(TransferStates.Completed); - - Console.WriteLine($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}"); - - if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded)) - { - _ = Client.SendUploadSpeedAsync((int)args.Transfer.AverageSpeed); - } - } - - private void Client_UserStatusChanged(object sender, UserStatusChangedEventArgs args) - { - Console.WriteLine($"[USER] {args.Username}: {args.Status}"); - } - - /// - /// Creates and returns a in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// The unique token for the request, supplied by the requesting user. - /// The requested directory. - /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. - private Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) - { - var result = new Soulseek.Directory(directory.Replace("/", @"\"), System.IO.Directory.GetFiles(directory) - .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))); - - return Task.FromResult(result); - } - - /// - /// Invoked upon a remote request to download a file. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// The filename of the requested file. - /// (for example purposes) the ITransferTracker used to track progress. - /// A Task representing the asynchronous operation. - /// - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// - /// - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for - /// security reasons. - /// - private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) - { - _ = endpoint; - var localFilename = filename.ToLocalOSPath(); - var fileInfo = new FileInfo(localFilename); - - if (!fileInfo.Exists) - { - Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); - throw new DownloadEnqueueException($"File not shared."); - } - - if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) - { - // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse - Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); - return Task.CompletedTask; - } - - // create a new cancellation token source so that we can cancel the upload from the UI. - var cts = new CancellationTokenSource(); - var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); - - // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and - // uploads would be handled separately. - Task.Run(async () => - { - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - await Client.UploadAsync(username, filename, fileInfo.Length, stream, options: topts, cancellationToken: cts.Token); - }).ContinueWith(t => - { - Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); - }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget - - // return a completed task so that the invoking code can respond to the remote client. - return Task.CompletedTask; - } - - /// - /// Creates and returns a in response to the given . - /// - /// The username of the requesting user. - /// The search token. - /// The search query. - /// A Task resolving a SearchResponse, or null. - private async Task SearchResponseResolver(string username, int token, SearchQuery query) - { - // some bots continually query for very common strings. blacklist known names here. - var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; - if (blacklist.Contains(username)) - { - return null; - } - - // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. - if (query.Query.Length < 3) - { - return null; - } - - var results = await SharedFileCache.SearchAsync(query); - - if (results.Any()) - { - Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - - return new SearchResponse( - SoulseekClient.Username, - token, - freeUploadSlots: 1, - uploadSpeed: 0, - queueLength: 0, - fileList: results); - } - - // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no - // response will be sent to the requestor. - return null; - } - - /// - /// Creates and returns a object in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// A Task resolving the UserInfo instance. - private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) - { - var info = new UserInfo( - description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", - picture: Array.Empty(), - uploadSlots: 1, - queueLength: 0, - hasFreeUploadSlot: false); - - return Task.FromResult(info); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/ServiceState.cs b/src/slskd/Application/ServiceState.cs deleted file mode 100644 index 3f3eda05..00000000 --- a/src/slskd/Application/ServiceState.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - /// - /// Application service state. - /// - public record ServiceState() - { - public bool PendingReconnect { get; init; } - public bool PendingRestart { get; init; } - public bool PendingShareRescan { get; init; } - public (int Directories, int Files) SharedCounts { get; init; } = (0, 0); - } -} \ No newline at end of file diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs new file mode 100644 index 00000000..a3edad9d --- /dev/null +++ b/src/slskd/Application/SharedFileCache.cs @@ -0,0 +1,273 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System.IO; +using Microsoft.Extensions.Options; + +namespace slskd +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Shared file cache. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + public SharedFileCache( + IOptionsMonitor optionsMonitor) + { + OptionsMonitor = optionsMonitor; + } + + /// + /// Gets the cache state. + /// + public IStateMonitor State { get; } = new StateMonitor(); + + private HashSet Directories { get; set; } + private Dictionary Files { get; set; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IOptionsMonitor OptionsMonitor { get; set; } + private SqliteConnection SQLite { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + var directories = new ConcurrentDictionary(); + + // 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 Directories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = Files + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values; + } + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + public async Task FillAsync() + { + if (SyncRoot.CurrentCount == 0) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + await Task.Yield(); + + await SyncRoot.WaitAsync(); + + try + { + State.SetValue(state => state with { Filling = true, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + var sw = new Stopwatch(); + sw.Start(); + var swSnapshot = 0L; + + // this destroys the old table and creates a new one. empty the other cached fields to reflect this + // todo: use an A/B style table naming schema so that the cache remains available while it is filling + CreateTable(); + Directories = new HashSet(); + Files = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; + + var directories = OptionsMonitor.CurrentValue.Directories.Shared + .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) + .ToHashSet(); + + State.SetValue(state => state with { Directories = directories.Count }); + + Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting recursive scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); + swSnapshot = sw.ElapsedMilliseconds; + + var files = new Dictionary(); + var current = 0; + + foreach (var directory in directories) + { + // 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("/", @"\"), 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) + { + 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; + } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)directories.Count, Files = files.Count }); + } + + Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + Directories = directories; + Files = files; + + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + FillProgress = 1, + Directories = Directories.Count, + Files = Files.Count, + }); + + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with + { + Filling = false, + Faulted = true, + FillProgress = 0, + }); + + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; + } + finally + { + SyncRoot.Release(); + } + } + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + public async Task> SearchAsync(SearchQuery query) + { + // sanitize the query string. there's probably more to it than this. + var text = query.Query + .Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " "); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; + + try + { + using var cmd = new SqliteCommand(sql, SQLite); + var results = new List(); + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + + return results.Select(r => Files[r.Replace("''", "'")]); + } + catch (Exception ex) + { + // temporary error trap to refine substitution rules + Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); + return Enumerable.Empty(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=:memory:"); + SQLite.Open(); + + using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Application/SharedFileCacheState.cs b/src/slskd/Application/SharedFileCacheState.cs new file mode 100644 index 00000000..54b56c22 --- /dev/null +++ b/src/slskd/Application/SharedFileCacheState.cs @@ -0,0 +1,52 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + + /// + /// Share cache state. + /// + public record SharedFileCacheState + { + /// + /// Gets a value indicating whether the cache is being filled. + /// + public bool Filling { get; init; } = false; + + /// + /// Gets a value indicating whether the cache is faulted. + /// + public bool Faulted { get; init; } = false; + + /// + /// Gets the current fill progress. + /// + public double FillProgress { get; init; } + + /// + /// Gets the number of cached directories. + /// + public int Directories { get; init; } + + /// + /// Gets the number of cached files. + /// + public int Files { get; init; } + } +} \ No newline at end of file diff --git a/src/slskd/Application/Shares/ISharedFileCache.cs b/src/slskd/Application/Shares/ISharedFileCache.cs deleted file mode 100644 index 163f4eea..00000000 --- a/src/slskd/Application/Shares/ISharedFileCache.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System.Collections.Generic; - using System.Threading.Tasks; - using Soulseek; - - /// - /// Shared file cache. - /// - public interface ISharedFileCache - { - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - IEnumerable Browse(); - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - Task FillAsync(); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - Task> SearchAsync(SearchQuery query); - } -} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCache.cs b/src/slskd/Application/Shares/SharedFileCache.cs deleted file mode 100644 index e9bddb09..00000000 --- a/src/slskd/Application/Shares/SharedFileCache.cs +++ /dev/null @@ -1,272 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -using System.IO; -using Microsoft.Extensions.Options; - -namespace slskd.Shares -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Shared file cache. - /// - public class SharedFileCache : ISharedFileCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SharedFileCache( - IStateMonitor stateMonitor, - IOptionsMonitor optionsMonitor) - { - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; - } - - private HashSet Directories { get; set; } - private Dictionary Files { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private SqliteConnection SQLite { get; set; } - private IStateMonitor StateMonitor { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - public IEnumerable Browse() - { - var directories = new ConcurrentDictionary(); - - // 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 Directories) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = Files - .GroupBy(f => Path.GetDirectoryName(f.Key)) - .Select(g => new Directory(g.Key, g.Select(g => - { - var f = g.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. - f.Size, - f.Extension, - f.Attributes); - }))); - - // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. - // entries with no files will remain untouched. - foreach (var group in groups) - { - directories.AddOrUpdate(group.Name, group, (_, _) => group); - } - - return directories.Values; - } - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - public async Task FillAsync() - { - if (SyncRoot.CurrentCount == 0) - { - Log.Warning("Shared file scan rejected; scan is already in progress."); - throw new ShareScanInProgressException("Shared files are already being scanned."); - } - - await Task.Yield(); - - await SyncRoot.WaitAsync(); - - try - { - StateMonitor.SetValue(state => state with { Filling = true, FillProgress = 0 }); - Log.Debug("Starting shared file scan"); - - var sw = new Stopwatch(); - sw.Start(); - var swSnapshot = 0L; - - // this destroys the old table and creates a new one. empty the other cached fields to reflect this - // todo: use an A/B style table naming schema so that the cache remains available while it is filling - CreateTable(); - Directories = new HashSet(); - Files = new Dictionary(); - StateMonitor.SetValue(state => state with { Directories = 0, Files = 0 }); - - Log.Debug("Enumerating shared directories"); - swSnapshot = sw.ElapsedMilliseconds; - - var directories = OptionsMonitor.CurrentValue.Directories.Shared - .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) - .ToHashSet(); - - StateMonitor.SetValue(state => state with { Directories = directories.Count }); - - Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting recursive scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); - swSnapshot = sw.ElapsedMilliseconds; - - var files = new Dictionary(); - var current = 0; - - foreach (var directory in directories) - { - // 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("/", @"\"), 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) - { - 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; - } - - current++; - StateMonitor.SetValue(state => state with { FillProgress = current / (double)directories.Count, Files = files.Count }); - } - - Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - Directories = directories; - Files = files; - - StateMonitor.SetValue(state => state with - { - Filling = false, - Faulted = false, - FillProgress = 1, - Directories = Directories.Count, - Files = Files.Count, - }); - - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); - } - catch (Exception ex) - { - StateMonitor.SetValue(state => state with - { - Filling = false, - Faulted = true, - FillProgress = 0, - }); - - Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); - throw; - } - finally - { - SyncRoot.Release(); - } - } - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - public async Task> SearchAsync(SearchQuery query) - { - // sanitize the query string. there's probably more to it than this. - var text = query.Query - .Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " "); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - - try - { - using var cmd = new SqliteCommand(sql, SQLite); - var results = new List(); - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - - return results.Select(r => Files[r.Replace("''", "'")]); - } - catch (Exception ex) - { - // temporary error trap to refine substitution rules - Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); - return Enumerable.Empty(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection("Data Source=:memory:"); - SQLite.Open(); - - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); - cmd.ExecuteNonQuery(); - } - } -} \ No newline at end of file diff --git a/src/slskd/Application/Shares/SharedFileCacheState.cs b/src/slskd/Application/Shares/SharedFileCacheState.cs deleted file mode 100644 index 37ac9f86..00000000 --- a/src/slskd/Application/Shares/SharedFileCacheState.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Shares -{ - using System; - - /// - /// Share cache state. - /// - public record SharedFileCacheState() - { - /// - /// Gets a value indicating whether the cache is being filled. - /// - public bool Filling { get; init; } = false; - - /// - /// Gets a value indicating whether the cache is faulted. - /// - public bool Faulted { get; init; } = false; - - /// - /// Gets the current fill progress. - /// - public double FillProgress { get; init; } - - /// - /// Gets the number of cached directories. - /// - public int Directories { get; init; } - - /// - /// Gets the number of cached files. - /// - public int Files { get; init; } - - /// - /// Gets the UTC timestamp of the last fill. - /// - public DateTime? LastFilled { get; init; } - } -} \ No newline at end of file diff --git a/src/slskd/Common/IStateMonitor.cs b/src/slskd/Common/IStateMonitor.cs index b2286aac..57055450 100644 --- a/src/slskd/Common/IStateMonitor.cs +++ b/src/slskd/Common/IStateMonitor.cs @@ -20,7 +20,7 @@ namespace slskd using System; /// - /// Used for notifications when changes. + /// Used for notifications when changes. /// /// The type of the tracked state object. public interface IStateMonitor diff --git a/src/slskd/Common/StateMonitor.cs b/src/slskd/Common/StateMonitor.cs index 22704398..1d52b9e9 100644 --- a/src/slskd/Common/StateMonitor.cs +++ b/src/slskd/Common/StateMonitor.cs @@ -20,7 +20,7 @@ namespace slskd using System; /// - /// Used for notifications when changes. + /// Used for notifications when changes. /// /// The type of the tracked state object. public class StateMonitor : IStateMonitor diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index c15e9f8a..ef955df9 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -41,7 +41,6 @@ namespace slskd using slskd.Messaging; using slskd.Peer; using slskd.Search; - using slskd.Shares; using slskd.Transfer; using slskd.Validation; @@ -105,11 +104,10 @@ namespace slskd return true; }); - // add IStateMonitor instances to DI, to track application state in an observable way. - // imilar to IOptionsMonitor, but state is managed by the application itself. + // add IStateMonitor instance to DI, to track application state in an observable way. + // similar to IOptionsMonitor, but state is managed by the application itself. // Usage is roughly the same. - services.AddSingleton, StateMonitor>(); - services.AddSingleton, StateMonitor>(); + services.AddSingleton, StateMonitor>(); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); @@ -220,8 +218,8 @@ namespace slskd services.AddSingleton(); - services.AddHostedService(); - services.AddSingleton(_ => Service.SoulseekClient); + services.AddHostedService(); + services.AddSingleton(_ => Application.SoulseekClient); } /// -- cgit v1.2.3 From 18dcdf4bd4d9f207bc4945adaaed610dd7f46279 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 Aug 2021 09:08:10 -0500 Subject: refine state changes --- src/slskd/Application/Application.cs | 15 +++++++++------ src/slskd/Application/ApplicationState.cs | 2 +- src/slskd/Application/SharedFileCache.cs | 2 +- src/slskd/Options.cs | 2 +- 4 files changed, 12 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Application/Application.cs b/src/slskd/Application/Application.cs index fc359b43..f1361b6e 100644 --- a/src/slskd/Application/Application.cs +++ b/src/slskd/Application/Application.cs @@ -334,20 +334,23 @@ namespace slskd if (!state.Previous.Filling && state.Current.Filling) { SharesRefreshStarted = DateTime.UtcNow; + + StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); Logger.Information("Scanning shares"); } var lastProgress = Math.Round(state.Previous.FillProgress * 100); var currentProgress = Math.Round(state.Current.FillProgress * 100); - if (lastProgress != currentProgress && currentProgress % 10 == 0) + if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { - Logger.Debug("Share scan progress {Percent}%", currentProgress); + StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); + Logger.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, state.Current.Files); } if (state.Previous.Filling && !state.Current.Filling) { - StateMonitor.SetValue(s => s with { SharedCounts = (state.Current.Directories, state.Current.Files) }); + StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); if (state.Current.Faulted) { @@ -356,13 +359,13 @@ namespace slskd else { StateMonitor.SetValue(s => s with { PendingShareRescan = false }); - Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", State.SharedCounts.Directories, State.SharedCounts.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", state.Current.Directories, state.Current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) { - _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); + _ = SoulseekClient.SetSharedCountsAsync(State.SharedFileCache.Directories, State.SharedFileCache.Files); } } } @@ -412,7 +415,7 @@ namespace slskd // send whatever counts we have currently. we'll probably connect before the cache is primed, // so these will be zero initially, but we'll update them when the cache is filled. - _ = SoulseekClient.SetSharedCountsAsync(State.SharedCounts.Directories, State.SharedCounts.Files); + _ = SoulseekClient.SetSharedCountsAsync(State.SharedFileCache.Directories, State.SharedFileCache.Files); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) diff --git a/src/slskd/Application/ApplicationState.cs b/src/slskd/Application/ApplicationState.cs index 2e3f627f..58f086bb 100644 --- a/src/slskd/Application/ApplicationState.cs +++ b/src/slskd/Application/ApplicationState.cs @@ -25,6 +25,6 @@ namespace slskd public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } public bool PendingShareRescan { get; init; } - public (int Directories, int Files) SharedCounts { get; init; } = (0, 0); + public SharedFileCacheState SharedFileCache { get; init; } } } \ No newline at end of file diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index a3edad9d..9a5770b6 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -140,7 +140,7 @@ namespace slskd State.SetValue(state => state with { Directories = directories.Count }); - Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting recursive scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); + Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting file scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); swSnapshot = sw.ElapsedMilliseconds; var files = new Dictionary(); diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 93895a2e..bf83e74f 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -166,7 +166,7 @@ namespace slskd [EnvironmentVariable("NO_SHARE_SCAN")] [Description("do not scan shares on startup")] [RequiresRestart] - public bool NoShareScan { get; private set; } = true; + public bool NoShareScan { get; private set; } = false; /// /// Gets the unique name for this instance. -- cgit v1.2.3 From 16da48c0b095a92064e10825f3750802f62cec7d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 Aug 2021 09:15:56 -0500 Subject: docs --- src/slskd/Common/IStateMonitor.cs | 2 +- src/slskd/Common/StateMonitor.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/IStateMonitor.cs b/src/slskd/Common/IStateMonitor.cs index 57055450..813dbfd5 100644 --- a/src/slskd/Common/IStateMonitor.cs +++ b/src/slskd/Common/IStateMonitor.cs @@ -20,7 +20,7 @@ namespace slskd using System; /// - /// Used for notifications when changes. + /// Provideds observable management of state objects. /// /// The type of the tracked state object. public interface IStateMonitor diff --git a/src/slskd/Common/StateMonitor.cs b/src/slskd/Common/StateMonitor.cs index 1d52b9e9..9397d9b2 100644 --- a/src/slskd/Common/StateMonitor.cs +++ b/src/slskd/Common/StateMonitor.cs @@ -20,7 +20,7 @@ namespace slskd using System; /// - /// Used for notifications when changes. + /// Provideds observable management of state objects. /// /// The type of the tracked state object. public class StateMonitor : IStateMonitor -- cgit v1.2.3