From c67223f7b4d4c9f8baa80a9dbf48c8fd69c4c2eb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jul 2021 23:46:44 -0500 Subject: fix spacing --- src/slskd/Properties/slskd.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index 43c87f90..c6876249 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -55,7 +55,7 @@ # address: ~ # port: ~ # encryption_mode: auto -# ignore_certificate_errors: false +# ignore_certificate_errors: false # username: ~ # password: ~ # remote_path: / @@ -63,10 +63,10 @@ # connection_timeout: 5000 # retry_attempts: 3 # pushbullet: -# enabled: false -# access_token: ~ -# notification_prefix: "From slskd:" -# notify_on_private_message: true -# notify_on_room_mention: true -# retry_attempts: 3 -# cooldown_time: 900000 \ No newline at end of file +# enabled: false +# access_token: ~ +# notification_prefix: "From slskd:" +# notify_on_private_message: true +# notify_on_room_mention: true +# retry_attempts: 3 +# cooldown_time: 900000 \ No newline at end of file -- cgit v1.2.3 From de48f04b36c784061fd26bc47adaf244c0b8dfe8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jul 2021 23:51:16 -0500 Subject: add GetOptions() --- .../Application/Management/IManagementService.cs | 14 ++++++++++---- .../Application/Management/ManagementService.cs | 21 ++++++++++++++------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index 4ee2185e..5ece698b 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -25,6 +25,12 @@ namespace slskd.Management /// public interface IManagementService { + /// + /// Connects the Soulseek client to the server using the configured username and password. + /// + /// The operation context. + Task ConnectServerAsync(); + /// /// Disconnects the Soulseek client from the server. /// @@ -33,10 +39,10 @@ namespace slskd.Management void DisconnectServer(string message = null, Exception exception = null); /// - /// Connects the Soulseek client to the server using the configured username and password. + /// Gets the current application options. /// - /// The operation context. - Task ConnectServerAsync(); + /// + Options GetOptions(); /// /// Gets the current state of the connection to the Soulseek server. @@ -44,4 +50,4 @@ namespace slskd.Management /// The current server state. 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..4a385cff 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -35,12 +35,20 @@ namespace slskd.Management Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient) { - Options = optionsMonitor.CurrentValue; + OptionsMonitor = optionsMonitor; Client = soulseekClient; } private ISoulseekClient Client { get; } - private Options Options { get; } + private Options Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + + /// + /// Connects the Soulseek client to the server using the configured username and password. + /// + /// The operation context. + public Task ConnectServerAsync() + => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); /// /// Disconnects the Soulseek client from the server. @@ -51,11 +59,10 @@ namespace slskd.Management => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); /// - /// Connects the Soulseek client to the server using the configured username and password. + /// Gets the current application options. /// - /// The operation context. - public Task ConnectServerAsync() - => Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + /// + public Options GetOptions() => Options; /// /// Gets the current state of the connection to the Soulseek server. @@ -70,4 +77,4 @@ namespace slskd.Management Username = Client.Username, }; } -} +} \ No newline at end of file -- cgit v1.2.3 From eaa6a1be21747f46370b5b1d545b31513eeb3ed8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 00:01:42 -0500 Subject: add OptionsController --- .../API/Controllers/OptionsController.cs | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/slskd/Application/Management/API/Controllers/OptionsController.cs 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..b75adc97 --- /dev/null +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -0,0 +1,53 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Management.API +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Options. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class OptionsController : ControllerBase + { + public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + { + OptionsMonitor = optionsMonitor; + } + + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Options Options => OptionsMonitor.CurrentValue; + + /// + /// Gets the current application options. + /// + /// + [HttpGet] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Get() + { + return Ok(Options); + } + } +} -- cgit v1.2.3 From 728a275d667cdc1f5af87b8e64318c83c011124e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 21:38:19 -0500 Subject: pass TargetType to yaml config --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 062d3a48..987a39a0 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -340,6 +340,7 @@ namespace slskd prefix: environmentVariablePrefix) .AddYamlFile( path: Path.GetFileName(configurationFile), + targetType: typeof(Options), optional: true, reloadOnChange: false, provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory -- cgit v1.2.3 From 4aa95dfbfd81c478c2872ec7320d20036ecd867a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 21:39:29 -0500 Subject: derive config root from namespace --- src/slskd/Common/Configuration/YamlConfigurationSource.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs index 332df647..82e2227d 100644 --- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -37,6 +37,7 @@ namespace slskd.Configuration /// /// Path relative to the base path stored in of . /// + /// The type from which to map properties. /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. /// @@ -44,7 +45,7 @@ namespace slskd.Configuration /// /// The updated to use to access the file. /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) { if (builder == null) { @@ -59,6 +60,7 @@ namespace slskd.Configuration return builder.AddYamlFile(s => { s.Path = path; + s.TargetType = targetType; s.Optional = optional; s.ReloadOnChange = reloadOnChange; s.NormalizeKeys = normalizeKeys; @@ -89,9 +91,13 @@ namespace slskd.Configuration public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); NormalizeKeys = source.NormalizeKeys; } + private Type TargetType { get; set; } + private string Namespace { get; set; } private bool NormalizeKeys { get; set; } private string[] NullValues { get; } = new[] { "~", "null", string.Empty }; @@ -111,7 +117,7 @@ namespace slskd.Configuration if (yaml.Documents.Count > 0) { var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; - Traverse(rootNode); + Traverse(rootNode, Namespace); } } catch (YamlException e) @@ -161,6 +167,11 @@ namespace slskd.Configuration /// public class YamlConfigurationSource : FileConfigurationSource { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + /// /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). /// -- cgit v1.2.3 From b5167888d9dd6bb74ac632e4559716c7ca433f0f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 21:40:25 -0500 Subject: update config template --- src/slskd/Properties/slskd.yml | 135 ++++++++++++++++++++--------------------- 1 file changed, 67 insertions(+), 68 deletions(-) diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index c6876249..938d2a70 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -1,72 +1,71 @@ -# slskd: -# debug: false -# no_logo: false -# instance_name: default -# web: -# port: 5000 -# https: -# port: 5001 -# force: false -# certificate: -# pfx: ~ -# password: ~ -# url_base: / -# content_path: wwwroot -# authentication: -# disable: false -# username: slskd -# password: slskd -# jwt: -# key: ~ -# ttl: 604800000 -# directories: -# app: ~ -# incomplete: ~ -# downloads: ~ -# shared: ~ -# logger: -# loki: ~ -# feature: -# prometheus: false -# swagger: false -# soulseek: -# username: ~ -# password: ~ -# listen_port: 50000 -# diagnostic_level: Info -# distributed_network: -# disabled: false -# child_limit: 25 -# connection: -# timeout: -# connect: 10000 -# inactivity: 15000 -# buffer: -# read: 16384 -# write: 16384 -# proxy: -# address: ~ -# port: ~ -# username: ~ -# password: ~ -# integration: -# ftp: -# enabled: false +# debug: false +# no_logo: false +# instance_name: default +# web: +# port: 5000 +# https: +# port: 5001 +# force: false +# certificate: +# pfx: ~ +# password: ~ +# url_base: / +# content_path: wwwroot +# authentication: +# disable: false +# username: slskd +# password: slskd +# jwt: +# key: ~ +# ttl: 604800000 +# directories: +# app: ~ +# incomplete: ~ +# downloads: ~ +# shared: ~ +# logger: +# loki: ~ +# feature: +# prometheus: false +# swagger: false +# soulseek: +# username: ~ +# password: ~ +# listen_port: 50000 +# diagnostic_level: Info +# distributed_network: +# disabled: false +# child_limit: 25 +# connection: +# timeout: +# connect: 10000 +# inactivity: 15000 +# buffer: +# read: 16384 +# write: 16384 +# proxy: # address: ~ # port: ~ -# encryption_mode: auto -# ignore_certificate_errors: false # username: ~ # password: ~ -# remote_path: / -# overwrite_existing: true -# connection_timeout: 5000 -# retry_attempts: 3 -# pushbullet: -# enabled: false -# access_token: ~ -# notification_prefix: "From slskd:" -# notify_on_private_message: true -# notify_on_room_mention: true -# retry_attempts: 3 -# cooldown_time: 900000 \ No newline at end of file +# integration: +# ftp: +# enabled: false +# address: ~ +# port: ~ +# encryption_mode: auto +# ignore_certificate_errors: false +# username: ~ +# password: ~ +# remote_path: / +# overwrite_existing: true +# connection_timeout: 5000 +# retry_attempts: 3 +# pushbullet: +# enabled: false +# access_token: ~ +# notification_prefix: "From slskd:" +# notify_on_private_message: true +# notify_on_room_mention: true +# retry_attempts: 3 +# cooldown_time: 900000 \ No newline at end of file -- cgit v1.2.3 From d8eb620c39da4d6ac61fd2d55babb2d73558c9e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 22:08:50 -0500 Subject: rename Configuration namespace to ConfigurationSources --- .../CommandLineConfigurationSource.cs | 157 ----------------- .../DefaultValueConfigurationSource.cs | 136 --------------- .../EnvironmentVariableConfigurationSource.cs | 151 ---------------- .../Configuration/YamlConfigurationSource.cs | 191 --------------------- .../CommandLineConfigurationSource.cs | 157 +++++++++++++++++ .../DefaultValueConfigurationSource.cs | 136 +++++++++++++++ .../EnvironmentVariableConfigurationSource.cs | 151 ++++++++++++++++ .../YamlConfigurationSource.cs | 191 +++++++++++++++++++++ src/slskd/Program.cs | 2 +- 9 files changed, 636 insertions(+), 636 deletions(-) delete mode 100644 src/slskd/Common/Configuration/CommandLineConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs delete mode 100644 src/slskd/Common/Configuration/YamlConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs create mode 100644 src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs deleted file mode 100644 index 6cf59808..00000000 --- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs +++ /dev/null @@ -1,157 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Configuration -{ - using System; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - using Utility.CommandLine; - - /// - /// Extension methods for adding . - /// - public static class CommandLineConfigurationExtensions - { - /// - /// Adds a command line argument configuration soruce to . - /// - /// The to which to add. - /// The type from which to map properties. - /// The command line string from which to parse arguments. - /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddCommandLine(s => - { - s.TargetType = targetType; - s.CommandLine = commandLine ?? Environment.CommandLine; - }); - } - - /// - /// Adds a command line argument configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A command line argument . - /// - public class CommandLineConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public CommandLineConfigurationProvider(CommandLineConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - CommandLine = source.CommandLine; - } - - private string CommandLine { get; set; } - private string Namespace { get; set; } - private Type TargetType { get; set; } - - /// - /// Parses command line arguments from the specified string and maps them to the corresponding keys. - /// - public override void Load() - { - var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; - - void Map(Type type, string path) - { - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute)); - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (attribute != default) - { - var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString(); - var longName = (string)attribute.ConstructorArguments[1].Value; - var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i)); - - foreach (var argument in arguments) - { - if (dictionary.ContainsKey(argument)) - { - var value = dictionary[argument].ToString(); - - if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value)) - { - value = "true"; - } - - Data[key] = value; - } - } - } - else - { - Map(property.PropertyType, key); - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents command line arguments as an . - /// - public class CommandLineConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the command line string from which to parse arguments. - /// - public string CommandLine { get; set; } - - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); - } -} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs deleted file mode 100644 index 15cf4070..00000000 --- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Configuration -{ - using System; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - - /// - /// Extension methods for adding . - /// - public static class DefaultValueConfigurationExtensions - { - /// - /// Adds a default value configuration source to . - /// - /// The to which to add. - /// The type from which to load default values. - /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddDefaultValues(s => - { - s.TargetType = targetType; - }); - } - - /// - /// Adds a default value configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A default value . - /// - public class DefaultValueConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - } - - private string Namespace { get; set; } - private Type TargetType { get; set; } - - /// - /// Loads default values from the specified and maps them to the corresponding keys. - /// - public override void Load() - { - void Map(Type type, string path) - { - var defaults = Activator.CreateInstance(type); - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (property.PropertyType.Namespace.StartsWith(Namespace)) - { - Map(property.PropertyType, key); - } - else - { - var value = property.GetValue(defaults); - - if (value != null) - { - Data[key] = value.ToString(); - } - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents default values as an . - /// - public class DefaultValueConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new DefaultValueConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs deleted file mode 100644 index 9a09d4e1..00000000 --- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs +++ /dev/null @@ -1,151 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Configuration -{ - using System; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - using Utility.EnvironmentVariables; - - /// - /// Extension methods for adding . - /// - public static class EnvironmentVariableConfigurationExtensions - { - /// - /// Adds an environment variable configuration source to . - /// - /// The to which to add. - /// The type from which to map properties. - /// A prefix to prepend to all variable names. - /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddEnvironmentVariables(s => - { - s.TargetType = targetType; - s.Prefix = prefix ?? string.Empty; - }); - } - - /// - /// Adds an enviroment variable configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// An enviroment variable . - /// - public class EnvironmentVariableConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - Prefix = source.Prefix; - } - - private Type TargetType { get; set; } - private string Namespace { get; set; } - private string Prefix { get; set; } - - /// - /// Loads environment variables and maps them to the corresponding keys. - /// - public override void Load() - { - void Map(Type type, string path) - { - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute)); - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (attribute != default) - { - var name = (string)attribute.ConstructorArguments[0].Value; - - if (!string.IsNullOrEmpty(name)) - { - var value = Environment.GetEnvironmentVariable(Prefix + name); - - if (value != null) - { - Data[key] = value.ToString(); - } - } - } - else - { - Map(property.PropertyType, key); - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents environment variables as an . - /// - public class EnvironmentVariableConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Gets or sets a prefix to prepend to all variable names. - /// - public string Prefix { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new EnvironmentVariableConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs deleted file mode 100644 index 82e2227d..00000000 --- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs +++ /dev/null @@ -1,191 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Configuration -{ - using System; - using System.IO; - using System.Linq; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.FileProviders; - using YamlDotNet.Core; - using YamlDotNet.RepresentationModel; - - /// - /// Extension methods for adding . - /// - public static class YamlConfigurationExtensions - { - /// - /// Adds a YAML configuration source to . - /// - /// The to which to add . - /// - /// Path relative to the base path stored in of . - /// - /// The type from which to map properties. - /// Whether the file is optional. - /// Whether the configuration should be reloaded if the file changes. - /// - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - /// The updated to use to access the file. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("File path must be a non-empty string.", nameof(path)); - } - - return builder.AddYamlFile(s => - { - s.Path = path; - s.TargetType = targetType; - s.Optional = optional; - s.ReloadOnChange = reloadOnChange; - s.NormalizeKeys = normalizeKeys; - s.FileProvider = provider; - s.ResolveFileProvider(); - }); - } - - /// - /// Adds a YAML configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A YAML file based . - /// - public class YamlConfigurationProvider : FileConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public YamlConfigurationProvider(YamlConfigurationSource source) - : base(source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - NormalizeKeys = source.NormalizeKeys; - } - - private Type TargetType { get; set; } - private string Namespace { get; set; } - private bool NormalizeKeys { get; set; } - private string[] NullValues { get; } = new[] { "~", "null", string.Empty }; - - /// - /// Loads the YAML data from a stream. - /// - /// The stream to read. - public override void Load(Stream stream) - { - try - { - using var reader = new StreamReader(stream); - - var yaml = new YamlStream(); - yaml.Load(reader); - - if (yaml.Documents.Count > 0) - { - var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; - Traverse(rootNode, Namespace); - } - } - catch (YamlException e) - { - throw new FormatException("Could not parse the YAML file.", e); - } - } - - private void Traverse(YamlNode root, string path = null) - { - string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; - - if (root is YamlScalarNode scalar) - { - if (Data.ContainsKey(Normalize(path))) - { - throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); - } - - var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - - if (value != null) - { - Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - } - } - else if (root is YamlMappingNode map) - { - foreach (var node in map.Children) - { - var key = Normalize(((YamlScalarNode)node.Key).Value); - Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); - } - } - else if (root is YamlSequenceNode sequence) - { - for (int i = 0; i < sequence.Children.Count; i++) - { - Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); - } - } - } - } - - /// - /// Represents a YAML file as an . - /// - public class YamlConfigurationSource : FileConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKeys { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - EnsureDefaults(builder); - return new YamlConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs new file mode 100644 index 00000000..724a52b3 --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs @@ -0,0 +1,157 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.ConfigurationSources +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + using Utility.CommandLine; + + /// + /// Extension methods for adding . + /// + public static class CommandLineConfigurationExtensions + { + /// + /// Adds a command line argument configuration soruce to . + /// + /// The to which to add. + /// The type from which to map properties. + /// The command line string from which to parse arguments. + /// The updated . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddCommandLine(s => + { + s.TargetType = targetType; + s.CommandLine = commandLine ?? Environment.CommandLine; + }); + } + + /// + /// Adds a command line argument configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A command line argument . + /// + public class CommandLineConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public CommandLineConfigurationProvider(CommandLineConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + CommandLine = source.CommandLine; + } + + private string CommandLine { get; set; } + private string Namespace { get; set; } + private Type TargetType { get; set; } + + /// + /// Parses command line arguments from the specified string and maps them to the corresponding keys. + /// + public override void Load() + { + var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; + + void Map(Type type, string path) + { + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute)); + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (attribute != default) + { + var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString(); + var longName = (string)attribute.ConstructorArguments[1].Value; + var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i)); + + foreach (var argument in arguments) + { + if (dictionary.ContainsKey(argument)) + { + var value = dictionary[argument].ToString(); + + if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value)) + { + value = "true"; + } + + Data[key] = value; + } + } + } + else + { + Map(property.PropertyType, key); + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents command line arguments as an . + /// + public class CommandLineConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the command line string from which to parse arguments. + /// + public string CommandLine { get; set; } + + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs new file mode 100644 index 00000000..1784ce26 --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs @@ -0,0 +1,136 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.ConfigurationSources +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + + /// + /// Extension methods for adding . + /// + public static class DefaultValueConfigurationExtensions + { + /// + /// Adds a default value configuration source to . + /// + /// The to which to add. + /// The type from which to load default values. + /// The updated . + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddDefaultValues(s => + { + s.TargetType = targetType; + }); + } + + /// + /// Adds a default value configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A default value . + /// + public class DefaultValueConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + } + + private string Namespace { get; set; } + private Type TargetType { get; set; } + + /// + /// Loads default values from the specified and maps them to the corresponding keys. + /// + public override void Load() + { + void Map(Type type, string path) + { + var defaults = Activator.CreateInstance(type); + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (property.PropertyType.Namespace.StartsWith(Namespace)) + { + Map(property.PropertyType, key); + } + else + { + var value = property.GetValue(defaults); + + if (value != null) + { + Data[key] = value.ToString(); + } + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents default values as an . + /// + public class DefaultValueConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new DefaultValueConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs new file mode 100644 index 00000000..94823d11 --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs @@ -0,0 +1,151 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.ConfigurationSources +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + using Utility.EnvironmentVariables; + + /// + /// Extension methods for adding . + /// + public static class EnvironmentVariableConfigurationExtensions + { + /// + /// Adds an environment variable configuration source to . + /// + /// The to which to add. + /// The type from which to map properties. + /// A prefix to prepend to all variable names. + /// The updated . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddEnvironmentVariables(s => + { + s.TargetType = targetType; + s.Prefix = prefix ?? string.Empty; + }); + } + + /// + /// Adds an enviroment variable configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// An enviroment variable . + /// + public class EnvironmentVariableConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + Prefix = source.Prefix; + } + + private Type TargetType { get; set; } + private string Namespace { get; set; } + private string Prefix { get; set; } + + /// + /// Loads environment variables and maps them to the corresponding keys. + /// + public override void Load() + { + void Map(Type type, string path) + { + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute)); + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (attribute != default) + { + var name = (string)attribute.ConstructorArguments[0].Value; + + if (!string.IsNullOrEmpty(name)) + { + var value = Environment.GetEnvironmentVariable(Prefix + name); + + if (value != null) + { + Data[key] = value.ToString(); + } + } + } + else + { + Map(property.PropertyType, key); + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents environment variables as an . + /// + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Gets or sets a prefix to prepend to all variable names. + /// + public string Prefix { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs new file mode 100644 index 00000000..654f5b2e --- /dev/null +++ b/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs @@ -0,0 +1,191 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.ConfigurationSources +{ + using System; + using System.IO; + using System.Linq; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// + /// Extension methods for adding . + /// + public static class YamlConfigurationExtensions + { + /// + /// Adds a YAML configuration source to . + /// + /// The to which to add . + /// + /// Path relative to the base path stored in of . + /// + /// The type from which to map properties. + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + /// The updated to use to access the file. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.Path = path; + s.TargetType = targetType; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.NormalizeKeys = normalizeKeys; + s.FileProvider = provider; + s.ResolveFileProvider(); + }); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A YAML file based . + /// + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public YamlConfigurationProvider(YamlConfigurationSource source) + : base(source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + NormalizeKeys = source.NormalizeKeys; + } + + private Type TargetType { get; set; } + private string Namespace { get; set; } + private bool NormalizeKeys { get; set; } + private string[] NullValues { get; } = new[] { "~", "null", string.Empty }; + + /// + /// Loads the YAML data from a stream. + /// + /// The stream to read. + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + if (yaml.Documents.Count > 0) + { + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + Traverse(rootNode, Namespace); + } + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Normalize(path))) + { + throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); + } + + var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + + if (value != null) + { + Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Normalize(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count; i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKeys { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 987a39a0..01618efb 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -36,7 +36,7 @@ namespace slskd using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; - using slskd.Configuration; + using slskd.ConfigurationSources; using slskd.Cryptography; using slskd.Validation; using Utility.CommandLine; -- cgit v1.2.3 From 373b2974614171f5492d2e36899a7c0a67fa4395 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 22:32:47 -0500 Subject: wip --- .../API/Controllers/OptionsController.cs | 8 +- .../API/Controllers/SessionController.cs | 4 +- .../Application/Management/IManagementService.cs | 2 +- .../Application/Management/ManagementService.cs | 8 +- src/slskd/Application/Service.cs | 66 +- .../API/Controllers/TransfersController.cs | 4 +- src/slskd/Common/Validation/Extensions.cs | 6 +- .../Common/Validation/X509CertificateAttribute.cs | 2 +- src/slskd/Configuration.cs | 769 +++++++++++++++++++++ src/slskd/Integrations/FTP/FTPClientFactory.cs | 6 +- src/slskd/Integrations/FTP/FTPService.cs | 6 +- .../Integrations/Pushbullet/PushbulletService.cs | 6 +- src/slskd/Options.cs | 769 --------------------- src/slskd/Program.cs | 72 +- src/slskd/Startup.cs | 44 +- 15 files changed, 886 insertions(+), 886 deletions(-) create mode 100644 src/slskd/Configuration.cs delete mode 100644 src/slskd/Options.cs diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index b75adc97..578b6b4c 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -30,13 +30,13 @@ namespace slskd.Management.API [Consumes("application/json")] public class OptionsController : ControllerBase { - public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { OptionsMonitor = optionsMonitor; } - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } - private Options Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Configuration Options => OptionsMonitor.CurrentValue; /// /// Gets the current application options. @@ -44,7 +44,7 @@ namespace slskd.Management.API /// [HttpGet] [Authorize] - [ProducesResponseType(typeof(Options), 200)] + [ProducesResponseType(typeof(Configuration), 200)] public IActionResult Get() { return Ok(Options); diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 09a95c24..1721f3f2 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,7 +37,7 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, + Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, SymmetricSecurityKey jwtSigningKey) { Options = optionsSnapshot.Value; @@ -45,7 +45,7 @@ namespace slskd.Management.API } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; set; } + private Configuration Options { get; set; } /// /// Checks whether the provided authentication is valid. diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index 5ece698b..d4f7ff51 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -42,7 +42,7 @@ namespace slskd.Management /// Gets the current application options. /// /// - Options GetOptions(); + Configuration GetOptions(); /// /// Gets the current state of the connection to the Soulseek server. diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 4a385cff..a1d807a0 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -32,7 +32,7 @@ namespace slskd.Management /// The options monitor used to derive application options. /// The Soulseek client. public ManagementService( - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient) { OptionsMonitor = optionsMonitor; @@ -40,8 +40,8 @@ namespace slskd.Management } private ISoulseekClient Client { get; } - private Options Options => OptionsMonitor.CurrentValue; - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Configuration Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } /// /// Connects the Soulseek client to the server using the configured username and password. @@ -62,7 +62,7 @@ namespace slskd.Management /// Gets the current application options. /// /// - public Options GetOptions() => Options; + public Configuration GetOptions() => Options; /// /// Gets the current state of the connection to the Soulseek server. diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index d9b682fc..9a65ae37 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -44,7 +44,7 @@ namespace slskd private (int Directories, int Files) sharedCounts = (0, 0); public Service( - IOptionsMonitor optionMonitor, + IOptionsMonitor optionMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -55,7 +55,7 @@ namespace slskd OptionsMonitor = optionMonitor; OptionsMonitor.OnChange(options => OptionsChanged(options)); - Options = OptionsMonitor.CurrentValue; + Configuration = OptionsMonitor.CurrentValue; TransferTracker = transferTracker; BrowseTracker = browseTracker; @@ -69,26 +69,26 @@ namespace slskd if (UsingProxy) { 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: Configuration.Soulseek.Connection.Proxy.Address, + port: Configuration.Soulseek.Connection.Proxy.Port.Value, + username: Configuration.Soulseek.Connection.Proxy.Username, + password: Configuration.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: Configuration.Soulseek.Connection.Buffer.Read, + writeBufferSize: Configuration.Soulseek.Connection.Buffer.Write, + connectTimeout: Configuration.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: Configuration.Soulseek.Connection.Timeout.Inactivity, proxyOptions: proxyOptions); var clientOptions = new SoulseekClientOptions( - listenPort: Options.Soulseek.ListenPort, + listenPort: Configuration.Soulseek.ListenPort, enableListener: true, userEndPointCache: new UserEndPointCache(), - distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, - minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel, + distributedChildLimit: Configuration.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !Configuration.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: Configuration.Soulseek.DiagnosticLevel, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, serverConnectionOptions: connectionOptions, @@ -137,31 +137,31 @@ namespace slskd private IConversationTracker ConversationTracker { get; set; } private ILogger Logger { get; set; } = Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); - private IOptionsMonitor OptionsMonitor { get; set; } - private Options Options { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private Configuration Configuration { get; set; } private IRoomTracker RoomTracker { 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 bool UsingProxy => !string.IsNullOrWhiteSpace(Configuration.Soulseek.Connection.Proxy.Address) && Configuration.Soulseek.Connection.Proxy.Port.HasValue; private IPushbulletService Pushbullet { get; } public async Task StartAsync(CancellationToken cancellationToken) { if (UsingProxy) { - Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); + Logger.Information($"Using Proxy {Configuration.Soulseek.Connection.Proxy.Address}:{Configuration.Soulseek.Connection.Proxy.Port}"); } Logger.Information("Client started"); - Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); + Logger.Information("Listening on port {Port}", Configuration.Soulseek.ListenPort); - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + if (string.IsNullOrEmpty(Configuration.Soulseek.Username) || string.IsNullOrEmpty(Configuration.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(Configuration.Soulseek.Username, Configuration.Soulseek.Password).ConfigureAwait(false); } } @@ -173,12 +173,12 @@ namespace slskd return Task.CompletedTask; } - private void OptionsChanged(Options options) + private void OptionsChanged(Configuration configuration) { Console.WriteLine($"Options changed. Old options:"); - Console.WriteLine(JsonSerializer.Serialize(Options)); + Console.WriteLine(JsonSerializer.Serialize(Configuration)); Console.WriteLine($"\tNew options:"); - Console.WriteLine(JsonSerializer.Serialize(options)); + Console.WriteLine(JsonSerializer.Serialize(configuration)); // 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 @@ -202,7 +202,7 @@ namespace slskd private Task BrowseResponseResolver(string username, IPEndPoint endpoint) { var directories = System.IO.Directory - .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) + .GetDirectories(Configuration.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,7 +237,7 @@ 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}", Configuration.Soulseek.Username); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) @@ -256,13 +256,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}", Configuration.Soulseek.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(Configuration.Soulseek.Username) || string.IsNullOrEmpty(Configuration.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 +284,7 @@ namespace slskd try { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + await Client.ConnectAsync(Configuration.Soulseek.Username, Configuration.Soulseek.Password); break; } catch (Exception ex) @@ -300,7 +300,7 @@ namespace slskd { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - if (Options.Integration.Pushbullet.Enabled && !args.Replayed) + if (Configuration.Integration.Pushbullet.Enabled && !args.Replayed) { Console.WriteLine("Pushing..."); _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); @@ -311,7 +311,7 @@ namespace slskd { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + if (Configuration.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); } @@ -320,7 +320,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 != Configuration.Soulseek.Username) { RoomTracker.TryAddUser(args.RoomName, args.UserData); } @@ -336,7 +336,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 (Configuration.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/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index 97b86689..b28e5b1a 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -46,7 +46,7 @@ namespace slskd.Transfer.API /// /// public TransfersController( - Microsoft.Extensions.Options.IOptionsSnapshot options, + Microsoft.Extensions.Options.IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker, IFTPService ftpClient) @@ -57,7 +57,7 @@ namespace slskd.Transfer.API FTP = ftpClient; } - private Options Options { get; } + private Configuration Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } private IFTPService FTP { get; } diff --git a/src/slskd/Common/Validation/Extensions.cs b/src/slskd/Common/Validation/Extensions.cs index b7e396a3..cc2e3c12 100644 --- a/src/slskd/Common/Validation/Extensions.cs +++ b/src/slskd/Common/Validation/Extensions.cs @@ -28,15 +28,15 @@ namespace slskd.Validation /// /// Validates options. /// - /// The options instance to validate. + /// The configuration instance to validate. /// The result of the validation, if invalid. /// A value indicating whether the instance is valid. - public static bool TryValidate(this Options options, out CompositeValidationResult result) + public static bool TryValidate(this Configuration configuration, out CompositeValidationResult result) { result = null; var results = new List(); - if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true)) + if (!Validator.TryValidateObject(configuration, new ValidationContext(configuration), results, true)) { result = new CompositeValidationResult("Invalid configuration", results); return false; diff --git a/src/slskd/Common/Validation/X509CertificateAttribute.cs b/src/slskd/Common/Validation/X509CertificateAttribute.cs index 7a080882..87cd776b 100644 --- a/src/slskd/Common/Validation/X509CertificateAttribute.cs +++ b/src/slskd/Common/Validation/X509CertificateAttribute.cs @@ -19,7 +19,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using slskd.Cryptography; - using static slskd.Options.WebOptions.HttpsOptions; + using static slskd.Configuration.WebOptions.HttpsOptions; /// /// Validates X509 certificate parameters specified through . diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs new file mode 100644 index 00000000..b1620632 --- /dev/null +++ b/src/slskd/Configuration.cs @@ -0,0 +1,769 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using FluentFTP; + using slskd.Validation; + using Soulseek.Diagnostics; + using Utility.CommandLine; + using Utility.EnvironmentVariables; + + /// + /// Application options. + /// + public class Configuration + { + /// + /// Gets a value indicating whether to display the application version. + /// + [Argument('v', "version")] + [Description("display version information")] + public bool ShowVersion { get; private set; } = false; + + /// + /// Gets a value indicating whether to display a list of command line arguments. + /// + [Argument('h', "help")] + [Description("display command line usage")] + public bool ShowHelp { get; private set; } = false; + + /// + /// Gets a value indicating whether to display a list of configuration environment variables. + /// + [Argument('e', "envars")] + [Description("display environment variables")] + public bool ShowEnvironmentVariables { get; private set; } = false; + + /// + /// Gets a value indicating whether to generate an X509 certificate and password. + /// + [Argument('g', "generate-cert")] + [Description("generate X509 certificate and password for HTTPs")] + public bool GenerateCertificate { get; private set; } = false; + + /// + /// Gets the path to the application configuration file. + /// + [Argument('c', "config")] + [EnvironmentVariable("CONFIG")] + [Description("path to configuration file")] + public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; + + /// + /// Gets a value indicating whether the application should run in debug mode. + /// + [Argument('d', "debug")] + [EnvironmentVariable("DEBUG")] + [Description("run in debug mode")] + public bool Debug { get; private set; } = Debugger.IsAttached; + + /// + /// Gets a value indicating whether the logo should be suppressed on startup. + /// + [Argument('n', "no-logo")] + [EnvironmentVariable("NO_LOGO")] + [Description("suppress logo on startup")] + public bool NoLogo { get; private set; } = false; + + /// + /// Gets a value indicating whether the application should quit after initialization. + /// + [Argument('x', "no-start")] + [EnvironmentVariable("NO_START")] + [Description("quit the application after initialization")] + public bool NoStart { get; private set; } = false; + + /// + /// Gets the unique name for this instance. + /// + [Argument('i', "instance-name")] + [EnvironmentVariable("INSTANCE_NAME")] + [Description("optional; a unique name for this instance")] + public string InstanceName { get; private set; } = "default"; + + /// + /// Gets directory options. + /// + [Validate] + public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); + + /// + /// Gets options for the web UI. + /// + [Validate] + public WebOptions Web { get; private set; } = new WebOptions(); + + /// + /// Gets logger options. + /// + [Validate] + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + + /// + /// Gets feature options. + /// + [Validate] + public FeatureOptions Feature { get; private set; } = new FeatureOptions(); + + /// + /// Gets options for the Soulseek client. + /// + [Validate] + public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); + + /// + /// Gets options for external integrations. + /// + [Validate] + public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); + + /// + /// Directory options. + /// + public class DirectoriesOptions + { + /// + /// Gets the path where application data is saved. + /// + [Argument(default, "app")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] + [DirectoryExists] + public string App { get; private set; } = Program.DefaultAppDirectory; + + /// + /// Gets the path where incomplete downloads are saved. + /// + [Argument(default, "incomplete")] + [EnvironmentVariable("INCOMPLETE_DIR")] + [Description("path where incomplete downloads are saved")] + [DirectoryExists] + public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; + + /// + /// Gets the path where downloaded files are saved. + /// + [Argument('o', "downloads")] + [EnvironmentVariable("DOWNLOADS_DIR")] + [Description("path where downloaded files are saved")] + [DirectoryExists] + public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; + + /// + /// Gets the path to shared files. + /// + [Argument('s', "shared")] + [EnvironmentVariable("SHARED_DIR")] + [Description("path to shared files")] + [DirectoryExists] + public string Shared { get; private set; } = Program.DefaultSharedDirectory; + } + + /// + /// Feature options. + /// + public class FeatureOptions + { + /// + /// Gets a value indicating whether prometheus metrics should be collected and published. + /// + [Argument(default, "prometheus")] + [EnvironmentVariable("PROMETHEUS")] + [Description("enable collection and publishing of prometheus metrics")] + public bool Prometheus { get; private set; } = false; + + /// + /// Gets a value indicating whether swagger documentation and UI should be enabled. + /// + [Argument(default, "swagger")] + [EnvironmentVariable("SWAGGER")] + [Description("enable swagger documentation and UI")] + public bool Swagger { get; private set; } = false; + } + + /// + /// Logger options. + /// + public class LoggerOptions + { + /// + /// Gets the URL to a Grafana Loki instance to which to log. + /// + [Argument(default, "loki")] + [EnvironmentVariable("LOKI")] + [Description("optional; url to a Grafana Loki instance to which to log")] + public string Loki { get; private set; } = null; + } + + /// + /// Soulseek client options. + /// + public class SoulseekOptions + { + /// + /// Gets the username for the Soulseek network. + /// + [Argument(default, "slsk-username")] + [EnvironmentVariable("SLSK_USERNAME")] + [Description("username for the Soulseek network")] + public string Username { get; private set; } = null; + + /// + /// Gets the password for the Soulseek network. + /// + [Argument(default, "slsk-password")] + [EnvironmentVariable("SLSK_PASSWORD")] + [Description("password for the Soulseek network")] + public string Password { get; private set; } = null; + + /// + /// Gets the port on which to listen for incoming connections. + /// + [Argument(default, "slsk-listen-port")] + [EnvironmentVariable("SLSK_LISTEN_PORT")] + [Description("port on which to listen for incoming connections")] + [Range(1024, 65535)] + public int ListenPort { get; private set; } = 50000; + + /// + /// Gets the minimum diagnostic level. + /// + [Argument(default, "slsk-diag-level")] + [EnvironmentVariable("SLSK_DIAG_LEVEL")] + [Description("minimum diagnostic level (None, Warning, Info, Debug)")] + public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; + + /// + /// Gets options for the distributed network. + /// + [Validate] + public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions(); + + /// + /// Gets connection options. + /// + [Validate] + public ConnectionOptions Connection { get; private set; } = new ConnectionOptions(); + + /// + /// Connection options. + /// + public class ConnectionOptions + { + /// + /// Gets connection timeout options. + /// + [Validate] + public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions(); + + /// + /// Gets connection buffer options. + /// + [Validate] + public BufferOptions Buffer { get; private set; } = new BufferOptions(); + + /// + /// Gets connection proxy options. + /// + [Validate] + public ProxyOptions Proxy { get; private set; } = new ProxyOptions(); + + /// + /// Connection buffer options. + /// + public class BufferOptions + { + /// + /// Gets the connection read buffer size. + /// + [Argument(default, "slsk-read-buffer")] + [EnvironmentVariable("SLSK_READ_BUFFER")] + [Description("read buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Read { get; private set; } = 16384; + + /// + /// Gets the connection write buffer size. + /// + [Argument(default, "slsk-write-buffer")] + [EnvironmentVariable("SLSK_WRITE_BUFFER")] + [Description("write buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Write { get; private set; } = 16384; + } + + /// + /// Connection timeout options. + /// + public class TimeoutOptions + { + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "slsk-connection-timeout")] + [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] + [Description("connection timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Connect { get; private set; } = 10000; + + /// + /// Gets the connection inactivity timeout, in milliseconds. + /// + [Argument(default, "slsk-inactivity-timeout")] + [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] + [Description("connection inactivity timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Inactivity { get; private set; } = 15000; + } + + /// + /// Connection proxy options. + /// + public class ProxyOptions + { + /// + /// Gets the proxy address. + /// + [Argument(default, "slsk-proxy-address")] + [EnvironmentVariable("SLSK_PROXY_ADDRESS")] + [Description("connection proxy address")] + [StringLength(255, MinimumLength = 1)] + public string Address { get; private set; } + + /// + /// Gets the proxy port. + /// + [Argument(default, "slsk-proxy-port")] + [EnvironmentVariable("SLSK_PROXY_PORT")] + [Description("connection proxy port")] + [Range(1, 65535)] + public int? Port { get; private set; } + + /// + /// Gets the proxy username, if applicable. + /// + [Argument(default, "slsk-proxy-username")] + [EnvironmentVariable("SLSK_PROXY_USERNAME")] + [Description("connection proxy username")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; private set; } + + /// + /// Gets the proxy password, if applicable. + /// + [Argument(default, "slsk-proxy-password")] + [EnvironmentVariable("SLSK_PROXY_PASSWORD")] + [Description("connection proxy password")] + [StringLength(255, MinimumLength = 1)] + public string Password { get; private set; } + } + } + + /// + /// Distributed network options. + /// + public class DistributedNetworkOptions + { + /// + /// Gets a value indicating whether the distributed network should be disabled. + /// + [Argument(default, "slsk-no-dnet")] + [EnvironmentVariable("SLSK_NO_DNET")] + [Description("disable the distributed network")] + public bool Disabled { get; private set; } = false; + + /// + /// Gets the distributed child connection limit. + /// + [Argument(default, "slsk-dnet-children")] + [EnvironmentVariable("SLSK_DNET_CHILDREN")] + [Description("max number of distributed children")] + [Range(1, int.MaxValue)] + public int ChildLimit { get; private set; } = 25; + } + } + + /// + /// Web server options. + /// + public class WebOptions + { + /// + /// Gets the HTTP listen port. + /// + [Argument('l', "http-port")] + [EnvironmentVariable("HTTP_PORT")] + [Description("HTTP listen port for web UI")] + [Range(1, 65535)] + public int Port { get; private set; } = 5000; + + /// + /// Gets HTTPS options. + /// + [Validate] + public HttpsOptions Https { get; private set; } = new HttpsOptions(); + + /// + /// Gets the base url for web requests. + /// + [Argument(default, "url-base")] + [EnvironmentVariable("URL_BASE")] + [Description("base url for web requests")] + public string UrlBase { get; private set; } = "/"; + + /// + /// Gets the path to static web content. + /// + [Argument(default, "content-path")] + [EnvironmentVariable("CONTENT_PATH")] + [Description("path to static web content")] + [StringLength(255, MinimumLength = 1)] + public string ContentPath { get; private set; } = "wwwroot"; + + /// + /// Gets authentication options. + /// + [Validate] + public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); + + /// + /// Authentication options. + /// + public class AuthenticationOptions + { + /// + /// Gets a value indicating whether authentication should be disabled. + /// + [Argument('x', "no-auth")] + [EnvironmentVariable("NO_AUTH")] + [Description("disable authentication for web requests")] + public bool Disable { get; private set; } = false; + + /// + /// Gets the username for the web UI. + /// + [Argument('u', "username")] + [EnvironmentVariable("USERNAME")] + [Description("username for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; private set; } = Program.AppName; + + /// + /// Gets the password for the web UI. + /// + [Argument('p', "password")] + [EnvironmentVariable("PASSWORD")] + [Description("password for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Password { get; private set; } = Program.AppName; + + /// + /// Gets JWT options. + /// + [Validate] + public JwtOptions Jwt { get; private set; } = new JwtOptions(); + + /// + /// JWT options. + /// + public class JwtOptions + { + /// + /// Gets the key with which to sign JWTs. + /// + [Argument(default, "jwt-key")] + [EnvironmentVariable("JWT_KEY")] + [Description("JWT signing key")] + [StringLength(255, MinimumLength = 1)] + public string Key { get; private set; } = Guid.NewGuid().ToString(); + + /// + /// Gets the TTL for JWTs. + /// + [Argument(default, "jwt-ttl")] + [EnvironmentVariable("JWT_TTL")] + [Description("TTL for JWTs")] + [Range(3600, int.MaxValue)] + public int Ttl { get; private set; } = 604800000; + } + } + + /// + /// HTTPS options. + /// + public class HttpsOptions + { + /// + /// Gets the HTTPS listen port. + /// + [Argument('L', "https-port")] + [EnvironmentVariable("HTTPS_PORT")] + [Description("HTTPS listen port for web UI")] + [Range(1, 65535)] + public int Port { get; private set; } = 5001; + + /// + /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. + /// + [Argument('f', "force-https")] + [EnvironmentVariable("HTTPS_FORCE")] + [Description("redirect HTTP to HTTPS")] + public bool Force { get; private set; } = false; + + /// + /// Gets certificate options. + /// + [Validate] + public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); + + /// + /// Certificate options. + /// + [X509Certificate] + public class CertificateOptions + { + /// + /// Gets the path to the the X509 certificate .pfx file. + /// + [Argument(default, "https-cert-pfx")] + [EnvironmentVariable("HTTPS_CERT_PFX")] + [Description("path to X509 certificate .pfx")] + [FileExists] + public string Pfx { get; private set; } + + /// + /// Gets the password for the X509 certificate. + /// + [Argument(default, "https-cert-password")] + [EnvironmentVariable("HTTPS_CERT_PASSWORD")] + [Description("X509 certificate password")] + public string Password { get; private set; } + } + } + } + + /// + /// Options for external integrations. + /// + public class IntegrationOptions + { + /// + /// Gets FTP options. + /// + [Validate] + public FTPOptions FTP { get; private set; } = new FTPOptions(); + + /// + /// Gets Pushbullet options. + /// + [Validate] + public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); + + /// + /// FTP options. + /// + public class FTPOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the FTP integration is enabled. + /// + [Argument(default, "ftp")] + [EnvironmentVariable("FTP_ENABLED")] + [Description("enable FTP integration")] + public bool Enabled { get; private set; } + + /// + /// Gets the FTP address. + /// + [Argument(default, "ftp-address")] + [EnvironmentVariable("FTP_ADDRESS")] + [Description("FTP address")] + public string Address { get; private set; } + + /// + /// Gets the FTP port. + /// + [Argument(default, "ftp-port")] + [EnvironmentVariable("FTP_PORT")] + [Description("FTP port")] + [Range(1, 65535)] + public int Port { get; private set; } = 21; + + /// + /// Gets the FTP encryption mode. + /// + [Argument(default, "ftp-encryption-mode")] + [EnvironmentVariable("FTP_ENCRYPTION_MODE")] + [Description("FTP encryption mode; none, implicit, explicit, auto")] + [Enum(typeof(FtpEncryptionMode))] + public string EncryptionMode { get; private set; } = "auto"; + + /// + /// Gets a value indicating whether FTP certificate errors should be ignored. + /// + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; private set; } = false; + + /// + /// Gets the FTP username. + /// + [Argument(default, "ftp-username")] + [EnvironmentVariable("FTP_USERNAME")] + [Description("FTP username")] + public string Username { get; private set; } + + /// + /// Gets the FTP password. + /// + [Argument(default, "ftp-password")] + [EnvironmentVariable("FTP_PASSWORD")] + [Description("FTP password")] + public string Password { get; private set; } + + /// + /// Gets the remote path for uploads. + /// + [Argument(default, "ftp-remote-path")] + [EnvironmentVariable("FTP_REMOTE_PATH")] + [Description("remote path for FTP uploads")] + public string RemotePath { get; private set; } = "/"; + + /// + /// Gets a value indicating whether existing files should be overwritten. + /// + [Argument(default, "ftp-overwrite-existing")] + [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] + [Description("overwrite existing files when uploading to FTP")] + public bool OverwriteExisting { get; private set; } = true; + + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "ftp-connection-timeout")] + [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] + [Description("FTP connection timeout, in milliseconds")] + [Range(0, int.MaxValue)] + public int ConnectionTimeout { get; private set; } = 5000; + + /// + /// Gets the number of times failing uploads will be retried. + /// + [Argument(default, "ftp-retry-attempts")] + [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] + [Description("number of times failing FTP uploads will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + return results; + } + } + + /// + /// Pushbullet options. + /// + public class PushbulletOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET_ENABLED")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; private set; } = false; + + /// + /// Gets the Pushbullet API access token. + /// + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + public string AccessToken { get; private set; } + + /// + /// Gets the prefix for Pushbullet notification titles. + /// + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; private set; } = "From slskd:"; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// + [Argument(default, "pushbullet-notify-on-pm")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] + [Description("send Pushbullet notifications when private messages are received")] + public bool NotifyOnPrivateMessage { get; private set; } = true; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// + [Argument(default, "pushbullet-notify-on-room-mention")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] + [Description("send Pushbullet notifications when your username is mentioned in a room")] + public bool NotifyOnRoomMention { get; private set; } = true; + + /// + /// Gets the number of times failing Pushbullet notifications will be retried. + /// + [Argument(default, "pushbullet-retry-attempts")] + [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] + [Description("number of times failing Pushbullet notifications will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + /// + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// + [Argument(default, "pushbullet-cooldown")] + [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] + [Description("cooldown time for Pushbullet notifications, in milliseconds")] + public int CooldownTime { get; private set; } = 900000; // 15 minutes + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); + } + + return results; + } + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index cc076ca1..5b8639dc 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -19,7 +19,7 @@ namespace slskd.Integrations.FTP { using System; using FluentFTP; - using static slskd.Options.IntegrationOptions; + using static slskd.Configuration.IntegrationOptions; /// /// FTP client factory. @@ -30,7 +30,7 @@ namespace slskd.Integrations.FTP /// Initializes a new instance of the class. /// /// The options monitor used to derive application options. - public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { Options = optionsMonitor.CurrentValue; @@ -48,7 +48,7 @@ namespace slskd.Integrations.FTP private FtpEncryptionMode EncryptionMode { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; - private Options Options { get; set; } + private Configuration Options { get; set; } /// /// Creates an instance of . diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index a5fe6a8f..f7fd1ddd 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -23,7 +23,7 @@ namespace slskd.Integrations.FTP using System.Threading.Tasks; using FluentFTP; using Microsoft.Extensions.Logging; - using static slskd.Options.IntegrationOptions; + using static slskd.Configuration.IntegrationOptions; /// /// FTP Integration service. @@ -38,7 +38,7 @@ namespace slskd.Integrations.FTP /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ILogger log) { Factory = ftpClientFactory; @@ -49,7 +49,7 @@ namespace slskd.Integrations.FTP private IFTPClientFactory Factory { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; private ILogger Log { get; set; } - private Options Options { get; } + private Configuration Options { get; } /// /// Uploads the specified to the configured FTP server. diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index cb31e6dc..8bf94af9 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -24,7 +24,7 @@ namespace slskd.Integrations.Pushbullet using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; - using static slskd.Options.IntegrationOptions; + using static slskd.Configuration.IntegrationOptions; /// /// Pushbullet integration service. @@ -41,7 +41,7 @@ namespace slskd.Integrations.Pushbullet /// The logger. public PushbulletService( IHttpClientFactory httpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ILogger log) { HttpClientFactory = httpClientFactory; @@ -52,7 +52,7 @@ namespace slskd.Integrations.Pushbullet } private IHttpClientFactory HttpClientFactory { get; } - private Options Options { get; } + private Configuration Options { get; } private ILogger Log { get; } private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet; private IMemoryCache RecentlySent { get; } diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs deleted file mode 100644 index 7e4880c6..00000000 --- a/src/slskd/Options.cs +++ /dev/null @@ -1,769 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.ComponentModel.DataAnnotations; - using System.Diagnostics; - using FluentFTP; - using slskd.Validation; - using Soulseek.Diagnostics; - using Utility.CommandLine; - using Utility.EnvironmentVariables; - - /// - /// Application options. - /// - public class Options - { - /// - /// Gets a value indicating whether to display the application version. - /// - [Argument('v', "version")] - [Description("display version information")] - public bool ShowVersion { get; private set; } = false; - - /// - /// Gets a value indicating whether to display a list of command line arguments. - /// - [Argument('h', "help")] - [Description("display command line usage")] - public bool ShowHelp { get; private set; } = false; - - /// - /// Gets a value indicating whether to display a list of configuration environment variables. - /// - [Argument('e', "envars")] - [Description("display environment variables")] - public bool ShowEnvironmentVariables { get; private set; } = false; - - /// - /// Gets a value indicating whether to generate an X509 certificate and password. - /// - [Argument('g', "generate-cert")] - [Description("generate X509 certificate and password for HTTPs")] - public bool GenerateCertificate { get; private set; } = false; - - /// - /// Gets the path to the application configuration file. - /// - [Argument('c', "config")] - [EnvironmentVariable("CONFIG")] - [Description("path to configuration file")] - public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; - - /// - /// Gets a value indicating whether the application should run in debug mode. - /// - [Argument('d', "debug")] - [EnvironmentVariable("DEBUG")] - [Description("run in debug mode")] - public bool Debug { get; private set; } = Debugger.IsAttached; - - /// - /// Gets a value indicating whether the logo should be suppressed on startup. - /// - [Argument('n', "no-logo")] - [EnvironmentVariable("NO_LOGO")] - [Description("suppress logo on startup")] - public bool NoLogo { get; private set; } = false; - - /// - /// Gets a value indicating whether the application should quit after initialization. - /// - [Argument('x', "no-start")] - [EnvironmentVariable("NO_START")] - [Description("quit the application after initialization")] - public bool NoStart { get; private set; } = false; - - /// - /// Gets the unique name for this instance. - /// - [Argument('i', "instance-name")] - [EnvironmentVariable("INSTANCE_NAME")] - [Description("optional; a unique name for this instance")] - public string InstanceName { get; private set; } = "default"; - - /// - /// Gets directory options. - /// - [Validate] - public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); - - /// - /// Gets options for the web UI. - /// - [Validate] - public WebOptions Web { get; private set; } = new WebOptions(); - - /// - /// Gets logger options. - /// - [Validate] - public LoggerOptions Logger { get; private set; } = new LoggerOptions(); - - /// - /// Gets feature options. - /// - [Validate] - public FeatureOptions Feature { get; private set; } = new FeatureOptions(); - - /// - /// Gets options for the Soulseek client. - /// - [Validate] - public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); - - /// - /// Gets options for external integrations. - /// - [Validate] - public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); - - /// - /// Directory options. - /// - public class DirectoriesOptions - { - /// - /// Gets the path where application data is saved. - /// - [Argument(default, "app")] - [EnvironmentVariable("APP_DIR")] - [Description("path where application data is saved")] - [DirectoryExists] - public string App { get; private set; } = Program.DefaultAppDirectory; - - /// - /// Gets the path where incomplete downloads are saved. - /// - [Argument(default, "incomplete")] - [EnvironmentVariable("INCOMPLETE_DIR")] - [Description("path where incomplete downloads are saved")] - [DirectoryExists] - public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; - - /// - /// Gets the path where downloaded files are saved. - /// - [Argument('o', "downloads")] - [EnvironmentVariable("DOWNLOADS_DIR")] - [Description("path where downloaded files are saved")] - [DirectoryExists] - public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; - - /// - /// Gets the path to shared files. - /// - [Argument('s', "shared")] - [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - [DirectoryExists] - public string Shared { get; private set; } = Program.DefaultSharedDirectory; - } - - /// - /// Feature options. - /// - public class FeatureOptions - { - /// - /// Gets a value indicating whether prometheus metrics should be collected and published. - /// - [Argument(default, "prometheus")] - [EnvironmentVariable("PROMETHEUS")] - [Description("enable collection and publishing of prometheus metrics")] - public bool Prometheus { get; private set; } = false; - - /// - /// Gets a value indicating whether swagger documentation and UI should be enabled. - /// - [Argument(default, "swagger")] - [EnvironmentVariable("SWAGGER")] - [Description("enable swagger documentation and UI")] - public bool Swagger { get; private set; } = false; - } - - /// - /// Logger options. - /// - public class LoggerOptions - { - /// - /// Gets the URL to a Grafana Loki instance to which to log. - /// - [Argument(default, "loki")] - [EnvironmentVariable("LOKI")] - [Description("optional; url to a Grafana Loki instance to which to log")] - public string Loki { get; private set; } = null; - } - - /// - /// Soulseek client options. - /// - public class SoulseekOptions - { - /// - /// Gets the username for the Soulseek network. - /// - [Argument(default, "slsk-username")] - [EnvironmentVariable("SLSK_USERNAME")] - [Description("username for the Soulseek network")] - public string Username { get; private set; } = null; - - /// - /// Gets the password for the Soulseek network. - /// - [Argument(default, "slsk-password")] - [EnvironmentVariable("SLSK_PASSWORD")] - [Description("password for the Soulseek network")] - public string Password { get; private set; } = null; - - /// - /// Gets the port on which to listen for incoming connections. - /// - [Argument(default, "slsk-listen-port")] - [EnvironmentVariable("SLSK_LISTEN_PORT")] - [Description("port on which to listen for incoming connections")] - [Range(1024, 65535)] - public int ListenPort { get; private set; } = 50000; - - /// - /// Gets the minimum diagnostic level. - /// - [Argument(default, "slsk-diag-level")] - [EnvironmentVariable("SLSK_DIAG_LEVEL")] - [Description("minimum diagnostic level (None, Warning, Info, Debug)")] - public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; - - /// - /// Gets options for the distributed network. - /// - [Validate] - public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions(); - - /// - /// Gets connection options. - /// - [Validate] - public ConnectionOptions Connection { get; private set; } = new ConnectionOptions(); - - /// - /// Connection options. - /// - public class ConnectionOptions - { - /// - /// Gets connection timeout options. - /// - [Validate] - public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions(); - - /// - /// Gets connection buffer options. - /// - [Validate] - public BufferOptions Buffer { get; private set; } = new BufferOptions(); - - /// - /// Gets connection proxy options. - /// - [Validate] - public ProxyOptions Proxy { get; private set; } = new ProxyOptions(); - - /// - /// Connection buffer options. - /// - public class BufferOptions - { - /// - /// Gets the connection read buffer size. - /// - [Argument(default, "slsk-read-buffer")] - [EnvironmentVariable("SLSK_READ_BUFFER")] - [Description("read buffer size for connections")] - [Range(1024, int.MaxValue)] - public int Read { get; private set; } = 16384; - - /// - /// Gets the connection write buffer size. - /// - [Argument(default, "slsk-write-buffer")] - [EnvironmentVariable("SLSK_WRITE_BUFFER")] - [Description("write buffer size for connections")] - [Range(1024, int.MaxValue)] - public int Write { get; private set; } = 16384; - } - - /// - /// Connection timeout options. - /// - public class TimeoutOptions - { - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "slsk-connection-timeout")] - [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] - [Description("connection timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Connect { get; private set; } = 10000; - - /// - /// Gets the connection inactivity timeout, in milliseconds. - /// - [Argument(default, "slsk-inactivity-timeout")] - [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] - [Description("connection inactivity timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Inactivity { get; private set; } = 15000; - } - - /// - /// Connection proxy options. - /// - public class ProxyOptions - { - /// - /// Gets the proxy address. - /// - [Argument(default, "slsk-proxy-address")] - [EnvironmentVariable("SLSK_PROXY_ADDRESS")] - [Description("connection proxy address")] - [StringLength(255, MinimumLength = 1)] - public string Address { get; private set; } - - /// - /// Gets the proxy port. - /// - [Argument(default, "slsk-proxy-port")] - [EnvironmentVariable("SLSK_PROXY_PORT")] - [Description("connection proxy port")] - [Range(1, 65535)] - public int? Port { get; private set; } - - /// - /// Gets the proxy username, if applicable. - /// - [Argument(default, "slsk-proxy-username")] - [EnvironmentVariable("SLSK_PROXY_USERNAME")] - [Description("connection proxy username")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; private set; } - - /// - /// Gets the proxy password, if applicable. - /// - [Argument(default, "slsk-proxy-password")] - [EnvironmentVariable("SLSK_PROXY_PASSWORD")] - [Description("connection proxy password")] - [StringLength(255, MinimumLength = 1)] - public string Password { get; private set; } - } - } - - /// - /// Distributed network options. - /// - public class DistributedNetworkOptions - { - /// - /// Gets a value indicating whether the distributed network should be disabled. - /// - [Argument(default, "slsk-no-dnet")] - [EnvironmentVariable("SLSK_NO_DNET")] - [Description("disable the distributed network")] - public bool Disabled { get; private set; } = false; - - /// - /// Gets the distributed child connection limit. - /// - [Argument(default, "slsk-dnet-children")] - [EnvironmentVariable("SLSK_DNET_CHILDREN")] - [Description("max number of distributed children")] - [Range(1, int.MaxValue)] - public int ChildLimit { get; private set; } = 25; - } - } - - /// - /// Web server options. - /// - public class WebOptions - { - /// - /// Gets the HTTP listen port. - /// - [Argument('l', "http-port")] - [EnvironmentVariable("HTTP_PORT")] - [Description("HTTP listen port for web UI")] - [Range(1, 65535)] - public int Port { get; private set; } = 5000; - - /// - /// Gets HTTPS options. - /// - [Validate] - public HttpsOptions Https { get; private set; } = new HttpsOptions(); - - /// - /// Gets the base url for web requests. - /// - [Argument(default, "url-base")] - [EnvironmentVariable("URL_BASE")] - [Description("base url for web requests")] - public string UrlBase { get; private set; } = "/"; - - /// - /// Gets the path to static web content. - /// - [Argument(default, "content-path")] - [EnvironmentVariable("CONTENT_PATH")] - [Description("path to static web content")] - [StringLength(255, MinimumLength = 1)] - public string ContentPath { get; private set; } = "wwwroot"; - - /// - /// Gets authentication options. - /// - [Validate] - public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); - - /// - /// Authentication options. - /// - public class AuthenticationOptions - { - /// - /// Gets a value indicating whether authentication should be disabled. - /// - [Argument('x', "no-auth")] - [EnvironmentVariable("NO_AUTH")] - [Description("disable authentication for web requests")] - public bool Disable { get; private set; } = false; - - /// - /// Gets the username for the web UI. - /// - [Argument('u', "username")] - [EnvironmentVariable("USERNAME")] - [Description("username for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; private set; } = Program.AppName; - - /// - /// Gets the password for the web UI. - /// - [Argument('p', "password")] - [EnvironmentVariable("PASSWORD")] - [Description("password for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Password { get; private set; } = Program.AppName; - - /// - /// Gets JWT options. - /// - [Validate] - public JwtOptions Jwt { get; private set; } = new JwtOptions(); - - /// - /// JWT options. - /// - public class JwtOptions - { - /// - /// Gets the key with which to sign JWTs. - /// - [Argument(default, "jwt-key")] - [EnvironmentVariable("JWT_KEY")] - [Description("JWT signing key")] - [StringLength(255, MinimumLength = 1)] - public string Key { get; private set; } = Guid.NewGuid().ToString(); - - /// - /// Gets the TTL for JWTs. - /// - [Argument(default, "jwt-ttl")] - [EnvironmentVariable("JWT_TTL")] - [Description("TTL for JWTs")] - [Range(3600, int.MaxValue)] - public int Ttl { get; private set; } = 604800000; - } - } - - /// - /// HTTPS options. - /// - public class HttpsOptions - { - /// - /// Gets the HTTPS listen port. - /// - [Argument('L', "https-port")] - [EnvironmentVariable("HTTPS_PORT")] - [Description("HTTPS listen port for web UI")] - [Range(1, 65535)] - public int Port { get; private set; } = 5001; - - /// - /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. - /// - [Argument('f', "force-https")] - [EnvironmentVariable("HTTPS_FORCE")] - [Description("redirect HTTP to HTTPS")] - public bool Force { get; private set; } = false; - - /// - /// Gets certificate options. - /// - [Validate] - public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); - - /// - /// Certificate options. - /// - [X509Certificate] - public class CertificateOptions - { - /// - /// Gets the path to the the X509 certificate .pfx file. - /// - [Argument(default, "https-cert-pfx")] - [EnvironmentVariable("HTTPS_CERT_PFX")] - [Description("path to X509 certificate .pfx")] - [FileExists] - public string Pfx { get; private set; } - - /// - /// Gets the password for the X509 certificate. - /// - [Argument(default, "https-cert-password")] - [EnvironmentVariable("HTTPS_CERT_PASSWORD")] - [Description("X509 certificate password")] - public string Password { get; private set; } - } - } - } - - /// - /// Options for external integrations. - /// - public class IntegrationOptions - { - /// - /// Gets FTP options. - /// - [Validate] - public FTPOptions FTP { get; private set; } = new FTPOptions(); - - /// - /// Gets Pushbullet options. - /// - [Validate] - public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); - - /// - /// FTP options. - /// - public class FTPOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the FTP integration is enabled. - /// - [Argument(default, "ftp")] - [EnvironmentVariable("FTP_ENABLED")] - [Description("enable FTP integration")] - public bool Enabled { get; private set; } - - /// - /// Gets the FTP address. - /// - [Argument(default, "ftp-address")] - [EnvironmentVariable("FTP_ADDRESS")] - [Description("FTP address")] - public string Address { get; private set; } - - /// - /// Gets the FTP port. - /// - [Argument(default, "ftp-port")] - [EnvironmentVariable("FTP_PORT")] - [Description("FTP port")] - [Range(1, 65535)] - public int Port { get; private set; } = 21; - - /// - /// Gets the FTP encryption mode. - /// - [Argument(default, "ftp-encryption-mode")] - [EnvironmentVariable("FTP_ENCRYPTION_MODE")] - [Description("FTP encryption mode; none, implicit, explicit, auto")] - [Enum(typeof(FtpEncryptionMode))] - public string EncryptionMode { get; private set; } = "auto"; - - /// - /// Gets a value indicating whether FTP certificate errors should be ignored. - /// - [Argument(default, "ftp-ignore-certificate-errors")] - [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] - [Description("ignore FTP certificate errors")] - public bool IgnoreCertificateErrors { get; private set; } = false; - - /// - /// Gets the FTP username. - /// - [Argument(default, "ftp-username")] - [EnvironmentVariable("FTP_USERNAME")] - [Description("FTP username")] - public string Username { get; private set; } - - /// - /// Gets the FTP password. - /// - [Argument(default, "ftp-password")] - [EnvironmentVariable("FTP_PASSWORD")] - [Description("FTP password")] - public string Password { get; private set; } - - /// - /// Gets the remote path for uploads. - /// - [Argument(default, "ftp-remote-path")] - [EnvironmentVariable("FTP_REMOTE_PATH")] - [Description("remote path for FTP uploads")] - public string RemotePath { get; private set; } = "/"; - - /// - /// Gets a value indicating whether existing files should be overwritten. - /// - [Argument(default, "ftp-overwrite-existing")] - [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] - [Description("overwrite existing files when uploading to FTP")] - public bool OverwriteExisting { get; private set; } = true; - - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "ftp-connection-timeout")] - [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] - [Description("FTP connection timeout, in milliseconds")] - [Range(0, int.MaxValue)] - public int ConnectionTimeout { get; private set; } = 5000; - - /// - /// Gets the number of times failing uploads will be retried. - /// - [Argument(default, "ftp-retry-attempts")] - [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] - [Description("number of times failing FTP uploads will be retried")] - [Range(0, 5)] - public int RetryAttempts { get; private set; } = 3; - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(Address)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); - } - - return results; - } - } - - /// - /// Pushbullet options. - /// - public class PushbulletOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the Pushbullet integration is enabled. - /// - [Argument(default, "pushbullet")] - [EnvironmentVariable("PUSHBULLET_ENABLED")] - [Description("enable Pushbullet integration")] - public bool Enabled { get; private set; } = false; - - /// - /// Gets the Pushbullet API access token. - /// - [Argument(default, "pushbullet-token")] - [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] - [Description("Pushbullet access token")] - public string AccessToken { get; private set; } - - /// - /// Gets the prefix for Pushbullet notification titles. - /// - [Argument(default, "pushbullet-prefix")] - [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] - [Description("prefix for Pushbullet notification titles")] - public string NotificationPrefix { get; private set; } = "From slskd:"; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. - /// - [Argument(default, "pushbullet-notify-on-pm")] - [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] - [Description("send Pushbullet notifications when private messages are received")] - public bool NotifyOnPrivateMessage { get; private set; } = true; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged - /// in user's username is mentioned in a room. - /// - [Argument(default, "pushbullet-notify-on-room-mention")] - [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] - [Description("send Pushbullet notifications when your username is mentioned in a room")] - public bool NotifyOnRoomMention { get; private set; } = true; - - /// - /// Gets the number of times failing Pushbullet notifications will be retried. - /// - [Argument(default, "pushbullet-retry-attempts")] - [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] - [Description("number of times failing Pushbullet notifications will be retried")] - [Range(0, 5)] - public int RetryAttempts { get; private set; } = 3; - - /// - /// Gets the cooldown time for Pushbullet notifications, in milliseconds. - /// - [Argument(default, "pushbullet-cooldown")] - [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] - [Description("cooldown time for Pushbullet notifications, in milliseconds")] - public int CooldownTime { get; private set; } = 900000; // 15 minutes - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); - } - - return results; - } - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 01618efb..b83a9d8c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -119,8 +119,8 @@ namespace slskd /// public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; - private static IConfigurationRoot Configuration { get; set; } - private static Options Options { get; } = new Options(); + private static IConfigurationRoot ConfigurationRoot { get; set; } + private static Configuration Configuration { get; } = new Configuration(); [EnvironmentVariable("CONFIG")] [Argument('c', "config", "path to configuration file")] @@ -167,12 +167,12 @@ namespace slskd if (ShowHelp) { - PrintCommandLineArguments(typeof(Options)); + PrintCommandLineArguments(typeof(Configuration)); } if (ShowEnvironmentVariables) { - PrintEnvironmentVariables(typeof(Options), EnvironmentVariablePrefix); + PrintEnvironmentVariables(typeof(Configuration), EnvironmentVariablePrefix); } return; @@ -188,19 +188,19 @@ namespace slskd // with bootstrapping. try { - Configuration = new ConfigurationBuilder() + ConfigurationRoot = new ConfigurationBuilder() .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile) .Build(); - Configuration.GetSection(AppName) - .Bind(Options, (o) => { o.BindNonPublicProperties = true; }); + ConfigurationRoot.GetSection(AppName) + .Bind(Configuration, (o) => { o.BindNonPublicProperties = true; }); - if (Options.Debug) + if (Configuration.Debug) { - Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}"); + Console.WriteLine($"Configuration:\n{ConfigurationRoot.GetDebugView()}"); } - if (!Options.TryValidate(out var result)) + if (!Configuration.TryValidate(out var result)) { Console.WriteLine(result.GetResultView()); return; @@ -208,16 +208,16 @@ namespace slskd } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {(!Options.Debug ? ex : ex.Message)}"); + Console.WriteLine($"Invalid configuration: {(!Configuration.Debug ? ex : ex.Message)}"); return; } try { - VerifyOrCreateDirectory(Options.Directories.App); - VerifyOrCreateDirectory(Options.Directories.Incomplete); - VerifyOrCreateDirectory(Options.Directories.Downloads); - VerifyOrCreateDirectory(Options.Directories.Shared, verifyWriteable: false); + VerifyOrCreateDirectory(Configuration.Directories.App); + VerifyOrCreateDirectory(Configuration.Directories.Incomplete); + VerifyOrCreateDirectory(Configuration.Directories.Downloads); + VerifyOrCreateDirectory(Configuration.Directories.Shared, verifyWriteable: false); } catch (Exception ex) { @@ -225,31 +225,31 @@ namespace slskd return; } - Log.Logger = (Options.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + Log.Logger = (Configuration.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", Options.InstanceName) + .Enrich.WithProperty("InstanceName", Configuration.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( - outputTemplate: (Options.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + outputTemplate: (Configuration.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (Options.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (Configuration.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => !string.IsNullOrEmpty(Options.Logger.Loki), + e => !string.IsNullOrEmpty(Configuration.Logger.Loki), config => config.GrafanaLoki( - Options.Logger.Loki ?? string.Empty, + Configuration.Logger.Loki ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); var logger = Log.ForContext(typeof(Program)); - if (!Options.NoLogo) + if (!Configuration.NoLogo) { PrintLogo(Version); } @@ -260,18 +260,18 @@ namespace slskd } logger.Information("Version: {Version}", Version); - logger.Information("Instance Name: {InstanceName}", Options.InstanceName); + logger.Information("Instance Name: {InstanceName}", Configuration.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); - if (!string.IsNullOrEmpty(Options.Logger.Loki)) + if (!string.IsNullOrEmpty(Configuration.Logger.Loki)) { - logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Options.Logger.Loki); + logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Configuration.Logger.Loki); } try { - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } @@ -287,13 +287,13 @@ namespace slskd .UseUrls() .UseKestrel(options => { - logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Options.Web.Port}/"); - options.Listen(IPAddress.Any, Options.Web.Port); + logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Configuration.Web.Port}/"); + options.Listen(IPAddress.Any, Configuration.Web.Port); - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Options.Web.Https.Port}/"); - options.Listen(IPAddress.Any, Options.Web.Https.Port, listenOptions => + logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Configuration.Web.Https.Port}/"); + options.Listen(IPAddress.Any, Configuration.Web.Https.Port, listenOptions => { - var cert = Options.Web.Https.Certificate; + var cert = Configuration.Web.Https.Certificate; if (!string.IsNullOrEmpty(cert.Pfx)) { @@ -310,7 +310,7 @@ namespace slskd .UseStartup() .Build(); - if (Options.NoStart) + if (Configuration.NoStart) { logger.Information("Qutting because 'no-start' option is enabled"); return; @@ -334,18 +334,18 @@ namespace slskd return builder .AddDefaultValues( - targetType: typeof(Options)) + targetType: typeof(Configuration)) .AddEnvironmentVariables( - targetType: typeof(Options), + targetType: typeof(Configuration), prefix: environmentVariablePrefix) .AddYamlFile( path: Path.GetFileName(configurationFile), - targetType: typeof(Options), + targetType: typeof(Configuration), optional: true, reloadOnChange: false, provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory .AddCommandLine( - targetType: typeof(Options), + targetType: typeof(Configuration), commandLine: Environment.CommandLine); } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 635a6890..07216937 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -51,29 +51,29 @@ namespace slskd /// /// Initializes a new instance of the class. /// - /// The application configuration. - public Startup(IConfiguration configuration) + /// The application configuration root. + public Startup(IConfiguration configurationRoot) { - Configuration = configuration; + ConfigurationRoot = configurationRoot; - Options = new Options(); - Configuration.GetSection(Program.AppName).Bind(Options, (o) => + Configuration = new Configuration(); + ConfigurationRoot.GetSection(Program.AppName).Bind(Configuration, (o) => { o.BindNonPublicProperties = true; }); - UrlBase = Options.Web.UrlBase; + UrlBase = Configuration.Web.UrlBase; UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - ContentPath = Path.GetFullPath(Options.Web.ContentPath); + ContentPath = Path.GetFullPath(Configuration.Web.ContentPath); - JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Options.Web.Authentication.Jwt.Key)); + JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Configuration.Web.Authentication.Jwt.Key)); } - private IConfiguration Configuration { get; } + private IConfiguration ConfigurationRoot { get; } private string ContentPath { get; set; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; } + private Configuration Configuration { get; } private string UrlBase { get; set; } /// @@ -84,14 +84,14 @@ namespace slskd { var logger = Log.ForContext(); - services.AddOptions() - .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); + services.AddOptions() + .Bind(ConfigurationRoot.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddSingleton(JwtSigningKey); - if (!Options.Web.Authentication.Disable) + if (!Configuration.Web.Authentication.Disable) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => @@ -139,7 +139,7 @@ namespace slskd options.SubstituteApiVersionInUrl = true; }); - if (Options.Feature.Swagger) + if (Configuration.Feature.Swagger) { services.AddSwaggerGen(options => { @@ -163,19 +163,19 @@ namespace slskd }); } - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { services.AddSystemMetrics(); } services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Configuration.Directories.App, "search.db")}"); }); services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "peer.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Configuration.Directories.App, "peer.db")}"); }); services.AddHttpClient(); @@ -185,7 +185,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(_ => - new SharedFileCache(Options.Directories.Shared, 3600000)); + new SharedFileCache(Configuration.Directories.Shared, 3600000)); services.AddSingleton(); services.AddSingleton(); @@ -213,7 +213,7 @@ namespace slskd app.UseCors("AllowAll"); - if (Options.Web.Https.Force) + if (Configuration.Web.Https.Force) { app.UseHttpsRedirection(); app.UseHsts(); @@ -258,7 +258,7 @@ namespace slskd logger.Information("Serving static content from {ContentPath}", ContentPath); } - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { app.UseHttpMetrics(); logger.Information("Publishing Prometheus metrics to /metrics"); @@ -275,13 +275,13 @@ namespace slskd endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { endpoints.MapMetrics(); } }); - if (Options.Feature.Swagger) + if (Configuration.Feature.Swagger) { app.UseSwagger(); app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList() -- cgit v1.2.3 From e05b98574e6da694924163674353f836fcafb180 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jul 2021 08:14:14 -0500 Subject: fix bug restarting app --- .../Application/Management/API/Controllers/ApplicationController.cs | 4 ---- 1 file changed, 4 deletions(-) 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(); -- cgit v1.2.3 From 7cb3260349e0affb271d0a44cc78c4f9139a8b94 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jul 2021 20:40:54 -0500 Subject: rename back to Common --- .../CommandLineConfigurationSource.cs | 157 +++++++++++++++++ .../DefaultValueConfigurationSource.cs | 136 +++++++++++++++ .../EnvironmentVariableConfigurationSource.cs | 151 ++++++++++++++++ .../Configuration/RequiresRestartAttribute.cs | 26 +++ .../Configuration/YamlConfigurationSource.cs | 191 +++++++++++++++++++++ .../CommandLineConfigurationSource.cs | 157 ----------------- .../DefaultValueConfigurationSource.cs | 136 --------------- .../EnvironmentVariableConfigurationSource.cs | 151 ---------------- .../YamlConfigurationSource.cs | 191 --------------------- 9 files changed, 661 insertions(+), 635 deletions(-) create mode 100644 src/slskd/Common/Configuration/CommandLineConfigurationSource.cs create mode 100644 src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs create mode 100644 src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs create mode 100644 src/slskd/Common/Configuration/RequiresRestartAttribute.cs create mode 100644 src/slskd/Common/Configuration/YamlConfigurationSource.cs delete mode 100644 src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs delete mode 100644 src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs delete mode 100644 src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs delete mode 100644 src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs new file mode 100644 index 00000000..6cf59808 --- /dev/null +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -0,0 +1,157 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Configuration +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + using Utility.CommandLine; + + /// + /// Extension methods for adding . + /// + public static class CommandLineConfigurationExtensions + { + /// + /// Adds a command line argument configuration soruce to . + /// + /// The to which to add. + /// The type from which to map properties. + /// The command line string from which to parse arguments. + /// The updated . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddCommandLine(s => + { + s.TargetType = targetType; + s.CommandLine = commandLine ?? Environment.CommandLine; + }); + } + + /// + /// Adds a command line argument configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A command line argument . + /// + public class CommandLineConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public CommandLineConfigurationProvider(CommandLineConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + CommandLine = source.CommandLine; + } + + private string CommandLine { get; set; } + private string Namespace { get; set; } + private Type TargetType { get; set; } + + /// + /// Parses command line arguments from the specified string and maps them to the corresponding keys. + /// + public override void Load() + { + var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; + + void Map(Type type, string path) + { + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute)); + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (attribute != default) + { + var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString(); + var longName = (string)attribute.ConstructorArguments[1].Value; + var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i)); + + foreach (var argument in arguments) + { + if (dictionary.ContainsKey(argument)) + { + var value = dictionary[argument].ToString(); + + if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value)) + { + value = "true"; + } + + Data[key] = value; + } + } + } + else + { + Map(property.PropertyType, key); + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents command line arguments as an . + /// + public class CommandLineConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the command line string from which to parse arguments. + /// + public string CommandLine { get; set; } + + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); + } +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs new file mode 100644 index 00000000..15cf4070 --- /dev/null +++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs @@ -0,0 +1,136 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Configuration +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + + /// + /// Extension methods for adding . + /// + public static class DefaultValueConfigurationExtensions + { + /// + /// Adds a default value configuration source to . + /// + /// The to which to add. + /// The type from which to load default values. + /// The updated . + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddDefaultValues(s => + { + s.TargetType = targetType; + }); + } + + /// + /// Adds a default value configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A default value . + /// + public class DefaultValueConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + } + + private string Namespace { get; set; } + private Type TargetType { get; set; } + + /// + /// Loads default values from the specified and maps them to the corresponding keys. + /// + public override void Load() + { + void Map(Type type, string path) + { + var defaults = Activator.CreateInstance(type); + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (property.PropertyType.Namespace.StartsWith(Namespace)) + { + Map(property.PropertyType, key); + } + else + { + var value = property.GetValue(defaults); + + if (value != null) + { + Data[key] = value.ToString(); + } + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents default values as an . + /// + public class DefaultValueConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new DefaultValueConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs new file mode 100644 index 00000000..9a09d4e1 --- /dev/null +++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs @@ -0,0 +1,151 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Configuration +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.Configuration; + using Utility.EnvironmentVariables; + + /// + /// Extension methods for adding . + /// + public static class EnvironmentVariableConfigurationExtensions + { + /// + /// Adds an environment variable configuration source to . + /// + /// The to which to add. + /// The type from which to map properties. + /// A prefix to prepend to all variable names. + /// The updated . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (targetType == null) + { + throw new ArgumentNullException(nameof(targetType)); + } + + return builder.AddEnvironmentVariables(s => + { + s.TargetType = targetType; + s.Prefix = prefix ?? string.Empty; + }); + } + + /// + /// Adds an enviroment variable configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// An enviroment variable . + /// + public class EnvironmentVariableConfigurationProvider : ConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + Prefix = source.Prefix; + } + + private Type TargetType { get; set; } + private string Namespace { get; set; } + private string Prefix { get; set; } + + /// + /// Loads environment variables and maps them to the corresponding keys. + /// + public override void Load() + { + void Map(Type type, string path) + { + var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + + foreach (PropertyInfo property in props) + { + var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute)); + var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); + + if (attribute != default) + { + var name = (string)attribute.ConstructorArguments[0].Value; + + if (!string.IsNullOrEmpty(name)) + { + var value = Environment.GetEnvironmentVariable(Prefix + name); + + if (value != null) + { + Data[key] = value.ToString(); + } + } + } + else + { + Map(property.PropertyType, key); + } + } + } + + Map(TargetType, Namespace); + } + } + + /// + /// Represents environment variables as an . + /// + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Gets or sets a prefix to prepend to all variable names. + /// + public string Prefix { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/RequiresRestartAttribute.cs b/src/slskd/Common/Configuration/RequiresRestartAttribute.cs new file mode 100644 index 00000000..9b90eabe --- /dev/null +++ b/src/slskd/Common/Configuration/RequiresRestartAttribute.cs @@ -0,0 +1,26 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Configuration +{ + using System; + + [AttributeUsage(AttributeTargets.Property)] + public class RequiresRestartAttribute : Attribute + { + } +} diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs new file mode 100644 index 00000000..82e2227d --- /dev/null +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -0,0 +1,191 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Configuration +{ + using System; + using System.IO; + using System.Linq; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// + /// Extension methods for adding . + /// + public static class YamlConfigurationExtensions + { + /// + /// Adds a YAML configuration source to . + /// + /// The to which to add . + /// + /// Path relative to the base path stored in of . + /// + /// The type from which to map properties. + /// Whether the file is optional. + /// Whether the configuration should be reloaded if the file changes. + /// + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + /// The updated to use to access the file. + /// The . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.Path = path; + s.TargetType = targetType; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.NormalizeKeys = normalizeKeys; + s.FileProvider = provider; + s.ResolveFileProvider(); + }); + } + + /// + /// Adds a YAML configuration source to . + /// + /// The to which to add. + /// Configures the source. + /// The updated . + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) + => builder.Add(configureSource); + } + + /// + /// A YAML file based . + /// + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// + /// Initializes a new instance of the class. + /// + /// The source settings. + public YamlConfigurationProvider(YamlConfigurationSource source) + : base(source) + { + TargetType = source.TargetType; + Namespace = TargetType.Namespace.Split('.').First(); + NormalizeKeys = source.NormalizeKeys; + } + + private Type TargetType { get; set; } + private string Namespace { get; set; } + private bool NormalizeKeys { get; set; } + private string[] NullValues { get; } = new[] { "~", "null", string.Empty }; + + /// + /// Loads the YAML data from a stream. + /// + /// The stream to read. + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + if (yaml.Documents.Count > 0) + { + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + Traverse(rootNode, Namespace); + } + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Normalize(path))) + { + throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); + } + + var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + + if (value != null) + { + Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Normalize(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count; i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Gets or sets the type from which to map properties. + /// + public Type TargetType { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKeys { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs deleted file mode 100644 index 724a52b3..00000000 --- a/src/slskd/Common/ConfigurationSources/CommandLineConfigurationSource.cs +++ /dev/null @@ -1,157 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.ConfigurationSources -{ - using System; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - using Utility.CommandLine; - - /// - /// Extension methods for adding . - /// - public static class CommandLineConfigurationExtensions - { - /// - /// Adds a command line argument configuration soruce to . - /// - /// The to which to add. - /// The type from which to map properties. - /// The command line string from which to parse arguments. - /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddCommandLine(s => - { - s.TargetType = targetType; - s.CommandLine = commandLine ?? Environment.CommandLine; - }); - } - - /// - /// Adds a command line argument configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A command line argument . - /// - public class CommandLineConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public CommandLineConfigurationProvider(CommandLineConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - CommandLine = source.CommandLine; - } - - private string CommandLine { get; set; } - private string Namespace { get; set; } - private Type TargetType { get; set; } - - /// - /// Parses command line arguments from the specified string and maps them to the corresponding keys. - /// - public override void Load() - { - var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; - - void Map(Type type, string path) - { - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute)); - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (attribute != default) - { - var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString(); - var longName = (string)attribute.ConstructorArguments[1].Value; - var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i)); - - foreach (var argument in arguments) - { - if (dictionary.ContainsKey(argument)) - { - var value = dictionary[argument].ToString(); - - if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value)) - { - value = "true"; - } - - Data[key] = value; - } - } - } - else - { - Map(property.PropertyType, key); - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents command line arguments as an . - /// - public class CommandLineConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the command line string from which to parse arguments. - /// - public string CommandLine { get; set; } - - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); - } -} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs deleted file mode 100644 index 1784ce26..00000000 --- a/src/slskd/Common/ConfigurationSources/DefaultValueConfigurationSource.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.ConfigurationSources -{ - using System; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - - /// - /// Extension methods for adding . - /// - public static class DefaultValueConfigurationExtensions - { - /// - /// Adds a default value configuration source to . - /// - /// The to which to add. - /// The type from which to load default values. - /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddDefaultValues(s => - { - s.TargetType = targetType; - }); - } - - /// - /// Adds a default value configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A default value . - /// - public class DefaultValueConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - } - - private string Namespace { get; set; } - private Type TargetType { get; set; } - - /// - /// Loads default values from the specified and maps them to the corresponding keys. - /// - public override void Load() - { - void Map(Type type, string path) - { - var defaults = Activator.CreateInstance(type); - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (property.PropertyType.Namespace.StartsWith(Namespace)) - { - Map(property.PropertyType, key); - } - else - { - var value = property.GetValue(defaults); - - if (value != null) - { - Data[key] = value.ToString(); - } - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents default values as an . - /// - public class DefaultValueConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new DefaultValueConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs deleted file mode 100644 index 94823d11..00000000 --- a/src/slskd/Common/ConfigurationSources/EnvironmentVariableConfigurationSource.cs +++ /dev/null @@ -1,151 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.ConfigurationSources -{ - using System; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.Configuration; - using Utility.EnvironmentVariables; - - /// - /// Extension methods for adding . - /// - public static class EnvironmentVariableConfigurationExtensions - { - /// - /// Adds an environment variable configuration source to . - /// - /// The to which to add. - /// The type from which to map properties. - /// A prefix to prepend to all variable names. - /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - - return builder.AddEnvironmentVariables(s => - { - s.TargetType = targetType; - s.Prefix = prefix ?? string.Empty; - }); - } - - /// - /// Adds an enviroment variable configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// An enviroment variable . - /// - public class EnvironmentVariableConfigurationProvider : ConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - Prefix = source.Prefix; - } - - private Type TargetType { get; set; } - private string Namespace { get; set; } - private string Prefix { get; set; } - - /// - /// Loads environment variables and maps them to the corresponding keys. - /// - public override void Load() - { - void Map(Type type, string path) - { - var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - - foreach (PropertyInfo property in props) - { - var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute)); - var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant()); - - if (attribute != default) - { - var name = (string)attribute.ConstructorArguments[0].Value; - - if (!string.IsNullOrEmpty(name)) - { - var value = Environment.GetEnvironmentVariable(Prefix + name); - - if (value != null) - { - Data[key] = value.ToString(); - } - } - } - else - { - Map(property.PropertyType, key); - } - } - } - - Map(TargetType, Namespace); - } - } - - /// - /// Represents environment variables as an . - /// - public class EnvironmentVariableConfigurationSource : IConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Gets or sets a prefix to prepend to all variable names. - /// - public string Prefix { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new EnvironmentVariableConfigurationProvider(this); - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs b/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs deleted file mode 100644 index 654f5b2e..00000000 --- a/src/slskd/Common/ConfigurationSources/YamlConfigurationSource.cs +++ /dev/null @@ -1,191 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.ConfigurationSources -{ - using System; - using System.IO; - using System.Linq; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.FileProviders; - using YamlDotNet.Core; - using YamlDotNet.RepresentationModel; - - /// - /// Extension methods for adding . - /// - public static class YamlConfigurationExtensions - { - /// - /// Adds a YAML configuration source to . - /// - /// The to which to add . - /// - /// Path relative to the base path stored in of . - /// - /// The type from which to map properties. - /// Whether the file is optional. - /// Whether the configuration should be reloaded if the file changes. - /// - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - /// The updated to use to access the file. - /// The . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, Type targetType, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("File path must be a non-empty string.", nameof(path)); - } - - return builder.AddYamlFile(s => - { - s.Path = path; - s.TargetType = targetType; - s.Optional = optional; - s.ReloadOnChange = reloadOnChange; - s.NormalizeKeys = normalizeKeys; - s.FileProvider = provider; - s.ResolveFileProvider(); - }); - } - - /// - /// Adds a YAML configuration source to . - /// - /// The to which to add. - /// Configures the source. - /// The updated . - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) - => builder.Add(configureSource); - } - - /// - /// A YAML file based . - /// - public class YamlConfigurationProvider : FileConfigurationProvider - { - /// - /// Initializes a new instance of the class. - /// - /// The source settings. - public YamlConfigurationProvider(YamlConfigurationSource source) - : base(source) - { - TargetType = source.TargetType; - Namespace = TargetType.Namespace.Split('.').First(); - NormalizeKeys = source.NormalizeKeys; - } - - private Type TargetType { get; set; } - private string Namespace { get; set; } - private bool NormalizeKeys { get; set; } - private string[] NullValues { get; } = new[] { "~", "null", string.Empty }; - - /// - /// Loads the YAML data from a stream. - /// - /// The stream to read. - public override void Load(Stream stream) - { - try - { - using var reader = new StreamReader(stream); - - var yaml = new YamlStream(); - yaml.Load(reader); - - if (yaml.Documents.Count > 0) - { - var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; - Traverse(rootNode, Namespace); - } - } - catch (YamlException e) - { - throw new FormatException("Could not parse the YAML file.", e); - } - } - - private void Traverse(YamlNode root, string path = null) - { - string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; - - if (root is YamlScalarNode scalar) - { - if (Data.ContainsKey(Normalize(path))) - { - throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); - } - - var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - - if (value != null) - { - Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - } - } - else if (root is YamlMappingNode map) - { - foreach (var node in map.Children) - { - var key = Normalize(((YamlScalarNode)node.Key).Value); - Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); - } - } - else if (root is YamlSequenceNode sequence) - { - for (int i = 0; i < sequence.Children.Count; i++) - { - Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); - } - } - } - } - - /// - /// Represents a YAML file as an . - /// - public class YamlConfigurationSource : FileConfigurationSource - { - /// - /// Gets or sets the type from which to map properties. - /// - public Type TargetType { get; set; } - - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKeys { get; set; } - - /// - /// Builds the for this source. - /// - /// The . - /// A . - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - EnsureDefaults(builder); - return new YamlConfigurationProvider(this); - } - } -} \ No newline at end of file -- cgit v1.2.3 From dceadccf469009f9d4f9faba22acca68e8d918e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jul 2021 20:41:21 -0500 Subject: mark some options as RequiresRestart --- src/slskd/Options.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 7e4880c6..2ff0df97 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -23,6 +23,7 @@ namespace slskd using System.ComponentModel.DataAnnotations; using System.Diagnostics; using FluentFTP; + using slskd.Configuration; using slskd.Validation; using Soulseek.Diagnostics; using Utility.CommandLine; @@ -38,6 +39,7 @@ namespace slskd /// [Argument('v', "version")] [Description("display version information")] + [Obsolete("Used only for documentation; see Program for actual implementation")] public bool ShowVersion { get; private set; } = false; /// @@ -45,6 +47,7 @@ namespace slskd /// [Argument('h', "help")] [Description("display command line usage")] + [Obsolete("Used only for documentation; see Program for actual implementation")] public bool ShowHelp { get; private set; } = false; /// @@ -52,6 +55,7 @@ namespace slskd /// [Argument('e', "envars")] [Description("display environment variables")] + [Obsolete("Used only for documentation; see Program for actual implementation")] public bool ShowEnvironmentVariables { get; private set; } = false; /// @@ -59,6 +63,7 @@ namespace slskd /// [Argument('g', "generate-cert")] [Description("generate X509 certificate and password for HTTPs")] + [Obsolete("Used only for documentation; see Program for actual implementation")] public bool GenerateCertificate { get; private set; } = false; /// @@ -67,6 +72,7 @@ namespace slskd [Argument('c', "config")] [EnvironmentVariable("CONFIG")] [Description("path to configuration file")] + [Obsolete("Used only for documentation; see Program for actual implementation")] public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; /// @@ -75,6 +81,7 @@ namespace slskd [Argument('d', "debug")] [EnvironmentVariable("DEBUG")] [Description("run in debug mode")] + [RequiresRestart] public bool Debug { get; private set; } = Debugger.IsAttached; /// @@ -83,6 +90,7 @@ namespace slskd [Argument('n', "no-logo")] [EnvironmentVariable("NO_LOGO")] [Description("suppress logo on startup")] + [RequiresRestart] public bool NoLogo { get; private set; } = false; /// @@ -91,6 +99,7 @@ namespace slskd [Argument('x', "no-start")] [EnvironmentVariable("NO_START")] [Description("quit the application after initialization")] + [RequiresRestart] public bool NoStart { get; private set; } = false; /// @@ -99,6 +108,7 @@ namespace slskd [Argument('i', "instance-name")] [EnvironmentVariable("INSTANCE_NAME")] [Description("optional; a unique name for this instance")] + [RequiresRestart] public string InstanceName { get; private set; } = "default"; /// -- cgit v1.2.3 From 07133bd2a51acf5275578b7d4167dd3b9f689d7f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jul 2021 20:41:37 -0500 Subject: reload yaml on change --- src/slskd/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 01618efb..2ce98454 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -36,7 +36,7 @@ namespace slskd using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; - using slskd.ConfigurationSources; + using slskd.Configuration; using slskd.Cryptography; using slskd.Validation; using Utility.CommandLine; @@ -342,7 +342,7 @@ namespace slskd path: Path.GetFileName(configurationFile), targetType: typeof(Options), optional: true, - reloadOnChange: false, + reloadOnChange: true, provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory .AddCommandLine( targetType: typeof(Options), -- cgit v1.2.3 From e49e586955cb5005b336f87a68c9d538972b1533 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jul 2021 22:02:38 -0500 Subject: rename Configuration to Options --- .../API/Controllers/OptionsController.cs | 8 +- .../API/Controllers/SessionController.cs | 4 +- .../Application/Management/IManagementService.cs | 2 +- .../Application/Management/ManagementService.cs | 8 +- src/slskd/Application/Service.cs | 66 +- .../API/Controllers/TransfersController.cs | 4 +- src/slskd/Common/Validation/Extensions.cs | 6 +- .../Common/Validation/X509CertificateAttribute.cs | 2 +- src/slskd/Configuration.cs | 779 --------------------- src/slskd/Integrations/FTP/FTPClientFactory.cs | 6 +- src/slskd/Integrations/FTP/FTPService.cs | 6 +- .../Integrations/Pushbullet/PushbulletService.cs | 6 +- src/slskd/Options.cs | 779 +++++++++++++++++++++ src/slskd/Program.cs | 70 +- src/slskd/Startup.cs | 42 +- 15 files changed, 894 insertions(+), 894 deletions(-) delete mode 100644 src/slskd/Configuration.cs create mode 100644 src/slskd/Options.cs diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index 578b6b4c..b75adc97 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -30,13 +30,13 @@ namespace slskd.Management.API [Consumes("application/json")] public class OptionsController : ControllerBase { - public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { OptionsMonitor = optionsMonitor; } - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } - private Configuration Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Options Options => OptionsMonitor.CurrentValue; /// /// Gets the current application options. @@ -44,7 +44,7 @@ namespace slskd.Management.API /// [HttpGet] [Authorize] - [ProducesResponseType(typeof(Configuration), 200)] + [ProducesResponseType(typeof(Options), 200)] public IActionResult Get() { return Ok(Options); diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 1721f3f2..09a95c24 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,7 +37,7 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, + Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, SymmetricSecurityKey jwtSigningKey) { Options = optionsSnapshot.Value; @@ -45,7 +45,7 @@ namespace slskd.Management.API } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Configuration Options { get; set; } + private Options Options { get; set; } /// /// Checks whether the provided authentication is valid. diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index d4f7ff51..5ece698b 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -42,7 +42,7 @@ namespace slskd.Management /// Gets the current application options. /// /// - Configuration GetOptions(); + Options GetOptions(); /// /// Gets the current state of the connection to the Soulseek server. diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index a1d807a0..4a385cff 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -32,7 +32,7 @@ namespace slskd.Management /// The options monitor used to derive application options. /// The Soulseek client. public ManagementService( - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient) { OptionsMonitor = optionsMonitor; @@ -40,8 +40,8 @@ namespace slskd.Management } private ISoulseekClient Client { get; } - private Configuration Options => OptionsMonitor.CurrentValue; - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Options Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } /// /// Connects the Soulseek client to the server using the configured username and password. @@ -62,7 +62,7 @@ namespace slskd.Management /// Gets the current application options. /// /// - public Configuration GetOptions() => Options; + public Options GetOptions() => Options; /// /// Gets the current state of the connection to the Soulseek server. diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 9a65ae37..d9b682fc 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -44,7 +44,7 @@ namespace slskd private (int Directories, int Files) sharedCounts = (0, 0); public Service( - IOptionsMonitor optionMonitor, + IOptionsMonitor optionMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -55,7 +55,7 @@ namespace slskd OptionsMonitor = optionMonitor; OptionsMonitor.OnChange(options => OptionsChanged(options)); - Configuration = OptionsMonitor.CurrentValue; + Options = OptionsMonitor.CurrentValue; TransferTracker = transferTracker; BrowseTracker = browseTracker; @@ -69,26 +69,26 @@ namespace slskd if (UsingProxy) { proxyOptions = new ProxyOptions( - address: Configuration.Soulseek.Connection.Proxy.Address, - port: Configuration.Soulseek.Connection.Proxy.Port.Value, - username: Configuration.Soulseek.Connection.Proxy.Username, - password: Configuration.Soulseek.Connection.Proxy.Password); + 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); } var connectionOptions = new ConnectionOptions( - readBufferSize: Configuration.Soulseek.Connection.Buffer.Read, - writeBufferSize: Configuration.Soulseek.Connection.Buffer.Write, - connectTimeout: Configuration.Soulseek.Connection.Timeout.Connect, - inactivityTimeout: Configuration.Soulseek.Connection.Timeout.Inactivity, + readBufferSize: Options.Soulseek.Connection.Buffer.Read, + writeBufferSize: Options.Soulseek.Connection.Buffer.Write, + connectTimeout: Options.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity, proxyOptions: proxyOptions); var clientOptions = new SoulseekClientOptions( - listenPort: Configuration.Soulseek.ListenPort, + listenPort: Options.Soulseek.ListenPort, enableListener: true, userEndPointCache: new UserEndPointCache(), - distributedChildLimit: Configuration.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !Configuration.Soulseek.DistributedNetwork.Disabled, - minimumDiagnosticLevel: Configuration.Soulseek.DiagnosticLevel, + distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, serverConnectionOptions: connectionOptions, @@ -137,31 +137,31 @@ namespace slskd private IConversationTracker ConversationTracker { get; set; } private ILogger Logger { get; set; } = Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); - private IOptionsMonitor OptionsMonitor { get; set; } - private Configuration Configuration { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private Options Options { get; set; } private IRoomTracker RoomTracker { get; set; } private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } - private bool UsingProxy => !string.IsNullOrWhiteSpace(Configuration.Soulseek.Connection.Proxy.Address) && Configuration.Soulseek.Connection.Proxy.Port.HasValue; + private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue; private IPushbulletService Pushbullet { get; } public async Task StartAsync(CancellationToken cancellationToken) { if (UsingProxy) { - Logger.Information($"Using Proxy {Configuration.Soulseek.Connection.Proxy.Address}:{Configuration.Soulseek.Connection.Proxy.Port}"); + Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); } Logger.Information("Client started"); - Logger.Information("Listening on port {Port}", Configuration.Soulseek.ListenPort); + Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); - if (string.IsNullOrEmpty(Configuration.Soulseek.Username) || string.IsNullOrEmpty(Configuration.Soulseek.Password)) + if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.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(Configuration.Soulseek.Username, Configuration.Soulseek.Password).ConfigureAwait(false); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); } } @@ -173,12 +173,12 @@ namespace slskd return Task.CompletedTask; } - private void OptionsChanged(Configuration configuration) + private void OptionsChanged(Options options) { Console.WriteLine($"Options changed. Old options:"); - Console.WriteLine(JsonSerializer.Serialize(Configuration)); + Console.WriteLine(JsonSerializer.Serialize(Options)); Console.WriteLine($"\tNew options:"); - Console.WriteLine(JsonSerializer.Serialize(configuration)); + 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 @@ -202,7 +202,7 @@ namespace slskd private Task BrowseResponseResolver(string username, IPEndPoint endpoint) { var directories = System.IO.Directory - .GetDirectories(Configuration.Directories.Shared, "*", SearchOption.AllDirectories) + .GetDirectories(Options.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,7 +237,7 @@ namespace slskd private void Client_LoggedIn(object sender, EventArgs e) { - Logger.Information("Logged in to the Soulseek server as {Username}", Configuration.Soulseek.Username); + Logger.Information("Logged in to the Soulseek server as {Username}", Options.Soulseek.Username); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) @@ -256,13 +256,13 @@ namespace slskd } else if (args.Exception is KickedFromServerException) { - Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Configuration.Soulseek.Username); + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Options.Soulseek.Username); } else { Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - if (string.IsNullOrEmpty(Configuration.Soulseek.Username) || string.IsNullOrEmpty(Configuration.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; @@ -284,7 +284,7 @@ namespace slskd try { - await Client.ConnectAsync(Configuration.Soulseek.Username, Configuration.Soulseek.Password); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); break; } catch (Exception ex) @@ -300,7 +300,7 @@ namespace slskd { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - if (Configuration.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); @@ -311,7 +311,7 @@ namespace slskd { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - if (Configuration.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); } @@ -320,7 +320,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 != Configuration.Soulseek.Username) + if (args.Username != Options.Soulseek.Username) { RoomTracker.TryAddUser(args.RoomName, args.UserData); } @@ -336,7 +336,7 @@ namespace slskd var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); - if (Configuration.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); } diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index b28e5b1a..97b86689 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -46,7 +46,7 @@ namespace slskd.Transfer.API /// /// public TransfersController( - Microsoft.Extensions.Options.IOptionsSnapshot options, + Microsoft.Extensions.Options.IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker, IFTPService ftpClient) @@ -57,7 +57,7 @@ namespace slskd.Transfer.API FTP = ftpClient; } - private Configuration Options { get; } + private Options Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } private IFTPService FTP { get; } diff --git a/src/slskd/Common/Validation/Extensions.cs b/src/slskd/Common/Validation/Extensions.cs index cc2e3c12..b7e396a3 100644 --- a/src/slskd/Common/Validation/Extensions.cs +++ b/src/slskd/Common/Validation/Extensions.cs @@ -28,15 +28,15 @@ namespace slskd.Validation /// /// Validates options. /// - /// The configuration instance to validate. + /// The options instance to validate. /// The result of the validation, if invalid. /// A value indicating whether the instance is valid. - public static bool TryValidate(this Configuration configuration, out CompositeValidationResult result) + public static bool TryValidate(this Options options, out CompositeValidationResult result) { result = null; var results = new List(); - if (!Validator.TryValidateObject(configuration, new ValidationContext(configuration), results, true)) + if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true)) { result = new CompositeValidationResult("Invalid configuration", results); return false; diff --git a/src/slskd/Common/Validation/X509CertificateAttribute.cs b/src/slskd/Common/Validation/X509CertificateAttribute.cs index 87cd776b..7a080882 100644 --- a/src/slskd/Common/Validation/X509CertificateAttribute.cs +++ b/src/slskd/Common/Validation/X509CertificateAttribute.cs @@ -19,7 +19,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using slskd.Cryptography; - using static slskd.Configuration.WebOptions.HttpsOptions; + using static slskd.Options.WebOptions.HttpsOptions; /// /// Validates X509 certificate parameters specified through . diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs deleted file mode 100644 index 237b3caa..00000000 --- a/src/slskd/Configuration.cs +++ /dev/null @@ -1,779 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.ComponentModel.DataAnnotations; - using System.Diagnostics; - using FluentFTP; - using slskd.Configuration; - using slskd.Validation; - using Soulseek.Diagnostics; - using Utility.CommandLine; - using Utility.EnvironmentVariables; - - /// - /// Application options. - /// - public class Configuration - { - /// - /// Gets a value indicating whether to display the application version. - /// - [Argument('v', "version")] - [Description("display version information")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public bool ShowVersion { get; private set; } = false; - - /// - /// Gets a value indicating whether to display a list of command line arguments. - /// - [Argument('h', "help")] - [Description("display command line usage")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public bool ShowHelp { get; private set; } = false; - - /// - /// Gets a value indicating whether to display a list of configuration environment variables. - /// - [Argument('e', "envars")] - [Description("display environment variables")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public bool ShowEnvironmentVariables { get; private set; } = false; - - /// - /// Gets a value indicating whether to generate an X509 certificate and password. - /// - [Argument('g', "generate-cert")] - [Description("generate X509 certificate and password for HTTPs")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public bool GenerateCertificate { get; private set; } = false; - - /// - /// Gets the path to the application configuration file. - /// - [Argument('c', "config")] - [EnvironmentVariable("CONFIG")] - [Description("path to configuration file")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; - - /// - /// Gets a value indicating whether the application should run in debug mode. - /// - [Argument('d', "debug")] - [EnvironmentVariable("DEBUG")] - [Description("run in debug mode")] - [RequiresRestart] - public bool Debug { get; private set; } = Debugger.IsAttached; - - /// - /// Gets a value indicating whether the logo should be suppressed on startup. - /// - [Argument('n', "no-logo")] - [EnvironmentVariable("NO_LOGO")] - [Description("suppress logo on startup")] - [RequiresRestart] - public bool NoLogo { get; private set; } = false; - - /// - /// Gets a value indicating whether the application should quit after initialization. - /// - [Argument('x', "no-start")] - [EnvironmentVariable("NO_START")] - [Description("quit the application after initialization")] - [RequiresRestart] - public bool NoStart { get; private set; } = false; - - /// - /// Gets the unique name for this instance. - /// - [Argument('i', "instance-name")] - [EnvironmentVariable("INSTANCE_NAME")] - [Description("optional; a unique name for this instance")] - [RequiresRestart] - public string InstanceName { get; private set; } = "default"; - - /// - /// Gets directory options. - /// - [Validate] - public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); - - /// - /// Gets options for the web UI. - /// - [Validate] - public WebOptions Web { get; private set; } = new WebOptions(); - - /// - /// Gets logger options. - /// - [Validate] - public LoggerOptions Logger { get; private set; } = new LoggerOptions(); - - /// - /// Gets feature options. - /// - [Validate] - public FeatureOptions Feature { get; private set; } = new FeatureOptions(); - - /// - /// Gets options for the Soulseek client. - /// - [Validate] - public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); - - /// - /// Gets options for external integrations. - /// - [Validate] - public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); - - /// - /// Directory options. - /// - public class DirectoriesOptions - { - /// - /// Gets the path where application data is saved. - /// - [Argument(default, "app")] - [EnvironmentVariable("APP_DIR")] - [Description("path where application data is saved")] - [DirectoryExists] - public string App { get; private set; } = Program.DefaultAppDirectory; - - /// - /// Gets the path where incomplete downloads are saved. - /// - [Argument(default, "incomplete")] - [EnvironmentVariable("INCOMPLETE_DIR")] - [Description("path where incomplete downloads are saved")] - [DirectoryExists] - public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; - - /// - /// Gets the path where downloaded files are saved. - /// - [Argument('o', "downloads")] - [EnvironmentVariable("DOWNLOADS_DIR")] - [Description("path where downloaded files are saved")] - [DirectoryExists] - public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; - - /// - /// Gets the path to shared files. - /// - [Argument('s', "shared")] - [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - [DirectoryExists] - public string Shared { get; private set; } = Program.DefaultSharedDirectory; - } - - /// - /// Feature options. - /// - public class FeatureOptions - { - /// - /// Gets a value indicating whether prometheus metrics should be collected and published. - /// - [Argument(default, "prometheus")] - [EnvironmentVariable("PROMETHEUS")] - [Description("enable collection and publishing of prometheus metrics")] - public bool Prometheus { get; private set; } = false; - - /// - /// Gets a value indicating whether swagger documentation and UI should be enabled. - /// - [Argument(default, "swagger")] - [EnvironmentVariable("SWAGGER")] - [Description("enable swagger documentation and UI")] - public bool Swagger { get; private set; } = false; - } - - /// - /// Logger options. - /// - public class LoggerOptions - { - /// - /// Gets the URL to a Grafana Loki instance to which to log. - /// - [Argument(default, "loki")] - [EnvironmentVariable("LOKI")] - [Description("optional; url to a Grafana Loki instance to which to log")] - public string Loki { get; private set; } = null; - } - - /// - /// Soulseek client options. - /// - public class SoulseekOptions - { - /// - /// Gets the username for the Soulseek network. - /// - [Argument(default, "slsk-username")] - [EnvironmentVariable("SLSK_USERNAME")] - [Description("username for the Soulseek network")] - public string Username { get; private set; } = null; - - /// - /// Gets the password for the Soulseek network. - /// - [Argument(default, "slsk-password")] - [EnvironmentVariable("SLSK_PASSWORD")] - [Description("password for the Soulseek network")] - public string Password { get; private set; } = null; - - /// - /// Gets the port on which to listen for incoming connections. - /// - [Argument(default, "slsk-listen-port")] - [EnvironmentVariable("SLSK_LISTEN_PORT")] - [Description("port on which to listen for incoming connections")] - [Range(1024, 65535)] - public int ListenPort { get; private set; } = 50000; - - /// - /// Gets the minimum diagnostic level. - /// - [Argument(default, "slsk-diag-level")] - [EnvironmentVariable("SLSK_DIAG_LEVEL")] - [Description("minimum diagnostic level (None, Warning, Info, Debug)")] - public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; - - /// - /// Gets options for the distributed network. - /// - [Validate] - public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions(); - - /// - /// Gets connection options. - /// - [Validate] - public ConnectionOptions Connection { get; private set; } = new ConnectionOptions(); - - /// - /// Connection options. - /// - public class ConnectionOptions - { - /// - /// Gets connection timeout options. - /// - [Validate] - public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions(); - - /// - /// Gets connection buffer options. - /// - [Validate] - public BufferOptions Buffer { get; private set; } = new BufferOptions(); - - /// - /// Gets connection proxy options. - /// - [Validate] - public ProxyOptions Proxy { get; private set; } = new ProxyOptions(); - - /// - /// Connection buffer options. - /// - public class BufferOptions - { - /// - /// Gets the connection read buffer size. - /// - [Argument(default, "slsk-read-buffer")] - [EnvironmentVariable("SLSK_READ_BUFFER")] - [Description("read buffer size for connections")] - [Range(1024, int.MaxValue)] - public int Read { get; private set; } = 16384; - - /// - /// Gets the connection write buffer size. - /// - [Argument(default, "slsk-write-buffer")] - [EnvironmentVariable("SLSK_WRITE_BUFFER")] - [Description("write buffer size for connections")] - [Range(1024, int.MaxValue)] - public int Write { get; private set; } = 16384; - } - - /// - /// Connection timeout options. - /// - public class TimeoutOptions - { - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "slsk-connection-timeout")] - [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] - [Description("connection timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Connect { get; private set; } = 10000; - - /// - /// Gets the connection inactivity timeout, in milliseconds. - /// - [Argument(default, "slsk-inactivity-timeout")] - [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] - [Description("connection inactivity timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Inactivity { get; private set; } = 15000; - } - - /// - /// Connection proxy options. - /// - public class ProxyOptions - { - /// - /// Gets the proxy address. - /// - [Argument(default, "slsk-proxy-address")] - [EnvironmentVariable("SLSK_PROXY_ADDRESS")] - [Description("connection proxy address")] - [StringLength(255, MinimumLength = 1)] - public string Address { get; private set; } - - /// - /// Gets the proxy port. - /// - [Argument(default, "slsk-proxy-port")] - [EnvironmentVariable("SLSK_PROXY_PORT")] - [Description("connection proxy port")] - [Range(1, 65535)] - public int? Port { get; private set; } - - /// - /// Gets the proxy username, if applicable. - /// - [Argument(default, "slsk-proxy-username")] - [EnvironmentVariable("SLSK_PROXY_USERNAME")] - [Description("connection proxy username")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; private set; } - - /// - /// Gets the proxy password, if applicable. - /// - [Argument(default, "slsk-proxy-password")] - [EnvironmentVariable("SLSK_PROXY_PASSWORD")] - [Description("connection proxy password")] - [StringLength(255, MinimumLength = 1)] - public string Password { get; private set; } - } - } - - /// - /// Distributed network options. - /// - public class DistributedNetworkOptions - { - /// - /// Gets a value indicating whether the distributed network should be disabled. - /// - [Argument(default, "slsk-no-dnet")] - [EnvironmentVariable("SLSK_NO_DNET")] - [Description("disable the distributed network")] - public bool Disabled { get; private set; } = false; - - /// - /// Gets the distributed child connection limit. - /// - [Argument(default, "slsk-dnet-children")] - [EnvironmentVariable("SLSK_DNET_CHILDREN")] - [Description("max number of distributed children")] - [Range(1, int.MaxValue)] - public int ChildLimit { get; private set; } = 25; - } - } - - /// - /// Web server options. - /// - public class WebOptions - { - /// - /// Gets the HTTP listen port. - /// - [Argument('l', "http-port")] - [EnvironmentVariable("HTTP_PORT")] - [Description("HTTP listen port for web UI")] - [Range(1, 65535)] - public int Port { get; private set; } = 5000; - - /// - /// Gets HTTPS options. - /// - [Validate] - public HttpsOptions Https { get; private set; } = new HttpsOptions(); - - /// - /// Gets the base url for web requests. - /// - [Argument(default, "url-base")] - [EnvironmentVariable("URL_BASE")] - [Description("base url for web requests")] - public string UrlBase { get; private set; } = "/"; - - /// - /// Gets the path to static web content. - /// - [Argument(default, "content-path")] - [EnvironmentVariable("CONTENT_PATH")] - [Description("path to static web content")] - [StringLength(255, MinimumLength = 1)] - public string ContentPath { get; private set; } = "wwwroot"; - - /// - /// Gets authentication options. - /// - [Validate] - public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); - - /// - /// Authentication options. - /// - public class AuthenticationOptions - { - /// - /// Gets a value indicating whether authentication should be disabled. - /// - [Argument('x', "no-auth")] - [EnvironmentVariable("NO_AUTH")] - [Description("disable authentication for web requests")] - public bool Disable { get; private set; } = false; - - /// - /// Gets the username for the web UI. - /// - [Argument('u', "username")] - [EnvironmentVariable("USERNAME")] - [Description("username for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; private set; } = Program.AppName; - - /// - /// Gets the password for the web UI. - /// - [Argument('p', "password")] - [EnvironmentVariable("PASSWORD")] - [Description("password for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Password { get; private set; } = Program.AppName; - - /// - /// Gets JWT options. - /// - [Validate] - public JwtOptions Jwt { get; private set; } = new JwtOptions(); - - /// - /// JWT options. - /// - public class JwtOptions - { - /// - /// Gets the key with which to sign JWTs. - /// - [Argument(default, "jwt-key")] - [EnvironmentVariable("JWT_KEY")] - [Description("JWT signing key")] - [StringLength(255, MinimumLength = 1)] - public string Key { get; private set; } = Guid.NewGuid().ToString(); - - /// - /// Gets the TTL for JWTs. - /// - [Argument(default, "jwt-ttl")] - [EnvironmentVariable("JWT_TTL")] - [Description("TTL for JWTs")] - [Range(3600, int.MaxValue)] - public int Ttl { get; private set; } = 604800000; - } - } - - /// - /// HTTPS options. - /// - public class HttpsOptions - { - /// - /// Gets the HTTPS listen port. - /// - [Argument('L', "https-port")] - [EnvironmentVariable("HTTPS_PORT")] - [Description("HTTPS listen port for web UI")] - [Range(1, 65535)] - public int Port { get; private set; } = 5001; - - /// - /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. - /// - [Argument('f', "force-https")] - [EnvironmentVariable("HTTPS_FORCE")] - [Description("redirect HTTP to HTTPS")] - public bool Force { get; private set; } = false; - - /// - /// Gets certificate options. - /// - [Validate] - public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); - - /// - /// Certificate options. - /// - [X509Certificate] - public class CertificateOptions - { - /// - /// Gets the path to the the X509 certificate .pfx file. - /// - [Argument(default, "https-cert-pfx")] - [EnvironmentVariable("HTTPS_CERT_PFX")] - [Description("path to X509 certificate .pfx")] - [FileExists] - public string Pfx { get; private set; } - - /// - /// Gets the password for the X509 certificate. - /// - [Argument(default, "https-cert-password")] - [EnvironmentVariable("HTTPS_CERT_PASSWORD")] - [Description("X509 certificate password")] - public string Password { get; private set; } - } - } - } - - /// - /// Options for external integrations. - /// - public class IntegrationOptions - { - /// - /// Gets FTP options. - /// - [Validate] - public FTPOptions FTP { get; private set; } = new FTPOptions(); - - /// - /// Gets Pushbullet options. - /// - [Validate] - public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); - - /// - /// FTP options. - /// - public class FTPOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the FTP integration is enabled. - /// - [Argument(default, "ftp")] - [EnvironmentVariable("FTP_ENABLED")] - [Description("enable FTP integration")] - public bool Enabled { get; private set; } - - /// - /// Gets the FTP address. - /// - [Argument(default, "ftp-address")] - [EnvironmentVariable("FTP_ADDRESS")] - [Description("FTP address")] - public string Address { get; private set; } - - /// - /// Gets the FTP port. - /// - [Argument(default, "ftp-port")] - [EnvironmentVariable("FTP_PORT")] - [Description("FTP port")] - [Range(1, 65535)] - public int Port { get; private set; } = 21; - - /// - /// Gets the FTP encryption mode. - /// - [Argument(default, "ftp-encryption-mode")] - [EnvironmentVariable("FTP_ENCRYPTION_MODE")] - [Description("FTP encryption mode; none, implicit, explicit, auto")] - [Enum(typeof(FtpEncryptionMode))] - public string EncryptionMode { get; private set; } = "auto"; - - /// - /// Gets a value indicating whether FTP certificate errors should be ignored. - /// - [Argument(default, "ftp-ignore-certificate-errors")] - [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] - [Description("ignore FTP certificate errors")] - public bool IgnoreCertificateErrors { get; private set; } = false; - - /// - /// Gets the FTP username. - /// - [Argument(default, "ftp-username")] - [EnvironmentVariable("FTP_USERNAME")] - [Description("FTP username")] - public string Username { get; private set; } - - /// - /// Gets the FTP password. - /// - [Argument(default, "ftp-password")] - [EnvironmentVariable("FTP_PASSWORD")] - [Description("FTP password")] - public string Password { get; private set; } - - /// - /// Gets the remote path for uploads. - /// - [Argument(default, "ftp-remote-path")] - [EnvironmentVariable("FTP_REMOTE_PATH")] - [Description("remote path for FTP uploads")] - public string RemotePath { get; private set; } = "/"; - - /// - /// Gets a value indicating whether existing files should be overwritten. - /// - [Argument(default, "ftp-overwrite-existing")] - [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] - [Description("overwrite existing files when uploading to FTP")] - public bool OverwriteExisting { get; private set; } = true; - - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "ftp-connection-timeout")] - [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] - [Description("FTP connection timeout, in milliseconds")] - [Range(0, int.MaxValue)] - public int ConnectionTimeout { get; private set; } = 5000; - - /// - /// Gets the number of times failing uploads will be retried. - /// - [Argument(default, "ftp-retry-attempts")] - [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] - [Description("number of times failing FTP uploads will be retried")] - [Range(0, 5)] - public int RetryAttempts { get; private set; } = 3; - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(Address)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); - } - - return results; - } - } - - /// - /// Pushbullet options. - /// - public class PushbulletOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the Pushbullet integration is enabled. - /// - [Argument(default, "pushbullet")] - [EnvironmentVariable("PUSHBULLET_ENABLED")] - [Description("enable Pushbullet integration")] - public bool Enabled { get; private set; } = false; - - /// - /// Gets the Pushbullet API access token. - /// - [Argument(default, "pushbullet-token")] - [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] - [Description("Pushbullet access token")] - public string AccessToken { get; private set; } - - /// - /// Gets the prefix for Pushbullet notification titles. - /// - [Argument(default, "pushbullet-prefix")] - [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] - [Description("prefix for Pushbullet notification titles")] - public string NotificationPrefix { get; private set; } = "From slskd:"; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. - /// - [Argument(default, "pushbullet-notify-on-pm")] - [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] - [Description("send Pushbullet notifications when private messages are received")] - public bool NotifyOnPrivateMessage { get; private set; } = true; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged - /// in user's username is mentioned in a room. - /// - [Argument(default, "pushbullet-notify-on-room-mention")] - [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] - [Description("send Pushbullet notifications when your username is mentioned in a room")] - public bool NotifyOnRoomMention { get; private set; } = true; - - /// - /// Gets the number of times failing Pushbullet notifications will be retried. - /// - [Argument(default, "pushbullet-retry-attempts")] - [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] - [Description("number of times failing Pushbullet notifications will be retried")] - [Range(0, 5)] - public int RetryAttempts { get; private set; } = 3; - - /// - /// Gets the cooldown time for Pushbullet notifications, in milliseconds. - /// - [Argument(default, "pushbullet-cooldown")] - [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] - [Description("cooldown time for Pushbullet notifications, in milliseconds")] - public int CooldownTime { get; private set; } = 900000; // 15 minutes - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); - } - - return results; - } - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index 5b8639dc..cc076ca1 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -19,7 +19,7 @@ namespace slskd.Integrations.FTP { using System; using FluentFTP; - using static slskd.Configuration.IntegrationOptions; + using static slskd.Options.IntegrationOptions; /// /// FTP client factory. @@ -30,7 +30,7 @@ namespace slskd.Integrations.FTP /// Initializes a new instance of the class. /// /// The options monitor used to derive application options. - public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { Options = optionsMonitor.CurrentValue; @@ -48,7 +48,7 @@ namespace slskd.Integrations.FTP private FtpEncryptionMode EncryptionMode { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; - private Configuration Options { get; set; } + private Options Options { get; set; } /// /// Creates an instance of . diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index f7fd1ddd..a5fe6a8f 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -23,7 +23,7 @@ namespace slskd.Integrations.FTP using System.Threading.Tasks; using FluentFTP; using Microsoft.Extensions.Logging; - using static slskd.Configuration.IntegrationOptions; + using static slskd.Options.IntegrationOptions; /// /// FTP Integration service. @@ -38,7 +38,7 @@ namespace slskd.Integrations.FTP /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ILogger log) { Factory = ftpClientFactory; @@ -49,7 +49,7 @@ namespace slskd.Integrations.FTP private IFTPClientFactory Factory { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; private ILogger Log { get; set; } - private Configuration Options { get; } + private Options Options { get; } /// /// Uploads the specified to the configured FTP server. diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index 8bf94af9..cb31e6dc 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -24,7 +24,7 @@ namespace slskd.Integrations.Pushbullet using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; - using static slskd.Configuration.IntegrationOptions; + using static slskd.Options.IntegrationOptions; /// /// Pushbullet integration service. @@ -41,7 +41,7 @@ namespace slskd.Integrations.Pushbullet /// The logger. public PushbulletService( IHttpClientFactory httpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ILogger log) { HttpClientFactory = httpClientFactory; @@ -52,7 +52,7 @@ namespace slskd.Integrations.Pushbullet } private IHttpClientFactory HttpClientFactory { get; } - private Configuration Options { get; } + private Options Options { get; } private ILogger Log { get; } private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet; private IMemoryCache RecentlySent { get; } diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs new file mode 100644 index 00000000..2ff0df97 --- /dev/null +++ b/src/slskd/Options.cs @@ -0,0 +1,779 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using FluentFTP; + using slskd.Configuration; + using slskd.Validation; + using Soulseek.Diagnostics; + using Utility.CommandLine; + using Utility.EnvironmentVariables; + + /// + /// Application options. + /// + public class Options + { + /// + /// Gets a value indicating whether to display the application version. + /// + [Argument('v', "version")] + [Description("display version information")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + public bool ShowVersion { get; private set; } = false; + + /// + /// Gets a value indicating whether to display a list of command line arguments. + /// + [Argument('h', "help")] + [Description("display command line usage")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + public bool ShowHelp { get; private set; } = false; + + /// + /// Gets a value indicating whether to display a list of configuration environment variables. + /// + [Argument('e', "envars")] + [Description("display environment variables")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + public bool ShowEnvironmentVariables { get; private set; } = false; + + /// + /// Gets a value indicating whether to generate an X509 certificate and password. + /// + [Argument('g', "generate-cert")] + [Description("generate X509 certificate and password for HTTPs")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + public bool GenerateCertificate { get; private set; } = false; + + /// + /// Gets the path to the application configuration file. + /// + [Argument('c', "config")] + [EnvironmentVariable("CONFIG")] + [Description("path to configuration file")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; + + /// + /// Gets a value indicating whether the application should run in debug mode. + /// + [Argument('d', "debug")] + [EnvironmentVariable("DEBUG")] + [Description("run in debug mode")] + [RequiresRestart] + public bool Debug { get; private set; } = Debugger.IsAttached; + + /// + /// Gets a value indicating whether the logo should be suppressed on startup. + /// + [Argument('n', "no-logo")] + [EnvironmentVariable("NO_LOGO")] + [Description("suppress logo on startup")] + [RequiresRestart] + public bool NoLogo { get; private set; } = false; + + /// + /// Gets a value indicating whether the application should quit after initialization. + /// + [Argument('x', "no-start")] + [EnvironmentVariable("NO_START")] + [Description("quit the application after initialization")] + [RequiresRestart] + public bool NoStart { get; private set; } = false; + + /// + /// Gets the unique name for this instance. + /// + [Argument('i', "instance-name")] + [EnvironmentVariable("INSTANCE_NAME")] + [Description("optional; a unique name for this instance")] + [RequiresRestart] + public string InstanceName { get; private set; } = "default"; + + /// + /// Gets directory options. + /// + [Validate] + public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); + + /// + /// Gets options for the web UI. + /// + [Validate] + public WebOptions Web { get; private set; } = new WebOptions(); + + /// + /// Gets logger options. + /// + [Validate] + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + + /// + /// Gets feature options. + /// + [Validate] + public FeatureOptions Feature { get; private set; } = new FeatureOptions(); + + /// + /// Gets options for the Soulseek client. + /// + [Validate] + public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); + + /// + /// Gets options for external integrations. + /// + [Validate] + public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); + + /// + /// Directory options. + /// + public class DirectoriesOptions + { + /// + /// Gets the path where application data is saved. + /// + [Argument(default, "app")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] + [DirectoryExists] + public string App { get; private set; } = Program.DefaultAppDirectory; + + /// + /// Gets the path where incomplete downloads are saved. + /// + [Argument(default, "incomplete")] + [EnvironmentVariable("INCOMPLETE_DIR")] + [Description("path where incomplete downloads are saved")] + [DirectoryExists] + public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; + + /// + /// Gets the path where downloaded files are saved. + /// + [Argument('o', "downloads")] + [EnvironmentVariable("DOWNLOADS_DIR")] + [Description("path where downloaded files are saved")] + [DirectoryExists] + public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; + + /// + /// Gets the path to shared files. + /// + [Argument('s', "shared")] + [EnvironmentVariable("SHARED_DIR")] + [Description("path to shared files")] + [DirectoryExists] + public string Shared { get; private set; } = Program.DefaultSharedDirectory; + } + + /// + /// Feature options. + /// + public class FeatureOptions + { + /// + /// Gets a value indicating whether prometheus metrics should be collected and published. + /// + [Argument(default, "prometheus")] + [EnvironmentVariable("PROMETHEUS")] + [Description("enable collection and publishing of prometheus metrics")] + public bool Prometheus { get; private set; } = false; + + /// + /// Gets a value indicating whether swagger documentation and UI should be enabled. + /// + [Argument(default, "swagger")] + [EnvironmentVariable("SWAGGER")] + [Description("enable swagger documentation and UI")] + public bool Swagger { get; private set; } = false; + } + + /// + /// Logger options. + /// + public class LoggerOptions + { + /// + /// Gets the URL to a Grafana Loki instance to which to log. + /// + [Argument(default, "loki")] + [EnvironmentVariable("LOKI")] + [Description("optional; url to a Grafana Loki instance to which to log")] + public string Loki { get; private set; } = null; + } + + /// + /// Soulseek client options. + /// + public class SoulseekOptions + { + /// + /// Gets the username for the Soulseek network. + /// + [Argument(default, "slsk-username")] + [EnvironmentVariable("SLSK_USERNAME")] + [Description("username for the Soulseek network")] + public string Username { get; private set; } = null; + + /// + /// Gets the password for the Soulseek network. + /// + [Argument(default, "slsk-password")] + [EnvironmentVariable("SLSK_PASSWORD")] + [Description("password for the Soulseek network")] + public string Password { get; private set; } = null; + + /// + /// Gets the port on which to listen for incoming connections. + /// + [Argument(default, "slsk-listen-port")] + [EnvironmentVariable("SLSK_LISTEN_PORT")] + [Description("port on which to listen for incoming connections")] + [Range(1024, 65535)] + public int ListenPort { get; private set; } = 50000; + + /// + /// Gets the minimum diagnostic level. + /// + [Argument(default, "slsk-diag-level")] + [EnvironmentVariable("SLSK_DIAG_LEVEL")] + [Description("minimum diagnostic level (None, Warning, Info, Debug)")] + public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; + + /// + /// Gets options for the distributed network. + /// + [Validate] + public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions(); + + /// + /// Gets connection options. + /// + [Validate] + public ConnectionOptions Connection { get; private set; } = new ConnectionOptions(); + + /// + /// Connection options. + /// + public class ConnectionOptions + { + /// + /// Gets connection timeout options. + /// + [Validate] + public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions(); + + /// + /// Gets connection buffer options. + /// + [Validate] + public BufferOptions Buffer { get; private set; } = new BufferOptions(); + + /// + /// Gets connection proxy options. + /// + [Validate] + public ProxyOptions Proxy { get; private set; } = new ProxyOptions(); + + /// + /// Connection buffer options. + /// + public class BufferOptions + { + /// + /// Gets the connection read buffer size. + /// + [Argument(default, "slsk-read-buffer")] + [EnvironmentVariable("SLSK_READ_BUFFER")] + [Description("read buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Read { get; private set; } = 16384; + + /// + /// Gets the connection write buffer size. + /// + [Argument(default, "slsk-write-buffer")] + [EnvironmentVariable("SLSK_WRITE_BUFFER")] + [Description("write buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Write { get; private set; } = 16384; + } + + /// + /// Connection timeout options. + /// + public class TimeoutOptions + { + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "slsk-connection-timeout")] + [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] + [Description("connection timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Connect { get; private set; } = 10000; + + /// + /// Gets the connection inactivity timeout, in milliseconds. + /// + [Argument(default, "slsk-inactivity-timeout")] + [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] + [Description("connection inactivity timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Inactivity { get; private set; } = 15000; + } + + /// + /// Connection proxy options. + /// + public class ProxyOptions + { + /// + /// Gets the proxy address. + /// + [Argument(default, "slsk-proxy-address")] + [EnvironmentVariable("SLSK_PROXY_ADDRESS")] + [Description("connection proxy address")] + [StringLength(255, MinimumLength = 1)] + public string Address { get; private set; } + + /// + /// Gets the proxy port. + /// + [Argument(default, "slsk-proxy-port")] + [EnvironmentVariable("SLSK_PROXY_PORT")] + [Description("connection proxy port")] + [Range(1, 65535)] + public int? Port { get; private set; } + + /// + /// Gets the proxy username, if applicable. + /// + [Argument(default, "slsk-proxy-username")] + [EnvironmentVariable("SLSK_PROXY_USERNAME")] + [Description("connection proxy username")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; private set; } + + /// + /// Gets the proxy password, if applicable. + /// + [Argument(default, "slsk-proxy-password")] + [EnvironmentVariable("SLSK_PROXY_PASSWORD")] + [Description("connection proxy password")] + [StringLength(255, MinimumLength = 1)] + public string Password { get; private set; } + } + } + + /// + /// Distributed network options. + /// + public class DistributedNetworkOptions + { + /// + /// Gets a value indicating whether the distributed network should be disabled. + /// + [Argument(default, "slsk-no-dnet")] + [EnvironmentVariable("SLSK_NO_DNET")] + [Description("disable the distributed network")] + public bool Disabled { get; private set; } = false; + + /// + /// Gets the distributed child connection limit. + /// + [Argument(default, "slsk-dnet-children")] + [EnvironmentVariable("SLSK_DNET_CHILDREN")] + [Description("max number of distributed children")] + [Range(1, int.MaxValue)] + public int ChildLimit { get; private set; } = 25; + } + } + + /// + /// Web server options. + /// + public class WebOptions + { + /// + /// Gets the HTTP listen port. + /// + [Argument('l', "http-port")] + [EnvironmentVariable("HTTP_PORT")] + [Description("HTTP listen port for web UI")] + [Range(1, 65535)] + public int Port { get; private set; } = 5000; + + /// + /// Gets HTTPS options. + /// + [Validate] + public HttpsOptions Https { get; private set; } = new HttpsOptions(); + + /// + /// Gets the base url for web requests. + /// + [Argument(default, "url-base")] + [EnvironmentVariable("URL_BASE")] + [Description("base url for web requests")] + public string UrlBase { get; private set; } = "/"; + + /// + /// Gets the path to static web content. + /// + [Argument(default, "content-path")] + [EnvironmentVariable("CONTENT_PATH")] + [Description("path to static web content")] + [StringLength(255, MinimumLength = 1)] + public string ContentPath { get; private set; } = "wwwroot"; + + /// + /// Gets authentication options. + /// + [Validate] + public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); + + /// + /// Authentication options. + /// + public class AuthenticationOptions + { + /// + /// Gets a value indicating whether authentication should be disabled. + /// + [Argument('x', "no-auth")] + [EnvironmentVariable("NO_AUTH")] + [Description("disable authentication for web requests")] + public bool Disable { get; private set; } = false; + + /// + /// Gets the username for the web UI. + /// + [Argument('u', "username")] + [EnvironmentVariable("USERNAME")] + [Description("username for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; private set; } = Program.AppName; + + /// + /// Gets the password for the web UI. + /// + [Argument('p', "password")] + [EnvironmentVariable("PASSWORD")] + [Description("password for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Password { get; private set; } = Program.AppName; + + /// + /// Gets JWT options. + /// + [Validate] + public JwtOptions Jwt { get; private set; } = new JwtOptions(); + + /// + /// JWT options. + /// + public class JwtOptions + { + /// + /// Gets the key with which to sign JWTs. + /// + [Argument(default, "jwt-key")] + [EnvironmentVariable("JWT_KEY")] + [Description("JWT signing key")] + [StringLength(255, MinimumLength = 1)] + public string Key { get; private set; } = Guid.NewGuid().ToString(); + + /// + /// Gets the TTL for JWTs. + /// + [Argument(default, "jwt-ttl")] + [EnvironmentVariable("JWT_TTL")] + [Description("TTL for JWTs")] + [Range(3600, int.MaxValue)] + public int Ttl { get; private set; } = 604800000; + } + } + + /// + /// HTTPS options. + /// + public class HttpsOptions + { + /// + /// Gets the HTTPS listen port. + /// + [Argument('L', "https-port")] + [EnvironmentVariable("HTTPS_PORT")] + [Description("HTTPS listen port for web UI")] + [Range(1, 65535)] + public int Port { get; private set; } = 5001; + + /// + /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. + /// + [Argument('f', "force-https")] + [EnvironmentVariable("HTTPS_FORCE")] + [Description("redirect HTTP to HTTPS")] + public bool Force { get; private set; } = false; + + /// + /// Gets certificate options. + /// + [Validate] + public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); + + /// + /// Certificate options. + /// + [X509Certificate] + public class CertificateOptions + { + /// + /// Gets the path to the the X509 certificate .pfx file. + /// + [Argument(default, "https-cert-pfx")] + [EnvironmentVariable("HTTPS_CERT_PFX")] + [Description("path to X509 certificate .pfx")] + [FileExists] + public string Pfx { get; private set; } + + /// + /// Gets the password for the X509 certificate. + /// + [Argument(default, "https-cert-password")] + [EnvironmentVariable("HTTPS_CERT_PASSWORD")] + [Description("X509 certificate password")] + public string Password { get; private set; } + } + } + } + + /// + /// Options for external integrations. + /// + public class IntegrationOptions + { + /// + /// Gets FTP options. + /// + [Validate] + public FTPOptions FTP { get; private set; } = new FTPOptions(); + + /// + /// Gets Pushbullet options. + /// + [Validate] + public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); + + /// + /// FTP options. + /// + public class FTPOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the FTP integration is enabled. + /// + [Argument(default, "ftp")] + [EnvironmentVariable("FTP_ENABLED")] + [Description("enable FTP integration")] + public bool Enabled { get; private set; } + + /// + /// Gets the FTP address. + /// + [Argument(default, "ftp-address")] + [EnvironmentVariable("FTP_ADDRESS")] + [Description("FTP address")] + public string Address { get; private set; } + + /// + /// Gets the FTP port. + /// + [Argument(default, "ftp-port")] + [EnvironmentVariable("FTP_PORT")] + [Description("FTP port")] + [Range(1, 65535)] + public int Port { get; private set; } = 21; + + /// + /// Gets the FTP encryption mode. + /// + [Argument(default, "ftp-encryption-mode")] + [EnvironmentVariable("FTP_ENCRYPTION_MODE")] + [Description("FTP encryption mode; none, implicit, explicit, auto")] + [Enum(typeof(FtpEncryptionMode))] + public string EncryptionMode { get; private set; } = "auto"; + + /// + /// Gets a value indicating whether FTP certificate errors should be ignored. + /// + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; private set; } = false; + + /// + /// Gets the FTP username. + /// + [Argument(default, "ftp-username")] + [EnvironmentVariable("FTP_USERNAME")] + [Description("FTP username")] + public string Username { get; private set; } + + /// + /// Gets the FTP password. + /// + [Argument(default, "ftp-password")] + [EnvironmentVariable("FTP_PASSWORD")] + [Description("FTP password")] + public string Password { get; private set; } + + /// + /// Gets the remote path for uploads. + /// + [Argument(default, "ftp-remote-path")] + [EnvironmentVariable("FTP_REMOTE_PATH")] + [Description("remote path for FTP uploads")] + public string RemotePath { get; private set; } = "/"; + + /// + /// Gets a value indicating whether existing files should be overwritten. + /// + [Argument(default, "ftp-overwrite-existing")] + [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] + [Description("overwrite existing files when uploading to FTP")] + public bool OverwriteExisting { get; private set; } = true; + + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "ftp-connection-timeout")] + [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] + [Description("FTP connection timeout, in milliseconds")] + [Range(0, int.MaxValue)] + public int ConnectionTimeout { get; private set; } = 5000; + + /// + /// Gets the number of times failing uploads will be retried. + /// + [Argument(default, "ftp-retry-attempts")] + [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] + [Description("number of times failing FTP uploads will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + return results; + } + } + + /// + /// Pushbullet options. + /// + public class PushbulletOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET_ENABLED")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; private set; } = false; + + /// + /// Gets the Pushbullet API access token. + /// + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + public string AccessToken { get; private set; } + + /// + /// Gets the prefix for Pushbullet notification titles. + /// + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; private set; } = "From slskd:"; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// + [Argument(default, "pushbullet-notify-on-pm")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] + [Description("send Pushbullet notifications when private messages are received")] + public bool NotifyOnPrivateMessage { get; private set; } = true; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// + [Argument(default, "pushbullet-notify-on-room-mention")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] + [Description("send Pushbullet notifications when your username is mentioned in a room")] + public bool NotifyOnRoomMention { get; private set; } = true; + + /// + /// Gets the number of times failing Pushbullet notifications will be retried. + /// + [Argument(default, "pushbullet-retry-attempts")] + [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] + [Description("number of times failing Pushbullet notifications will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + /// + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// + [Argument(default, "pushbullet-cooldown")] + [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] + [Description("cooldown time for Pushbullet notifications, in milliseconds")] + public int CooldownTime { get; private set; } = 900000; // 15 minutes + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); + } + + return results; + } + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e022237b..abd27268 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -119,8 +119,8 @@ namespace slskd /// public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; - private static IConfigurationRoot ConfigurationRoot { get; set; } - private static Configuration Configuration { get; } = new Configuration(); + private static IConfigurationRoot Configuration { get; set; } + private static Options Options { get; } = new Options(); [EnvironmentVariable("CONFIG")] [Argument('c', "config", "path to configuration file")] @@ -167,12 +167,12 @@ namespace slskd if (ShowHelp) { - PrintCommandLineArguments(typeof(Configuration)); + PrintCommandLineArguments(typeof(Options)); } if (ShowEnvironmentVariables) { - PrintEnvironmentVariables(typeof(Configuration), EnvironmentVariablePrefix); + PrintEnvironmentVariables(typeof(Options), EnvironmentVariablePrefix); } return; @@ -188,19 +188,19 @@ namespace slskd // with bootstrapping. try { - ConfigurationRoot = new ConfigurationBuilder() + Configuration = new ConfigurationBuilder() .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile) .Build(); - ConfigurationRoot.GetSection(AppName) + Configuration.GetSection(AppName) .Bind(Configuration, (o) => { o.BindNonPublicProperties = true; }); - if (Configuration.Debug) + if (Options.Debug) { - Console.WriteLine($"Configuration:\n{ConfigurationRoot.GetDebugView()}"); + Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}"); } - if (!Configuration.TryValidate(out var result)) + if (!Options.TryValidate(out var result)) { Console.WriteLine(result.GetResultView()); return; @@ -208,16 +208,16 @@ namespace slskd } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {(!Configuration.Debug ? ex : ex.Message)}"); + Console.WriteLine($"Invalid configuration: {(!Options.Debug ? ex : ex.Message)}"); return; } try { - VerifyOrCreateDirectory(Configuration.Directories.App); - VerifyOrCreateDirectory(Configuration.Directories.Incomplete); - VerifyOrCreateDirectory(Configuration.Directories.Downloads); - VerifyOrCreateDirectory(Configuration.Directories.Shared, verifyWriteable: false); + VerifyOrCreateDirectory(Options.Directories.App); + VerifyOrCreateDirectory(Options.Directories.Incomplete); + VerifyOrCreateDirectory(Options.Directories.Downloads); + VerifyOrCreateDirectory(Options.Directories.Shared, verifyWriteable: false); } catch (Exception ex) { @@ -225,31 +225,31 @@ namespace slskd return; } - Log.Logger = (Configuration.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + Log.Logger = (Options.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", Configuration.InstanceName) + .Enrich.WithProperty("InstanceName", Options.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( - outputTemplate: (Configuration.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + outputTemplate: (Options.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (Configuration.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (Options.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => !string.IsNullOrEmpty(Configuration.Logger.Loki), + e => !string.IsNullOrEmpty(Options.Logger.Loki), config => config.GrafanaLoki( - Configuration.Logger.Loki ?? string.Empty, + Options.Logger.Loki ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); var logger = Log.ForContext(typeof(Program)); - if (!Configuration.NoLogo) + if (!Options.NoLogo) { PrintLogo(Version); } @@ -260,18 +260,18 @@ namespace slskd } logger.Information("Version: {Version}", Version); - logger.Information("Instance Name: {InstanceName}", Configuration.InstanceName); + logger.Information("Instance Name: {InstanceName}", Options.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); - if (!string.IsNullOrEmpty(Configuration.Logger.Loki)) + if (!string.IsNullOrEmpty(Options.Logger.Loki)) { - logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Configuration.Logger.Loki); + logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Options.Logger.Loki); } try { - if (Configuration.Feature.Prometheus) + if (Options.Feature.Prometheus) { using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } @@ -287,13 +287,13 @@ namespace slskd .UseUrls() .UseKestrel(options => { - logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Configuration.Web.Port}/"); - options.Listen(IPAddress.Any, Configuration.Web.Port); + logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Options.Web.Port}/"); + options.Listen(IPAddress.Any, Options.Web.Port); - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Configuration.Web.Https.Port}/"); - options.Listen(IPAddress.Any, Configuration.Web.Https.Port, listenOptions => + logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Options.Web.Https.Port}/"); + options.Listen(IPAddress.Any, Options.Web.Https.Port, listenOptions => { - var cert = Configuration.Web.Https.Certificate; + var cert = Options.Web.Https.Certificate; if (!string.IsNullOrEmpty(cert.Pfx)) { @@ -310,7 +310,7 @@ namespace slskd .UseStartup() .Build(); - if (Configuration.NoStart) + if (Options.NoStart) { logger.Information("Qutting because 'no-start' option is enabled"); return; @@ -334,18 +334,18 @@ namespace slskd return builder .AddDefaultValues( - targetType: typeof(Configuration)) + targetType: typeof(Options)) .AddEnvironmentVariables( - targetType: typeof(Configuration), + targetType: typeof(Options), prefix: environmentVariablePrefix) .AddYamlFile( path: Path.GetFileName(configurationFile), - targetType: typeof(Configuration), + targetType: typeof(Options), optional: true, reloadOnChange: true, provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory .AddCommandLine( - targetType: typeof(Configuration), + targetType: typeof(Options), commandLine: Environment.CommandLine); } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 07216937..f5cd2d13 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -52,28 +52,28 @@ namespace slskd /// Initializes a new instance of the class. /// /// The application configuration root. - public Startup(IConfiguration configurationRoot) + public Startup(IConfiguration configuration) { - ConfigurationRoot = configurationRoot; + Configuration = configuration; - Configuration = new Configuration(); - ConfigurationRoot.GetSection(Program.AppName).Bind(Configuration, (o) => + Options = new Options(); + Configuration.GetSection(Program.AppName).Bind(Options, (o) => { o.BindNonPublicProperties = true; }); - UrlBase = Configuration.Web.UrlBase; + UrlBase = Options.Web.UrlBase; UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - ContentPath = Path.GetFullPath(Configuration.Web.ContentPath); + ContentPath = Path.GetFullPath(Options.Web.ContentPath); - JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Configuration.Web.Authentication.Jwt.Key)); + JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Options.Web.Authentication.Jwt.Key)); } - private IConfiguration ConfigurationRoot { get; } + private IConfiguration Configuration { get; } private string ContentPath { get; set; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Configuration Configuration { get; } + private Options Options { get; } private string UrlBase { get; set; } /// @@ -84,14 +84,14 @@ namespace slskd { var logger = Log.ForContext(); - services.AddOptions() - .Bind(ConfigurationRoot.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); + services.AddOptions() + .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddSingleton(JwtSigningKey); - if (!Configuration.Web.Authentication.Disable) + if (!Options.Web.Authentication.Disable) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => @@ -139,7 +139,7 @@ namespace slskd options.SubstituteApiVersionInUrl = true; }); - if (Configuration.Feature.Swagger) + if (Options.Feature.Swagger) { services.AddSwaggerGen(options => { @@ -163,19 +163,19 @@ namespace slskd }); } - if (Configuration.Feature.Prometheus) + if (Options.Feature.Prometheus) { services.AddSystemMetrics(); } services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Configuration.Directories.App, "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}"); }); services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Configuration.Directories.App, "peer.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "peer.db")}"); }); services.AddHttpClient(); @@ -185,7 +185,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(_ => - new SharedFileCache(Configuration.Directories.Shared, 3600000)); + new SharedFileCache(Options.Directories.Shared, 3600000)); services.AddSingleton(); services.AddSingleton(); @@ -213,7 +213,7 @@ namespace slskd app.UseCors("AllowAll"); - if (Configuration.Web.Https.Force) + if (Options.Web.Https.Force) { app.UseHttpsRedirection(); app.UseHsts(); @@ -258,7 +258,7 @@ namespace slskd logger.Information("Serving static content from {ContentPath}", ContentPath); } - if (Configuration.Feature.Prometheus) + if (Options.Feature.Prometheus) { app.UseHttpMetrics(); logger.Information("Publishing Prometheus metrics to /metrics"); @@ -275,13 +275,13 @@ namespace slskd endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); - if (Configuration.Feature.Prometheus) + if (Options.Feature.Prometheus) { endpoints.MapMetrics(); } }); - if (Configuration.Feature.Swagger) + if (Options.Feature.Swagger) { app.UseSwagger(); app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList() -- cgit v1.2.3 From ecc8551fd1797a52b9d9e75e9326560d372c2711 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Jul 2021 08:36:41 -0500 Subject: docs --- src/slskd/Options.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 2ff0df97..7651d462 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -32,6 +32,39 @@ namespace slskd /// /// Application options. /// + /// + /// + /// This class contains all application options, which may be sourced from (in order of precedence): + /// + /// + /// Defaults + /// Default values, statically defined in this class. + /// + /// + /// Environment Variables + /// Environment variables set at either the system or user scope. + /// + /// + /// YAML Configuration File + /// A YAML file containing a mapping of this class. + /// + /// + /// Command Line + /// Options provided via the command line when starting the application. + /// + /// + /// Higher precedent sources override lower precedent sources. As the command line is the most immediate and final source, + /// options specified via the command line cannot be overwritten at runtime by any other source. + /// + /// + /// Only the YAML configuration source can change at runtime, and consumers of this class must be aware of this, either using + /// in components with a singleton lifetime, or for transient or scoped lifetimes. + /// + /// + /// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable + /// nature of the command line string after the application is started. + /// + /// public class Options { /// -- cgit v1.2.3 From 0973fb54ac4aa7555622b8d81f32b3f3e43f1279 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Jul 2021 08:36:50 -0500 Subject: fix binding bug --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index abd27268..2ce98454 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -193,7 +193,7 @@ namespace slskd .Build(); Configuration.GetSection(AppName) - .Bind(Configuration, (o) => { o.BindNonPublicProperties = true; }); + .Bind(Options, (o) => { o.BindNonPublicProperties = true; }); if (Options.Debug) { -- cgit v1.2.3 From 511860676eec56e3687397f11a04cc3db14fb4aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Jul 2021 18:12:39 -0500 Subject: add static Options to DI --- src/slskd/Startup.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index f5cd2d13..227e3de1 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -84,6 +84,11 @@ namespace slskd { var logger = Log.ForContext(); + // add an instance of Options to DI as they were at startup. use when Options might change, but + // the values at startup are to be used. + services.AddSingleton(Options); + + // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used. services.AddOptions() .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); -- cgit v1.2.3 From d1637bafbff1d9cbf64bb8702ed48513b7edfcc6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Jul 2021 18:14:02 -0500 Subject: use startup options --- src/slskd/Application/Management/API/Controllers/SessionController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 09a95c24..511643a6 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,10 +37,10 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, + Options optionsSnapshotAtStartup, SymmetricSecurityKey jwtSigningKey) { - Options = optionsSnapshot.Value; + Options = optionsSnapshotAtStartup; JwtSigningKey = jwtSigningKey; } -- cgit v1.2.3 From b8602ec4d701f24bdde8663f001d85505e173f60 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Jul 2021 18:21:20 -0500 Subject: first pass at marking RequiresRestart --- src/slskd/Options.cs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 7651d462..09ea668b 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -61,6 +61,9 @@ namespace slskd /// in components with a singleton lifetime, or for transient or scoped lifetimes. /// /// + /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject . + /// + /// /// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable /// nature of the command line string after the application is started. /// @@ -148,6 +151,7 @@ namespace slskd /// Gets directory options. /// [Validate] + [RequiresRestart] public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); /// @@ -160,12 +164,14 @@ namespace slskd /// Gets logger options. /// [Validate] + [RequiresRestart] public LoggerOptions Logger { get; private set; } = new LoggerOptions(); /// /// Gets feature options. /// [Validate] + [RequiresRestart] public FeatureOptions Feature { get; private set; } = new FeatureOptions(); /// @@ -192,6 +198,7 @@ namespace slskd [EnvironmentVariable("APP_DIR")] [Description("path where application data is saved")] [DirectoryExists] + [RequiresRestart] public string App { get; private set; } = Program.DefaultAppDirectory; /// @@ -201,6 +208,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [DirectoryExists] + [RequiresRestart] public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; /// @@ -210,6 +218,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [DirectoryExists] + [RequiresRestart] public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; /// @@ -219,6 +228,7 @@ namespace slskd [EnvironmentVariable("SHARED_DIR")] [Description("path to shared files")] [DirectoryExists] + [RequiresRestart] public string Shared { get; private set; } = Program.DefaultSharedDirectory; } @@ -233,6 +243,7 @@ namespace slskd [Argument(default, "prometheus")] [EnvironmentVariable("PROMETHEUS")] [Description("enable collection and publishing of prometheus metrics")] + [RequiresRestart] public bool Prometheus { get; private set; } = false; /// @@ -241,6 +252,7 @@ namespace slskd [Argument(default, "swagger")] [EnvironmentVariable("SWAGGER")] [Description("enable swagger documentation and UI")] + [RequiresRestart] public bool Swagger { get; private set; } = false; } @@ -255,6 +267,7 @@ namespace slskd [Argument(default, "loki")] [EnvironmentVariable("LOKI")] [Description("optional; url to a Grafana Loki instance to which to log")] + [RequiresRestart] public string Loki { get; private set; } = null; } @@ -458,12 +471,14 @@ namespace slskd [EnvironmentVariable("HTTP_PORT")] [Description("HTTP listen port for web UI")] [Range(1, 65535)] + [RequiresRestart] public int Port { get; private set; } = 5000; /// /// Gets HTTPS options. /// [Validate] + [RequiresRestart] public HttpsOptions Https { get; private set; } = new HttpsOptions(); /// @@ -472,6 +487,7 @@ namespace slskd [Argument(default, "url-base")] [EnvironmentVariable("URL_BASE")] [Description("base url for web requests")] + [RequiresRestart] public string UrlBase { get; private set; } = "/"; /// @@ -481,6 +497,7 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] + [RequiresRestart] public string ContentPath { get; private set; } = "wwwroot"; /// @@ -500,6 +517,7 @@ namespace slskd [Argument('x', "no-auth")] [EnvironmentVariable("NO_AUTH")] [Description("disable authentication for web requests")] + [RequiresRestart] public bool Disable { get; private set; } = false; /// @@ -524,6 +542,7 @@ namespace slskd /// Gets JWT options. /// [Validate] + [RequiresRestart] public JwtOptions Jwt { get; private set; } = new JwtOptions(); /// @@ -538,6 +557,7 @@ namespace slskd [EnvironmentVariable("JWT_KEY")] [Description("JWT signing key")] [StringLength(255, MinimumLength = 1)] + [RequiresRestart] public string Key { get; private set; } = Guid.NewGuid().ToString(); /// @@ -547,6 +567,7 @@ namespace slskd [EnvironmentVariable("JWT_TTL")] [Description("TTL for JWTs")] [Range(3600, int.MaxValue)] + [RequiresRestart] public int Ttl { get; private set; } = 604800000; } } @@ -563,6 +584,7 @@ namespace slskd [EnvironmentVariable("HTTPS_PORT")] [Description("HTTPS listen port for web UI")] [Range(1, 65535)] + [RequiresRestart] public int Port { get; private set; } = 5001; /// @@ -571,12 +593,14 @@ namespace slskd [Argument('f', "force-https")] [EnvironmentVariable("HTTPS_FORCE")] [Description("redirect HTTP to HTTPS")] + [RequiresRestart] public bool Force { get; private set; } = false; /// /// Gets certificate options. /// [Validate] + [RequiresRestart] public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); /// @@ -592,6 +616,7 @@ namespace slskd [EnvironmentVariable("HTTPS_CERT_PFX")] [Description("path to X509 certificate .pfx")] [FileExists] + [RequiresRestart] public string Pfx { get; private set; } /// @@ -600,6 +625,7 @@ namespace slskd [Argument(default, "https-cert-password")] [EnvironmentVariable("HTTPS_CERT_PASSWORD")] [Description("X509 certificate password")] + [RequiresRestart] public string Password { get; private set; } } } -- cgit v1.2.3 From b9d8a4809620ebab2896e03b55115560f484d1e5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 14 Jul 2021 08:04:56 -0500 Subject: tweak docs --- src/slskd/Options.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 09ea668b..ca979dc9 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -53,11 +53,9 @@ namespace slskd /// Options provided via the command line when starting the application. /// /// - /// Higher precedent sources override lower precedent sources. As the command line is the most immediate and final source, - /// options specified via the command line cannot be overwritten at runtime by any other source. /// /// - /// Only the YAML configuration source can change at runtime, and consumers of this class must be aware of this, either using + /// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting /// in components with a singleton lifetime, or for transient or scoped lifetimes. /// /// -- cgit v1.2.3 From c10a01c6d58ca71ec629d08998bea47698a1d3c2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 14 Jul 2021 08:33:45 -0500 Subject: add endpoint to retrieve startup options --- .../API/Controllers/OptionsController.cs | 28 ++++++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index b75adc97..7bc93724 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Management.API { using Microsoft.AspNetCore.Authorization; @@ -30,13 +32,16 @@ namespace slskd.Management.API [Consumes("application/json")] public class OptionsController : ControllerBase { - public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public OptionsController( + Options optionsSnapshotAtStartup, + IOptionsMonitor optionsMonitor) { + OptionsSnapshotAtStartup = optionsSnapshotAtStartup; OptionsMonitor = optionsMonitor; } - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } - private Options Options => OptionsMonitor.CurrentValue; + private IOptionsMonitor OptionsMonitor { get; } + private Options OptionsSnapshotAtStartup { get; } /// /// Gets the current application options. @@ -45,9 +50,22 @@ namespace slskd.Management.API [HttpGet] [Authorize] [ProducesResponseType(typeof(Options), 200)] - public IActionResult Get() + public IActionResult Current() + { + return Ok(OptionsMonitor.CurrentValue); + } + + /// + /// Gets the application options provided at startup. + /// + /// + [HttpGet] + [Route("startup")] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Startup() { - return Ok(Options); + return Ok(OptionsSnapshotAtStartup); } } } -- cgit v1.2.3 From 3f5ebfde9be34a80a28dc8c08efaa4c9417184dc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 14 Jul 2021 08:39:15 -0500 Subject: simplify using for microsoft Options --- src/slskd/Application/Management/ManagementService.cs | 6 ++++-- .../Application/Transfer/API/Controllers/TransfersController.cs | 4 +++- src/slskd/Integrations/FTP/FTPClientFactory.cs | 4 +++- src/slskd/Integrations/FTP/FTPService.cs | 4 +++- src/slskd/Integrations/Pushbullet/PushbulletService.cs | 4 +++- src/slskd/Properties/analysis.ruleset | 1 + 6 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 4a385cff..7bcdc7be 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/. // +using Microsoft.Extensions.Options; + namespace slskd.Management { using System; @@ -32,7 +34,7 @@ namespace slskd.Management /// The options monitor used to derive application options. /// The Soulseek client. public ManagementService( - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient) { OptionsMonitor = optionsMonitor; @@ -41,7 +43,7 @@ namespace slskd.Management private ISoulseekClient Client { get; } private Options Options => OptionsMonitor.CurrentValue; - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private IOptionsMonitor OptionsMonitor { get; } /// /// Connects the Soulseek client to the server using the configured username and password. 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/. // +using Microsoft.Extensions.Options; + namespace slskd.Transfer.API { using System; @@ -46,7 +48,7 @@ namespace slskd.Transfer.API /// /// public TransfersController( - Microsoft.Extensions.Options.IOptionsSnapshot options, + IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker, IFTPService ftpClient) diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index cc076ca1..7c55195f 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Integrations.FTP { using System; @@ -30,7 +32,7 @@ namespace slskd.Integrations.FTP /// Initializes a new instance of the class. /// /// The options monitor used to derive application options. - public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public FTPClientFactory(IOptionsMonitor optionsMonitor) { Options = optionsMonitor.CurrentValue; diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index a5fe6a8f..4b3f45ce 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Integrations.FTP { using System; @@ -38,7 +40,7 @@ namespace slskd.Integrations.FTP /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + IOptionsMonitor optionsMonitor, ILogger log) { Factory = ftpClientFactory; diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index cb31e6dc..04994d92 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Integrations.Pushbullet { using System; @@ -41,7 +43,7 @@ namespace slskd.Integrations.Pushbullet /// The logger. public PushbulletService( IHttpClientFactory httpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + IOptionsMonitor optionsMonitor, ILogger log) { HttpClientFactory = httpClientFactory; diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset index 09e99d9e..4e4ae5cf 100644 --- a/src/slskd/Properties/analysis.ruleset +++ b/src/slskd/Properties/analysis.ruleset @@ -45,6 +45,7 @@ + -- cgit v1.2.3 From 6376d1ed6f4bbae46e1dc4aecec36bfe5de044e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 15 Jul 2021 08:26:37 -0500 Subject: update PushbulletService for options changes, implement IDisposable --- .../Integrations/Pushbullet/IPushbulletService.cs | 3 +- .../Integrations/Pushbullet/PushbulletService.cs | 36 +++++++++++++++++++--- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/slskd/Integrations/Pushbullet/IPushbulletService.cs b/src/slskd/Integrations/Pushbullet/IPushbulletService.cs index 6da42326..bad33903 100644 --- a/src/slskd/Integrations/Pushbullet/IPushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/IPushbulletService.cs @@ -17,12 +17,13 @@ namespace slskd.Integrations.Pushbullet { + using System; using System.Threading.Tasks; /// /// Pushbullet integration service. /// - public interface IPushbulletService + public interface IPushbulletService : IDisposable { /// /// Sends a push notification to Pushbullet. diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index 04994d92..1a224321 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -47,18 +47,28 @@ namespace slskd.Integrations.Pushbullet ILogger log) { HttpClientFactory = httpClientFactory; - Options = optionsMonitor.CurrentValue; + OptionsMonitor = optionsMonitor; Log = log; RecentlySent = new MemoryCache(new MemoryCacheOptions()); } + private bool Disposed { get; set; } private IHttpClientFactory HttpClientFactory { get; } - private Options Options { get; } private ILogger Log { get; } - private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet; + private IOptionsMonitor OptionsMonitor { get; } + private PushbulletOptions PushbulletOptions => OptionsMonitor.CurrentValue.Integration.Pushbullet; private IMemoryCache RecentlySent { get; } + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + /// /// Sends a push notification to Pushbullet. /// @@ -68,6 +78,11 @@ namespace slskd.Integrations.Pushbullet /// The operation context. public Task PushAsync(string title, string cacheKey, string body) { + if (!PushbulletOptions.Enabled) + { + return Task.CompletedTask; + } + if (string.IsNullOrWhiteSpace(title)) { throw new ArgumentException("A notification title must be supplied", nameof(title)); @@ -93,6 +108,19 @@ namespace slskd.Integrations.Pushbullet return PushInternalAsync(title, body); } + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + RecentlySent.Dispose(); + } + + Disposed = true; + } + } + private async Task PushInternalAsync(string title, string body) { try @@ -135,4 +163,4 @@ namespace slskd.Integrations.Pushbullet } } } -} +} \ No newline at end of file -- cgit v1.2.3 From 4c52f877c197ef287f1afd36b25ade1bf65f0edb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 15 Jul 2021 09:28:49 -0500 Subject: use OptionsSnapshot for FTPService --- src/slskd/Integrations/FTP/FTPClientFactory.cs | 10 +++++----- src/slskd/Integrations/FTP/FTPService.cs | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index 7c55195f..b0c136a0 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -31,10 +31,10 @@ namespace slskd.Integrations.FTP /// /// Initializes a new instance of the class. /// - /// The options monitor used to derive application options. - public FTPClientFactory(IOptionsMonitor optionsMonitor) + /// The options monitor used to derive application options. + public FTPClientFactory(IOptionsSnapshot optionsSnapshot) { - Options = optionsMonitor.CurrentValue; + OptionsSnapshot = optionsSnapshot; try { @@ -49,8 +49,8 @@ namespace slskd.Integrations.FTP } private FtpEncryptionMode EncryptionMode { get; set; } - private FTPOptions FTPOptions => Options.Integration.FTP; - private Options Options { get; set; } + private FTPOptions FTPOptions => OptionsSnapshot.Value.Integration.FTP; + private IOptionsSnapshot OptionsSnapshot { get; set; } /// /// Creates an instance of . diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index 4b3f45ce..fdd04d56 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -36,22 +36,22 @@ namespace slskd.Integrations.FTP /// Initializes a new instance of the class. /// /// The FTP client factory to use. - /// The options monitor used to derive application options. + /// The options snapshot used to derive application options. /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, - IOptionsMonitor optionsMonitor, + IOptionsSnapshot optionsSnapshot, ILogger log) { Factory = ftpClientFactory; - Options = optionsMonitor.CurrentValue; + OptionsSnapshot = optionsSnapshot; Log = log; } private IFTPClientFactory Factory { get; set; } - private FTPOptions FTPOptions => Options.Integration.FTP; + private FTPOptions FTPOptions => OptionsSnapshot.Value.Integration.FTP; private ILogger Log { get; set; } - private Options Options { get; } + private IOptionsSnapshot OptionsSnapshot { get; } /// /// Uploads the specified to the configured FTP server. -- cgit v1.2.3 From 104200c46fe8ee66cc48cf61aead4dad2813e8b3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 15 Jul 2021 09:29:19 -0500 Subject: validate options on re-configure. use scoped lifetime for FTP --- src/slskd/Startup.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 227e3de1..76041643 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -42,6 +42,7 @@ namespace slskd using slskd.Peer; using slskd.Search; using slskd.Transfer; + using slskd.Validation; /// /// ASP.NET Startup. @@ -90,7 +91,19 @@ namespace slskd // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used. services.AddOptions() - .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); + .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }) + .Validate(options => + { + if (!options.TryValidate(out var result)) + { + logger.Warning("Options (re)configuration rejected."); + logger.Warning(result.GetResultView()); + return false; + } + + logger.Information("Options (re)configured successfully."); + return true; + }); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); @@ -196,8 +209,8 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); - services.AddTransient(); + services.AddScoped(); + services.AddScoped(); services.AddSingleton(); -- cgit v1.2.3 From 975c74f41a9af878220e962bb4216598186cdf52 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 16 Jul 2021 08:06:36 -0500 Subject: add OptionsAtStartup --- src/slskd/Options.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index ca979dc9..f93e5d4a 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd { using System; @@ -29,6 +31,18 @@ namespace slskd using Utility.CommandLine; using Utility.EnvironmentVariables; + /// + /// Disambiguates options derived at startup from options that may update at run time. + /// + /// + /// This class is added directly to dependency injection, but is not, so consumers must inject + /// instead of to make it clear that these options will not change. Options that may change should be accessed by injecting + /// or , depending on the lifetime of the component. + /// + public class OptionsAtStartup : Options + { + } + /// /// Application options. /// @@ -56,10 +70,10 @@ namespace slskd /// /// /// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting - /// in components with a singleton lifetime, or for transient or scoped lifetimes. + /// in components with a singleton lifetime, or for transient or scoped lifetimes. /// /// - /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject . + /// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject . /// /// /// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable -- cgit v1.2.3 From 0bbd9e843b3558b631c8a313913dd562eda00572 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 16 Jul 2021 08:10:18 -0500 Subject: use OptionsAtStartup in startup code --- src/slskd/Program.cs | 52 ++++++++++++++++++++++++++-------------------------- src/slskd/Startup.cs | 40 ++++++++++++++++++++-------------------- 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 2ce98454..d22ab433 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -120,7 +120,7 @@ namespace slskd public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; private static IConfigurationRoot Configuration { get; set; } - private static Options Options { get; } = new Options(); + private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); [EnvironmentVariable("CONFIG")] [Argument('c', "config", "path to configuration file")] @@ -193,14 +193,14 @@ namespace slskd .Build(); Configuration.GetSection(AppName) - .Bind(Options, (o) => { o.BindNonPublicProperties = true; }); + .Bind(OptionsAtStartup, (o) => { o.BindNonPublicProperties = true; }); - if (Options.Debug) + if (OptionsAtStartup.Debug) { Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}"); } - if (!Options.TryValidate(out var result)) + if (!OptionsAtStartup.TryValidate(out var result)) { Console.WriteLine(result.GetResultView()); return; @@ -208,16 +208,16 @@ namespace slskd } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {(!Options.Debug ? ex : ex.Message)}"); + Console.WriteLine($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); return; } try { - VerifyOrCreateDirectory(Options.Directories.App); - VerifyOrCreateDirectory(Options.Directories.Incomplete); - VerifyOrCreateDirectory(Options.Directories.Downloads); - VerifyOrCreateDirectory(Options.Directories.Shared, verifyWriteable: false); + VerifyOrCreateDirectory(OptionsAtStartup.Directories.App); + VerifyOrCreateDirectory(OptionsAtStartup.Directories.Incomplete); + VerifyOrCreateDirectory(OptionsAtStartup.Directories.Downloads); + VerifyOrCreateDirectory(OptionsAtStartup.Directories.Shared, verifyWriteable: false); } catch (Exception ex) { @@ -225,31 +225,31 @@ namespace slskd return; } - Log.Logger = (Options.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", Options.InstanceName) + .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( - outputTemplate: (Options.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (Options.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => !string.IsNullOrEmpty(Options.Logger.Loki), + e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), config => config.GrafanaLoki( - Options.Logger.Loki ?? string.Empty, + OptionsAtStartup.Logger.Loki ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); var logger = Log.ForContext(typeof(Program)); - if (!Options.NoLogo) + if (!OptionsAtStartup.NoLogo) { PrintLogo(Version); } @@ -260,18 +260,18 @@ namespace slskd } logger.Information("Version: {Version}", Version); - logger.Information("Instance Name: {InstanceName}", Options.InstanceName); + logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); - if (!string.IsNullOrEmpty(Options.Logger.Loki)) + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Options.Logger.Loki); + logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); } try { - if (Options.Feature.Prometheus) + if (OptionsAtStartup.Feature.Prometheus) { using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } @@ -287,13 +287,13 @@ namespace slskd .UseUrls() .UseKestrel(options => { - logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Options.Web.Port}/"); - options.Listen(IPAddress.Any, Options.Web.Port); + logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); + options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Options.Web.Https.Port}/"); - options.Listen(IPAddress.Any, Options.Web.Https.Port, listenOptions => + logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); + options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => { - var cert = Options.Web.Https.Certificate; + var cert = OptionsAtStartup.Web.Https.Certificate; if (!string.IsNullOrEmpty(cert.Pfx)) { @@ -310,7 +310,7 @@ namespace slskd .UseStartup() .Build(); - if (Options.NoStart) + if (OptionsAtStartup.NoStart) { logger.Information("Qutting because 'no-start' option is enabled"); return; diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 76041643..33e82736 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -57,24 +57,24 @@ namespace slskd { Configuration = configuration; - Options = new Options(); - Configuration.GetSection(Program.AppName).Bind(Options, (o) => + OptionsAtStartup = new OptionsAtStartup(); + Configuration.GetSection(Program.AppName).Bind(OptionsAtStartup, (o) => { o.BindNonPublicProperties = true; }); - UrlBase = Options.Web.UrlBase; + UrlBase = OptionsAtStartup.Web.UrlBase; UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - ContentPath = Path.GetFullPath(Options.Web.ContentPath); + ContentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); - JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Options.Web.Authentication.Jwt.Key)); + JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(OptionsAtStartup.Web.Authentication.Jwt.Key)); } private IConfiguration Configuration { get; } private string ContentPath { get; set; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; } + private OptionsAtStartup OptionsAtStartup { get; } private string UrlBase { get; set; } /// @@ -85,9 +85,9 @@ namespace slskd { var logger = Log.ForContext(); - // add an instance of Options to DI as they were at startup. use when Options might change, but + // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but // the values at startup are to be used. - services.AddSingleton(Options); + services.AddSingleton(OptionsAtStartup); // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used. services.AddOptions() @@ -109,7 +109,7 @@ namespace slskd services.AddSingleton(JwtSigningKey); - if (!Options.Web.Authentication.Disable) + if (!OptionsAtStartup.Web.Authentication.Disable) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => @@ -157,7 +157,7 @@ namespace slskd options.SubstituteApiVersionInUrl = true; }); - if (Options.Feature.Swagger) + if (OptionsAtStartup.Feature.Swagger) { services.AddSwaggerGen(options => { @@ -181,19 +181,19 @@ namespace slskd }); } - if (Options.Feature.Prometheus) + if (OptionsAtStartup.Feature.Prometheus) { services.AddSystemMetrics(); } services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "search.db")}"); }); services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "peer.db")}"); + options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "peer.db")}"); }); services.AddHttpClient(); @@ -203,14 +203,14 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(_ => - new SharedFileCache(Options.Directories.Shared, 3600000)); + new SharedFileCache(OptionsAtStartup.Directories.Shared, 3600000)); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddScoped(); - services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); @@ -231,7 +231,7 @@ namespace slskd app.UseCors("AllowAll"); - if (Options.Web.Https.Force) + if (OptionsAtStartup.Web.Https.Force) { app.UseHttpsRedirection(); app.UseHsts(); @@ -276,7 +276,7 @@ namespace slskd logger.Information("Serving static content from {ContentPath}", ContentPath); } - if (Options.Feature.Prometheus) + if (OptionsAtStartup.Feature.Prometheus) { app.UseHttpMetrics(); logger.Information("Publishing Prometheus metrics to /metrics"); @@ -293,13 +293,13 @@ namespace slskd endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); - if (Options.Feature.Prometheus) + if (OptionsAtStartup.Feature.Prometheus) { endpoints.MapMetrics(); } }); - if (Options.Feature.Swagger) + if (OptionsAtStartup.Feature.Swagger) { app.UseSwagger(); app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList() -- cgit v1.2.3 From 2c772284155b99cbe16707e8f990466a868c3af6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 16 Jul 2021 08:10:31 -0500 Subject: inject OptionsAtStartup --- .../Management/API/Controllers/OptionsController.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index 7bc93724..6f6275d1 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -33,15 +33,15 @@ namespace slskd.Management.API public class OptionsController : ControllerBase { public OptionsController( - Options optionsSnapshotAtStartup, - IOptionsMonitor optionsMonitor) + OptionsAtStartup optionsAtStartup, + IOptionsSnapshot optionsSnapshot) { - OptionsSnapshotAtStartup = optionsSnapshotAtStartup; - OptionsMonitor = optionsMonitor; + OptionsAtStartup = optionsAtStartup; + OptionsSnapshot = optionsSnapshot; } - private IOptionsMonitor OptionsMonitor { get; } - private Options OptionsSnapshotAtStartup { get; } + private IOptionsSnapshot OptionsSnapshot { get; } + private OptionsAtStartup OptionsAtStartup { get; } /// /// Gets the current application options. @@ -52,7 +52,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(Options), 200)] public IActionResult Current() { - return Ok(OptionsMonitor.CurrentValue); + return Ok(OptionsSnapshot.Value); } /// @@ -65,7 +65,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(Options), 200)] public IActionResult Startup() { - return Ok(OptionsSnapshotAtStartup); + return Ok(OptionsAtStartup); } } } -- cgit v1.2.3 From 9f1443ff4869a2685e855e5b09090c2b375dea5b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 16 Jul 2021 08:12:05 -0500 Subject: make FTP services singletons again --- src/slskd/Integrations/FTP/FTPClientFactory.cs | 38 ++++++++++++++------------ src/slskd/Integrations/FTP/FTPService.cs | 10 +++---- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index b0c136a0..e9ee0721 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -31,26 +31,14 @@ namespace slskd.Integrations.FTP /// /// Initializes a new instance of the class. /// - /// The options monitor used to derive application options. - public FTPClientFactory(IOptionsSnapshot optionsSnapshot) + /// The options monitor used to derive application options. + public FTPClientFactory(IOptionsMonitor optionsMonitor) { - OptionsSnapshot = optionsSnapshot; - - try - { - EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); - } - catch (Exception ex) - { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this - // throws there's a bug somewhere. - throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); - } + OptionsMonitor = optionsMonitor; } - private FtpEncryptionMode EncryptionMode { get; set; } - private FTPOptions FTPOptions => OptionsSnapshot.Value.Integration.FTP; - private IOptionsSnapshot OptionsSnapshot { get; set; } + private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP; + private IOptionsMonitor OptionsMonitor { get; set; } /// /// Creates an instance of . @@ -59,10 +47,24 @@ namespace slskd.Integrations.FTP public FtpClient CreateFtpClient() { var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); - client.EncryptionMode = EncryptionMode; + client.EncryptionMode = ParseFtpEncryptionMode(FTPOptions.EncryptionMode); client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; return client; } + + private FtpEncryptionMode ParseFtpEncryptionMode(string encryptionMode) + { + try + { + return (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), encryptionMode, ignoreCase: true); + } + catch (Exception ex) + { + // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this + // throws there's a bug somewhere. + throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); + } + } } } \ No newline at end of file diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index fdd04d56..becf1a12 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -36,22 +36,22 @@ namespace slskd.Integrations.FTP /// Initializes a new instance of the class. /// /// The FTP client factory to use. - /// The options snapshot used to derive application options. + /// The options monitor used to derive application options. /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, - IOptionsSnapshot optionsSnapshot, + IOptionsMonitor optionsMonitor, ILogger log) { Factory = ftpClientFactory; - OptionsSnapshot = optionsSnapshot; + OptionsMonitor = optionsMonitor; Log = log; } private IFTPClientFactory Factory { get; set; } - private FTPOptions FTPOptions => OptionsSnapshot.Value.Integration.FTP; + private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP; private ILogger Log { get; set; } - private IOptionsSnapshot OptionsSnapshot { get; } + private IOptionsMonitor OptionsMonitor { get; } /// /// Uploads the specified to the configured FTP server. -- cgit v1.2.3 From a5e40e0f29ae26de8c172fe9d29afae11832e7be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 16 Jul 2021 08:52:28 -0500 Subject: log a note about updated options --- src/slskd/Application/Service.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index d9b682fc..03a287ca 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -175,13 +175,7 @@ namespace slskd private void OptionsChanged(Options options) { - 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 + Logger.Information("Options changed, but changes to the Soulseek configuration have not been propagated. This functionality will come in a later update."); } private void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e) -- cgit v1.2.3 From 2092189312e158cf01fc972b407624828d1bcd80 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Jul 2021 23:10:48 -0500 Subject: add DiffWith --- src/slskd/Common/Extensions.cs | 46 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index a7a89a71..eab5b02a 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -19,18 +19,56 @@ namespace slskd { using System; using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; - using System.Security.Cryptography; - using System.Text; - using slskd.Validation; + using System.Reflection; /// /// Extensions. /// public static class Extensions { + /// + /// Deeply compares this object with the specified object and returns a list of properties that are different. + /// + /// The left side of the comparison. + /// The right side of the comparison. + /// The root path for recursive calls. + /// A list of differences between the two objects. + public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) + { + if (left.GetType() != right.GetType()) + { + throw new InvalidCastException($"Unable to diff types {left.GetType()} and {right.GetType()}"); + } + + var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); + + foreach (var prop in left.GetType().GetProperties()) + { + var leftVal = prop.GetValue(left); + var rightVal = prop.GetValue(right); + var propType = prop.PropertyType; + var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); + + var quasiPrimitives = new[] { typeof(string), typeof(decimal) }; + + if (propType.IsPrimitive || quasiPrimitives.Contains(propType)) + { + if (!leftVal.Equals(rightVal)) + { + differences.Add((prop, fqn, leftVal, rightVal)); + } + } + else + { + differences.AddRange(DiffWith(leftVal, rightVal, fqn)); + } + } + + return differences; + } + /// /// Returns the directory from the given path, regardless of separator format. /// -- cgit v1.2.3 From aa496feb60f34e7fab5d16314b2852dd640e998a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jul 2021 17:41:45 -0500 Subject: make DiffWith nullable friendly --- src/slskd/Common/Extensions.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index eab5b02a..3b52c650 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -37,25 +37,23 @@ namespace slskd /// A list of differences between the two objects. public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) { - if (left.GetType() != right.GetType()) + if (left?.GetType() != right?.GetType()) { - throw new InvalidCastException($"Unable to diff types {left.GetType()} and {right.GetType()}"); + throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}"); } var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); - foreach (var prop in left.GetType().GetProperties()) + foreach (var prop in left?.GetType().GetProperties()) { var leftVal = prop.GetValue(left); var rightVal = prop.GetValue(right); var propType = prop.PropertyType; var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); - var quasiPrimitives = new[] { typeof(string), typeof(decimal) }; - - if (propType.IsPrimitive || quasiPrimitives.Contains(propType)) + if (propType.IsPrimitive || Nullable.GetUnderlyingType(propType) != null || new[] { typeof(string), typeof(decimal) }.Contains(propType)) { - if (!leftVal.Equals(rightVal)) + if (!Equals(leftVal, rightVal)) { differences.Add((prop, fqn, leftVal, rightVal)); } -- cgit v1.2.3 From ae0c7e3d0e52e0e301f864bb4f66cffe4f762288 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jul 2021 17:42:15 -0500 Subject: add Enabled and validator for ProxyOptions --- src/slskd/Options.cs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index f93e5d4a..b2476364 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -407,8 +407,16 @@ namespace slskd /// /// Connection proxy options. /// - public class ProxyOptions + public class ProxyOptions : IValidatableObject { + /// + /// Gets a value indicating whether the proxy is enabled. + /// + [Argument(default, "slsk-proxy")] + [EnvironmentVariable("SLSK_PROXY_ENABLED")] + [Description("enable connection proxy")] + public bool Enabled { get; private set; } = false; + /// /// Gets the proxy address. /// @@ -444,6 +452,23 @@ namespace slskd [Description("connection proxy password")] [StringLength(255, MinimumLength = 1)] public string Password { get; private set; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + if (Enabled && !Port.HasValue) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Port has been specified.")); + } + + return results; + } } } -- cgit v1.2.3 From 46485c8be4cd214018bbc09cfad135423687f13b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jul 2021 20:44:22 -0500 Subject: stub handling of options updates --- src/slskd/Application/Service.cs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 03a287ca..77657342 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -22,13 +22,13 @@ namespace slskd using System.IO; using System.Linq; using System.Net; - using System.Text.Json; 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; @@ -132,6 +132,8 @@ namespace slskd } public static ISoulseekClient SoulseekClient { get; private set; } + public static bool PendingRestart { get; private set; } + private IBrowseTracker BrowseTracker { get; set; } private ISoulseekClient Client { get; set; } private IConversationTracker ConversationTracker { get; set; } @@ -142,7 +144,7 @@ namespace slskd private IRoomTracker RoomTracker { 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 bool UsingProxy => Options.Soulseek.Connection.Proxy.Enabled; private IPushbulletService Pushbullet { get; } public async Task StartAsync(CancellationToken cancellationToken) @@ -175,6 +177,23 @@ namespace slskd private void OptionsChanged(Options options) { + var diff = Options.DiffWith(options); + + if (Options.Debug) + { + foreach (var d in diff) + { + Console.WriteLine($"{d.FQN} changed from {d.Left ?? ""} to {d.Right ?? ""}"); + } + } + + if (diff.Select(d => d.Property).Any(d => d.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)))) + { + Console.WriteLine("One or more updated options requires a restart to take effect."); + PendingRestart = true; + } + + Options = options; Logger.Information("Options changed, but changes to the Soulseek configuration have not been propagated. This functionality will come in a later update."); } -- cgit v1.2.3 From 7367955adae20a15b6b664a232700030cb4e713b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jul 2021 09:50:06 -0500 Subject: tweak reconfiguration logging --- src/slskd/Startup.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 33e82736..65604197 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -92,6 +92,7 @@ namespace slskd // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used. services.AddOptions() .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }) + .PostConfigure(_ => logger.Debug("Options (re)configured.")) .Validate(options => { if (!options.TryValidate(out var result)) @@ -101,7 +102,7 @@ namespace slskd return false; } - logger.Information("Options (re)configured successfully."); + logger.Debug("Options validated successfully."); return true; }); -- cgit v1.2.3 From 72e60e948d8dc5a40ac6a937f7fa38642fefc55f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jul 2021 09:50:27 -0500 Subject: syncronize options update and document double-firing --- src/slskd/Application/Service.cs | 43 ++++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 77657342..9cb7b3fb 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -22,6 +22,7 @@ namespace slskd using System.IO; using System.Linq; using System.Net; + using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; @@ -146,6 +147,7 @@ namespace slskd private ITransferTracker TransferTracker { get; set; } private bool UsingProxy => Options.Soulseek.Connection.Proxy.Enabled; private IPushbulletService Pushbullet { get; } + private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); public async Task StartAsync(CancellationToken cancellationToken) { @@ -177,24 +179,45 @@ namespace slskd private void OptionsChanged(Options options) { - var diff = Options.DiffWith(options); + // 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(); - if (Options.Debug) + try { + var diff = Options.DiffWith(options); + + // don't react to duplicate/no-change events + // https://github.com/slskd/slskd/issues/126 + if (!diff.Any()) + { + return; + } + + bool RequiresRestart(PropertyInfo prop) => prop.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)); + foreach (var d in diff) { - Console.WriteLine($"{d.FQN} changed from {d.Left ?? ""} to {d.Right ?? ""}"); + Logger.Debug($"{d.FQN} changed from '{d.Left ?? ""}' to '{d.Right ?? ""}'{(RequiresRestart(d.Property) ? "; Requires restart." : string.Empty)}"); } - } - if (diff.Select(d => d.Property).Any(d => d.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)))) + var changesRequiringRestart = diff.Where(d => d.Property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute))); + + if (changesRequiringRestart.Any()) + { + Logger.Information("One or more updated options requires a restart to take effect."); + PendingRestart = true; + } + + Options = options; + Logger.Information("Options changed, but changes to the Soulseek configuration have not been propagated. This functionality will come in a later update."); + } + finally { - Console.WriteLine("One or more updated options requires a restart to take effect."); - PendingRestart = true; + OptionsSyncRoot.ExitWriteLock(); } - - Options = options; - Logger.Information("Options changed, but changes to the Soulseek configuration have not been propagated. This functionality will come in a later update."); } private void SharedFileCache_Refreshed(object sender, (int Directories, int Files) e) -- cgit v1.2.3 From 1a4722442bf12770cfbb84e673c055f0c25e79e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 20 Jul 2021 07:41:54 -0500 Subject: remove noisy option logging --- src/slskd/Startup.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 65604197..7843bf5d 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -92,7 +92,6 @@ namespace slskd // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used. services.AddOptions() .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }) - .PostConfigure(_ => logger.Debug("Options (re)configured.")) .Validate(options => { if (!options.TryValidate(out var result)) @@ -102,7 +101,6 @@ namespace slskd return false; } - logger.Debug("Options validated successfully."); return true; }); -- cgit v1.2.3 From 921243f9df8020e09c895996f6fed30ec8a1ac29 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 20 Jul 2021 07:42:09 -0500 Subject: docs --- src/slskd/Options.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index b2476364..966c1e21 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -453,6 +453,11 @@ namespace slskd [StringLength(255, MinimumLength = 1)] public string Password { get; private set; } + /// + /// Extended validation. + /// + /// + /// public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); @@ -782,6 +787,11 @@ namespace slskd [Range(0, 5)] public int RetryAttempts { get; private set; } = 3; + /// + /// Extended validation. + /// + /// + /// public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); @@ -858,6 +868,11 @@ namespace slskd [Description("cooldown time for Pushbullet notifications, in milliseconds")] public int CooldownTime { get; private set; } = 900000; // 15 minutes + /// + /// Extended validation. + /// + /// + /// public IEnumerable Validate(ValidationContext validationContext) { var results = new List(); -- cgit v1.2.3 From f090a7760e13f6325bade11b3b996128f690584e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jul 2021 21:21:29 -0500 Subject: add State --- src/slskd/State.cs | 133 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 src/slskd/State.cs diff --git a/src/slskd/State.cs b/src/slskd/State.cs new file mode 100644 index 00000000..735b4706 --- /dev/null +++ b/src/slskd/State.cs @@ -0,0 +1,133 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Text.Json; + using Microsoft.Extensions.Logging; + + /// + /// Application state. + /// + public record State(bool PendingReconnect = false, bool PendingRestart = false); + + /// + /// Used for notifications when changes. + /// + public interface IStateMonitor + { + /// + /// Gets the current application state. + /// + State Current { get; } + + /// + /// Registers a listener to be called whenever changes. + /// + /// Registers a listener to be called whenver state changes. + /// An which should be disposed to stop listening for changes. + IDisposable OnChange(Action<(State Previous, State Current)> listener); + + /// + /// Replaces the current state with the value resolved by the . + /// + /// Given the current state, resolves a new state value. + void Set(Func setter); + } + + /// + /// Used for notifications when changes. + /// + public class StateMonitor : IStateMonitor + { + public StateMonitor( + ILogger log) + { + Log = log; + } + + private event Action<(State, State)> Changed; + + /// + /// Gets the current application state. + /// + public State Current { get; private set; } = new State(); + + private ILogger Log { get; } + + /// + /// Registers a listener to be called whenever changes. + /// + /// Registers a listener to be called whenver state changes. + /// An which should be disposed to stop listening for changes. + public IDisposable OnChange(Action<(State Previous, State Current)> listener) + { + var disposable = new StateTrackerDisposable(this, listener); + Changed += disposable.OnChange; + return disposable; + } + + /// + /// Replaces the current state with the value resolved by the . + /// + /// Given the current state, resolves a new state value. + public void Set(Func setter) + { + var previous = JsonSerializer.Deserialize(JsonSerializer.Serialize(Current)); + Current = setter(Current); + + Changed?.Invoke((previous, Current)); + + Log.LogDebug("State changed from {Previous} to {Current}", JsonSerializer.Serialize(previous), JsonSerializer.Serialize(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; + } + } + } + } +} \ No newline at end of file -- cgit v1.2.3 From 48470d5e41647ad0182d02df91ebee6e2936fab2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jul 2021 21:21:51 -0500 Subject: add StateMonitor to DI --- src/slskd/Startup.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 7843bf5d..af0fd329 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -104,6 +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(); + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddSingleton(JwtSigningKey); -- cgit v1.2.3 From 0971ea1cf147b77a5c6544f02021325aa0b44bc2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jul 2021 21:22:07 -0500 Subject: mark DiagnosticLevel as RequiresRestart --- src/slskd/Options.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 966c1e21..221ec6c0 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -319,6 +319,7 @@ namespace slskd [Argument(default, "slsk-diag-level")] [EnvironmentVariable("SLSK_DIAG_LEVEL")] [Description("minimum diagnostic level (None, Warning, Info, Debug)")] + [RequiresRestart] public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; /// -- cgit v1.2.3 From b1e25db8fbdfbef854ddaa7e1ef586bcf33e3f7f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 07:33:39 -0500 Subject: split and move State --- src/slskd/Application/IStateMonitor.cs | 46 +++++++++++++++++ src/slskd/Application/State.cs | 27 ++++++++++ src/slskd/Application/StateMonitor.cs | 94 ++++++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 src/slskd/Application/IStateMonitor.cs create mode 100644 src/slskd/Application/State.cs create mode 100644 src/slskd/Application/StateMonitor.cs 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 (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + + /// + /// Used for notifications when changes. + /// + public interface IStateMonitor + { + /// + /// Gets the current application state. + /// + State Current { get; } + + /// + /// Registers a listener to be called whenever changes. + /// + /// Registers a listener to be called whenver state changes. + /// An which should be disposed to stop listening for changes. + IDisposable OnChange(Action<(State Previous, State Current)> listener); + + /// + /// Replaces the current state with the value resolved by the . + /// + /// Given the current state, resolves a new state value. + /// The updated state. + State Set(Func setter); + } +} diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/State.cs new file mode 100644 index 00000000..684bfb4f --- /dev/null +++ b/src/slskd/Application/State.cs @@ -0,0 +1,27 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Text.Json; + + /// + /// Application state. + /// + 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 (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + + /// + /// Used for notifications when changes. + /// + public class StateMonitor : IStateMonitor + { + private event Action<(State, State)> Changed; + + /// + /// Gets the current application state. + /// + public State Current { get; private set; } = new State(); + + /// + /// Registers a listener to be called whenever changes. + /// + /// Registers a listener to be called whenver state changes. + /// An which should be disposed to stop listening for changes. + public IDisposable OnChange(Action<(State Previous, State Current)> listener) + { + var disposable = new StateTrackerDisposable(this, listener); + Changed += disposable.OnChange; + return disposable; + } + + /// + /// Replaces the current state with the value resolved by the . + /// + /// Given the current state, resolves a new state value. + /// The updated state. + public State Set(Func setter) + { + var previous = Current.ToJson().ToObject(); + 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; + } + } + } + } +} -- cgit v1.2.3 From 3001b460068e9c84ef2ce4b56735a7fe0e04ea65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 07:33:55 -0500 Subject: add ToJson and ToObject extensions --- src/slskd/Common/Extensions.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 3b52c650..3e4f6e68 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -22,12 +22,28 @@ namespace slskd using System.IO; using System.Linq; using System.Reflection; + using System.Text.Json; /// /// Extensions. /// public static class Extensions { + /// + /// Serializes this object to json. + /// + /// The object to serialize. + /// A string containing the serialized object. + public static string ToJson(this object obj) => JsonSerializer.Serialize(obj); + + /// + /// Deserializes this string from json to an object of type . + /// + /// The type to which to deserialize the string. + /// The string to deserialize. + /// The new object deserialzied from the string. + public static T ToObject(this string str) => JsonSerializer.Deserialize(str); + /// /// Deeply compares this object with the specified object and returns a list of properties that are different. /// -- cgit v1.2.3 From 8f7f5a7733e61ce01f7d2d3e13739578b09b2692 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 07:34:11 -0500 Subject: deprecate old state --- src/slskd/State.cs | 133 ----------------------------------------------------- 1 file changed, 133 deletions(-) delete mode 100644 src/slskd/State.cs diff --git a/src/slskd/State.cs b/src/slskd/State.cs deleted file mode 100644 index 735b4706..00000000 --- a/src/slskd/State.cs +++ /dev/null @@ -1,133 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Text.Json; - using Microsoft.Extensions.Logging; - - /// - /// Application state. - /// - public record State(bool PendingReconnect = false, bool PendingRestart = false); - - /// - /// Used for notifications when changes. - /// - public interface IStateMonitor - { - /// - /// Gets the current application state. - /// - State Current { get; } - - /// - /// Registers a listener to be called whenever changes. - /// - /// Registers a listener to be called whenver state changes. - /// An which should be disposed to stop listening for changes. - IDisposable OnChange(Action<(State Previous, State Current)> listener); - - /// - /// Replaces the current state with the value resolved by the . - /// - /// Given the current state, resolves a new state value. - void Set(Func setter); - } - - /// - /// Used for notifications when changes. - /// - public class StateMonitor : IStateMonitor - { - public StateMonitor( - ILogger log) - { - Log = log; - } - - private event Action<(State, State)> Changed; - - /// - /// Gets the current application state. - /// - public State Current { get; private set; } = new State(); - - private ILogger Log { get; } - - /// - /// Registers a listener to be called whenever changes. - /// - /// Registers a listener to be called whenver state changes. - /// An which should be disposed to stop listening for changes. - public IDisposable OnChange(Action<(State Previous, State Current)> listener) - { - var disposable = new StateTrackerDisposable(this, listener); - Changed += disposable.OnChange; - return disposable; - } - - /// - /// Replaces the current state with the value resolved by the . - /// - /// Given the current state, resolves a new state value. - public void Set(Func setter) - { - var previous = JsonSerializer.Deserialize(JsonSerializer.Serialize(Current)); - Current = setter(Current); - - Changed?.Invoke((previous, Current)); - - Log.LogDebug("State changed from {Previous} to {Current}", JsonSerializer.Serialize(previous), JsonSerializer.Serialize(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; - } - } - } - } -} \ No newline at end of file -- cgit v1.2.3 From 7fc63ec68afd3bcd9213846dd75a5afb008acd55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 07:35:28 -0500 Subject: remove UsingProxy shorthand --- src/slskd/Application/Service.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 9cb7b3fb..e04b7a3f 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -67,7 +67,7 @@ namespace slskd ProxyOptions proxyOptions = default; - if (UsingProxy) + if (Options.Soulseek.Connection.Proxy.Enabled) { proxyOptions = new ProxyOptions( address: Options.Soulseek.Connection.Proxy.Address, @@ -145,13 +145,12 @@ namespace slskd private IRoomTracker RoomTracker { get; set; } private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } - private bool UsingProxy => Options.Soulseek.Connection.Proxy.Enabled; private IPushbulletService Pushbullet { get; } private ReaderWriterLockSlim OptionsSyncRoot { get; } = new ReaderWriterLockSlim(); public async Task StartAsync(CancellationToken cancellationToken) { - if (UsingProxy) + if (Options.Soulseek.Connection.Proxy.Enabled) { Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); } -- cgit v1.2.3 From 5d558e5c026ace22457fe66c9656d2fc2e5607eb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 07:36:45 -0500 Subject: add StateMonitor --- src/slskd/Application/Service.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index e04b7a3f..b01a3ccf 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -46,6 +46,7 @@ namespace slskd public Service( IOptionsMonitor optionMonitor, + IStateMonitor stateMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -54,7 +55,9 @@ namespace slskd IPushbulletService pushbulletService) { OptionsMonitor = optionMonitor; - OptionsMonitor.OnChange(options => OptionsChanged(options)); + + StateMonitor = stateMonitor; + StateMonitor.OnChange(state => StateMonitor_OnChange(state)); Options = OptionsMonitor.CurrentValue; @@ -143,6 +146,7 @@ namespace slskd private IOptionsMonitor OptionsMonitor { get; set; } private Options Options { get; set; } private IRoomTracker RoomTracker { get; set; } + private IStateMonitor StateMonitor { get; set; } private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } private IPushbulletService Pushbullet { get; } @@ -219,6 +223,11 @@ namespace slskd } } + 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) { if (sharedCounts != e) -- cgit v1.2.3 From 5cb76a5ac0f0228fc5fd8421575a3cfe2cb15eed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 09:00:06 -0500 Subject: complete options update --- src/slskd/Application/Service.cs | 98 ++++++++++++++++++++++++++++++++++------ 1 file changed, 85 insertions(+), 13 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index b01a3ccf..3603bd9a 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -22,7 +22,7 @@ namespace slskd using System.IO; using System.Linq; using System.Net; - using System.Reflection; + using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; @@ -55,6 +55,7 @@ namespace slskd IPushbulletService pushbulletService) { OptionsMonitor = optionMonitor; + OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); @@ -136,7 +137,6 @@ namespace slskd } public static ISoulseekClient SoulseekClient { get; private set; } - public static bool PendingRestart { get; private set; } private IBrowseTracker BrowseTracker { get; set; } private ISoulseekClient Client { get; set; } @@ -180,7 +180,7 @@ namespace slskd return Task.CompletedTask; } - private void OptionsChanged(Options options) + private async Task OptionsMonitor_OnChange(Options options) { // 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 @@ -190,6 +190,9 @@ namespace slskd try { + var pendingRestart = false; + var pendingReconnect = false; + var diff = Options.DiffWith(options); // don't react to duplicate/no-change events @@ -199,23 +202,92 @@ namespace slskd return; } - bool RequiresRestart(PropertyInfo prop) => prop.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)); - - foreach (var d in diff) + foreach (var (property, fqn, left, right) in diff) { - Logger.Debug($"{d.FQN} changed from '{d.Left ?? ""}' to '{d.Right ?? ""}'{(RequiresRestart(d.Property) ? "; Requires restart." : string.Empty)}"); + var requiresRestart = property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)); + + Logger.Debug($"{fqn} changed from '{left ?? ""}' to '{right ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}"); + + if (requiresRestart) + { + pendingRestart = true; + } } - var changesRequiringRestart = diff.Where(d => d.Property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute))); + // determine whether any Soulseek options changed. if so, we need to construct a patch + // and invoke ReconfigureOptionsAsync(). + var slskDiff = Options.Soulseek.DiffWith(options.Soulseek); - if (changesRequiringRestart.Any()) + if (slskDiff.Any()) { - Logger.Information("One or more updated options requires a restart to take effect."); - PendingRestart = true; + var old = Options.Soulseek; + var update = options.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()); + + pendingReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); + + if (pendingReconnect) + { + 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."); } Options = options; - Logger.Information("Options changed, but changes to the Soulseek configuration have not been propagated. This functionality will come in a later update."); + Logger.Information("Options updated successfully."); + } + catch (Exception ex) + { + Logger.Error(ex, "Failed to apply option update: {Message}", ex.Message); } finally { -- cgit v1.2.3 From 11a50210bc50a15a48ef481248cbc04c07ab63f4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jul 2021 09:32:24 -0500 Subject: swap Options for OptionsAtStartup to be more explicit about the lifecycle --- src/slskd/Application/Service.cs | 62 ++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 3603bd9a..d070f5c6 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -45,7 +45,8 @@ namespace slskd private (int Directories, int Files) sharedCounts = (0, 0); public Service( - IOptionsMonitor optionMonitor, + OptionsAtStartup optionsAtStartup, + IOptionsMonitor optionsMonitor, IStateMonitor stateMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, @@ -54,14 +55,14 @@ namespace slskd ISharedFileCache sharedFileCache, IPushbulletService pushbulletService) { - OptionsMonitor = optionMonitor; + OptionsAtStartup = optionsAtStartup; + + OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); - Options = OptionsMonitor.CurrentValue; - TransferTracker = transferTracker; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; @@ -71,29 +72,29 @@ namespace slskd ProxyOptions proxyOptions = default; - if (Options.Soulseek.Connection.Proxy.Enabled) + 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, @@ -144,7 +145,7 @@ namespace slskd private ILogger Logger { get; set; } = Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; set; } - private Options Options { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } private IRoomTracker RoomTracker { get; set; } private IStateMonitor StateMonitor { get; set; } private ISharedFileCache SharedFileCache { get; set; } @@ -154,21 +155,21 @@ namespace slskd public async Task StartAsync(CancellationToken cancellationToken) { - if (Options.Soulseek.Connection.Proxy.Enabled) + 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); } } @@ -193,7 +194,7 @@ namespace slskd var pendingRestart = false; var pendingReconnect = false; - var diff = Options.DiffWith(options); + var diff = OptionsMonitor.CurrentValue.DiffWith(options); // don't react to duplicate/no-change events // https://github.com/slskd/slskd/issues/126 @@ -216,11 +217,11 @@ namespace slskd // determine whether any Soulseek options changed. if so, we need to construct a patch // and invoke ReconfigureOptionsAsync(). - var slskDiff = Options.Soulseek.DiffWith(options.Soulseek); + var slskDiff = OptionsMonitor.CurrentValue.Soulseek.DiffWith(options.Soulseek); if (slskDiff.Any()) { - var old = Options.Soulseek; + var old = OptionsMonitor.CurrentValue.Soulseek; var update = options.Soulseek; Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); @@ -282,7 +283,6 @@ namespace slskd Logger.Information("One or more updated options requires an application restart to take effect."); } - Options = options; Logger.Information("Options updated successfully."); } catch (Exception ex) @@ -318,7 +318,7 @@ namespace slskd private Task 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))))); @@ -416,7 +416,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); @@ -427,7 +427,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); } @@ -452,7 +452,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); } -- cgit v1.2.3 From 1e198f11e1f5bd5501837259387561d849f06702 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:09:50 -0500 Subject: add RequiresReconnectAttribute, mark Username and Password --- .../Configuration/RequiresReconnectAttribute.cs | 26 ++++++++++++++++++++++ src/slskd/Options.cs | 2 ++ 2 files changed, 28 insertions(+) create mode 100644 src/slskd/Common/Configuration/RequiresReconnectAttribute.cs diff --git a/src/slskd/Common/Configuration/RequiresReconnectAttribute.cs b/src/slskd/Common/Configuration/RequiresReconnectAttribute.cs new file mode 100644 index 00000000..cd5edd14 --- /dev/null +++ b/src/slskd/Common/Configuration/RequiresReconnectAttribute.cs @@ -0,0 +1,26 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Configuration +{ + using System; + + [AttributeUsage(AttributeTargets.Property)] + public class RequiresReconnectAttribute : Attribute + { + } +} diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 221ec6c0..4a032c47 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -294,6 +294,7 @@ namespace slskd [Argument(default, "slsk-username")] [EnvironmentVariable("SLSK_USERNAME")] [Description("username for the Soulseek network")] + [RequiresReconnect] public string Username { get; private set; } = null; /// @@ -302,6 +303,7 @@ namespace slskd [Argument(default, "slsk-password")] [EnvironmentVariable("SLSK_PASSWORD")] [Description("password for the Soulseek network")] + [RequiresReconnect] public string Password { get; private set; } = null; /// -- cgit v1.2.3 From 1f77e1046033096286e211d4b8641c52f1924ddf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:25:19 -0500 Subject: remove unused using --- src/slskd/Application/Service.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index d070f5c6..ba071496 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -22,7 +22,6 @@ namespace slskd using System.IO; using System.Linq; using System.Net; - using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; -- cgit v1.2.3 From 842d95169d74cb11d4fbee56285f2a6d2c524c77 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:28:58 -0500 Subject: add OptionPostConfigurationSnapshot --- src/slskd/Application/Service.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index ba071496..890f9311 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -59,6 +59,8 @@ namespace slskd OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + OptionPostConfigurationSnapshot = OptionsMonitor.CurrentValue; + StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); @@ -145,6 +147,7 @@ namespace slskd private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } + private Options OptionPostConfigurationSnapshot { get; set; } private IRoomTracker RoomTracker { get; set; } private IStateMonitor StateMonitor { get; set; } private ISharedFileCache SharedFileCache { get; set; } @@ -193,7 +196,7 @@ namespace slskd var pendingRestart = false; var pendingReconnect = false; - var diff = OptionsMonitor.CurrentValue.DiffWith(options); + var diff = OptionPostConfigurationSnapshot.DiffWith(options); // don't react to duplicate/no-change events // https://github.com/slskd/slskd/issues/126 @@ -216,11 +219,11 @@ namespace slskd // determine whether any Soulseek options changed. if so, we need to construct a patch // and invoke ReconfigureOptionsAsync(). - var slskDiff = OptionsMonitor.CurrentValue.Soulseek.DiffWith(options.Soulseek); + var slskDiff = OptionPostConfigurationSnapshot.Soulseek.DiffWith(options.Soulseek); if (slskDiff.Any()) { - var old = OptionsMonitor.CurrentValue.Soulseek; + var old = OptionPostConfigurationSnapshot.Soulseek; var update = options.Soulseek; Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); @@ -290,6 +293,7 @@ namespace slskd } finally { + OptionPostConfigurationSnapshot = OptionsMonitor.CurrentValue; OptionsSyncRoot.ExitWriteLock(); } } -- cgit v1.2.3 From c54d6d8c1c6f13bc2a5c14bde0af204cd6e59d99 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:39:56 -0500 Subject: if a reconnect is pending, set PendingReconnect = false on disconnect --- src/slskd/Application/Service.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 890f9311..e2f63750 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -361,6 +361,11 @@ namespace slskd 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"); -- cgit v1.2.3 From 0684e1c22edea317374289b1ca63eb0c34f0b3c9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:40:17 -0500 Subject: use the latest credentials when reconnecting --- src/slskd/Application/Service.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index e2f63750..7c3b9756 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -408,7 +408,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) -- cgit v1.2.3 From e0fa9554fdcd29e3f400d56234228b6728a933f1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:41:22 -0500 Subject: the Client instance is the source of truth for current username --- src/slskd/Application/Service.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 7c3b9756..61b5da12 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -356,7 +356,7 @@ 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) @@ -380,7 +380,7 @@ 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 { @@ -446,7 +446,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); } -- cgit v1.2.3 From 06a324feff453f7dcc817b7b964ac7547f658e34 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:41:44 -0500 Subject: validate current un/pw options prior to reconnect attempt --- src/slskd/Application/Service.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 61b5da12..41097730 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -386,7 +386,7 @@ namespace slskd { 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; -- cgit v1.2.3 From 805f24fc7f34ec200d1a9ed8a57c8d22b8a32675 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 23 Jul 2021 10:58:12 -0500 Subject: detect changes that require reconnect --- src/slskd/Application/Service.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 41097730..81e558a0 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -208,13 +208,12 @@ namespace slskd foreach (var (property, fqn, left, right) in diff) { var requiresRestart = property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)); + var requiresReconnect = property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresReconnectAttribute)); - Logger.Debug($"{fqn} changed from '{left ?? ""}' to '{right ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}"); + Logger.Debug($"{fqn} changed from '{left ?? ""}' to '{right ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); - if (requiresRestart) - { - pendingRestart = true; - } + pendingRestart |= requiresRestart; + pendingReconnect |= requiresReconnect; } // determine whether any Soulseek options changed. if so, we need to construct a patch @@ -270,9 +269,9 @@ namespace slskd Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); - pendingReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); + var reconfigRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); - if (pendingReconnect) + if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) | reconfigRequiresReconnect) { 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."); -- cgit v1.2.3 From 2cefc34a71c4edf8e70cd1a276223a7b6fc2cd73 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 13:21:17 -0500 Subject: remove unused usings --- src/slskd/Application/State.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/slskd/Application/State.cs b/src/slskd/Application/State.cs index 684bfb4f..75d46dec 100644 --- a/src/slskd/Application/State.cs +++ b/src/slskd/Application/State.cs @@ -17,9 +17,6 @@ namespace slskd { - using System; - using System.Text.Json; - /// /// Application state. /// -- cgit v1.2.3 From 3f070819630bfd48b478c2d097c0e5902854f769 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 13:21:44 -0500 Subject: remove GetOptions(); access should be handled through injection --- src/slskd/Application/Management/IManagementService.cs | 6 ------ src/slskd/Application/Management/ManagementService.cs | 6 ------ 2 files changed, 12 deletions(-) diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index 5ece698b..b3e13477 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -38,12 +38,6 @@ namespace slskd.Management /// An optional Exception to associate with the disconnect. void DisconnectServer(string message = null, Exception exception = null); - /// - /// Gets the current application options. - /// - /// - Options GetOptions(); - /// /// Gets the current state of the connection to the Soulseek server. /// diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 7bcdc7be..66ed2b97 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -60,12 +60,6 @@ namespace slskd.Management public void DisconnectServer(string message = null, Exception exception = null) => Client.Disconnect(message, exception ?? new IntentionalDisconnectException(message)); - /// - /// Gets the current application options. - /// - /// - public Options GetOptions() => Options; - /// /// Gets the current state of the connection to the Soulseek server. /// -- cgit v1.2.3 From 98c2f99198ecc48f8d4d0de1342a455a844e6c44 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 13:21:59 -0500 Subject: use OptionsAtStartup --- .../Management/API/Controllers/SessionController.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 511643a6..442970b9 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,15 +37,15 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Options optionsSnapshotAtStartup, + OptionsAtStartup optionsAtStartup, SymmetricSecurityKey jwtSigningKey) { - Options = optionsSnapshotAtStartup; + OptionsAtStartup = optionsAtStartup; JwtSigningKey = jwtSigningKey; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } /// /// Checks whether the provided authentication is valid. @@ -75,7 +75,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(bool), 200)] public IActionResult Enabled() { - return Ok(!Options.Web.Authentication.Disable); + return Ok(!OptionsAtStartup.Web.Authentication.Disable); } /// @@ -106,7 +106,7 @@ namespace slskd.Management.API } // only admin login for now - if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password) + if (OptionsAtStartup.Web.Authentication.Username == login.Username && OptionsAtStartup.Web.Authentication.Password == login.Password) { return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); } @@ -117,7 +117,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() { -- cgit v1.2.3 From f210cb335277b17a18ca01591223adad53e60e2d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 13:25:17 -0500 Subject: allow web un/pw to be changed at runtime --- .../Application/Management/API/Controllers/SessionController.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 442970b9..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/. // +using Microsoft.Extensions.Options; + namespace slskd.Management.API { using System; @@ -37,14 +39,17 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( + IOptionsSnapshot optionsSnapshot, OptionsAtStartup optionsAtStartup, SymmetricSecurityKey jwtSigningKey) { + OptionsSnapshot = optionsSnapshot; OptionsAtStartup = optionsAtStartup; JwtSigningKey = jwtSigningKey; } private SymmetricSecurityKey JwtSigningKey { get; set; } + private IOptionsSnapshot OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } /// @@ -106,7 +111,7 @@ namespace slskd.Management.API } // only admin login for now - if (OptionsAtStartup.Web.Authentication.Username == login.Username && OptionsAtStartup.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))); } -- cgit v1.2.3 From 297c4a94f055de884f18b311cb06f8bc7474a66e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 14:23:40 -0500 Subject: make options update more readable --- src/slskd/Application/Service.cs | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index 81e558a0..8b44954d 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -22,6 +22,7 @@ namespace slskd using System.IO; using System.Linq; using System.Net; + using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; @@ -59,7 +60,7 @@ namespace slskd OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); - OptionPostConfigurationSnapshot = OptionsMonitor.CurrentValue; + PreviousOptions = OptionsMonitor.CurrentValue; StateMonitor = stateMonitor; StateMonitor.OnChange(state => StateMonitor_OnChange(state)); @@ -147,7 +148,7 @@ namespace slskd private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } - private Options OptionPostConfigurationSnapshot { get; set; } + private Options PreviousOptions { get; set; } private IRoomTracker RoomTracker { get; set; } private IStateMonitor StateMonitor { get; set; } private ISharedFileCache SharedFileCache { get; set; } @@ -183,7 +184,7 @@ namespace slskd return Task.CompletedTask; } - private async Task OptionsMonitor_OnChange(Options options) + private async Task OptionsMonitor_OnChange(Options newOptions) { // 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 @@ -195,8 +196,9 @@ namespace slskd { var pendingRestart = false; var pendingReconnect = false; + var soulseekRequiresReconnect = false; - var diff = OptionPostConfigurationSnapshot.DiffWith(options); + var diff = PreviousOptions.DiffWith(newOptions); // don't react to duplicate/no-change events // https://github.com/slskd/slskd/issues/126 @@ -207,8 +209,10 @@ namespace slskd foreach (var (property, fqn, left, right) in diff) { - var requiresRestart = property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresRestartAttribute)); - var requiresReconnect = property.CustomAttributes.Any(c => c.AttributeType == typeof(RequiresReconnectAttribute)); + static bool HasAttribute(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + + var requiresRestart = HasAttribute(property); + var requiresReconnect = HasAttribute(property); Logger.Debug($"{fqn} changed from '{left ?? ""}' to '{right ?? ""}'{(requiresRestart ? "; Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}"); @@ -218,12 +222,12 @@ namespace slskd // determine whether any Soulseek options changed. if so, we need to construct a patch // and invoke ReconfigureOptionsAsync(). - var slskDiff = OptionPostConfigurationSnapshot.Soulseek.DiffWith(options.Soulseek); + var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); if (slskDiff.Any()) { - var old = OptionPostConfigurationSnapshot.Soulseek; - var update = options.Soulseek; + var old = PreviousOptions.Soulseek; + var update = newOptions.Soulseek; Logger.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson()); @@ -269,13 +273,15 @@ namespace slskd Logger.Debug("Patching Soulseek options with {Patch}", patch.ToJson()); - var reconfigRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); + soulseekRequiresReconnect = await SoulseekClient.ReconfigureOptionsAsync(patch); + } - if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) | reconfigRequiresReconnect) - { - 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."); - } + // 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) @@ -292,7 +298,7 @@ namespace slskd } finally { - OptionPostConfigurationSnapshot = OptionsMonitor.CurrentValue; + PreviousOptions = OptionsMonitor.CurrentValue; OptionsSyncRoot.ExitWriteLock(); } } @@ -407,7 +413,7 @@ namespace slskd try { - // reconnect with the latest configuration values we have for username and password, instead of the options that were + // 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; -- cgit v1.2.3