diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-06-02 10:33:35 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-06-02 10:33:35 -0500 |
| commit | e044a75f285b1b1bfb19631ea2eef5509714a703 (patch) | |
| tree | a9bdec768dbd36d831fb655aeefd5754e96d8e87 /src/slskd | |
| parent | adf5e7800452e861903b00faa5729c92187ef3ce (diff) | |
| parent | 908972ae3655973cb2d1536e12b7c2dd42437062 (diff) | |
| download | slskd-e044a75f285b1b1bfb19631ea2eef5509714a703.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/eventsource-1.1.1
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Application.cs | 90 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/NotFoundException.cs (renamed from src/slskd/Common/Exceptions/ShareAliasException.cs) | 22 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs | 15 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/OptionsController.cs | 20 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs | 15 | ||||
| -rw-r--r-- | src/slskd/Shares/API/Controllers/SharesController.cs | 195 | ||||
| -rw-r--r-- | src/slskd/Shares/API/DTO/SummarizedShare.cs | 32 | ||||
| -rw-r--r-- | src/slskd/Shares/Domain/Share.cs | 26 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareService.cs | 82 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 183 | ||||
| -rw-r--r-- | src/slskd/Shares/SharedFileCache.cs | 53 | ||||
| -rw-r--r-- | src/slskd/Shares/SoulseekFileFactory.cs | 2 | ||||
| -rw-r--r-- | src/slskd/State.cs | 23 |
14 files changed, 655 insertions, 107 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1064e56a..0144daa2 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(); } @@ -83,7 +82,7 @@ namespace slskd IRoomTracker roomTracker, IRoomService roomService, IUserService userService, - ISharedFileCache sharedFileCache, + IShareService shareService, IPushbulletService pushbulletService, IHubContext<ApplicationHub> applicationHub, IHubContext<LogsHub> logHub) @@ -98,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; @@ -153,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> State { get; } private ITransferTracker TransferTracker { get; set; } @@ -161,6 +159,7 @@ namespace slskd private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } private IUserService Users { get; set; } + private IShareService Shares { get; set; } public void CollectGarbage() { @@ -226,12 +225,6 @@ namespace slskd } } - /// <summary> - /// Re-scans shared directories. - /// </summary> - /// <returns>The operation context.</returns> - public Task RescanSharesAsync() => SharedFileCache.FillAsync(); - async Task IHostedService.StartAsync(CancellationToken cancellationToken) { Log.Information("Configuring client"); @@ -313,7 +306,7 @@ namespace slskd } else { - _ = SharedFileCache.FillAsync(); + _ = Shares.StartScanAsync(); } if (OptionsAtStartup.NoConnect) @@ -344,12 +337,12 @@ namespace slskd /// <param name="username">The username of the requesting user.</param> /// <param name="endpoint">The IP endpoint of the requesting user.</param> /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> - private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) + private async Task<BrowseResponse> 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) @@ -448,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.Directories, State.CurrentValue.Shares.Files); } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) @@ -516,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) @@ -560,10 +551,10 @@ namespace slskd /// <param name="token">The unique token for the request, supplied by the requesting user.</param> /// <param name="directory">The requested directory.</param> /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> - private Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) + private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = SharedFileCache.List(directory); - return Task.FromResult(dir); + var dir = await Shares.ListDirectoryAsync(directory); + return dir; } /// <summary> @@ -581,18 +572,28 @@ namespace slskd /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for /// security reasons. /// </exception> - 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 fileInfo = new FileInfo(localFilename); + string localFilename; + FileInfo fileInfo = default; Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); - if (!fileInfo.Exists) + try { - Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); + localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); + + fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + throw new NotFoundException(); + } + } + catch (NotFoundException) + { + Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); throw new DownloadEnqueueException($"File not shared."); } @@ -600,7 +601,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. @@ -623,7 +624,7 @@ namespace slskd // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. - Task.Run(async () => + _ = Task.Run(async () => { // users with uploads must be watched so that we can keep informed of their // online status, privileges, and statistics. this is so that we can accurately @@ -639,9 +640,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) @@ -681,14 +679,14 @@ namespace slskd if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) { - State.SetValue(state => state with { PendingShareRescan = true }); + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect."); } if (PreviousOptions.Filters.Share.Except(newOptions.Filters.Share).Any() || newOptions.Filters.Share.Except(PreviousOptions.Filters.Share).Any()) { - State.SetValue(state => state with { PendingShareRescan = true }); + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } }); Log.Information("File filter configuration changed. Shares must be re-scanned for changes to take effect."); } @@ -826,7 +824,7 @@ namespace slskd return null; } - var results = await SharedFileCache.SearchAsync(query); + var results = await Shares.SearchAsync(query); if (results.Any()) { @@ -846,30 +844,30 @@ 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.Scanning && current.Scanning) { 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.ScanProgress * 100); + var currentProgress = Math.Round(current.ScanProgress * 100); if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) { - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files); } - if (previous.Filling && !current.Filling) + if (previous.Scanning && !current.Scanning) { - State.SetValue(s => s with { SharedFileCache = current }); + State.SetValue(s => s with { Shares = current }); if (current.Faulted) { @@ -877,14 +875,14 @@ namespace slskd } else { - State.SetValue(s => s with { PendingShareRescan = false }); + State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } }); 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.SharedFileCache.Directories, State.CurrentValue.SharedFileCache.Files); + _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); } } } diff --git a/src/slskd/Common/Exceptions/ShareAliasException.cs b/src/slskd/Common/Exceptions/NotFoundException.cs index 3047d0a9..cc0f6969 100644 --- a/src/slskd/Common/Exceptions/ShareAliasException.cs +++ b/src/slskd/Common/Exceptions/NotFoundException.cs @@ -1,4 +1,4 @@ -// <copyright file="ShareAliasException.cs" company="slskd Team"> +// <copyright file="NotFoundException.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -22,31 +22,31 @@ namespace slskd using System.Runtime.Serialization; /// <summary> - /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// Represents errors that originate when a searched resource can't be located. /// </summary> [ExcludeFromCodeCoverage] [Serializable] - public class ShareAliasException : SlskdException + public class NotFoundException : SlskdException { /// <summary> - /// Initializes a new instance of the <see cref="ShareAliasException"/> class. + /// Initializes a new instance of the <see cref="NotFoundException"/> class. /// </summary> - public ShareAliasException() + public NotFoundException() : base() { } /// <summary> - /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message. + /// Initializes a new instance of the <see cref="NotFoundException"/> class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> - public ShareAliasException(string message) + public NotFoundException(string message) : base(message) { } /// <summary> - /// Initializes a new instance of the <see cref="ShareAliasException"/> class with a specified error message and a + /// Initializes a new instance of the <see cref="NotFoundException"/> class with a specified error message and a /// reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The message that describes the error.</param> @@ -54,17 +54,17 @@ namespace slskd /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no /// inner exception is specified. /// </param> - public ShareAliasException(string message, Exception innerException) + public NotFoundException(string message, Exception innerException) : base(message, innerException) { } /// <summary> - /// Initializes a new instance of the <see cref="ShareAliasException"/> class with serialized data. + /// Initializes a new instance of the <see cref="NotFoundException"/> class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> - protected ShareAliasException(SerializationInfo info, StreamingContext context) + protected NotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } 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/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs index 062de8f7..b0856ed3 100644 --- a/src/slskd/Core/API/Controllers/OptionsController.cs +++ b/src/slskd/Core/API/Controllers/OptionsController.cs @@ -21,8 +21,10 @@ namespace slskd.Core.API { using System; using System.IO; + using System.Reflection; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Microsoft.Extensions.Configuration; using Serilog; using slskd.Validation; using IOFile = System.IO.File; @@ -74,6 +76,24 @@ namespace slskd.Core.API return Ok(OptionsAtStartup.Redact()); } + /// <summary> + /// Gets the debug view of the current application options. + /// </summary> + /// <returns></returns> + [HttpGet] + [Route("debug")] + [Authorize] + [ProducesResponseType(typeof(string), 200)] + public IActionResult Debug() + { + // retrieve the IConfigurationRoot instance with reflection to avoid + // exposing it as a public member of Program. + var property = typeof(Program).GetProperty("Configuration", BindingFlags.NonPublic | BindingFlags.Static); + var configurationRoot = (IConfigurationRoot)property.GetValue(null, null); + + return Ok(configurationRoot.GetDebugView()); + } + [HttpGet] [Authorize] [Route("yaml/location")] diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 40e6e72d..df1fb55c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -453,7 +453,7 @@ namespace slskd services.AddSingleton<IConversationTracker, ConversationTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton<ISharedFileCache, SharedFileCache>(); + services.AddSingleton<IShareService, ShareService>(); services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IUserService, UserService>(); @@ -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 /// </summary> /// <param name="search">The search to delete.</param> /// <returns>The operation context.</returns> - 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); + } } /// <summary> diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs new file mode 100644 index 00000000..41178bac --- /dev/null +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -0,0 +1,195 @@ +// <copyright file="SharesController.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Shares.API +{ + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Shares. + /// </summary> + [ApiController] + [ApiVersion("0")] + [Produces("application/json")] + [Consumes("application/json")] + [Route("api/v{version:apiVersion}/[controller]")] + [Authorize] + public class SharesController : ControllerBase + { + /// <summary> + /// Initializes a new instance of the <see cref="SharesController"/> class. + /// </summary> + /// <param name="shareService"></param> + public SharesController( + IShareService shareService) + { + Shares = shareService; + } + + private IShareService Shares { get; } + + /// <summary> + /// Gets the current list of shares. + /// </summary> + /// <response code="200">The request completed successfully.</response> + /// <returns></returns> + [HttpGet("")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable<SummarizedShare>), 200)] + public async Task<IActionResult> List() + { + var browse = await Shares.BrowseAsync(); + + var summary = Shares.CachedShares.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); + } + + /// <summary> + /// Gets the share associated with the specified <see paramref="id"/>. + /// </summary> + /// <param name="id">The id of the share.</param> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The requested share could not be found.</response> + /// <returns></returns> + [HttpGet("{id}")] + [Authorize] + [ProducesResponseType(typeof(SummarizedShare), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> Get(string id) + { + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); + + if (share == default) + { + return NotFound(); + } + + var browse = await Shares.BrowseAsync(); + 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); + } + + /// <summary> + /// Returns a list of all shared directories and files. + /// </summary> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + [HttpGet("contents")] + [Authorize] + [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] + public async Task<IActionResult> BrowseAll() + { + return Ok(await Shares.BrowseAsync()); + } + + /// <summary> + /// Gets the contents of the share associated with the specified <see paramref="id"/>. + /// </summary> + /// <param name="id">The id of the share.</param> + /// <returns></returns> + /// <response code="200">The request completed successfully.</response> + /// <response code="404">The requested share could not be found.</response> + [HttpGet("{id}/contents")] + [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] + [ProducesResponseType(404)] + public async Task<IActionResult> BrowseShare(string id) + { + var share = Shares.Shares.FirstOrDefault(share => share.Id == id); + + if (share == default) + { + return NotFound(); + } + + var contents = (await Shares.BrowseAsync()) + .Where(directory => directory.Name.StartsWith(share.RemotePath)); + + return Ok(contents); + } + + /// <summary> + /// Initiates a scan of the configured shares. + /// </summary> + /// <returns></returns> + /// <response code="204">The request completed successfully.</response> + /// <response code="409">A share scan is already in progress.</response> + [HttpPut] + [Route("")] + [Authorize] + [ProducesResponseType(204)] + [ProducesResponseType(409)] + public async Task<IActionResult> RescanSharesAsync() + { + try + { + await Shares.StartScanAsync(); + } + catch (ShareScanInProgressException) + { + return Conflict("A share scan is already in progress."); + } + + 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 file="SummarizedShare.cs" company="slskd Team"> +// 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/. +// </copyright> + +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 diff --git a/src/slskd/Shares/Domain/Share.cs b/src/slskd/Shares/Domain/Share.cs index 890c8565..9bdbc002 100644 --- a/src/slskd/Shares/Domain/Share.cs +++ b/src/slskd/Shares/Domain/Share.cs @@ -18,6 +18,7 @@ namespace slskd.Shares { using System.Linq; + using System.Text.Json.Serialization; using System.Text.RegularExpressions; /// <summary> @@ -28,6 +29,28 @@ namespace slskd.Shares /// <summary> /// Initializes a new instance of the <see cref="Share"/> class. /// </summary> + /// <param name="id"></param> + /// <param name="alias"></param> + /// <param name="isExcluded"></param> + /// <param name="localPath"></param> + /// <param name="mask"></param> + /// <param name="raw"></param> + /// <param name="remotePath"></param> + [JsonConstructor] + public Share (string id, string alias, bool isExcluded, string localPath, string mask, string raw, string remotePath) + { + Id = id; + Alias = alias; + IsExcluded = isExcluded; + LocalPath = localPath; + Mask = mask; + Raw = raw; + RemotePath = remotePath; + } + + /// <summary> + /// Initializes a new instance of the <see cref="Share"/> class. + /// </summary> /// <param name="share"></param> public Share(string share) { @@ -63,8 +86,11 @@ namespace slskd.Shares var aliasedSegment = LocalPath[(parent.Length + 1)..]; RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias); + + Id = Compute.Sha1Hash(RemotePath); } + public string Id { get; init; } public string Alias { get; init; } public bool IsExcluded { get; init; } public string LocalPath { get; init; } diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs new file mode 100644 index 00000000..fd88f2b0 --- /dev/null +++ b/src/slskd/Shares/IShareService.cs @@ -0,0 +1,82 @@ +// <copyright file="IShareService.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Soulseek; + + /// <summary> + /// Provides control and interactions with configured shares and shared files. + /// </summary> + public interface IShareService + { + /// <summary> + /// Gets the list of shares stored in the cache. + /// </summary> + IReadOnlyList<Share> CachedShares { get; } + + /// <summary> + /// Gets the list of configured shares. + /// </summary> + IReadOnlyList<Share> Shares { get; } + + /// <summary> + /// Gets the state monitor for the service. + /// </summary> + public IStateMonitor<ShareState> StateMonitor { get; } + + /// <summary> + /// Returns the entire contents of the share. + /// </summary> + /// <returns>The entire contents of the share.</returns> + Task<IEnumerable<Directory>> BrowseAsync(); + + /// <summary> + /// Returns the contents of the specified <paramref name="directory"/>. + /// </summary> + /// <param name="directory">The directory for which the contents are to be listed.</param> + /// <returns>The contents of the directory.</returns> + Task<Directory> ListDirectoryAsync(string directory); + + /// <summary> + /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a + /// configured share. + /// </summary> + /// <param name="remoteFilename">The fully qualified filename to resolve.</param> + /// <returns>The resolved local filename.</returns> + /// <exception cref="NotFoundException"> + /// Thrown when the specified remote filename can not be associated with a configured share. + /// </exception> + Task<string> ResolveFilenameAsync(string remoteFilename); + + /// <summary> + /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. + /// </summary> + /// <param name="query">The query for which to search.</param> + /// <returns>The matching files.</returns> + Task<IEnumerable<File>> SearchAsync(SearchQuery query); + + /// <summary> + /// Starts a scan of the configured shares. + /// </summary> + /// <returns>The operation context.</returns> + /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception> + Task StartScanAsync(); + } +} diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs new file mode 100644 index 00000000..ead96d10 --- /dev/null +++ b/src/slskd/Shares/ShareService.cs @@ -0,0 +1,183 @@ +// <copyright file="ShareService.cs" company="slskd Team"> +// 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/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Shares +{ + using System.Collections.Generic; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Soulseek; + + /// <summary> + /// Provides control and interactions with configured shares and shared files. + /// </summary> + public class ShareService : IShareService + { + /// <summary> + /// Initializes a new instance of the <see cref="ShareService"/> class. + /// </summary> + /// <param name="optionsMonitor"></param> + /// <param name="sharedFileCache"></param> + public ShareService( + IOptionsMonitor<Options> optionsMonitor, + ISharedFileCache sharedFileCache = null) + { + Cache = sharedFileCache ?? new SharedFileCache(); + Cache.StateMonitor.OnChange(cacheState => + { + var (previous, current) = cacheState; + + State.SetValue(state => state with + { + // 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, + }); + + if (previous.Filling && !current.Filling) + { + CachedShares = current.Shares.ToList().AsReadOnly(); + } + }); + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + /// <summary> + /// Gets the list of configured shares. + /// </summary> + public IReadOnlyList<Share> Shares => SharesList.AsReadOnly(); + + /// <summary> + /// Gets the list of shares stored in the cache. + /// </summary> + public IReadOnlyList<Share> CachedShares { get; private set; } = new List<Share>().AsReadOnly(); + + /// <summary> + /// Gets the state monitor for the service. + /// </summary> + public IStateMonitor<ShareState> StateMonitor => State; + + private ISharedFileCache Cache { get; } + private string LastOptionsHash { get; set; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private List<Share> SharesList { get; set; } = new List<Share>(); + private IManagedState<ShareState> State { get; } = new ManagedState<ShareState>(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private List<Regex> FilterRegexes { get; set; } = new List<Regex>(); + + /// <summary> + /// Returns the entire contents of the share. + /// </summary> + /// <returns>The entire contents of the share.</returns> + public Task<IEnumerable<Directory>> BrowseAsync() + => Task.FromResult(Cache.Browse()); + + /// <summary> + /// Returns the contents of the specified <paramref name="directory"/>. + /// </summary> + /// <param name="directory">The directory for which the contents are to be listed.</param> + /// <returns>The contents of the directory.</returns> + public Task<Directory> ListDirectoryAsync(string directory) + => Task.FromResult(Cache.List(directory)); + + /// <summary> + /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a + /// configured share. + /// </summary> + /// <param name="remoteFilename">The fully qualified filename to resolve.</param> + /// <returns>The resolved local filename.</returns> + /// <exception cref="NotFoundException"> + /// Thrown when the specified remote filename can not be associated with a configured share. + /// </exception> + public Task<string> ResolveFilenameAsync(string remoteFilename) + { + var resolvedFilename = Cache.Resolve(remoteFilename); + + if (resolvedFilename == remoteFilename) + { + throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a configured share."); + } + + return Task.FromResult(resolvedFilename); + } + + /// <summary> + /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. + /// </summary> + /// <param name="query">The query for which to search.</param> + /// <returns>The matching files.</returns> + public Task<IEnumerable<File>> SearchAsync(SearchQuery query) + => Cache.SearchAsync(query); + + /// <summary> + /// Starts a scan of the configured shares. + /// </summary> + /// <returns>The operation context.</returns> + /// <exception cref="ShareScanInProgressException">Thrown when a scan is already in progress.</exception> + public Task StartScanAsync() + => Cache.FillAsync(Shares, FilterRegexes); + + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(string.Join(';', options.Directories.Shared)); + + if (optionsHash == LastOptionsHash) + { + return; + } + + var shares = options.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(); + + var regexes = options.Filters.Share + .Select(filter => new Regex(filter, RegexOptions.Compiled)) + .ToList(); + + SharesList = shares; + FilterRegexes = regexes; + + State.SetValue(state => state with { ScanPending = true }); + + LastOptionsHash = optionsHash; + } + finally + { + SyncRoot.Release(); + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs index ac996fa6..6b7a3ca3 100644 --- a/src/slskd/Shares/SharedFileCache.cs +++ b/src/slskd/Shares/SharedFileCache.cs @@ -16,7 +16,6 @@ // </copyright> using System.IO; -using Microsoft.Extensions.Options; namespace slskd.Shares { @@ -51,8 +50,11 @@ namespace slskd.Shares /// <summary> /// Scans the configured shares and fills the cache. /// </summary> + /// <remarks>Initiates the scan, then yields execution back to the caller; does not wait for the operation to complete.</remarks> + /// <param name="shares">The list of shares from which to fill the cache.</param> + /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> /// <returns>The operation context.</returns> - Task FillAsync(); + Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters); /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. @@ -85,13 +87,9 @@ namespace slskd.Shares /// <summary> /// Initializes a new instance of the <see cref="SharedFileCache"/> class. /// </summary> - /// <param name="optionsMonitor"></param> /// <param name="soulseekFileFactory"></param> - public SharedFileCache( - IOptionsMonitor<Options> optionsMonitor, - ISoulseekFileFactory soulseekFileFactory = null) + public SharedFileCache(ISoulseekFileFactory soulseekFileFactory = null) { - OptionsMonitor = optionsMonitor; SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory(); } @@ -100,15 +98,14 @@ namespace slskd.Shares /// </summary> public IStateMonitor<SharedFileCacheState> StateMonitor => State; - private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); private HashSet<string> MaskedDirectories { get; set; } private Dictionary<string, File> MaskedFiles { get; set; } - private IOptionsMonitor<Options> OptionsMonitor { get; set; } private List<Share> Shares { get; set; } + private ISoulseekFileFactory SoulseekFileFactory { get; } private SqliteConnection SQLite { get; set; } + private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); - private ISoulseekFileFactory SoulseekFileFactory { get; } /// <summary> /// Returns the contents of the cache. @@ -164,8 +161,10 @@ namespace slskd.Shares /// <summary> /// Scans the configured shares and fills the cache. /// </summary> + /// <param name="shares">The list of shares from which to fill the cache.</param> + /// <param name="filters">The list of regular expressions used to exclude files or paths from scanning.</param> /// <returns>The operation context.</returns> - public async Task FillAsync() + public async Task FillAsync(IEnumerable<Share> shares, IEnumerable<Regex> filters) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -176,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<Share>().ToList().AsReadOnly(), + }); + Log.Debug("Starting shared file scan"); await Task.Yield(); @@ -187,12 +193,7 @@ namespace slskd.Shares 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(); + Shares = shares.ToList(); if (!Shares.Any()) { @@ -236,9 +237,6 @@ namespace slskd.Shares Log.Debug("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; - var filters = OptionsMonitor.CurrentValue.Filters.Share - .Select(filter => new Regex(filter, RegexOptions.Compiled)); - var files = new Dictionary<string, File>(); var maskedDirectories = new HashSet<string>(); var current = 0; @@ -300,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) @@ -451,7 +458,7 @@ namespace slskd.Shares SQLite = new SqliteConnection("Data Source=file:shares?mode=memory&cache=shared"); SQLite.Open(); - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + using var cmd = new SqliteCommand("DROP TABLE IF EXISTS cache; CREATE VIRTUAL TABLE cache USING fts5(filename);", SQLite); cmd.ExecuteNonQuery(); } 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<string> SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet(); - private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); + private ILogger Log { get; } = Serilog.Log.ForContext<SoulseekFileFactory>(); /// <summary> /// Creates an instance of <see cref="Soulseek.File"/> from the given path. diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 0daa5d76..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,10 +33,9 @@ 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 SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); + public ShareState Shares { get; init; } = new ShareState(); public string[] Rooms { get; init; } = Array.Empty<string>(); public User[] Users { get; init; } = Array.Empty<User>(); } @@ -69,15 +69,25 @@ namespace slskd public string BranchRoot { get; init; } public bool CanAcceptChildren { get; init; } public int ChildLimit { get; init; } - public IReadOnlyCollection<string> Children { get; init; } + public IReadOnlyCollection<string> Children { get; init; } = new List<string>().AsReadOnly(); public bool HasParent { get; init; } public bool IsBranchRoot { get; init; } public string Parent { get; init; } } /// <summary> - /// Share cache state. + /// Share state. /// </summary> + public record ShareState + { + 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; } + } + public record SharedFileCacheState { /// <summary> @@ -114,5 +124,10 @@ namespace slskd /// Gets the number of directories excluded by filters. /// </summary> public int ExcludedDirectories { get; init; } + + /// <summary> + /// Gets the list of shares stored in the cache. + /// </summary> + public IReadOnlyCollection<Share> Shares { get; init; } = new List<Share>().AsReadOnly(); } }
\ No newline at end of file |
