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(+) (limited to 'src/slskd/Program.cs') 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 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 (limited to 'src/slskd/Program.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 (limited to 'src/slskd/Program.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 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(-) (limited to 'src/slskd/Program.cs') 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 (limited to 'src/slskd/Program.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 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(-) (limited to 'src/slskd/Program.cs') 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 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(-) (limited to 'src/slskd/Program.cs') 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