From cc85c944e7206608105a46c6fd8bcfaa6d00228f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 21:20:44 -0500 Subject: expose Shares --- src/slskd/Shares/SharedFileCache.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index ac996fa6..1b35aacf 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -37,6 +37,11 @@ namespace slskd.Shares /// public interface ISharedFileCache { + /// + /// Gets the list of shares. + /// + public List Shares { get; } + /// /// Gets the cache state monitor. /// @@ -100,12 +105,16 @@ namespace slskd.Shares /// public IStateMonitor StateMonitor => State; + /// + /// Gets the list of shares. + /// + public List Shares { get; private set; } + private IManagedState State { get; } = new ManagedState(); private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } private Dictionary MaskedFiles { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } - private List Shares { get; set; } private SqliteConnection SQLite { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private ISoulseekFileFactory SoulseekFileFactory { get; } -- cgit v1.2.3 From 89b75c295de97096a6c5dbef8d9b93f28d2a1767 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:07:56 -0500 Subject: drop cache table when starting scan --- src/slskd/Shares/SharedFileCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 1b35aacf..5a218835 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -460,7 +460,7 @@ namespace slskd.Shares SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); SQLite.Open(); - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); cmd.ExecuteNonQuery(); } -- cgit v1.2.3 From 38255041d2e68a6fee1f481b3922869d9b577510 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 29 May 2022 22:44:53 -0500 Subject: refactor shares service/cache --- src/slskd/Application.cs | 59 ++- src/slskd/Program.cs | 1 - .../Shares/API/Controllers/SharesController.cs | 27 +- src/slskd/Shares/ShareService.cs | 72 ++- src/slskd/Shares/SharedFileCache.cs | 482 --------------------- src/slskd/Shares/SharesCache.cs | 482 +++++++++++++++++++++ src/slskd/Shares/SoulseekFileFactory.cs | 2 +- src/slskd/State.cs | 68 +-- 8 files changed, 623 insertions(+), 570 deletions(-) delete mode 100644 src/slskd/Shares/SharedFileCache.cs create mode 100644 src/slskd/Shares/SharesCache.cs (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c2a8632b..c0390c5a 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -82,7 +82,7 @@ namespace slskd IRoomTracker roomTracker, IRoomService roomService, IUserService userService, - ISharedFileCache sharedFileCache, + IShareService shareService, IPushbulletService pushbulletService, IHubContext applicationHub, IHubContext logHub) @@ -97,8 +97,8 @@ namespace slskd State = state; State.OnChange(state => State_OnChange(state)); - SharedFileCache = sharedFileCache; - SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); + Shares = shareService; + Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); TransferTracker = transferTracker; Transfers = transferService; @@ -152,7 +152,6 @@ namespace slskd private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } - private ISharedFileCache SharedFileCache { get; set; } private DateTime SharesRefreshStarted { get; set; } private IManagedState State { get; } private ITransferTracker TransferTracker { get; set; } @@ -160,6 +159,7 @@ namespace slskd private IHubContext ApplicationHub { get; set; } private IHubContext LogHub { get; set; } private IUserService Users { get; set; } + private IShareService Shares { get; set; } public void CollectGarbage() { @@ -306,7 +306,7 @@ namespace slskd } else { - _ = SharedFileCache.FillAsync(); + _ = Shares.StartScanAsync(); } if (OptionsAtStartup.NoConnect) @@ -337,12 +337,12 @@ namespace slskd /// 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) + private async Task BrowseResponseResolver(string username, IPEndPoint endpoint) { - var directories = SharedFileCache.Browse() + var directories = (await Shares.BrowseAsync()) .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes - return Task.FromResult(new BrowseResponse(directories)); + return new BrowseResponse(directories); } private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) @@ -441,7 +441,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. - _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -553,10 +553,10 @@ namespace slskd /// 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) + private async Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = SharedFileCache.List(directory); - return Task.FromResult(dir); + var dir = await Shares.ListAsync(directory); + return dir; } /// @@ -574,10 +574,10 @@ namespace slskd /// 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) + private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; - var localFilename = SharedFileCache.Resolve(filename).ToLocalOSPath(); + var localFilename = (await Shares.ResolveAsync(filename)).ToLocalOSPath(); var fileInfo = new FileInfo(localFilename); @@ -593,7 +593,7 @@ namespace slskd { // 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; + return; } // create a new cancellation token source so that we can cancel the upload from the UI. @@ -632,9 +632,6 @@ namespace slskd { 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; } private async Task OptionsMonitor_OnChange(Options newOptions) @@ -819,7 +816,7 @@ namespace slskd return null; } - var results = await SharedFileCache.SearchAsync(query); + var results = await Shares.SearchAsync(query); if (results.Any()) { @@ -839,45 +836,45 @@ namespace slskd return null; } - private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) + private void ShareState_OnChange((ShareState Previous, ShareState Current) state) { var (previous, current) = state; - if (!previous.Filling && current.Filling) + if (!previous.Cache.Filling && current.Cache.Filling) { SharesRefreshStarted = DateTime.UtcNow; - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); Log.Information("Scanning shares"); } - var lastProgress = Math.Round(previous.FillProgress * 100); - var currentProgress = Math.Round(current.FillProgress * 100); + var lastProgress = Math.Round(previous.Cache.FillProgress * 100); + var currentProgress = Math.Round(current.Cache.FillProgress * 100); if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { - State.SetValue(s => s with { SharedFileCache = current }); - Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); + State.SetValue(s => s with { Shares = current }); + Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Cache.Files); } - if (previous.Filling && !current.Filling) + if (previous.Cache.Filling && !current.Cache.Filling) { - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); - if (current.Faulted) + if (current.Cache.Faulted) { Log.Error("Failed to scan shares."); } else { State.SetValue(s => s with { PendingShareRescan = false }); - Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Cache.Directories, current.Cache.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) { - _ = Client.SetSharedCountsAsync(State.CurrentValue.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4643daa0..1a5d2a28 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -453,7 +453,6 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 0b397bfd..251f50b9 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -19,6 +19,7 @@ namespace slskd.Shares.API { using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -57,11 +58,11 @@ namespace slskd.Shares.API [HttpGet("")] [Authorize] [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult List() + public async Task List() { - var browse = Shares.Cache.Browse(); + var browse = await Shares.BrowseAsync(); - var summary = Shares.Cache.Shares.Select(share => + var summary = Shares.Shares.Select(share => { var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => @@ -98,16 +99,16 @@ namespace slskd.Shares.API [Authorize] [ProducesResponseType(typeof(SummarizedShare), 200)] [ProducesResponseType(404)] - public IActionResult Get(string id) + public async Task Get(string id) { - var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - var browse = Shares.Cache.Browse(); + var browse = await Shares.BrowseAsync(); var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => { @@ -139,9 +140,9 @@ namespace slskd.Shares.API [HttpGet("contents")] [Authorize] [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult BrowseAll() + public async Task BrowseAll() { - return Ok(Shares.Cache.Browse()); + return Ok(await Shares.BrowseAsync()); } /// @@ -154,16 +155,16 @@ namespace slskd.Shares.API [HttpGet("{id}/contents")] [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] - public IActionResult BrowseShare(string id) + public async Task BrowseShare(string id) { - var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - var contents = Shares.Cache.Browse() + var contents = (await Shares.BrowseAsync()) .Where(directory => directory.Name.StartsWith(share.RemotePath)); return Ok(contents); @@ -182,12 +183,12 @@ namespace slskd.Shares.API [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { - if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) + if (ApplicationStateMonitor.CurrentValue.Shares.Cache.Filling) { return Conflict("A share scan is already in progress."); } - _ = Shares.Cache.FillAsync(); + _ = Shares.StartScanAsync(); return Ok(); } diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 763bb819..68b3c629 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -1,3 +1,20 @@ +// +// 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 @@ -5,31 +22,64 @@ namespace slskd.Shares using System; using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; + using Soulseek; public interface IShareService { - ISharedFileCache Cache { get; } - IReadOnlyList List(Func expression = null); + IReadOnlyList Shares { get; } + + Task> BrowseAsync(); + + Task ListAsync(string directory); + + Task> SearchAsync(SearchQuery query); + + Task StartScanAsync(); + + Task ResolveAsync(string remoteFilename); + + public IStateMonitor StateMonitor { get; } } public class ShareService : IShareService { public ShareService( - ISharedFileCache sharedFileCache, - IOptionsMonitor optionsMonitor) + IOptionsMonitor optionsMonitor, + IShareCache sharesCache = null) { - Cache = sharedFileCache; OptionsMonitor = optionsMonitor; + + // todo: when options change, fill SharesList with configured shares + // and set ScanPending = true + + Cache = sharesCache ?? new ShareCache(OptionsMonitor); + Cache.StateMonitor.OnChange(cacheState + => State.SetValue(state + => state with { Cache = cacheState.Current })); } - public ISharedFileCache Cache { get; } + public IReadOnlyList Shares => SharesList.AsReadOnly(); + public IStateMonitor StateMonitor => State; + private IShareCache Cache { get; } private IOptionsMonitor OptionsMonitor { get; } - private List Shares { get; set; } = new List(); + private List SharesList { get; set; } = new List(); + private IManagedState State { get; } = new ManagedState(); - public IReadOnlyList List(Func expression = null) - { - return Shares.Where(expression).ToList().AsReadOnly(); - } + public Task> BrowseAsync() + => Task.FromResult(Cache.Browse()); + + public Task ListAsync(string directory) + => Task.FromResult(Cache.List(directory)); + + public Task> SearchAsync(SearchQuery query) + => Cache.SearchAsync(query); + + public Task StartScanAsync() + => Cache.FillAsync(); + + public Task ResolveAsync(string remoteFilename) + => Task.FromResult(Cache.Resolve(remoteFilename)); } } \ No newline at end of file diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs deleted file mode 100644 index 5a218835..00000000 --- a/src/slskd/Shares/SharedFileCache.cs +++ /dev/null @@ -1,482 +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.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Shared file cache. - /// - public interface ISharedFileCache - { - /// - /// Gets the list of shares. - /// - public List Shares { get; } - - /// - /// Gets the cache state monitor. - /// - IStateMonitor StateMonitor { 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(); - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - Directory List(string directory); - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - Task> SearchAsync(SearchQuery query); - } - - /// - /// Shared file cache. - /// - public class SharedFileCache : ISharedFileCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public SharedFileCache( - IOptionsMonitor optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) - { - OptionsMonitor = optionsMonitor; - SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); - } - - /// - /// Gets the cache state monitor. - /// - public IStateMonitor StateMonitor => State; - - /// - /// Gets the list of shares. - /// - public List Shares { get; private set; } - - private IManagedState State { get; } = new ManagedState(); - private ILogger Log { get; } = Serilog.Log.ForContext(); - private HashSet MaskedDirectories { get; set; } - private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private SqliteConnection SQLite { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private ISoulseekFileFactory SoulseekFileFactory { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - public IEnumerable Browse() - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; - } - - 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 MaskedDirectories) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = MaskedFiles - .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.OrderBy(f => f.Name); - } - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - public async Task FillAsync() - { - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. - if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) - { - Log.Warning("Shared file scan rejected; scan is already in progress."); - throw new ShareScanInProgressException("Shared files are already being scanned."); - } - - try - { - State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); - Log.Debug("Starting shared file scan"); - - await Task.Yield(); - - ResetCache(); - - var sw = new Stopwatch(); - var swSnapshot = 0L; - sw.Start(); - - Shares = OptionsMonitor.CurrentValue.Directories.Shared - .Select(share => share.TrimEnd('/', '\\')) - .ToHashSet() // remove duplicates - .Select(share => new Share(share)) // convert to Shares - .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent - .ToList(); - - if (!Shares.Any()) - { - Log.Warning("Aborting shared file scan; no shares configured."); - } - - Shares.ForEach(s => Log.Debug(s.ToJson())); - - Shares.Where(s => !s.IsExcluded).ToList() - .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); - - Shares.Where(s => s.IsExcluded).ToList() - .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); - - Log.Debug("Enumerating shared directories"); - swSnapshot = sw.ElapsedMilliseconds; - - var unmaskedDirectories = Shares - .SelectMany(share => - { - try - { - return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); - } - catch (Exception ex) - { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) - - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); - - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); - - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - - var files = new Dictionary(); - var maskedDirectories = new HashSet(); - var current = 0; - var filtered = 0; - - foreach (var directory in unmaskedDirectories) - { - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - - // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized - // filename and with a value of a Soulseek.File object - try - { - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) - .ToDictionary(file => file.Filename, file => file); - - // 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 (filters.Any(filter => filter.IsMatch(file.Key))) - { - filtered++; - continue; - } - - if (files.ContainsKey(file.Key)) - { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - files[file.Key] = file.Value; - } - } - catch (Exception ex) - { - Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } - - current++; - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); - } - - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - MaskedDirectories = maskedDirectories; - MaskedFiles = files; - - State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); - } - catch (Exception ex) - { - State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); - Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); - throw; - } - finally - { - SyncRoot.Release(); - } - } - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - public Directory List(string directory) - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); - } - - return null; - } - - var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => - { - var f = kvp.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), - f.Size, - f.Extension, - f.Attributes); - }); - - return new Directory(directory, files); - } - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename) - { - filename = filename.ToLocalOSPath(); - var resolved = filename; - - // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a - // file. split the requested filename so we can examine the first two segments - var parts = filename.Split(new[] { '/', '\\' }); - - if (parts.Length < 2) - { - Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); - return resolved; - } - - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); - - if (share == default) - { - Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); - return resolved; - } - - resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); - - if (resolved == filename) - { - Log.Warning($"Failed to resolve shared file {filename}"); - } - - Log.Debug($"Resolved requested shared file {filename} to {resolved}"); - return resolved; - } - - /// - /// 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) - { - if (!State.CurrentValue.Filled) - { - return Enumerable.Empty(); - } - - string Clean(string str) => str.Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " ") - .Replace("'", "''"); - - var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); - var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; - var results = new List(); - - try - { - using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - using var cmd = new SqliteCommand(sql, conn); - await conn.OpenAsync(); - - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - - try - { - return results.Select(r => MaskedFiles[r]).ToList(); - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); - return Enumerable.Empty(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - SQLite.Open(); - - using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; 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)", SQLite); - cmd.Parameters.AddWithValue("filename", filename); - cmd.ExecuteNonQuery(); - } - - private void ResetCache() - { - CreateTable(); - MaskedDirectories = new HashSet(); - MaskedFiles = new Dictionary(); - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - } -} \ No newline at end of file diff --git a/src/slskd/Shares/SharesCache.cs b/src/slskd/Shares/SharesCache.cs new file mode 100644 index 00000000..22e72c77 --- /dev/null +++ b/src/slskd/Shares/SharesCache.cs @@ -0,0 +1,482 @@ +// +// 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.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface IShareCache + { + /// + /// Gets the list of shares. + /// + public List Shares { get; } // todo: remove this + + /// + /// Gets the cache state monitor. + /// + IStateMonitor StateMonitor { 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(); // TODO: accept a list of shares here + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Directory List(string directory); + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } + + /// + /// Shared file cache. + /// + public class ShareCache : IShareCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public ShareCache( + IOptionsMonitor optionsMonitor, + ISoulseekFileFactory soulseekFileFactory = null) + { + OptionsMonitor = optionsMonitor; + SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); + } + + /// + /// Gets the cache state monitor. + /// + public IStateMonitor StateMonitor => State; + + /// + /// Gets the list of shares. + /// + public List Shares { get; private set; } + + private IManagedState State { get; } = new ManagedState(); + private ILogger Log { get; } = Serilog.Log.ForContext(); + private HashSet MaskedDirectories { get; set; } + private Dictionary MaskedFiles { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private SqliteConnection SQLite { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + private ISoulseekFileFactory SoulseekFileFactory { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; + } + + 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 MaskedDirectories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = MaskedFiles + .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.OrderBy(f => f.Name); + } + + /// + /// Scans the configured shares and fills the cache. + /// + /// The operation context. + public async Task FillAsync() + { + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. + if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + try + { + State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + await Task.Yield(); + + ResetCache(); + + var sw = new Stopwatch(); + var swSnapshot = 0L; + sw.Start(); + + Shares = OptionsMonitor.CurrentValue.Directories.Shared + .Select(share => share.TrimEnd('/', '\\')) + .ToHashSet() // remove duplicates + .Select(share => new Share(share)) // convert to Shares + .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent + .ToList(); + + if (!Shares.Any()) + { + Log.Warning("Aborting shared file scan; no shares configured."); + } + + Shares.ForEach(s => Log.Debug(s.ToJson())); + + Shares.Where(s => !s.IsExcluded).ToList() + .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); + + Shares.Where(s => s.IsExcluded).ToList() + .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; + + var unmaskedDirectories = Shares + .SelectMany(share => + { + try + { + return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + return Array.Empty(); + } + }) + .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. + .ToHashSet(); // remove duplicates (in case shares overlap) + + var excludedDirectories = unmaskedDirectories + .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + + unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); + Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + var filters = OptionsMonitor.CurrentValue.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)); + + var files = new Dictionary(); + var maskedDirectories = new HashSet(); + var current = 0; + var filtered = 0; + + foreach (var directory in unmaskedDirectories) + { + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized + // filename and with a value of a Soulseek.File object + try + { + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) + .ToDictionary(file => file.Filename, file => file); + + // 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 (filters.Any(filter => filter.IsMatch(file.Key))) + { + filtered++; + continue; + } + + if (files.ContainsKey(file.Key)) + { + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + } + + files[file.Key] = file.Value; + } + } + catch (Exception ex) + { + Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); + } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); + } + + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + MaskedDirectories = maskedDirectories; + MaskedFiles = files; + + State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; + } + finally + { + SyncRoot.Release(); + } + } + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + public Directory List(string directory) + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); + } + + return null; + } + + var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => + { + var f = kvp.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), + f.Size, + f.Extension, + f.Attributes); + }); + + return new Directory(directory, files); + } + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename) + { + filename = filename.ToLocalOSPath(); + var resolved = filename; + + // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a + // file. split the requested filename so we can examine the first two segments + var parts = filename.Split(new[] { '/', '\\' }); + + if (parts.Length < 2) + { + Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); + return resolved; + } + + // find the share with a matching mask and alias/local directory + var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); + + if (share == default) + { + Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); + return resolved; + } + + resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); + + if (resolved == filename) + { + Log.Warning($"Failed to resolve shared file {filename}"); + } + + Log.Debug($"Resolved requested shared file {filename} to {resolved}"); + return resolved; + } + + /// + /// 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) + { + if (!State.CurrentValue.Filled) + { + return Enumerable.Empty(); + } + + string Clean(string str) => str.Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " ") + .Replace("'", "''"); + + var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); + var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; + var results = new List(); + + try + { + using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + using var cmd = new SqliteCommand(sql, conn); + await conn.OpenAsync(); + + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); + return Enumerable.Empty(); + } + + try + { + return results.Select(r => MaskedFiles[r]).ToList(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); + return Enumerable.Empty(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + SQLite.Open(); + + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; 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)", SQLite); + cmd.Parameters.AddWithValue("filename", filename); + cmd.ExecuteNonQuery(); + } + + private void ResetCache() + { + CreateTable(); + MaskedDirectories = new HashSet(); + MaskedFiles = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/SoulseekFileFactory.cs b/src/slskd/Shares/SoulseekFileFactory.cs index 5221265b..7cdd6174 100644 --- a/src/slskd/Shares/SoulseekFileFactory.cs +++ b/src/slskd/Shares/SoulseekFileFactory.cs @@ -48,7 +48,7 @@ namespace slskd.Shares private static readonly string[] VideoExtensions = { "mkv", "ogv", "avi", "wmv", "asf", "mp4", "m4p", "m4v", "mpg", "mpe", "mpv", "mpg", "m2v" }; private static readonly HashSet SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet(); - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Creates an instance of from the given path. diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 0daa5d76..b84efb6c 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -35,7 +35,7 @@ namespace slskd public bool PendingShareRescan { get; init; } public ServerState Server { get; init; } = new ServerState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); - public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); + public ShareState Shares { get; init; } = new ShareState(); public string[] Rooms { get; init; } = Array.Empty(); public User[] Users { get; init; } = Array.Empty(); } @@ -76,43 +76,49 @@ namespace slskd } /// - /// Share cache state. + /// Share state. /// - public record SharedFileCacheState + public record ShareState { - /// - /// Gets a value indicating whether the cache is being filled. - /// - public bool Filling { get; init; } = false; + public ShareCacheState Cache { get; init; } = new ShareCacheState(); + public bool ScanPending { get; init; } - /// - /// Gets a value indicating whether the cache is filled. - /// - public bool Filled { get; init; } = false; + public record ShareCacheState + { + /// + /// 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 a value indicating whether the cache is filled. + /// + public bool Filled { get; init; } = false; - /// - /// Gets the current fill progress. - /// - public double FillProgress { get; init; } + /// + /// Gets a value indicating whether the cache is faulted. + /// + public bool Faulted { get; init; } = false; - /// - /// Gets the number of cached directories. - /// - public int Directories { get; init; } + /// + /// Gets the current fill progress. + /// + public double FillProgress { get; init; } - /// - /// Gets the number of cached files. - /// - public int Files { get; init; } + /// + /// Gets the number of cached directories. + /// + public int Directories { get; init; } - /// - /// Gets the number of directories excluded by filters. - /// - public int ExcludedDirectories { get; init; } + /// + /// Gets the number of cached files. + /// + public int Files { get; init; } + + /// + /// Gets the number of directories excluded by filters. + /// + public int ExcludedDirectories { get; init; } + } } } \ No newline at end of file -- cgit v1.2.3 From b5557cc484f7a24b3a6f35d4e3398ffeddb4e371 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 14:41:36 -0500 Subject: rename once again --- src/slskd/Shares/SharedFileCache.cs | 473 +++++++++++++++++++++++++++++++++++ src/slskd/Shares/SharesCache.cs | 482 ------------------------------------ 2 files changed, 473 insertions(+), 482 deletions(-) create mode 100644 src/slskd/Shares/SharedFileCache.cs delete mode 100644 src/slskd/Shares/SharesCache.cs (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs new file mode 100644 index 00000000..1a465903 --- /dev/null +++ b/src/slskd/Shares/SharedFileCache.cs @@ -0,0 +1,473 @@ +// +// 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.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Serilog; + using Soulseek; + + /// + /// Shared file cache. + /// + public interface ISharedFileCache + { + /// + /// Gets the cache state monitor. + /// + IStateMonitor StateMonitor { get; } + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + IEnumerable Browse(); + + /// + /// Scans the configured shares and fills the cache. + /// + /// + /// Initiates the scan, then yields + /// + /// The list of shares from which to fill the cache. + /// The operation context. + Task FillAsync(IEnumerable shares); + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + Directory List(string directory); + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename); + + /// + /// Searches the cache for the specified and returns the matching files. + /// + /// The query for which to search. + /// The matching files. + Task> SearchAsync(SearchQuery query); + } + + /// + /// Shared file cache. + /// + public class SharedFileCache : ISharedFileCache + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public SharedFileCache( + IOptionsMonitor optionsMonitor, + ISoulseekFileFactory soulseekFileFactory = null) + { + OptionsMonitor = optionsMonitor; + SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); + } + + /// + /// Gets the cache state monitor. + /// + public IStateMonitor StateMonitor => State; + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private HashSet MaskedDirectories { get; set; } + private Dictionary MaskedFiles { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private List Shares { get; set; } + private ISoulseekFileFactory SoulseekFileFactory { get; } + private SqliteConnection SQLite { get; set; } + private IManagedState State { get; } = new ManagedState(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + + /// + /// Returns the contents of the cache. + /// + /// The contents of the cache. + public IEnumerable Browse() + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; + } + + 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 MaskedDirectories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = MaskedFiles + .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.OrderBy(f => f.Name); + } + + /// + /// Scans the configured shares and fills the cache. + /// + /// The list of shares from which to fill the cache. + /// The operation context. + public async Task FillAsync(IEnumerable shares) + { + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. + if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + try + { + State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + await Task.Yield(); + + ResetCache(); + + var sw = new Stopwatch(); + var swSnapshot = 0L; + sw.Start(); + + Shares = shares.ToList(); + + if (!Shares.Any()) + { + Log.Warning("Aborting shared file scan; no shares configured."); + } + + Shares.ForEach(s => Log.Debug(s.ToJson())); + + Shares.Where(s => !s.IsExcluded).ToList() + .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); + + Shares.Where(s => s.IsExcluded).ToList() + .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); + + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; + + var unmaskedDirectories = Shares + .SelectMany(share => + { + try + { + return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + return Array.Empty(); + } + }) + .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) + .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. + .ToHashSet(); // remove duplicates (in case shares overlap) + + var excludedDirectories = unmaskedDirectories + .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + + unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); + Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + var filters = OptionsMonitor.CurrentValue.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)); + + var files = new Dictionary(); + var maskedDirectories = new HashSet(); + var current = 0; + var filtered = 0; + + foreach (var directory in unmaskedDirectories) + { + var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + + maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); + + // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized + // filename and with a value of a Soulseek.File object + try + { + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) + .ToDictionary(file => file.Filename, file => file); + + // 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 (filters.Any(filter => filter.IsMatch(file.Key))) + { + filtered++; + continue; + } + + if (files.ContainsKey(file.Key)) + { + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); + } + + files[file.Key] = file.Value; + } + } + catch (Exception ex) + { + Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); + Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); + } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); + } + + Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + foreach (var file in files) + { + InsertFilename(file.Key); + } + + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + MaskedDirectories = maskedDirectories; + MaskedFiles = files; + + State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; + } + finally + { + SyncRoot.Release(); + } + } + + /// + /// Returns the contents of the specified . + /// + /// The directory for which the contents are to be listed. + /// The contents of the directory. + public Directory List(string directory) + { + if (!State.CurrentValue.Filled) + { + if (State.CurrentValue.Filling) + { + return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); + } + + return null; + } + + var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => + { + var f = kvp.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), + f.Size, + f.Extension, + f.Attributes); + }); + + return new Directory(directory, files); + } + + /// + /// Substitutes the mask in the specified with the original path, if the mask is tracked + /// by the cache. + /// + /// The fully qualified filename to unmask. + /// The unmasked filename. + public string Resolve(string filename) + { + filename = filename.ToLocalOSPath(); + var resolved = filename; + + // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a + // file. split the requested filename so we can examine the first two segments + var parts = filename.Split(new[] { '/', '\\' }); + + if (parts.Length < 2) + { + Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); + return resolved; + } + + // find the share with a matching mask and alias/local directory + var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); + + if (share == default) + { + Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); + return resolved; + } + + resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); + + if (resolved == filename) + { + Log.Warning($"Failed to resolve shared file {filename}"); + } + + Log.Debug($"Resolved requested shared file {filename} to {resolved}"); + return resolved; + } + + /// + /// 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) + { + if (!State.CurrentValue.Filled) + { + return Enumerable.Empty(); + } + + string Clean(string str) => str.Replace("/", " ") + .Replace("\\", " ") + .Replace(":", " ") + .Replace("\"", " ") + .Replace("'", "''"); + + var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); + var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); + + var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; + var results = new List(); + + try + { + using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + using var cmd = new SqliteCommand(sql, conn); + await conn.OpenAsync(); + + var reader = await cmd.ExecuteReaderAsync(); + + while (reader.Read()) + { + results.Add(reader.GetString(0)); + } + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); + return Enumerable.Empty(); + } + + try + { + return results.Select(r => MaskedFiles[r]).ToList(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); + return Enumerable.Empty(); + } + } + + private void CreateTable() + { + if (SQLite != null) + { + SQLite.Dispose(); + } + + SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); + SQLite.Open(); + + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; 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)", SQLite); + cmd.Parameters.AddWithValue("filename", filename); + cmd.ExecuteNonQuery(); + } + + private void ResetCache() + { + CreateTable(); + MaskedDirectories = new HashSet(); + MaskedFiles = new Dictionary(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); + } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/SharesCache.cs b/src/slskd/Shares/SharesCache.cs deleted file mode 100644 index 22e72c77..00000000 --- a/src/slskd/Shares/SharesCache.cs +++ /dev/null @@ -1,482 +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.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Data.Sqlite; - using Serilog; - using Soulseek; - - /// - /// Shared file cache. - /// - public interface IShareCache - { - /// - /// Gets the list of shares. - /// - public List Shares { get; } // todo: remove this - - /// - /// Gets the cache state monitor. - /// - IStateMonitor StateMonitor { 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(); // TODO: accept a list of shares here - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - Directory List(string directory); - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename); - - /// - /// Searches the cache for the specified and returns the matching files. - /// - /// The query for which to search. - /// The matching files. - Task> SearchAsync(SearchQuery query); - } - - /// - /// Shared file cache. - /// - public class ShareCache : IShareCache - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public ShareCache( - IOptionsMonitor optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) - { - OptionsMonitor = optionsMonitor; - SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); - } - - /// - /// Gets the cache state monitor. - /// - public IStateMonitor StateMonitor => State; - - /// - /// Gets the list of shares. - /// - public List Shares { get; private set; } - - private IManagedState State { get; } = new ManagedState(); - private ILogger Log { get; } = Serilog.Log.ForContext(); - private HashSet MaskedDirectories { get; set; } - private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } - private SqliteConnection SQLite { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private ISoulseekFileFactory SoulseekFileFactory { get; } - - /// - /// Returns the contents of the cache. - /// - /// The contents of the cache. - public IEnumerable Browse() - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new[] { new Directory("Scanning shares, please check back in a few minutes.") }; - } - - 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 MaskedDirectories) - { - directories.TryAdd(directory, new Directory(directory)); - } - - var groups = MaskedFiles - .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.OrderBy(f => f.Name); - } - - /// - /// Scans the configured shares and fills the cache. - /// - /// The operation context. - public async Task FillAsync() - { - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. - if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) - { - Log.Warning("Shared file scan rejected; scan is already in progress."); - throw new ShareScanInProgressException("Shared files are already being scanned."); - } - - try - { - State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); - Log.Debug("Starting shared file scan"); - - await Task.Yield(); - - ResetCache(); - - var sw = new Stopwatch(); - var swSnapshot = 0L; - sw.Start(); - - Shares = OptionsMonitor.CurrentValue.Directories.Shared - .Select(share => share.TrimEnd('/', '\\')) - .ToHashSet() // remove duplicates - .Select(share => new Share(share)) // convert to Shares - .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent - .ToList(); - - if (!Shares.Any()) - { - Log.Warning("Aborting shared file scan; no shares configured."); - } - - Shares.ForEach(s => Log.Debug(s.ToJson())); - - Shares.Where(s => !s.IsExcluded).ToList() - .ForEach(s => Log.Information("Sharing {Local} as {Remote}", s.LocalPath, s.RemotePath)); - - Shares.Where(s => s.IsExcluded).ToList() - .ForEach(s => Log.Information("Excluding {Local}", s.LocalPath)); - - Log.Debug("Enumerating shared directories"); - swSnapshot = sw.ElapsedMilliseconds; - - var unmaskedDirectories = Shares - .SelectMany(share => - { - try - { - return System.IO.Directory.GetDirectories(share.LocalPath, "*", SearchOption.AllDirectories); - } - catch (Exception ex) - { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) - - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); - - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); - - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - - var files = new Dictionary(); - var maskedDirectories = new HashSet(); - var current = 0; - var filtered = 0; - - foreach (var directory in unmaskedDirectories) - { - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); - - maskedDirectories.Add(directory.ReplaceFirst(share.LocalPath, share.RemotePath)); - - // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized - // filename and with a value of a Soulseek.File object - try - { - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) - .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath))) - .ToDictionary(file => file.Filename, file => file); - - // 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 (filters.Any(filter => filter.IsMatch(file.Key))) - { - filtered++; - continue; - } - - if (files.ContainsKey(file.Key)) - { - Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); - } - - files[file.Key] = file.Value; - } - } - catch (Exception ex) - { - Log.Debug("Failed to scan files in directory {Directory}: {Exception}", directory, ex); - Log.Warning("Failed to scan files in directory {Directory}: {Message}", directory, ex.Message); - } - - current++; - State.SetValue(state => state with { FillProgress = current / (double)unmaskedDirectories.Count, Files = files.Count }); - } - - Log.Debug("Directory scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms. Populating filename database", files.Count, filtered, sw.ElapsedMilliseconds - swSnapshot); - swSnapshot = sw.ElapsedMilliseconds; - - // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite - foreach (var file in files) - { - InsertFilename(file.Key); - } - - Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); - - MaskedDirectories = maskedDirectories; - MaskedFiles = files; - - State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); - Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); - } - catch (Exception ex) - { - State.SetValue(state => state with { Filling = false, Faulted = true, Filled = false, FillProgress = 0 }); - Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); - throw; - } - finally - { - SyncRoot.Release(); - } - } - - /// - /// Returns the contents of the specified . - /// - /// The directory for which the contents are to be listed. - /// The contents of the directory. - public Directory List(string directory) - { - if (!State.CurrentValue.Filled) - { - if (State.CurrentValue.Filling) - { - return new Directory(directory, new[] { new File(1, "Scanning shares, please check back in a few minutes.", 0, string.Empty) }); - } - - return null; - } - - var files = MaskedFiles.Where(f => f.Key.StartsWith(directory)).Select(kvp => - { - var f = kvp.Value; - return new File( - f.Code, - Path.GetFileName(f.Filename), - f.Size, - f.Extension, - f.Attributes); - }); - - return new Directory(directory, files); - } - - /// - /// Substitutes the mask in the specified with the original path, if the mask is tracked - /// by the cache. - /// - /// The fully qualified filename to unmask. - /// The unmasked filename. - public string Resolve(string filename) - { - filename = filename.ToLocalOSPath(); - var resolved = filename; - - // a well-formed path will consist of a mask, either an alias or a local directory, and a fully qualified path to a - // file. split the requested filename so we can examine the first two segments - var parts = filename.Split(new[] { '/', '\\' }); - - if (parts.Length < 2) - { - Log.Warning($"Failed to resolve shared file {filename}; filename is badly formed"); - return resolved; - } - - // find the share with a matching mask and alias/local directory - var share = Shares.FirstOrDefault(share => share.Mask == parts[0] && share.Alias == parts[1]); - - if (share == default) - { - Log.Warning("Failed to resolve shared file {Filename}; unable to resolve share from mask '{Mask}' and alias '{Alias}'", filename, parts[0], parts[1]); - return resolved; - } - - resolved = resolved.ReplaceFirst(share.RemotePath, share.LocalPath); - - if (resolved == filename) - { - Log.Warning($"Failed to resolve shared file {filename}"); - } - - Log.Debug($"Resolved requested shared file {filename} to {resolved}"); - return resolved; - } - - /// - /// 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) - { - if (!State.CurrentValue.Filled) - { - return Enumerable.Empty(); - } - - string Clean(string str) => str.Replace("/", " ") - .Replace("\\", " ") - .Replace(":", " ") - .Replace("\"", " ") - .Replace("'", "''"); - - var match = string.Join(" AND ", query.Terms.Select(token => $"\"{Clean(token)}\"")); - var exclusions = string.Join(" OR ", query.Exclusions.Select(exclusion => $"\"{Clean(exclusion)}\"")); - - var sql = $"SELECT * FROM cache WHERE cache MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}'"; - var results = new List(); - - try - { - using var conn = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - using var cmd = new SqliteCommand(sql, conn); - await conn.OpenAsync(); - - var reader = await cmd.ExecuteReaderAsync(); - - while (reader.Read()) - { - results.Add(reader.GetString(0)); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to execute shared file query '{Query}': {Message}", query, ex.Message); - return Enumerable.Empty(); - } - - try - { - return results.Select(r => MaskedFiles[r]).ToList(); - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to map shared file result: {Message}", ex.Message); - return Enumerable.Empty(); - } - } - - private void CreateTable() - { - if (SQLite != null) - { - SQLite.Dispose(); - } - - SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); - SQLite.Open(); - - using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; 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)", SQLite); - cmd.Parameters.AddWithValue("filename", filename); - cmd.ExecuteNonQuery(); - } - - private void ResetCache() - { - CreateTable(); - MaskedDirectories = new HashSet(); - MaskedFiles = new Dictionary(); - State.SetValue(state => state with { Directories = 0, Files = 0 }); - } - } -} \ No newline at end of file -- cgit v1.2.3 From 5b7744f92c8b3913844942d2d44f90cdbc65cb4e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:11:24 -0500 Subject: rename one final time --- src/slskd/Shares/SharedFileCache.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 1a465903..b06f7be6 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -40,7 +40,7 @@ namespace slskd.Shares /// /// Gets the cache state monitor. /// - IStateMonitor StateMonitor { get; } + IStateMonitor StateMonitor { get; } /// /// Returns the contents of the cache. @@ -51,9 +51,7 @@ namespace slskd.Shares /// /// Scans the configured shares and fills the cache. /// - /// - /// Initiates the scan, then yields - /// + /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. /// The list of shares from which to fill the cache. /// The operation context. Task FillAsync(IEnumerable shares); @@ -102,7 +100,7 @@ namespace slskd.Shares /// /// Gets the cache state monitor. /// - public IStateMonitor StateMonitor => State; + public IStateMonitor StateMonitor => State; private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } @@ -111,7 +109,7 @@ namespace slskd.Shares private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private SqliteConnection SQLite { get; set; } - private IManagedState State { get; } = new ManagedState(); + private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); /// -- cgit v1.2.3 From 1da4e1f198aff7f5ad7f61381d481acc8dc7119c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:56:34 -0500 Subject: pass filters to cache --- src/slskd/Shares/ShareService.cs | 22 +++++++++++++++++----- src/slskd/Shares/SharedFileCache.cs | 19 ++++++++----------- 2 files changed, 25 insertions(+), 16 deletions(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 7c08ad13..9cae0d42 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -21,6 +21,7 @@ namespace slskd.Shares { using System.Collections.Generic; using System.Linq; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Soulseek; @@ -39,10 +40,7 @@ namespace slskd.Shares IOptionsMonitor optionsMonitor, ISharedFileCache sharedFileCache = null) { - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); - - Cache = sharedFileCache ?? new SharedFileCache(OptionsMonitor); + Cache = sharedFileCache ?? new SharedFileCache(); Cache.StateMonitor.OnChange(cacheState => { var (previous, current) = cacheState; @@ -58,6 +56,11 @@ namespace slskd.Shares Files = current.Files, }); }); + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); } /// @@ -65,6 +68,8 @@ namespace slskd.Shares /// public IReadOnlyList Shares => SharesList.AsReadOnly(); + public IReadOnlyList FilterRegexes => FilterRegexList.AsReadOnly(); + /// /// Gets the state monitor for the service. /// @@ -76,6 +81,7 @@ namespace slskd.Shares private List SharesList { get; set; } = new List(); private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private List FilterRegexList { get; set; } = new List(); /// /// Returns the entire contents of the share. @@ -127,7 +133,7 @@ namespace slskd.Shares /// The operation context. /// Thrown when a scan is already in progress. public Task StartScanAsync() - => Cache.FillAsync(Shares); + => Cache.FillAsync(Shares, FilterRegexes); private void Configure(Options options) { @@ -149,7 +155,13 @@ namespace slskd.Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); + var regexes = options.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)) + .ToList(); + SharesList = shares; + FilterRegexList = regexes; + State.SetValue(state => state with { ScanPending = true }); LastOptionsHash = optionsHash; diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index b06f7be6..cb1ccdee 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -53,8 +53,9 @@ namespace slskd.Shares /// /// Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete. /// The list of shares from which to fill the cache. + /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - Task FillAsync(IEnumerable shares); + Task FillAsync(IEnumerable shares, IEnumerable filters); /// /// Returns the contents of the specified . @@ -87,13 +88,9 @@ namespace slskd.Shares /// /// Initializes a new instance of the class. /// - /// /// - public SharedFileCache( - IOptionsMonitor optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null) { - OptionsMonitor = optionsMonitor; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -105,7 +102,6 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext(); private HashSet MaskedDirectories { get; set; } private Dictionary MaskedFiles { get; set; } - private IOptionsMonitor OptionsMonitor { get; set; } private List Shares { get; set; } private ISoulseekFileFactory SoulseekFileFactory { get; } private SqliteConnection SQLite { get; set; } @@ -118,6 +114,7 @@ namespace slskd.Shares /// The contents of the cache. public IEnumerable Browse() { + Console.WriteLine(State.ToJson()); if (!State.CurrentValue.Filled) { if (State.CurrentValue.Filling) @@ -167,9 +164,12 @@ namespace slskd.Shares /// Scans the configured shares and fills the cache. /// /// The list of shares from which to fill the cache. + /// The list of regular expressions used to exclude files or paths from scanning. /// The operation context. - public async Task FillAsync(IEnumerable shares) + public async Task FillAsync(IEnumerable shares, IEnumerable filters) { + Console.WriteLine($"Filling: {shares.ToJson()}"); + // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) { @@ -234,9 +234,6 @@ namespace slskd.Shares Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - var files = new Dictionary(); var maskedDirectories = new HashSet(); var current = 0; -- cgit v1.2.3 From f3b2e02168e77ea8cc9bc68d151aba56e279f9c4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:56:46 -0500 Subject: show empty row in tables --- src/slskd/Shares/SharedFileCache.cs | 4 --- .../src/components/System/Shares/ExclusionTable.js | 20 +++++++++------ src/web/src/components/System/Shares/ShareTable.js | 29 ++++++++++++++-------- src/web/src/components/System/Shares/index.js | 7 ------ 4 files changed, 32 insertions(+), 28 deletions(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index cb1ccdee..8ac52462 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -16,7 +16,6 @@ // using System.IO; -using Microsoft.Extensions.Options; namespace slskd.Shares { @@ -114,7 +113,6 @@ namespace slskd.Shares /// The contents of the cache. public IEnumerable Browse() { - Console.WriteLine(State.ToJson()); if (!State.CurrentValue.Filled) { if (State.CurrentValue.Filling) @@ -168,8 +166,6 @@ namespace slskd.Shares /// The operation context. public async Task FillAsync(IEnumerable shares, IEnumerable filters) { - Console.WriteLine($"Filling: {shares.ToJson()}"); - // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) { diff --git a/src/web/src/components/System/Shares/ExclusionTable.js b/src/web/src/components/System/Shares/ExclusionTable.js index 90ee2eff..5e010e30 100644 --- a/src/web/src/components/System/Shares/ExclusionTable.js +++ b/src/web/src/components/System/Shares/ExclusionTable.js @@ -5,11 +5,9 @@ import { Icon, } from 'semantic-ui-react'; -const ExclusionTable = ({ exclusions = [] } = {}) => { - if (exclusions.length === 0) { - return <>; - } +import { Switch } from '../../Shared'; +const ExclusionTable = ({ exclusions = [] } = {}) => { return ( @@ -18,9 +16,17 @@ const ExclusionTable = ({ exclusions = [] } = {}) => { - {exclusions.map((share, index) => ( - {share.localPath} - ))} + + + No exclusions configured + + } + > + {exclusions.map((share, index) => ( + {share.localPath} + ))} +
); diff --git a/src/web/src/components/System/Shares/ShareTable.js b/src/web/src/components/System/Shares/ShareTable.js index ecd83e3f..d264fc8f 100644 --- a/src/web/src/components/System/Shares/ShareTable.js +++ b/src/web/src/components/System/Shares/ShareTable.js @@ -6,6 +6,7 @@ import { } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; +import { Switch } from '../../Shared'; const ShareTable = ({ shares, onClick }) => { return ( @@ -20,16 +21,24 @@ const ShareTable = ({ shares, onClick }) => { - {shares.map((share, index) => ( - onClick(share)}> - - {share.localPath} - - {share.directories} - {share.files} - {share.alias} - {share.remotePath} - ))} + + + No shares configured + + } + > + {shares.map((share, index) => ( + onClick(share)}> + + {share.localPath} + + {share.directories} + {share.files} + {share.alias} + {share.remotePath} + ))} + ); diff --git a/src/web/src/components/System/Shares/index.js b/src/web/src/components/System/Shares/index.js index 53018b45..5fe59cb2 100644 --- a/src/web/src/components/System/Shares/index.js +++ b/src/web/src/components/System/Shares/index.js @@ -4,7 +4,6 @@ import { toast } from 'react-toastify'; import * as sharesLib from '../../../lib/shares'; import { LoaderSegment, - PlaceholderSegment, ShrinkableButton, Switch, } from '../../Shared'; @@ -65,12 +64,6 @@ const Index = ({ state = {} } = {}) => { } - empty={shared.length === 0 && - } > -- cgit v1.2.3 From 2efd8278ce9a5a895fe0c75bd95080ecc386163b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Jun 2022 07:28:10 -0500 Subject: differentiate configured shares vs cached shares --- src/slskd/Shares/API/Controllers/SharesController.cs | 2 +- src/slskd/Shares/IShareService.cs | 5 +++++ src/slskd/Shares/ShareService.cs | 14 +++++++++++--- src/slskd/Shares/SharedFileCache.cs | 20 ++++++++++++++++++-- src/slskd/State.cs | 9 +++++++-- 5 files changed, 42 insertions(+), 8 deletions(-) (limited to 'src/slskd/Shares/SharedFileCache.cs') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 8ae8551f..41178bac 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -59,7 +59,7 @@ namespace slskd.Shares.API { var browse = await Shares.BrowseAsync(); - var summary = Shares.Shares.Select(share => + var summary = Shares.CachedShares.Select(share => { var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); var fileCount = directories.Aggregate(seed: 0, (sum, directory) => diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 16f1a890..fd88f2b0 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -26,6 +26,11 @@ namespace slskd.Shares ///
public interface IShareService { + /// + /// Gets the list of shares stored in the cache. + /// + IReadOnlyList CachedShares { get; } + /// /// Gets the list of configured shares. /// diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 9cae0d42..ead96d10 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -55,6 +55,11 @@ namespace slskd.Shares Directories = current.Directories, Files = current.Files, }); + + if (previous.Filling && !current.Filling) + { + CachedShares = current.Shares.ToList().AsReadOnly(); + } }); OptionsMonitor = optionsMonitor; @@ -68,7 +73,10 @@ namespace slskd.Shares ///
public IReadOnlyList Shares => SharesList.AsReadOnly(); - public IReadOnlyList FilterRegexes => FilterRegexList.AsReadOnly(); + /// + /// Gets the list of shares stored in the cache. + /// + public IReadOnlyList CachedShares { get; private set; } = new List().AsReadOnly(); /// /// Gets the state monitor for the service. @@ -81,7 +89,7 @@ namespace slskd.Shares private List SharesList { get; set; } = new List(); private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private List FilterRegexList { get; set; } = new List(); + private List FilterRegexes { get; set; } = new List(); /// /// Returns the entire contents of the share. @@ -160,7 +168,7 @@ namespace slskd.Shares .ToList(); SharesList = shares; - FilterRegexList = regexes; + FilterRegexes = regexes; State.SetValue(state => state with { ScanPending = true }); diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index 8ac52462..6b7a3ca3 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -175,7 +175,14 @@ namespace slskd.Shares try { - State.SetValue(state => state with { Filling = true, Filled = false, FillProgress = 0 }); + State.SetValue(state => state with + { + Filling = true, + Filled = false, + FillProgress = 0, + Shares = Enumerable.Empty().ToList().AsReadOnly(), + }); + Log.Debug("Starting shared file scan"); await Task.Yield(); @@ -291,7 +298,16 @@ namespace slskd.Shares MaskedDirectories = maskedDirectories; MaskedFiles = files; - State.SetValue(state => state with { Filling = false, Faulted = false, Filled = true, FillProgress = 1, Directories = MaskedDirectories.Count, Files = MaskedFiles.Count }); + State.SetValue(state => state with { + Filling = false, + Faulted = false, + Filled = true, + FillProgress = 1, + Directories = MaskedDirectories.Count, + Files = MaskedFiles.Count, + Shares = shares.ToList().AsReadOnly(), + }); + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {unmaskedDirectories.Count}, Files: {files.Count}"); } catch (Exception ex) diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 407aeb9e..10ed80f6 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -21,6 +21,7 @@ namespace slskd using System.Collections.Generic; using System.Net; using System.Text.Json.Serialization; + using slskd.Shares; using slskd.Users; using Soulseek; @@ -32,7 +33,6 @@ namespace slskd public VersionState Version { get; init; } = new VersionState(); public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } - public bool PendingShareRescan { get; init; } public ServerState Server { get; init; } = new ServerState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); public ShareState Shares { get; init; } = new ShareState(); @@ -69,7 +69,7 @@ namespace slskd public string BranchRoot { get; init; } public bool CanAcceptChildren { get; init; } public int ChildLimit { get; init; } - public IReadOnlyCollection Children { get; init; } + public IReadOnlyCollection Children { get; init; } = new List().AsReadOnly(); public bool HasParent { get; init; } public bool IsBranchRoot { get; init; } public string Parent { get; init; } @@ -124,5 +124,10 @@ namespace slskd /// Gets the number of directories excluded by filters. /// public int ExcludedDirectories { get; init; } + + /// + /// Gets the list of shares stored in the cache. + /// + public IReadOnlyCollection Shares { get; init; } = new List().AsReadOnly(); } } \ No newline at end of file -- cgit v1.2.3