diff options
Diffstat (limited to 'src')
16 files changed, 610 insertions, 187 deletions
diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Application.cs index ef47cf24..f1361b6e 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Application.cs @@ -1,4 +1,4 @@ -// <copyright file="Service.cs" company="slskd Team"> +// <copyright file="Application.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -19,7 +19,6 @@ namespace slskd { using System; using System.Collections.Concurrent; - using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; @@ -39,16 +38,14 @@ namespace slskd using Soulseek; using Soulseek.Diagnostics; - public class Service : IHostedService + public class Application : IHostedService { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes - private (int Directories, int Files) sharedCounts = (0, 0); - - public Service( + public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor<Options> optionsMonitor, - IStateMonitor stateMonitor, + IStateMonitor<ApplicationState> stateMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -66,11 +63,13 @@ namespace slskd StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); + SharedFileCache = sharedFileCache; + SharedFileCache.State.OnChange(state => SharedFileCacheState_OnChange(state)); + TransferTracker = transferTracker; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; RoomTracker = roomTracker; - SharedFileCache = sharedFileCache; Pushbullet = pushbulletService; ProxyOptions proxyOptions = default; @@ -136,8 +135,6 @@ namespace slskd Client.LoggedIn += Client_LoggedIn; SoulseekClient = Client; - - SharedFileCache.Refreshed += SharedFileCache_Refreshed; } public static ISoulseekClient SoulseekClient { get; private set; } @@ -145,20 +142,32 @@ namespace slskd private IBrowseTracker BrowseTracker { get; set; } private ISoulseekClient Client { get; set; } private IConversationTracker ConversationTracker { get; set; } - private ILogger Logger { get; set; } = Log.ForContext<Service>(); + private ILogger Logger { get; set; } = Log.ForContext<Application>(); private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); private IOptionsMonitor<Options> OptionsMonitor { get; set; } + private Options Options => OptionsMonitor.CurrentValue; private OptionsAtStartup OptionsAtStartup { get; set; } private Options PreviousOptions { get; set; } private IRoomTracker RoomTracker { get; set; } - private IStateMonitor StateMonitor { get; set; } + private IStateMonitor<ApplicationState> StateMonitor { get; set; } + private ApplicationState State => StateMonitor.CurrentValue; private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); + private DateTime SharesRefreshStarted { get; set; } public async Task StartAsync(CancellationToken cancellationToken) { + if (OptionsAtStartup.NoShareScan) + { + Logger.Warning("Not scanning shares; 'no-share-scan' option is enabled. Search and browse results will remain disabled until a manual scan is completed."); + } + else + { + _ = SharedFileCache.FillAsync(); + } + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); @@ -167,7 +176,11 @@ namespace slskd Logger.Information("Client started"); Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); - if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) + if (OptionsAtStartup.NoConnect) + { + Logger.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled"); + } + else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password)) { Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } @@ -221,6 +234,13 @@ namespace slskd pendingReconnect |= requiresReconnect; } + if (PreviousOptions.Directories.Shared.Except(newOptions.Directories.Shared).Any() + || newOptions.Directories.Shared.Except(PreviousOptions.Directories.Shared).Any()) + { + StateMonitor.SetValue(state => state with { PendingShareRescan = true }); + Logger.Information("Shared directory configuration changed. Shares must be re-scanned for changes to take effect."); + } + // determine whether any Soulseek options changed. if so, we need to construct a patch // and invoke ReconfigureOptionsAsync(). var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); @@ -281,13 +301,13 @@ namespace slskd // OR if the call to reconfigure the client requires a reconnect if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect) { - StateMonitor.Set(state => state with { PendingReconnect = true }); + StateMonitor.SetValue(state => state with { PendingReconnect = true }); Logger.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect."); } if (pendingRestart) { - StateMonitor.Set(state => state with { PendingRestart = true }); + StateMonitor.SetValue(state => state with { PendingRestart = true }); Logger.Information("One or more updated options requires an application restart to take effect."); } @@ -304,17 +324,50 @@ namespace slskd } } - private void StateMonitor_OnChange((State Previous, State Current) state) + private void StateMonitor_OnChange((ApplicationState Previous, ApplicationState Current) state) { Logger.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); } - private void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e) + private void SharedFileCacheState_OnChange((SharedFileCacheState Previous, SharedFileCacheState Current) state) { - if (sharedCounts != e) + if (!state.Previous.Filling && state.Current.Filling) { - _ = SoulseekClient.SetSharedCountsAsync(e.Directories, e.Files); - sharedCounts = e; + SharesRefreshStarted = DateTime.UtcNow; + + StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); + Logger.Information("Scanning shares"); + } + + var lastProgress = Math.Round(state.Previous.FillProgress * 100); + var currentProgress = Math.Round(state.Current.FillProgress * 100); + + if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 10 == 0) + { + StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); + Logger.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, state.Current.Files); + } + + if (state.Previous.Filling && !state.Current.Filling) + { + StateMonitor.SetValue(s => s with { SharedFileCache = state.Current }); + + if (state.Current.Faulted) + { + Logger.Error("Failed to scan shares."); + } + else + { + StateMonitor.SetValue(s => s with { PendingShareRescan = false }); + Logger.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", state.Current.Directories, state.Current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds); + + SharesRefreshStarted = default; + + if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn)) + { + _ = SoulseekClient.SetSharedCountsAsync(State.SharedFileCache.Directories, State.SharedFileCache.Files); + } + } } } @@ -326,17 +379,7 @@ namespace slskd /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) { - var shares = OptionsMonitor.CurrentValue.Directories.Shared; - var directories = new List<Soulseek.Directory>(); - - foreach (var share in shares) - { - directories.AddRange(System.IO.Directory - .GetDirectories(share, "*", SearchOption.AllDirectories) - .Select(dir => new Soulseek.Directory(dir.Replace("/", @"\"), System.IO.Directory.GetFiles(dir) - .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f)))))); - } - + var directories = SharedFileCache.Browse(); return Task.FromResult(new BrowseResponse(directories)); } @@ -369,13 +412,17 @@ namespace slskd private void Client_LoggedIn(object sender, EventArgs e) { Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); + + // send whatever counts we have currently. we'll probably connect before the cache is primed, + // so these will be zero initially, but we'll update them when the cache is filled. + _ = SoulseekClient.SetSharedCountsAsync(State.SharedFileCache.Directories, State.SharedFileCache.Files); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { - if (StateMonitor.Current.PendingReconnect) + if (State.PendingReconnect) { - StateMonitor.Set(state => state with { PendingReconnect = false }); + StateMonitor.SetValue(state => state with { PendingReconnect = false }); } if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) @@ -398,7 +445,7 @@ namespace slskd { Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - if (string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Username) || string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Password)) + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) { Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); return; @@ -422,7 +469,7 @@ namespace slskd { // reconnect with the latest configuration values we have for username and password, instead of the options that were // captured at startup. if a user has updated these values prior to the disconnect, the changes will take effect now. - await Client.ConnectAsync(OptionsMonitor.CurrentValue.Soulseek.Username, OptionsMonitor.CurrentValue.Soulseek.Password); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); break; } catch (Exception ex) @@ -438,7 +485,7 @@ namespace slskd { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && !args.Replayed) + if (Options.Integration.Pushbullet.Enabled && !args.Replayed) { Console.WriteLine("Pushing..."); _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); @@ -449,7 +496,7 @@ namespace slskd { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); } @@ -474,7 +521,7 @@ namespace slskd var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); - if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); } @@ -587,41 +634,39 @@ namespace slskd /// <param name="token">The search token.</param> /// <param name="query">The search query.</param> /// <returns>A Task resolving a SearchResponse, or null.</returns> - private Task<Soulseek.SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query) + private async Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query) { - var defaultResponse = Task.FromResult<Soulseek.SearchResponse>(null); - // some bots continually query for very common strings. blacklist known names here. var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; if (blacklist.Contains(username)) { - return defaultResponse; + return null; } // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. if (query.Query.Length < 3) { - return defaultResponse; + return null; } - var results = SharedFileCache.Search(query); + var results = await SharedFileCache.SearchAsync(query); if (results.Any()) { Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); - return Task.FromResult(new Soulseek.SearchResponse( + return new SearchResponse( SoulseekClient.Username, token, freeUploadSlots: 1, uploadSpeed: 0, queueLength: 0, - fileList: results)); + fileList: results); } // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no // response will be sent to the requestor. - return Task.FromResult<Soulseek.SearchResponse>(null); + return null; } /// <summary> diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/ApplicationState.cs index 75d46dec..58f086bb 100644 --- a/src/slskd/Application/State.cs +++ b/src/slskd/Application/ApplicationState.cs @@ -1,4 +1,4 @@ -// <copyright file="State.cs" company="slskd Team"> +// <copyright file="ApplicationState.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -18,7 +18,13 @@ namespace slskd { /// <summary> - /// Application state. + /// Application service state. /// </summary> - public record State(bool PendingReconnect = false, bool PendingRestart = false); + public record ApplicationState() + { + public bool PendingReconnect { get; init; } + public bool PendingRestart { get; init; } + public bool PendingShareRescan { get; init; } + public SharedFileCacheState SharedFileCache { get; init; } + } }
\ No newline at end of file diff --git a/src/slskd/Application/Exceptions/ShareScanInProgressException.cs b/src/slskd/Application/Exceptions/ShareScanInProgressException.cs new file mode 100644 index 00000000..2e548930 --- /dev/null +++ b/src/slskd/Application/Exceptions/ShareScanInProgressException.cs @@ -0,0 +1,72 @@ +// <copyright file="ShareScanInProgressException.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 +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareScanInProgressException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> class. + /// </summary> + public ShareScanInProgressException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ShareScanInProgressException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> 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> + /// <param name="innerException"> + /// 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 ShareScanInProgressException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ShareScanInProgressException"/> 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 ShareScanInProgressException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Application/ISharedFileCache.cs b/src/slskd/Application/ISharedFileCache.cs index 97133e40..291d78e4 100644 --- a/src/slskd/Application/ISharedFileCache.cs +++ b/src/slskd/Application/ISharedFileCache.cs @@ -17,20 +17,37 @@ namespace slskd { - using System; using System.Collections.Generic; + using System.Threading.Tasks; using Soulseek; + /// <summary> + /// Shared file cache. + /// </summary> public interface ISharedFileCache { - event EventHandler<(int Directories, int Files)> Refreshed; + /// <summary> + /// Gets the cache state. + /// </summary> + IStateMonitor<SharedFileCacheState> State { get; } - IEnumerable<string> Directories { get; } - DateTime? LastFill { get; } - long TTL { get; } + /// <summary> + /// Returns the contents of the cache. + /// </summary> + /// <returns>The contents of the cache.</returns> + IEnumerable<Directory> Browse(); - void Fill(); + /// <summary> + /// Scans the configured shares and fills the cache. + /// </summary> + /// <returns>The operation context.</returns> + Task FillAsync(); - IEnumerable<File> Search(SearchQuery query); + /// <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); } }
\ No newline at end of file diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs index ddac832a..dd115786 100644 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs @@ -22,7 +22,6 @@ namespace slskd.Management.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; - using Soulseek; /// <summary> /// Application. @@ -34,16 +33,27 @@ namespace slskd.Management.API [Consumes("application/json")] public class ApplicationController : ControllerBase { - public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime) + public ApplicationController(IManagementService managementService, IHostApplicationLifetime lifetime) { - Client = client; + Management = managementService; Lifetime = lifetime; } - private ISoulseekClient Client { get; } + private IManagementService Management { get; } private IHostApplicationLifetime Lifetime { get; } /// <summary> + /// Gets the current state of the application. + /// </summary> + /// <returns></returns> + [HttpGet] + [Authorize] + public IActionResult State() + { + return Ok(Management.ApplicationState); + } + + /// <summary> /// Stops the application. /// </summary> /// <returns></returns> diff --git a/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs new file mode 100644 index 00000000..f2b90718 --- /dev/null +++ b/src/slskd/Application/Management/API/Controllers/ConfigurationController.cs @@ -0,0 +1,71 @@ +// <copyright file="ConfigurationController.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.Management.API +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using slskd.Management; + + /// <summary> + /// Configuration. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ConfigurationController : ControllerBase + { + public ConfigurationController( + IOptionsSnapshot<Options> optionsShapshot, + IManagementService managementService) + { + OptionsShapshot = optionsShapshot; + ManagementService = managementService; + } + + private IManagementService ManagementService { get; } + private IOptionsSnapshot<Options> OptionsShapshot { get; } + + [HttpGet] + [Route("")] + [Authorize] + public IActionResult GetOptions() + { + // todo: sanitize this to remove passwords + return Ok(OptionsShapshot.Value); + } + + [HttpPut] + [Route("shares")] + [Authorize] + public IActionResult RescanSharesAsync() + { + if (ManagementService.SharedFileCacheState.Filling) + { + return Conflict("A share scan is already in progress."); + } + + _ = ManagementService.RescanSharesAsync(); + + return Ok(); + } + } +} diff --git a/src/slskd/Application/Management/API/Controllers/ServerController.cs b/src/slskd/Application/Management/API/Controllers/ServerController.cs index 6468063c..fc47f475 100644 --- a/src/slskd/Application/Management/API/Controllers/ServerController.cs +++ b/src/slskd/Application/Management/API/Controllers/ServerController.cs @@ -50,7 +50,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public async Task<IActionResult> Connect() { - if (!Management.GetServerState().IsConnected) + if (!Management.ServerState.IsConnected) { await Management.ConnectServerAsync(); } @@ -70,7 +70,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public IActionResult Disconnect([FromBody] string message) { - if (Management.GetServerState().IsConnected) + if (Management.ServerState.IsConnected) { Management.DisconnectServer(message); } @@ -90,7 +90,7 @@ namespace slskd.Management.API [ProducesResponseType(403)] public IActionResult Get() { - return Ok(Management.GetServerState()); + return Ok(Management.ServerState); } } }
\ No newline at end of file diff --git a/src/slskd/Application/Management/Domain/ServerState.cs b/src/slskd/Application/Management/API/DTO/ServerState.cs index 80c1e856..80c1e856 100644 --- a/src/slskd/Application/Management/Domain/ServerState.cs +++ b/src/slskd/Application/Management/API/DTO/ServerState.cs diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index b3e13477..9a06d961 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -26,6 +26,21 @@ namespace slskd.Management public interface IManagementService { /// <summary> + /// Gets the current state of the slskd service. + /// </summary> + ApplicationState ApplicationState { get; } + + /// <summary> + /// Gets the current state of the connection to the Soulseek server. + /// </summary> + ServerState ServerState { get; } + + /// <summary> + /// Gets the current state of the shared file cache. + /// </summary> + SharedFileCacheState SharedFileCacheState { get; } + + /// <summary> /// Connects the Soulseek client to the server using the configured username and password. /// </summary> /// <returns>The operation context.</returns> @@ -39,9 +54,9 @@ namespace slskd.Management void DisconnectServer(string message = null, Exception exception = null); /// <summary> - /// Gets the current state of the connection to the Soulseek server. + /// Re-scans shared directories. /// </summary> - /// <returns>The current server state.</returns> - ServerState GetServerState(); + /// <returns>The operation context.</returns> + Task RescanSharesAsync(); } }
\ No newline at end of file diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 66ed2b97..3d7bd442 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -32,18 +32,48 @@ namespace slskd.Management /// Initializes a new instance of the <see cref="ManagementService"/> class. /// </summary> /// <param name="optionsMonitor">The options monitor used to derive application options.</param> + /// <param name="serviceStateMonitor">The state monitor for application service state.</param> /// <param name="soulseekClient">The Soulseek client.</param> + /// <param name="sharedFileCache">The shared file cache.</param> public ManagementService( IOptionsMonitor<Options> optionsMonitor, - ISoulseekClient soulseekClient) + IStateMonitor<ApplicationState> serviceStateMonitor, + ISoulseekClient soulseekClient, + ISharedFileCache sharedFileCache) { OptionsMonitor = optionsMonitor; + ServiceStateMonitor = serviceStateMonitor; Client = soulseekClient; + SharedFileCache = sharedFileCache; } + /// <summary> + /// Gets the current state of the slskd service. + /// </summary> + public ApplicationState ApplicationState => ServiceStateMonitor.CurrentValue; + + /// <summary> + /// Gets the current state of the connection to the Soulseek server. + /// </summary> + public ServerState ServerState => + new ServerState() + { + Address = Client.Address, + IPEndPoint = Client.IPEndPoint, + State = Client.State, + Username = Client.Username, + }; + + /// <summary> + /// Gets the current state of the connection to the Soulseek server. + /// </summary> + public SharedFileCacheState SharedFileCacheState => SharedFileCache.State.CurrentValue; + private ISoulseekClient Client { get; } private Options Options => OptionsMonitor.CurrentValue; private IOptionsMonitor<Options> OptionsMonitor { get; } + private IStateMonitor<ApplicationState> ServiceStateMonitor { get; } + private ISharedFileCache SharedFileCache { get; } /// <summary> /// Connects the Soulseek client to the server using the configured username and password. @@ -61,16 +91,9 @@ namespace slskd.Management => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); /// <summary> - /// Gets the current state of the connection to the Soulseek server. + /// Re-scans shared directories. /// </summary> - /// <returns>The current server state.</returns> - public ServerState GetServerState() => - new ServerState() - { - Address = Client.Address, - IPEndPoint = Client.IPEndPoint, - State = Client.State, - Username = Client.Username, - }; + /// <returns>The operation context.</returns> + public Task RescanSharesAsync() => SharedFileCache.FillAsync(); } }
\ No newline at end of file diff --git a/src/slskd/Application/SharedFileCache.cs b/src/slskd/Application/SharedFileCache.cs index 45a810fc..9a5770b6 100644 --- a/src/slskd/Application/SharedFileCache.cs +++ b/src/slskd/Application/SharedFileCache.cs @@ -15,156 +15,225 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using System.IO; +using Microsoft.Extensions.Options; + namespace slskd { using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; - using System.IO; using System.Linq; using System.Threading; + using System.Threading.Tasks; using Microsoft.Data.Sqlite; + using Serilog; using Soulseek; /// <summary> - /// Caches shared files. + /// Shared file cache. /// </summary> public class SharedFileCache : ISharedFileCache { /// <summary> /// Initializes a new instance of the <see cref="SharedFileCache"/> class. /// </summary> - /// <param name="directories"></param> - /// <param name="ttl"></param> - public SharedFileCache(IEnumerable<string> directories, long ttl) + /// <param name="optionsMonitor"></param> + public SharedFileCache( + IOptionsMonitor<Options> optionsMonitor) { - Directories = directories; - TTL = ttl; + OptionsMonitor = optionsMonitor; } - public event EventHandler<(int Directories, int Files)> Refreshed; - - public IEnumerable<string> Directories { get; } - public DateTime? LastFill { get; set; } - public long TTL { get; } + /// <summary> + /// Gets the cache state. + /// </summary> + public IStateMonitor<SharedFileCacheState> State { get; } = new StateMonitor<SharedFileCacheState>(); - private Dictionary<string, Soulseek.File> Files { get; set; } + private HashSet<string> Directories { get; set; } + private Dictionary<string, File> Files { get; set; } + private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>(); + private IOptionsMonitor<Options> OptionsMonitor { get; set; } private SqliteConnection SQLite { get; set; } - private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); + + /// <summary> + /// Returns the contents of the cache. + /// </summary> + /// <returns>The contents of the cache.</returns> + public IEnumerable<Directory> Browse() + { + var directories = new ConcurrentDictionary<string, Directory>(); + + // Soulseek requires that each directory in the tree have an entry in the list returned in a browse response. if + // missing, files that are nested within directories which contain only directories (no files) are displayed as being + // in the root. to get around this, prime a dictionary with all known directories, and an empty Soulseek.Directory. if + // there are any files in the directory, this entry will be overwritten with a new Soulseek.Directory containing the + // files. if not they'll be left as is. + foreach (var directory in Directories) + { + directories.TryAdd(directory, new Directory(directory)); + } + + var groups = Files + .GroupBy(f => Path.GetDirectoryName(f.Key)) + .Select(g => new Directory(g.Key, g.Select(g => + { + var f = g.Value; + return new File( + f.Code, + Path.GetFileName(f.Filename), // we can send the full path, or just the filename. save bandwidth and omit the path. + f.Size, + f.Extension, + f.Attributes); + }))); + + // merge the dictionary containing all directories with the Soulseek.Directory instances containing their files. + // entries with no files will remain untouched. + foreach (var group in groups) + { + directories.AddOrUpdate(group.Name, group, (_, _) => group); + } + + return directories.Values; + } /// <summary> - /// Scans the configured <see cref="Directories"/> and fills the cache. + /// Scans the configured shares and fills the cache. /// </summary> - public void Fill() + /// <returns>The operation context.</returns> + public async Task FillAsync() { - var sw = new Stopwatch(); - sw.Start(); + if (SyncRoot.CurrentCount == 0) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } - Console.WriteLine($"[SHARED FILE CACHE]: Refreshing..."); + await Task.Yield(); - SyncRoot.EnterWriteLock(); + await SyncRoot.WaitAsync(); try { + State.SetValue(state => state with { Filling = true, FillProgress = 0 }); + Log.Debug("Starting shared file scan"); + + var sw = new Stopwatch(); + sw.Start(); + var swSnapshot = 0L; + + // this destroys the old table and creates a new one. empty the other cached fields to reflect this + // todo: use an A/B style table naming schema so that the cache remains available while it is filling CreateTable(); + Directories = new HashSet<string>(); + Files = new Dictionary<string, File>(); + State.SetValue(state => state with { Directories = 0, Files = 0 }); - var directories = 0; - var files = new Dictionary<string, Soulseek.File>(); + Log.Debug("Enumerating shared directories"); + swSnapshot = sw.ElapsedMilliseconds; - foreach (var directory in Directories) - { - directories += System.IO.Directory.GetDirectories(directory, "*", SearchOption.AllDirectories).Length; + var directories = OptionsMonitor.CurrentValue.Directories.Shared + .SelectMany(share => System.IO.Directory.GetDirectories(share, "*", SearchOption.AllDirectories)) + .ToHashSet(); + + State.SetValue(state => state with { Directories = directories.Count }); + + Log.Debug("Found {Directories} shared directories in {Elapsed}ms. Starting file scan.", sw.ElapsedMilliseconds - swSnapshot, directories.Count); + swSnapshot = sw.ElapsedMilliseconds; + var files = new Dictionary<string, File>(); + var current = 0; + + foreach (var directory in directories) + { // recursively find all files in the directory and stick a record in a dictionary, keyed on the sanitized // filename and with a value of a Soulseek.File object - var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.AllDirectories) - .Select(f => new Soulseek.File(1, f.Replace("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f))) + var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly) + .Select(f => new File(1, f.Replace("/", @"\"), new FileInfo(f).Length, Path.GetExtension(f))) .ToDictionary(f => f.Filename, f => f); - // merge the new dictionary with the rest - // this will overwrite any duplicate keys, but keys are the fully qualified name - // the only time this *should* cause problems is if one of the shares is a subdirectory of another. + // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully + // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. foreach (var file in newFiles) { if (files.ContainsKey(file.Key)) { - Console.WriteLine($"[WARNING] File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories."); + Log.Warning($"File {file.Key} shared in directory {directory} has already been cached. This is probably a misconfiguration of the shared directories (is a subdirectory being re-shared?)."); } files[file.Key] = file.Value; } + + current++; + State.SetValue(state => state with { FillProgress = current / (double)directories.Count, Files = files.Count }); } - // potentially optimize with multi-valued insert - // https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite + Log.Debug("Directory scan found {Files} in {Elapsed}ms. Populating filename database", files.Count, sw.ElapsedMilliseconds - swSnapshot); + swSnapshot = sw.ElapsedMilliseconds; + + // potentially optimize with multi-valued insert https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite foreach (var file in files) { InsertFilename(file.Key); } + Log.Debug("Inserted {Files} records in {Elapsed}ms", files.Count, sw.ElapsedMilliseconds - swSnapshot); + + Directories = directories; Files = files; - Refreshed?.Invoke(this, (directories, Files.Count)); + State.SetValue(state => state with + { + Filling = false, + Faulted = false, + FillProgress = 1, + Directories = Directories.Count, + Files = Files.Count, + }); + + Log.Debug($"Shared file cache recreated in {sw.ElapsedMilliseconds}ms. Directories: {directories.Count}, Files: {files.Count}"); + } + catch (Exception ex) + { + State.SetValue(state => state with + { + Filling = false, + Faulted = true, + FillProgress = 0, + }); + + Log.Warning(ex, "Encountered error during scan of shared files: {Message}", ex.Message); + throw; } finally { - SyncRoot.ExitWriteLock(); + SyncRoot.Release(); } - - sw.Stop(); - - Console.WriteLine($"[SHARED FILE CACHE]: Refreshed in {sw.ElapsedMilliseconds}ms. Found {Files.Count} files."); - LastFill = DateTime.UtcNow; } /// <summary> - /// Searches the cache for files matching the specified <paramref name="query"/>. + /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. /// </summary> - /// <param name="query"></param> - /// <returns></returns> - public IEnumerable<Soulseek.File> Search(SearchQuery query) - { - if (!LastFill.HasValue || LastFill.Value.AddMilliseconds(TTL) < DateTime.UtcNow) - { - Fill(); - } - - return QueryTable(query.Query); - } - - private void CreateTable() - { - SQLite = new SqliteConnection("Data Source=:memory:"); - SQLite.Open(); - - using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); - cmd.ExecuteNonQuery(); - } - - private void InsertFilename(string filename) - { - using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); - cmd.ExecuteNonQuery(); - } - - private IEnumerable<Soulseek.File> QueryTable(string text) + /// <param name="query">The query for which to search.</param> + /// <returns>The matching files.</returns> + public async Task<IEnumerable<File>> SearchAsync(SearchQuery query) { // sanitize the query string. there's probably more to it than this. - text = text + var text = query.Query .Replace("/", " ") .Replace("\\", " ") .Replace(":", " ") .Replace("\"", " "); - var query = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; - - SyncRoot.EnterReadLock(); + var sql = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'"; try { - using var cmd = new SqliteCommand(query, SQLite); + using var cmd = new SqliteCommand(sql, SQLite); var results = new List<string>(); - var reader = cmd.ExecuteReader(); + var reader = await cmd.ExecuteReaderAsync(); while (reader.Read()) { @@ -177,12 +246,28 @@ namespace slskd { // temporary error trap to refine substitution rules Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})"); - return Enumerable.Empty<Soulseek.File>(); + return Enumerable.Empty<File>(); } - finally + } + + private void CreateTable() + { + if (SQLite != null) { - SyncRoot.ExitReadLock(); + SQLite.Dispose(); } + + SQLite = new SqliteConnection("Data Source=:memory:"); + SQLite.Open(); + + using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite); + cmd.ExecuteNonQuery(); + } + + private void InsertFilename(string filename) + { + using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite); + cmd.ExecuteNonQuery(); } } }
\ No newline at end of file diff --git a/src/slskd/Application/SharedFileCacheState.cs b/src/slskd/Application/SharedFileCacheState.cs new file mode 100644 index 00000000..54b56c22 --- /dev/null +++ b/src/slskd/Application/SharedFileCacheState.cs @@ -0,0 +1,52 @@ +// <copyright file="SharedFileCacheState.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 +{ + using System; + + /// <summary> + /// Share cache state. + /// </summary> + public record SharedFileCacheState + { + /// <summary> + /// Gets a value indicating whether the cache is being filled. + /// </summary> + public bool Filling { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether the cache is faulted. + /// </summary> + public bool Faulted { get; init; } = false; + + /// <summary> + /// Gets the current fill progress. + /// </summary> + public double FillProgress { get; init; } + + /// <summary> + /// Gets the number of cached directories. + /// </summary> + public int Directories { get; init; } + + /// <summary> + /// Gets the number of cached files. + /// </summary> + public int Files { get; init; } + } +}
\ No newline at end of file diff --git a/src/slskd/Application/IStateMonitor.cs b/src/slskd/Common/IStateMonitor.cs index e4c8fc26..813dbfd5 100644 --- a/src/slskd/Application/IStateMonitor.cs +++ b/src/slskd/Common/IStateMonitor.cs @@ -20,27 +20,28 @@ namespace slskd using System; /// <summary> - /// Used for notifications when <see cref="State"/> changes. + /// Provideds observable management of state objects. /// </summary> - public interface IStateMonitor + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public interface IStateMonitor<T> { /// <summary> /// Gets the current application state. /// </summary> - State Current { get; } + T CurrentValue { get; } /// <summary> - /// Registers a listener to be called whenever <see cref="State"/> changes. + /// Registers a listener to be called whenever the tracked state changes. /// </summary> /// <param name="listener">Registers a listener to be called whenver state changes.</param> /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> - IDisposable OnChange(Action<(State Previous, State Current)> listener); + IDisposable OnChange(Action<(T Previous, T Current)> listener); /// <summary> /// Replaces the current state with the value resolved by the <paramref name="setter"/>. /// </summary> /// <param name="setter">Given the current state, resolves a new state value.</param> /// <returns>The updated state.</returns> - State Set(Func<State, State> setter); + T SetValue(Func<T, T> setter); } } diff --git a/src/slskd/Application/StateMonitor.cs b/src/slskd/Common/StateMonitor.cs index 5c9d90e3..9397d9b2 100644 --- a/src/slskd/Application/StateMonitor.cs +++ b/src/slskd/Common/StateMonitor.cs @@ -20,25 +20,28 @@ namespace slskd using System; /// <summary> - /// Used for notifications when <see cref="State"/> changes. + /// Provideds observable management of state objects. /// </summary> - public class StateMonitor : IStateMonitor + /// <typeparam name="T">The type of the tracked state object.</typeparam> + public class StateMonitor<T> : IStateMonitor<T> { - private event Action<(State, State)> Changed; + private event Action<(T, T)> Changed; /// <summary> /// Gets the current application state. /// </summary> - public State Current { get; private set; } = new State(); + public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); + + private object Lock { get; } = new object(); /// <summary> - /// Registers a listener to be called whenever <see cref="State"/> changes. + /// Registers a listener to be called whenever the stracked state changes. /// </summary> /// <param name="listener">Registers a listener to be called whenver state changes.</param> /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns> - public IDisposable OnChange(Action<(State Previous, State Current)> listener) + public IDisposable OnChange(Action<(T Previous, T Current)> listener) { - var disposable = new StateTrackerDisposable(this, listener); + var disposable = new StateTrackerDisposable<T>(this, listener); Changed += disposable.OnChange; return disposable; } @@ -48,26 +51,31 @@ namespace slskd /// </summary> /// <param name="setter">Given the current state, resolves a new state value.</param> /// <returns>The updated state.</returns> - public State Set(Func<State, State> setter) + public T SetValue(Func<T, T> setter) { - var previous = Current.ToJson().ToObject<State>(); - Current = setter(Current); + lock (Lock) + { + var previous = CurrentValue.ToJson().ToObject<T>(); + CurrentValue = setter(CurrentValue); - Changed?.Invoke((previous, Current)); - return Current; + Changed?.Invoke((previous, CurrentValue)); + return CurrentValue; + } } - private class StateTrackerDisposable : IDisposable +#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type + private class StateTrackerDisposable<T> : IDisposable +#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type { - public StateTrackerDisposable(StateMonitor stateMonitor, Action<(State Previous, State Current)> listener) + public StateTrackerDisposable(StateMonitor<T> stateMonitor, Action<(T Previous, T Current)> listener) { StateMonitor = stateMonitor; Listener = listener; } private bool Disposed { get; set; } - private Action<(State Previous, State Current)> Listener { get; } - private StateMonitor StateMonitor { get; } + private Action<(T Previous, T Current)> Listener { get; } + private StateMonitor<T> StateMonitor { get; } public void Dispose() { @@ -75,7 +83,7 @@ namespace slskd GC.SuppressFinalize(this); } - public void OnChange((State Previous, State Current) args) => Listener.Invoke(args); + public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); protected virtual void Dispose(bool disposing) { diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index ff791f39..bf83e74f 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -151,6 +151,24 @@ namespace slskd public bool NoStart { get; private set; } = false; /// <summary> + /// Gets a value indicating whether the application should connect to the Soulseek network on startup. + /// </summary> + [Argument(default, "no-connect")] + [EnvironmentVariable("NO_CONNECT")] + [Description("do not connect to the Soulseek network on startup")] + [RequiresRestart] + public bool NoConnect { get; private set; } = false; + + /// <summary> + /// Gets a value indicating whether the application should scan shared directories on startup. + /// </summary> + [Argument(default, "no-share-scan")] + [EnvironmentVariable("NO_SHARE_SCAN")] + [Description("do not scan shares on startup")] + [RequiresRestart] + public bool NoShareScan { get; private set; } = false; + + /// <summary> /// Gets the unique name for this instance. /// </summary> [Argument('i', "instance-name")] @@ -239,7 +257,6 @@ namespace slskd [Argument('s', "shared")] [EnvironmentVariable("SHARED_DIR")] [Description("path to shared files")] - [RequiresRestart] public string[] Shared { get; private set; } = new[] { Program.DefaultSharedDirectory }; } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index dcbf0a16..ef955df9 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -104,9 +104,10 @@ namespace slskd return true; }); - // add IStateMonitor to DI, to track application state in an observable way. similar to IOptionsMonitor, - // but state is managed by the application itself. Usage is roughly the same. - services.AddSingleton<IStateMonitor, StateMonitor>(); + // add IStateMonitor instance to DI, to track application state in an observable way. + // similar to IOptionsMonitor, but state is managed by the application itself. + // Usage is roughly the same. + services.AddSingleton<IStateMonitor<ApplicationState>, StateMonitor<ApplicationState>>(); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); @@ -205,8 +206,8 @@ namespace slskd services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IConversationTracker, ConversationTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); - services.AddSingleton<ISharedFileCache>(_ => - new SharedFileCache(OptionsAtStartup.Directories.Shared, 3600000)); + + services.AddSingleton<ISharedFileCache, SharedFileCache>(); services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IPeerService, PeerService>(); @@ -217,8 +218,8 @@ namespace slskd services.AddSingleton<IPushbulletService, PushbulletService>(); - services.AddHostedService<Service>(); - services.AddSingleton(_ => Service.SoulseekClient); + services.AddHostedService<Application>(); + services.AddSingleton(_ => Application.SoulseekClient); } /// <summary> |
