From 6bf6f6c1aa199f0a9878c7819606bed3cbccf312 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:29:38 -0500 Subject: add ShareService to DI --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 40e6e72d..4643daa0 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -454,6 +454,7 @@ namespace slskd services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- 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/Program.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 f6aad956a83155e8e89add7e24804d6b99ec4119 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 09:38:17 -0500 Subject: light refactoring --- src/slskd/Application.cs | 44 +++++++++++++++++++++++---------------- src/slskd/Program.cs | 2 +- src/slskd/Search/SearchService.cs | 15 ++++++++----- src/slskd/Shares/IShareService.cs | 4 ++-- src/slskd/Shares/ShareService.cs | 5 +++-- src/slskd/State.cs | 1 + 6 files changed, 43 insertions(+), 28 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 110b1d4f..880e8f74 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -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.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -509,9 +509,7 @@ namespace slskd private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) { - // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] - // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] - // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); + // no-op. this is really verbose, use for troubleshooting. } private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args) @@ -555,7 +553,7 @@ namespace slskd /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. private async Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = await Shares.ListAsync(directory); + var dir = await Shares.ListDirectoryAsync(directory); return dir; } @@ -577,15 +575,25 @@ namespace slskd private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; - var localFilename = (await Shares.ResolveAsync(filename)).ToLocalOSPath(); - - var fileInfo = new FileInfo(localFilename); + string localFilename; + FileInfo fileInfo = default; Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); - if (!fileInfo.Exists) + try + { + localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); + + fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + throw new NotFoundException(); + } + } + catch (NotFoundException) { - Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); throw new DownloadEnqueueException($"File not shared."); } @@ -840,7 +848,7 @@ namespace slskd { var (previous, current) = state; - if (!previous.Cache.Filling && current.Cache.Filling) + if (!previous.Scanning && current.Scanning) { SharesRefreshStarted = DateTime.UtcNow; @@ -848,33 +856,33 @@ namespace slskd Log.Information("Scanning shares"); } - var lastProgress = Math.Round(previous.Cache.FillProgress * 100); - var currentProgress = Math.Round(current.Cache.FillProgress * 100); + var lastProgress = Math.Round(previous.ScanProgress * 100); + var currentProgress = Math.Round(current.ScanProgress * 100); if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { State.SetValue(s => s with { Shares = current }); - Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Cache.Files); + Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); } - if (previous.Cache.Filling && !current.Cache.Filling) + if (previous.Scanning && !current.Scanning) { State.SetValue(s => s with { Shares = current }); - if (current.Cache.Faulted) + if (current.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.Cache.Directories, current.Cache.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); SharesRefreshStarted = default; if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) { - _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Cache.Directories, State.CurrentValue.Shares.Cache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 1a5d2a28..df1fb55c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -682,7 +682,7 @@ namespace slskd } // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused. - // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next + // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next // middleware app.Use(async (context, next) => { diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 949a7088..f077e76b 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -162,18 +162,23 @@ namespace slskd.Search /// /// The search to delete. /// The operation context. - public async Task DeleteAsync(Search search) + public Task DeleteAsync(Search search) { if (search == default) { throw new ArgumentNullException(nameof(search)); } - using var context = ContextFactory.CreateDbContext(); - context.Searches.Remove(search); - await context.SaveChangesAsync(); + return DoDeleteAsync(search); - await SearchHub.BroadcastDeleteAsync(search); + async Task DoDeleteAsync(Search search) + { + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + + await SearchHub.BroadcastDeleteAsync(search); + } } /// diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index cc91ba07..16f1a890 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -47,7 +47,7 @@ namespace slskd.Shares /// /// The directory for which the contents are to be listed. /// The contents of the directory. - Task ListAsync(string directory); + Task ListDirectoryAsync(string directory); /// /// Resolves the local filename of the specified , if the mask is associated with a @@ -58,7 +58,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - Task ResolveAsync(string remoteFilename); + Task ResolveFilenameAsync(string remoteFilename); /// /// Searches the cache for the specified and returns the matching files. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index d99c5f6a..7c08ad13 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -52,6 +52,7 @@ namespace slskd.Shares // scan is pending if faulted, or if state DIDN'T just transition from filling to not filling AND a scan was already pending ScanPending = current.Faulted || (!(previous.Filling && !current.Filling) && state.ScanPending), Scanning = current.Filling, + Faulted = current.Faulted, ScanProgress = current.FillProgress, Directories = current.Directories, Files = current.Files, @@ -88,7 +89,7 @@ namespace slskd.Shares /// /// The directory for which the contents are to be listed. /// The contents of the directory. - public Task ListAsync(string directory) + public Task ListDirectoryAsync(string directory) => Task.FromResult(Cache.List(directory)); /// @@ -100,7 +101,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - public Task ResolveAsync(string remoteFilename) + public Task ResolveFilenameAsync(string remoteFilename) { var resolvedFilename = Cache.Resolve(remoteFilename); diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 863c59da..407aeb9e 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -82,6 +82,7 @@ namespace slskd { public bool ScanPending { get; init; } public bool Scanning { get; init; } + public bool Faulted { get; init; } public double ScanProgress { get; init; } public int Directories { get; init; } public int Files { get; init; } -- cgit v1.2.3