diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-07-24 14:39:40 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-07-24 14:39:40 -0500 |
| commit | 58bc401dab5d7eb3bc6cb07a22e0ee9c97ddf4bd (patch) | |
| tree | 64072f5eaa896335cc04de8ffe84fa79a50a2be7 /src/slskd/Application | |
| parent | fc7800409dfbe0cf26a72dd1de17cbae23d0cb35 (diff) | |
| parent | 78b3b953d9c36c2cc2939ad00881b0cbf388865a (diff) | |
| download | slskd-58bc401dab5d7eb3bc6cb07a22e0ee9c97ddf4bd.tar.gz | |
Merge pull request #125 from slskd/options
Refactor configuration components to allow for run-time updates
Diffstat (limited to 'src/slskd/Application')
10 files changed, 443 insertions, 71 deletions
diff --git a/src/slskd/Application/IStateMonitor.cs b/src/slskd/Application/IStateMonitor.cs new file mode 100644 index 00000000..e4c8fc26 --- /dev/null +++ b/src/slskd/Application/IStateMonitor.cs @@ -0,0 +1,46 @@ +// <copyright file="IStateMonitor.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> + /// Used for notifications when <see cref="State"/> changes. + /// </summary> + public interface IStateMonitor + { + /// <summary> + /// Gets the current application state. + /// </summary> + State Current { get; } + + /// <summary> + /// Registers a listener to be called whenever <see cref="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); + + /// <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); + } +} diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs index f0121af9..ddac832a 100644 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs @@ -51,8 +51,6 @@ namespace slskd.Management.API [Authorize] public IActionResult Shutdown() { - Client.Disconnect("Shut down via API"); - Lifetime.StopApplication(); return NoContent(); } @@ -65,8 +63,6 @@ namespace slskd.Management.API [Authorize] public IActionResult Restart() { - Client.Disconnect("Restarted via API"); - Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); Lifetime.StopApplication(); diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs new file mode 100644 index 00000000..6f6275d1 --- /dev/null +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -0,0 +1,71 @@ +// <copyright file="OptionsController.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; + + /// <summary> + /// Options. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class OptionsController : ControllerBase + { + public OptionsController( + OptionsAtStartup optionsAtStartup, + IOptionsSnapshot<Options> optionsSnapshot) + { + OptionsAtStartup = optionsAtStartup; + OptionsSnapshot = optionsSnapshot; + } + + private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private OptionsAtStartup OptionsAtStartup { get; } + + /// <summary> + /// Gets the current application options. + /// </summary> + /// <returns></returns> + [HttpGet] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Current() + { + return Ok(OptionsSnapshot.Value); + } + + /// <summary> + /// Gets the application options provided at startup. + /// </summary> + /// <returns></returns> + [HttpGet] + [Route("startup")] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Startup() + { + return Ok(OptionsAtStartup); + } + } +} diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 09a95c24..02e8257e 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd.Management.API { using System; @@ -37,15 +39,18 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Microsoft.Extensions.Options.IOptionsSnapshot<Options> optionsSnapshot, + IOptionsSnapshot<Options> optionsSnapshot, + OptionsAtStartup optionsAtStartup, SymmetricSecurityKey jwtSigningKey) { - Options = optionsSnapshot.Value; + OptionsSnapshot = optionsSnapshot; + OptionsAtStartup = optionsAtStartup; JwtSigningKey = jwtSigningKey; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; set; } + private IOptionsSnapshot<Options> OptionsSnapshot { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } /// <summary> /// Checks whether the provided authentication is valid. @@ -75,7 +80,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(bool), 200)] public IActionResult Enabled() { - return Ok(!Options.Web.Authentication.Disable); + return Ok(!OptionsAtStartup.Web.Authentication.Disable); } /// <summary> @@ -106,7 +111,7 @@ namespace slskd.Management.API } // only admin login for now - if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password) + if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password) { return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); } @@ -117,7 +122,7 @@ namespace slskd.Management.API private JwtSecurityToken GetJwtSecurityToken(string username, Role role) { var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl); + var expiresUtc = DateTime.UtcNow.AddMilliseconds(OptionsAtStartup.Web.Authentication.Jwt.Ttl); var claims = new List<Claim>() { diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index 4ee2185e..b3e13477 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -26,6 +26,12 @@ namespace slskd.Management public interface IManagementService { /// <summary> + /// Connects the Soulseek client to the server using the configured username and password. + /// </summary> + /// <returns>The operation context.</returns> + Task ConnectServerAsync(); + + /// <summary> /// Disconnects the Soulseek client from the server. /// </summary> /// <param name="message">An optional message containing the reason for the disconnect.</param> @@ -33,15 +39,9 @@ namespace slskd.Management void DisconnectServer(string message = null, Exception exception = null); /// <summary> - /// Connects the Soulseek client to the server using the configured username and password. - /// </summary> - /// <returns>The operation context.</returns> - Task ConnectServerAsync(); - - /// <summary> /// Gets the current state of the connection to the Soulseek server. /// </summary> /// <returns>The current server state.</returns> ServerState GetServerState(); } -} +}
\ No newline at end of file diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 84935879..66ed2b97 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd.Management { using System; @@ -32,15 +34,23 @@ namespace slskd.Management /// <param name="optionsMonitor">The options monitor used to derive application options.</param> /// <param name="soulseekClient">The Soulseek client.</param> public ManagementService( - Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor, + IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient) { - Options = optionsMonitor.CurrentValue; + OptionsMonitor = optionsMonitor; Client = soulseekClient; } private ISoulseekClient Client { get; } - private Options Options { get; } + private Options Options => OptionsMonitor.CurrentValue; + private IOptionsMonitor<Options> OptionsMonitor { get; } + + /// <summary> + /// Connects the Soulseek client to the server using the configured username and password. + /// </summary> + /// <returns>The operation context.</returns> + public Task ConnectServerAsync() + => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); /// <summary> /// Disconnects the Soulseek client from the server. @@ -51,13 +61,6 @@ namespace slskd.Management => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); /// <summary> - /// Connects the Soulseek client to the server using the configured username and password. - /// </summary> - /// <returns>The operation context.</returns> - public Task ConnectServerAsync() - => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - - /// <summary> /// Gets the current state of the connection to the Soulseek server. /// </summary> /// <returns>The current server state.</returns> @@ -70,4 +73,4 @@ namespace slskd.Management Username = Client.Username, }; } -} +}
\ No newline at end of file diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index b40c43c9..62f6eb32 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -22,13 +22,14 @@ namespace slskd using System.IO; using System.Linq; using System.Net; - using System.Text.Json; + using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Serilog; using Serilog.Events; + using slskd.Configuration; using slskd.Integrations.Pushbullet; using slskd.Messaging; using slskd.Peer; @@ -44,7 +45,9 @@ namespace slskd private (int Directories, int Files) sharedCounts = (0, 0); public Service( - IOptionsMonitor<Options> optionMonitor, + OptionsAtStartup optionsAtStartup, + IOptionsMonitor<Options> optionsMonitor, + IStateMonitor stateMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -52,10 +55,15 @@ namespace slskd ISharedFileCache sharedFileCache, IPushbulletService pushbulletService) { - OptionsMonitor = optionMonitor; - OptionsMonitor.OnChange(options => OptionsChanged(options)); + OptionsAtStartup = optionsAtStartup; - Options = OptionsMonitor.CurrentValue; + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + + PreviousOptions = OptionsMonitor.CurrentValue; + + StateMonitor = stateMonitor; + StateMonitor.OnChange(state => StateMonitor_OnChange(state)); TransferTracker = transferTracker; BrowseTracker = browseTracker; @@ -66,29 +74,29 @@ namespace slskd ProxyOptions proxyOptions = default; - if (UsingProxy) + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { proxyOptions = new ProxyOptions( - address: Options.Soulseek.Connection.Proxy.Address, - port: Options.Soulseek.Connection.Proxy.Port.Value, - username: Options.Soulseek.Connection.Proxy.Username, - password: Options.Soulseek.Connection.Proxy.Password); + address: OptionsAtStartup.Soulseek.Connection.Proxy.Address, + port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value, + username: OptionsAtStartup.Soulseek.Connection.Proxy.Username, + password: OptionsAtStartup.Soulseek.Connection.Proxy.Password); } var connectionOptions = new ConnectionOptions( - readBufferSize: Options.Soulseek.Connection.Buffer.Read, - writeBufferSize: Options.Soulseek.Connection.Buffer.Write, - connectTimeout: Options.Soulseek.Connection.Timeout.Connect, - inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity, + readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read, + writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write, + connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, proxyOptions: proxyOptions); var clientOptions = new SoulseekClientOptions( - listenPort: Options.Soulseek.ListenPort, + listenPort: OptionsAtStartup.Soulseek.ListenPort, enableListener: true, userEndPointCache: new UserEndPointCache(), - distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, - minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel, + distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, serverConnectionOptions: connectionOptions, @@ -132,36 +140,39 @@ namespace slskd } public static ISoulseekClient SoulseekClient { get; private set; } + private IBrowseTracker BrowseTracker { get; set; } private ISoulseekClient Client { get; set; } private IConversationTracker ConversationTracker { get; set; } private ILogger Logger { get; set; } = Log.ForContext<Service>(); private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); private IOptionsMonitor<Options> OptionsMonitor { get; set; } - private Options Options { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } + private Options PreviousOptions { get; set; } private IRoomTracker RoomTracker { get; set; } + private IStateMonitor StateMonitor { get; set; } private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } - private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue; private IPushbulletService Pushbullet { get; } + private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); public async Task StartAsync(CancellationToken cancellationToken) { - if (UsingProxy) + if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { - Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); + Logger.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}"); } Logger.Information("Client started"); - Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); + Logger.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + 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."); } else { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); + await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); } } @@ -173,15 +184,128 @@ namespace slskd return Task.CompletedTask; } - private void OptionsChanged(Options options) + private async Task OptionsMonitor_OnChange(Options newOptions) { - Console.WriteLine($"Options changed. Old options:"); - Console.WriteLine(JsonSerializer.Serialize(Options)); - Console.WriteLine($"\tNew options:"); - Console.WriteLine(JsonSerializer.Serialize(options)); - // todo: did options really change? - // todo: if options did change, create a patch and ReconfigureOptionsAsync - // todo: if ReconfigureOptionsAsync = true, find some way to let the user know a reconnect is pending + // this code is known to fire more than once per update. i'm not sure + // whether these might be executed concurrently. lock to be safe, because + // we need to accurately track the last value of Options for diffing purposes. + // threading shenanigans here could lead to missed updates. + OptionsSyncRoot.EnterWriteLock(); + + try + { + var pendingRestart = false; + var pendingReconnect = false; + var soulseekRequiresReconnect = false; + + var diff = PreviousOptions.DiffWith(newOptions); + + // don't react to duplicate/no-change events + // https://github.com/slskd/slskd/issues/126 + if (!diff.Any()) + { + return; + } + + foreach (var (property, fqn, left, right) in diff) + { + static bool HasAttribute<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + + var requiresRestart = HasAttribute<RequiresRestartAttribute>(property); + var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property); + + Logger.Debug($"{fqn} changed from '{left ?? "<null>"}' to '{right ?? "<null>"}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); + + pendingRestart |= requiresRestart; + pendingReconnect |= requiresReconnect; + } + + // determine whether any Soulseek options changed. if so, we need to construct a patch + // and invoke ReconfigureOptionsAsync(). + var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); + + if (slskDiff.Any()) + { + var old = PreviousOptions.Soulseek; + var update = newOptions.Soulseek; + + Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); + + // determine whether any Connection options changed. if so, replace the whole object. + // Soulseek.NET doesn't offer a way to patch parts of connection options. the updates only affect + // new connections, so a partial patch doesn't make a lot of sense anyway. + var connectionDiff = old.Connection.DiffWith(update.Connection); + + ConnectionOptions connectionPatch = null; + + if (connectionDiff.Any()) + { + var connection = update.Connection; + + ProxyOptions proxyPatch = null; + + if (connection.Proxy.Enabled) + { + proxyPatch = new ProxyOptions( + connection.Proxy.Address, + connection.Proxy.Port.Value, + connection.Proxy.Username, + connection.Proxy.Password); + } + + connectionPatch = new ConnectionOptions( + connection.Buffer.Read, + connection.Buffer.Write, + connection.Timeout.Connect, + connection.Timeout.Inactivity, + proxyOptions: proxyPatch); + } + + var patch = new SoulseekClientOptionsPatch( + listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort, + enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, + distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, + serverConnectionOptions: connectionPatch, + peerConnectionOptions: connectionPatch, + transferConnectionOptions: connectionPatch, + incomingConnectionOptions: connectionPatch, + distributedConnectionOptions: connectionPatch); + + Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); + + soulseekRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); + } + + // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed, + // 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 }); + 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 }); + Logger.Information("One or more updated options requires an application restart to take effect."); + } + + Logger.Information("Options updated successfully."); + } + catch (Exception ex) + { + Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); + } + finally + { + PreviousOptions = OptionsMonitor.CurrentValue; + OptionsSyncRoot.ExitWriteLock(); + } + } + + private void StateMonitor_OnChange((State Previous, State 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) @@ -202,7 +326,7 @@ namespace slskd private Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) { var directories = System.IO.Directory - .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) + .GetDirectories(OptionsMonitor.CurrentValue.Directories.Shared, "*", 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))))); @@ -237,11 +361,16 @@ namespace slskd private void Client_LoggedIn(object sender, EventArgs e) { - Logger.Information("Logged in to the Soulseek server as {Username}", Options.Soulseek.Username); + Logger.Information("Logged in to the Soulseek server as {Username}", Client.Username); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { + if (StateMonitor.Current.PendingReconnect) + { + StateMonitor.Set(state => state with { PendingReconnect = false }); + } + if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException) { Logger.Information("Disconnected from the Soulseek server: the client is shutting down"); @@ -256,13 +385,13 @@ namespace slskd } else if (args.Exception is KickedFromServerException) { - Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Options.Soulseek.Username); + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); } else { Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + if (string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Soulseek.Username) || string.IsNullOrEmpty(OptionsMonitor.CurrentValue.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; @@ -284,7 +413,9 @@ namespace slskd try { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + // 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); break; } catch (Exception ex) @@ -300,7 +431,7 @@ namespace slskd { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - if (Options.Integration.Pushbullet.Enabled && !args.Replayed) + if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && !args.Replayed) { Console.WriteLine("Pushing..."); _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); @@ -311,7 +442,7 @@ namespace slskd { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); } @@ -320,7 +451,7 @@ namespace slskd private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) { // this will fire when we join a room; track that through the join operation. - if (args.Username != Options.Soulseek.Username) + if (args.Username != Client.Username) { RoomTracker.TryAddUser(args.RoomName, args.UserData); } @@ -336,7 +467,7 @@ namespace slskd var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); - if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + if (OptionsMonitor.CurrentValue.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); } diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/State.cs new file mode 100644 index 00000000..75d46dec --- /dev/null +++ b/src/slskd/Application/State.cs @@ -0,0 +1,24 @@ +// <copyright file="State.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 +{ + /// <summary> + /// Application state. + /// </summary> + public record State(bool PendingReconnect = false, bool PendingRestart = false); +}
\ No newline at end of file diff --git a/src/slskd/Application/StateMonitor.cs b/src/slskd/Application/StateMonitor.cs new file mode 100644 index 00000000..5c9d90e3 --- /dev/null +++ b/src/slskd/Application/StateMonitor.cs @@ -0,0 +1,94 @@ +// <copyright file="StateMonitor.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> + /// Used for notifications when <see cref="State"/> changes. + /// </summary> + public class StateMonitor : IStateMonitor + { + private event Action<(State, State)> Changed; + + /// <summary> + /// Gets the current application state. + /// </summary> + public State Current { get; private set; } = new State(); + + /// <summary> + /// Registers a listener to be called whenever <see cref="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) + { + var disposable = new StateTrackerDisposable(this, listener); + Changed += disposable.OnChange; + return disposable; + } + + /// <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> + public State Set(Func<State, State> setter) + { + var previous = Current.ToJson().ToObject<State>(); + Current = setter(Current); + + Changed?.Invoke((previous, Current)); + return Current; + } + + private class StateTrackerDisposable : IDisposable + { + public StateTrackerDisposable(StateMonitor stateMonitor, Action<(State Previous, State Current)> listener) + { + StateMonitor = stateMonitor; + Listener = listener; + } + + private bool Disposed { get; set; } + private Action<(State Previous, State Current)> Listener { get; } + private StateMonitor StateMonitor { get; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + public void OnChange((State Previous, State Current) args) => Listener.Invoke(args); + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + StateMonitor.Changed -= OnChange; + } + + Disposed = true; + } + } + } + } +} diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index 97b86689..9ed36d1b 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd.Transfer.API { using System; @@ -46,7 +48,7 @@ namespace slskd.Transfer.API /// <param name="tracker"></param> /// <param name="ftpClient"></param> public TransfersController( - Microsoft.Extensions.Options.IOptionsSnapshot<Options> options, + IOptionsSnapshot<Options> options, ISoulseekClient client, ITransferTracker tracker, IFTPService ftpClient) |
