From 28ab70b9aeb3a0060e3ca76b4faae586e724fd74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 25 May 2022 23:29:22 -0500 Subject: rough in SharesController --- .../Shares/API/Controllers/SharesController.cs | 90 ++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/slskd/Shares/API/Controllers/SharesController.cs (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs new file mode 100644 index 00000000..06a02de3 --- /dev/null +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -0,0 +1,90 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares.API +{ + using System; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Shares. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class SharesController : ControllerBase + { + public SharesController(IShareService shareService) + { + Shares = shareService; + } + + private IShareService Shares { get; } + + [HttpGet("")] + public IActionResult List() + { + return Ok(Shares.Cache.Shares); + } + + [HttpGet("{id}")] + public IActionResult Get(string id) + { + var share = Ok(Shares.Cache.Shares.FirstOrDefault(share => share.Id == id)); + + if (share == default) + { + return NotFound(); + } + + return share; + } + + [HttpGet("contents")] + public IActionResult BrowseAll() + { + return Ok(Shares.Cache.Browse()); + } + + [HttpGet("{id}/contents")] + public IActionResult BrowseShare(string id) + { + var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); + + if (share == default) + { + return NotFound(); + } + + var browse = Shares.Cache.Browse(); + + foreach (var dir in browse) + { + Console.WriteLine($"{dir.Name} ?? ${share.RemotePath}"); + } + + var contents = Shares.Cache.Browse().Where(directory => directory.Name.StartsWith(share.RemotePath)); + + return Ok(contents); + } + } +} -- cgit v1.2.3 From 388792b916fdba7b0200d04e7d12ca8f22e33fcc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 26 May 2022 19:07:29 -0500 Subject: move rescan share function, implement share summary --- src/slskd/Application.cs | 7 ---- .../Core/API/Controllers/ApplicationController.cs | 15 ------- .../Shares/API/Controllers/SharesController.cs | 48 +++++++++++++++++++++- src/slskd/Shares/API/DTO/SummarizedShare.cs | 32 +++++++++++++++ 4 files changed, 78 insertions(+), 24 deletions(-) create mode 100644 src/slskd/Shares/API/DTO/SummarizedShare.cs (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1064e56a..c2a8632b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -48,7 +48,6 @@ namespace slskd public interface IApplication : IHostedService { public Task CheckVersionAsync(); - public Task RescanSharesAsync(); public void CollectGarbage(); } @@ -226,12 +225,6 @@ namespace slskd } } - /// - /// Re-scans shared directories. - /// - /// The operation context. - public Task RescanSharesAsync() => SharedFileCache.FillAsync(); - async Task IHostedService.StartAsync(CancellationToken cancellationToken) { Log.Information("Configuring client"); diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index cd03d96f..3cf3c0a3 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -136,20 +136,5 @@ namespace slskd.Core.API return Ok(); } - - [HttpPut] - [Route("shares")] - [Authorize] - public IActionResult RescanSharesAsync() - { - if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) - { - return Conflict("A share scan is already in progress."); - } - - _ = Application.RescanSharesAsync(); - - return Ok(); - } } } diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 06a02de3..c569a150 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -33,17 +33,46 @@ namespace slskd.Shares.API [Consumes("application/json")] public class SharesController : ControllerBase { - public SharesController(IShareService shareService) + public SharesController( + IShareService shareService, + IStateMonitor applicationStateMonitor) { Shares = shareService; + ApplicationStateMonitor = applicationStateMonitor; } private IShareService Shares { get; } + private IStateMonitor ApplicationStateMonitor { get; } [HttpGet("")] public IActionResult List() { - return Ok(Shares.Cache.Shares); + var browse = Shares.Cache.Browse(); + + var summary = Shares.Cache.Shares.Select(share => + { + var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); + var fileCount = directories.Aggregate(seed: 0, (sum, directory) => + { + sum += directory.FileCount; + return sum; + }); + + return new SummarizedShare() + { + Id = share.Id, + Alias = share.Alias, + IsExcluded = share.IsExcluded, + LocalPath = share.LocalPath, + Mask = share.Mask, + Raw = share.Raw, + RemotePath = share.RemotePath, + Directories = directories.Count(), + Files = fileCount, + }; + }); + + return Ok(summary); } [HttpGet("{id}")] @@ -86,5 +115,20 @@ namespace slskd.Shares.API return Ok(contents); } + + [HttpPut] + [Route("")] + [Authorize] + public IActionResult RescanSharesAsync() + { + if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) + { + return Conflict("A share scan is already in progress."); + } + + _ = Shares.Cache.FillAsync(); + + return Ok(); + } } } diff --git a/src/slskd/Shares/API/DTO/SummarizedShare.cs b/src/slskd/Shares/API/DTO/SummarizedShare.cs new file mode 100644 index 00000000..a1d6ed7b --- /dev/null +++ b/src/slskd/Shares/API/DTO/SummarizedShare.cs @@ -0,0 +1,32 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Shares +{ + public record SummarizedShare + { + public string Id { get; init; } + public string Alias { get; init; } + public bool IsExcluded { get; init; } + public string LocalPath { get; init; } + public string Mask { get; init; } + public string Raw { get; init; } + public string RemotePath { get; init; } + public int Directories { get; init; } + public int Files { get; init; } + } +} \ No newline at end of file -- cgit v1.2.3 From c049c50f778c6129ead1d91e2bc3d2c88ba815e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 27 May 2022 00:58:57 -0500 Subject: tidy up --- src/slskd/Shares/API/Controllers/SharesController.cs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index c569a150..d6a31c4e 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -104,14 +104,8 @@ namespace slskd.Shares.API return NotFound(); } - var browse = Shares.Cache.Browse(); - - foreach (var dir in browse) - { - Console.WriteLine($"{dir.Name} ?? ${share.RemotePath}"); - } - - var contents = Shares.Cache.Browse().Where(directory => directory.Name.StartsWith(share.RemotePath)); + var contents = Shares.Cache.Browse() + .Where(directory => directory.Name.StartsWith(share.RemotePath)); return Ok(contents); } -- cgit v1.2.3 From e9c1a68650fa3567b04c8543f8cf77926b099a4f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 28 May 2022 23:00:54 -0500 Subject: docs --- .../Shares/API/Controllers/SharesController.cs | 79 ++++++++++++++++++++-- 1 file changed, 73 insertions(+), 6 deletions(-) (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index d6a31c4e..0b397bfd 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -17,22 +17,27 @@ namespace slskd.Shares.API { - using System; + using System.Collections.Generic; using System.Linq; - using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; /// /// Shares. /// - [Route("api/v{version:apiVersion}/[controller]")] - [ApiVersion("0")] [ApiController] + [ApiVersion("0")] [Produces("application/json")] [Consumes("application/json")] + [Route("api/v{version:apiVersion}/[controller]")] + [Authorize] public class SharesController : ControllerBase { + /// + /// Initializes a new instance of the class. + /// + /// + /// public SharesController( IShareService shareService, IStateMonitor applicationStateMonitor) @@ -44,7 +49,14 @@ namespace slskd.Shares.API private IShareService Shares { get; } private IStateMonitor ApplicationStateMonitor { get; } + /// + /// Gets the current list of shares. + /// + /// The request completed successfully. + /// [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] public IActionResult List() { var browse = Shares.Cache.Browse(); @@ -75,26 +87,73 @@ namespace slskd.Shares.API return Ok(summary); } + /// + /// Gets the share associated with the specified . + /// + /// The id of the share. + /// The request completed successfully. + /// The requested share could not be found. + /// [HttpGet("{id}")] + [Authorize] + [ProducesResponseType(typeof(SummarizedShare), 200)] + [ProducesResponseType(404)] public IActionResult Get(string id) { - var share = Ok(Shares.Cache.Shares.FirstOrDefault(share => share.Id == id)); + var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); if (share == default) { return NotFound(); } - return share; + var browse = Shares.Cache.Browse(); + var directories = browse.Where(directory => directory.Name.StartsWith(share.RemotePath)); + var fileCount = directories.Aggregate(seed: 0, (sum, directory) => + { + sum += directory.FileCount; + return sum; + }); + + var summary = new SummarizedShare() + { + Id = share.Id, + Alias = share.Alias, + IsExcluded = share.IsExcluded, + LocalPath = share.LocalPath, + Mask = share.Mask, + Raw = share.Raw, + RemotePath = share.RemotePath, + Directories = directories.Count(), + Files = fileCount, + }; + + return Ok(summary); } + /// + /// Returns a list of all shared directories and files. + /// + /// + /// The request completed successfully. [HttpGet("contents")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable), 200)] public IActionResult BrowseAll() { return Ok(Shares.Cache.Browse()); } + /// + /// Gets the contents of the share associated with the specified . + /// + /// The id of the share. + /// + /// The request completed successfully. + /// The requested share could not be found. [HttpGet("{id}/contents")] + [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(404)] public IActionResult BrowseShare(string id) { var share = Shares.Cache.Shares.FirstOrDefault(share => share.Id == id); @@ -110,9 +169,17 @@ namespace slskd.Shares.API return Ok(contents); } + /// + /// Initiates a scan of the configured shares. + /// + /// + /// The request completed successfully. + /// A share scan is already in progress. [HttpPut] [Route("")] [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { if (ApplicationStateMonitor.CurrentValue.SharedFileCache.Filling) -- 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/API') 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 c8c97202df9b7e25a1ee84d264f324960e1c548e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:15:29 -0500 Subject: remove app state monitor dependency --- src/slskd/Shares/API/Controllers/SharesController.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 251f50b9..990d6143 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -38,13 +38,10 @@ namespace slskd.Shares.API /// Initializes a new instance of the class. /// /// - /// public SharesController( - IShareService shareService, - IStateMonitor applicationStateMonitor) + IShareService shareService) { Shares = shareService; - ApplicationStateMonitor = applicationStateMonitor; } private IShareService Shares { get; } @@ -181,15 +178,17 @@ namespace slskd.Shares.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(409)] - public IActionResult RescanSharesAsync() + public async Task RescanSharesAsync() { - if (ApplicationStateMonitor.CurrentValue.Shares.Cache.Filling) + try + { + await Shares.StartScanAsync(); + } + catch (ShareScanInProgressException) { return Conflict("A share scan is already in progress."); } - _ = Shares.StartScanAsync(); - return Ok(); } } -- cgit v1.2.3 From d72da4b8a2134686a68c914b7b5537dc91ba5da5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 30 May 2022 16:16:44 -0500 Subject: using Soulseek --- src/slskd/Shares/API/Controllers/SharesController.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 990d6143..300bbf5a 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -22,6 +22,7 @@ namespace slskd.Shares.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Soulseek; /// /// Shares. @@ -136,7 +137,7 @@ namespace slskd.Shares.API /// The request completed successfully. [HttpGet("contents")] [Authorize] - [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(typeof(IEnumerable), 200)] public async Task BrowseAll() { return Ok(await Shares.BrowseAsync()); @@ -150,7 +151,7 @@ namespace slskd.Shares.API /// The request completed successfully. /// The requested share could not be found. [HttpGet("{id}/contents")] - [ProducesResponseType(typeof(IEnumerable), 200)] + [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] public async Task BrowseShare(string id) { -- cgit v1.2.3 From c85441d966446bda8e4ca771bb74ed02c7970209 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jun 2022 10:29:23 -0500 Subject: remove unused ApplicationStateMonitor --- src/slskd/Shares/API/Controllers/SharesController.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src/slskd/Shares/API') diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 300bbf5a..8ae8551f 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -46,7 +46,6 @@ namespace slskd.Shares.API } private IShareService Shares { get; } - private IStateMonitor ApplicationStateMonitor { get; } /// /// Gets the current list of shares. -- 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/API') 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