diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/CommandLineArgumentConfigurationSource.cs | 93 | ||||
| -rw-r--r-- | src/slskd/Common/EnvironmentVariableConfigurationSource.cs | 76 | ||||
| -rw-r--r-- | src/slskd/Common/Options/InstanceOptions.cs | 199 | ||||
| -rw-r--r-- | src/slskd/Common/Options/RuntimeOptions.cs | 156 | ||||
| -rw-r--r-- | src/slskd/Common/YamlConfigurationSource.cs | 214 | ||||
| -rw-r--r-- | src/slskd/Configuration.cs | 214 |
6 files changed, 214 insertions, 738 deletions
diff --git a/src/slskd/Common/CommandLineArgumentConfigurationSource.cs b/src/slskd/Common/CommandLineArgumentConfigurationSource.cs deleted file mode 100644 index 1762228d..00000000 --- a/src/slskd/Common/CommandLineArgumentConfigurationSource.cs +++ /dev/null @@ -1,93 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.Collections.Generic; - using System.Linq; - using Utility.CommandLine; - - public class Argument - { - public string Description { get; set; } - public char ShortName { get; set; } - public string LongName { get; set; } - public string Key { get; set; } - } - - public static class CommandLineArgumentExtensions - { - public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, IEnumerable<Argument> map, string commandLine) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - return builder.MapCommandLineArguments(s => - { - s.Map = map; - s.CommandLine = commandLine; - }); - } - - public static IConfigurationBuilder MapCommandLineArguments(this IConfigurationBuilder builder, Action<CommandLineArgumentConfigurationSource> configureSource) - => builder.Add(configureSource); - } - - public class CommandLineArgumentConfigurationSource : IConfigurationSource - { - public IEnumerable<Argument> Map { get; set; } - public string CommandLine { get; set; } - - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new CommandLineArgumentConfigurationProvider(this); - } - } - - public class CommandLineArgumentConfigurationProvider : ConfigurationProvider - { - public CommandLineArgumentConfigurationSource Source { get; set; } - - /// <summary> - /// Initializes a new instance with the specified source. - /// </summary> - /// <param name="source">The source settings.</param> - public CommandLineArgumentConfigurationProvider(CommandLineArgumentConfigurationSource source) - { - Source = source; - } - - public override void Load() - { - var dictionary = Arguments.Parse(Source.CommandLine).ArgumentDictionary; - - foreach (var item in Source.Map) - { - Console.WriteLine($"Item: {item.Key}"); - - if (string.IsNullOrEmpty(item.Key)) - { - continue; - } - - var arguments = new[] { item.ShortName.ToString(), item.LongName }.Where(i => !string.IsNullOrEmpty(i)); - - foreach (var argument in arguments) - { - if (dictionary.ContainsKey(argument)) - { - var value = dictionary[argument].ToString(); - - if (string.IsNullOrEmpty(value)) - { - value = "true"; - } - - Data[item.Key] = value; - } - } - } - } - } -} diff --git a/src/slskd/Common/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/EnvironmentVariableConfigurationSource.cs deleted file mode 100644 index 36a8ddf1..00000000 --- a/src/slskd/Common/EnvironmentVariableConfigurationSource.cs +++ /dev/null @@ -1,76 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.Collections.Generic; - - public class EnvironmentVariable - { - public string Description { get; set; } - public string Name { get; set; } - public string Key { get; set; } - } - - public static class EnvironmentVariableConfigurationExtensions - { - public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable<EnvironmentVariable> map) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - return builder.MapEnvironmentVariables(s => - { - s.Map = map; - }); - } - - public static IConfigurationBuilder MapEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariableConfigurationSource> configureSource) - => builder.Add(configureSource); - } - - public class EnvironmentVariableConfigurationSource : IConfigurationSource - { - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new EnvironmentVariableConfigurationProvider(this); - } - - public IEnumerable<EnvironmentVariable> Map { get; set; } - } - - public class EnvironmentVariableConfigurationProvider : ConfigurationProvider - { - public EnvironmentVariableConfigurationSource Source { get; set; } - /// <summary> - /// Initializes a new instance with the specified source. - /// </summary> - /// <param name="source">The source settings.</param> - public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) - { - Source = source; - } - - public override void Load() - { - foreach (var item in Source.Map) - { - if (string.IsNullOrEmpty(item.Key)) - { - continue; - } - - if (!string.IsNullOrEmpty(item.Name)) - { - var value = Environment.GetEnvironmentVariable(item.Name); - - if (!string.IsNullOrEmpty(value)) - { - Data[item.Key] = value; - } - } - } - } - } -} diff --git a/src/slskd/Common/Options/InstanceOptions.cs b/src/slskd/Common/Options/InstanceOptions.cs deleted file mode 100644 index 52b46722..00000000 --- a/src/slskd/Common/Options/InstanceOptions.cs +++ /dev/null @@ -1,199 +0,0 @@ -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using System; - using System.IO; - using System.Linq; - using Utility.CommandLine; - using Utility.EnvironmentVariables; - - public class InstanceOptions - { - [Argument('h', "help", "print usage")] - public static bool ShowHelp { get; private set; } - - [Argument('v', "version", "display version information")] - public static bool ShowVersion { get; private set; } - - [EnvironmentVariable("SLSKD_DEBUG")] - [Configuration("slskd:debug")] - [Argument('d', "debug", "run in debug mode")] - public static bool Debug { get; private set; } - - [EnvironmentVariable("SLSKD_NO_LOGO")] - [Configuration("slskd:no_logo")] - [Argument('n', "no-logo", "suppress logo on startup")] - public static bool DisableLogo { get; private set; } - - [EnvironmentVariable("SLSKD_NO_AUTH")] - [Configuration("slskd:no_auth")] - [Argument('x', "no-auth", "disable authentication for web requests")] - public static bool DisableAuthentication { get; private set; } - - [EnvironmentVariable("SLSKD_INSTANCE_NAME")] - [Configuration("slskd:instance_name")] - [Argument('i', "instance-name", "optional; a unique name for this instance")] - public static string InstanceName { get; private set; } = "default"; - - [EnvironmentVariable("SLSKD_FEATURE_PROMETHEUS")] - [Configuration("slskd:feature:prometheus")] - [Argument('m', "prometheus", "enable collection and publish of prometheus metrics")] - public static bool EnablePrometheus { get; private set; } - - [EnvironmentVariable("SLSKD_FEATURE_SWAGGER")] - [Configuration("slskd:feature:swagger")] - [Argument('s', "swagger", "enable swagger documentation")] - public static bool EnableSwagger { get; private set; } - - [EnvironmentVariable("SLSKD_LOKI")] - [Configuration("slskd:logger:loki")] - [Argument('l', "loki", "optional; the url to a Grafana Loki instance to which to log")] - public static string LokiUrl { get; private set; } - - [EnvironmentVariable("SLSKD_URL_BASE")] - [Configuration("slskd:web:url_base")] - [Argument('b', "url-base", "base url for web requests")] - public static string UrlBase { get; private set; } = "/"; - - [EnvironmentVariable("SLSKD_CONTENT_PATH")] - [Configuration("slskd:web:content_path")] - [Argument('c', "content-path", "path to static web content")] - public static string ContentPath { get; private set; } = Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot"); - - [EnvironmentVariable("SLSKD_JWT_KEY")] - [Configuration("slskd:web:jwt:key")] - [Argument('k', "jwt-key", "optional; the key with which to sign JWTs")] - public static string JwtKey { get; private set; } = Guid.NewGuid().ToString(); - - [EnvironmentVariable("SLSKD_JWT_TTL")] - [Configuration("slskd:web:jwt:ttl")] - [Argument('t', "jwt-ttl", "optional; the TTL for JWTs")] - public static int JwtTTL { get; private set; } = 604800000; - - [EnvironmentVariable("SLSKD_USERNAME")] - [Configuration("soulseek:username")] - [Argument('u', "username", "the username for the Soulseek network")] - public static string Username { get; private set; } - - [EnvironmentVariable("SLSKD_PASSWORD")] - [Configuration("soulseek:password")] - [Argument('p', "password", "the password for the Soulseek network")] - public static string Password { get; private set; } - - public static bool EnableLoki { get; private set; } - - //public static void Populate(string configurationFile = null, bool argumentsOnly = false) - //{ - // if (!argumentsOnly) - // { - // try - // { - // EnvironmentVariables.Populate(typeof(InstanceOptions)); - // } - // catch (Exception ex) - // { - // Console.WriteLine($"Error parsing environment variables: {ex.Message}"); - // return; - // } - - // try - // { - // var config = new ConfigurationBuilder() - // .SetBasePath(Directory.GetCurrentDirectory()) - // .AddMapping(new[] - // { - // new OptionMap { - // Description = "run in debug mode", - // EnvironmentVariable = "SLSK_DEBUG", - // ShortName = 'd', - // LongName = "debug", - // Key = "slskd:debug" - // }, - // new OptionMap { - // Description = "optional; a unique name for this instance", - // EnvironmentVariable = "SLSK_INSTANCE_NAME", - // ShortName = 'i', - // LongName = "instance-name", - // Key = "slskd:instancename" - // } - // }, Environment.CommandLine, configurationFile, optional: true, reloadOnChange: false) - // .Build(); - - // Console.WriteLine(config.GetDebugView()); - - // config.Populate(typeof(InstanceOptions)); - // } - // catch (Exception ex) - // { - // Console.WriteLine($"Error parsing configuration file '{configurationFile}': {ex.Message}"); - // return; - // } - // } - - // try - // { - // Arguments.Populate(typeof(InstanceOptions), clearExistingValues: false); - // } - // catch (Exception ex) - // { - // Console.WriteLine($"Error parsing command line input: {ex.Message}"); - // return; - // } - - // EnableLoki = !string.IsNullOrEmpty(LokiUrl); - // UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - // ContentPath = Path.GetFullPath(ContentPath); - //} - - public static void PrintHelp() - { - PrintArguments(); - } - - public static void PrintArguments() - { - static string GetLongName(ArgumentInfo info) - => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>"; - - static string GetShortName(ArgumentInfo info) - => info.ShortName > 0 ? $"-{info.ShortName}|" : " "; - - var arguments = Arguments.GetArgumentInfo(typeof(InstanceOptions)); - var longestName = arguments.Select(a => GetLongName(a)).Max(n => n.Length); - - Console.WriteLine("\nusage: slskd [arguments]\n"); - Console.WriteLine("arguments:\n"); - foreach (var info in arguments) - { - var envar = info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value; - - var result = $" {GetShortName(info)}--{GetLongName(info).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } - - public static void PrintEnvironmentVariables() - { - static string GetEnvironmentVariableName(ArgumentInfo info, bool includeType = false) - => info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value?.ToString() + (includeType ? $" <{info.Property.PropertyType.Name.ToLowerInvariant()}>" : ""); - - var arguments = Arguments.GetArgumentInfo(typeof(InstanceOptions)); - var longestName = arguments.Select(a => GetEnvironmentVariableName(a, includeType: true)).Where(a => a != null).Max(n => n.Length); - - Console.WriteLine("\nenvironment variables (arguments have precedence):\n"); - foreach (var info in arguments) - { - var envar = GetEnvironmentVariableName(info, includeType: false); - - if (string.IsNullOrEmpty(envar)) continue; - - var result = $" {GetEnvironmentVariableName(info, includeType: true).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } - } -} diff --git a/src/slskd/Common/Options/RuntimeOptions.cs b/src/slskd/Common/Options/RuntimeOptions.cs deleted file mode 100644 index cded2334..00000000 --- a/src/slskd/Common/Options/RuntimeOptions.cs +++ /dev/null @@ -1,156 +0,0 @@ -namespace slskd -{ - using System; - using System.Collections.Generic; - - public class RuntimeOptions - { - public static IEnumerable<EnvironmentVariable> EnvironmentVariableMap => new[] - { - new EnvironmentVariable { - Description = "run in debug mode", - Name = "SLSK_DEBUG", - Key = "slskd:debug" - }, - new EnvironmentVariable { - Description = "optional; a unique name for this instance", - Name = "SLSK_INSTANCE_NAME", - Key = "slskd:instancename" - }, - new EnvironmentVariable { - Description = "enable collection and publish of prometheus metrics", - Name = "SLSK_PROMETHEUS", - Key = "slskd:feature:prometheus" - }, - new EnvironmentVariable { - Description = "enable swagger documentation", - Name = "SLSK_SWAGGER", - Key = "slskd:feature:swagger" - }, - new EnvironmentVariable { - Description = "jwt signing key", - Name = "SLSKD_JWT_KEY", - Key = "slskd:web:jwt:key" - } - }; - - public static IEnumerable<Argument> ArgumentMap => new[] - { - new Argument - { - Description = "print usage", - ShortName = 'h', - LongName = "help", - Key = "slskd:showhelp" - }, - new Argument { - Description = "display version information", - ShortName = 'v', - LongName = "version", - Key = "slskd:showversion" - }, - new Argument { - Description = "run in debug mode", - ShortName = 'd', - LongName = "debug", - Key = "slskd:debug" - }, - new Argument - { - Description = "", - ShortName = 'i', - LongName = "instance-name", - Key = "slskd:instancename" - } - }; - - public class slskd - { - public bool ShowHelp { get; private set; } = false; - public bool ShowVersion { get; private set; } = false; - public bool Debug { get; private set; } = false; - public bool NoLogo { get; private set; } = false; - public bool NoAuth { get; private set; } = false; - public string InstanceName { get; private set; } = "default"; - public FeatureOptions Feature { get; private set; } = new FeatureOptions(); - public LoggerOptions Logger { get; private set; } = new LoggerOptions(); - public WebOptions Web { get; private set; } = new WebOptions(); - - public class FeatureOptions - { - public bool Prometheus { get; private set; } = false; - public bool Swagger { get; private set; } = false; - } - - public class LoggerOptions - { - public string Loki { get; private set; } = null; - } - - public class WebOptions - { - public string UrlBase { get; private set; } = "/"; - public string ContentPath { get; private set; } = "wwwroot"; - public JwtOptions Jwt { get; private set; } = new JwtOptions(); - - public class JwtOptions - { - public int TTL { get; private set; } = 1234567890; - public string Key { get; private set; } = Guid.NewGuid().ToString(); - } - } - } - - public class Soulseek - { - public string Username { get; set; } = InstanceOptions.Username; - public string Password { get; set; } = InstanceOptions.Password; - public int ListenPort { get; set; } = 50000; - public DistributedNetworkOptions DistributedNetwork { get; set; } - public ConnectionOptions Connection { get; set; } - - public class DistributedNetworkOptions - { - public bool Enabled { get; set; } = true; - public int ChildLimit { get; set; } = 10; - } - - public class ConnectionOptions - { - public TimeoutOptions Timeout { get; set; } - public BufferOptions Buffer { get; set; } - - public class TimeoutOptions - { - public int Connect { get; set; } = 5000; - public int Inactivity { get; set; } = 15000; - } - - public class BufferOptions - { - public int Read { get; set; } = 16384; - public int Write { get; set; } = 16384; - } - } - } - - public class Authentication - { - public IEnumerable<User> Users { get; set; } - public IEnumerable<ApiKey> ApiKeys { get; set; } - - public class User - { - public string Name { get; set; } - public string Password { get; set; } - public Role Role { get; set; } - } - - public class ApiKey - { - public string Key { get; set; } - public Role Role { get; set; } - } - } - } -} diff --git a/src/slskd/Common/YamlConfigurationSource.cs b/src/slskd/Common/YamlConfigurationSource.cs deleted file mode 100644 index a7c379e3..00000000 --- a/src/slskd/Common/YamlConfigurationSource.cs +++ /dev/null @@ -1,214 +0,0 @@ -/* - █▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀ ▀ ▀ ▀▀ - █ The MIT License (MIT) - █ - █ Copyright (c) 2021 JP Dillingham (jp@dillingham.ws) - █ - █ Permission is hereby granted, free of charge, to any person obtaining a copy - █ of this software and associated documentation files (the "Software"), to deal - █ in the Software without restriction, including without limitation the rights - █ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - █ copies of the Software, and to permit persons to whom the Software is - █ furnished to do so, subject to the following conditions: - █ - █ The above copyright notice and this permission notice shall be included in all - █ copies or substantial portions of the Software. - █ - █ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - █ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - █ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - █ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - █ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - █ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - █ SOFTWARE. - █ - ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██ - ██ - ▀█▄ ██ ▄█▀ - ▀████▀ - ▀▀ */ - -namespace slskd -{ - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.FileProviders; - using System; - using System.IO; - using System.Linq; - using YamlDotNet.Core; - using YamlDotNet.RepresentationModel; - - /// <summary> - /// Extension methods for adding <see cref="YamlConfigurationProvider"/>. - /// </summary> - public static class YamlConfigurationExtensions - { - /// <summary> - /// Adds the YAML configuration provider at <paramref name="path"/> to <paramref name="builder"/>. - /// </summary> - /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> - /// <param name="path">Path relative to the base path stored in - /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> - /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path) - { - return AddYamlFile(builder, provider: null, path: path, optional: false, reloadOnChange: false); - } - - /// <summary> - /// Adds the YAML configuration provider at <paramref name="path"/> to <paramref name="builder"/>. - /// </summary> - /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> - /// <param name="path">Path relative to the base path stored in - /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> - /// <param name="optional">Whether the file is optional.</param> - /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional) - { - return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: false); - } - - /// <summary> - /// Adds the YAML configuration provider at <paramref name="path"/> to <paramref name="builder"/>. - /// </summary> - /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> - /// <param name="path">Path relative to the base path stored in - /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> - /// <param name="optional">Whether the file is optional.</param> - /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> - /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) - { - return AddYamlFile(builder, provider: null, path: path, optional: optional, reloadOnChange: reloadOnChange); - } - - /// <summary> - /// Adds a YAML configuration source to <paramref name="builder"/>. - /// </summary> - /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> - /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param> - /// <param name="path">Path relative to the base path stored in - /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> - /// <param name="optional">Whether the file is optional.</param> - /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> - /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) - { - 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.FileProvider = provider; - s.Path = path; - s.Optional = optional; - s.ReloadOnChange = reloadOnChange; - s.ResolveFileProvider(); - }); - } - - /// <summary> - /// Adds a YAML configuration source to <paramref name="builder"/>. - /// </summary> - /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> - /// <param name="configureSource">Configures the source.</param> - /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> - public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action<YamlConfigurationSource> configureSource) - => builder.Add(configureSource); - } - - /// <summary> - /// Represents a YAML file as an <see cref="IConfigurationSource"/>. - /// </summary> - public class YamlConfigurationSource : FileConfigurationSource - { - /// <summary> - /// Builds the <see cref="YamlConfigurationProvider"/> for this source. - /// </summary> - /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> - /// <returns>A <see cref="YamlConfigurationProvider"/></returns> - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - EnsureDefaults(builder); - return new YamlConfigurationProvider(this); - } - } - - /// <summary> - /// A YAML file based <see cref="FileConfigurationProvider"/>. - /// </summary> - public class YamlConfigurationProvider : FileConfigurationProvider - { - /// <summary> - /// Initializes a new instance with the specified source. - /// </summary> - /// <param name="source">The source settings.</param> - public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { } - - private string[] NullValues { get; } = new[] { "~", "null", "" }; - - /// <summary> - /// Loads the YAML data from a stream. - /// </summary> - /// <param name="stream">The stream to read.</param> - public override void Load(Stream stream) - { - try - { - using var reader = new StreamReader(stream); - - var yaml = new YamlStream(); - yaml.Load(reader); - - var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; - - Traverse(rootNode); - } - catch (YamlException e) - { - throw new FormatException("Could not parse the YAML file.", e); - } - } - - private void Traverse(YamlNode root, string path = null) - { - static string Clean(string str) => str?.Replace("_", string.Empty).Replace("-", string.Empty); - - if (root is YamlScalarNode scalar) - { - if (Data.ContainsKey(Clean(path))) - { - throw new FormatException($"A duplicate key '{Clean(path)}' was found."); - } - - var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - - if (value != null) - { - Data[Clean(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; - } - } - else if (root is YamlMappingNode map) - { - foreach (var node in map.Children) - { - var key = Clean(((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())); - } - } - } - } -} diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs new file mode 100644 index 00000000..da7ccf48 --- /dev/null +++ b/src/slskd/Configuration.cs @@ -0,0 +1,214 @@ +namespace slskd +{ + using System; + using System.Collections.Generic; + + public record Option(char ShortName, string LongName, string EnvironmentVariable, Type Type, string Key, string Description = null); + + public static class Configuration + { + public static EnvironmentVariable ToEnvironmentVariable(this Option option) + => new EnvironmentVariable(option.EnvironmentVariable, option.Type, option.Key, option.Description); + + public static CommandLineArgument ToCommandLineArgument(this Option option) + => new CommandLineArgument(option.ShortName, option.LongName, option.Type, option.Key, option.Description); + + public static IEnumerable<Option> Map => new Option[] + { + new( + ShortName: 'v', + LongName: "version", + EnvironmentVariable: null, + Type: typeof(bool), + Key: null, + Description: "display version information"), + new( + ShortName: 'h', + LongName: "help", + EnvironmentVariable: null, + Type: typeof(bool), + Key: null, + Description: "print usage"), + new( + ShortName: 'd', + LongName: "debug", + EnvironmentVariable: "DEBUG", + Type: typeof(bool), + Key: "slskd:debug", + Description: "run in debug mode"), + new( + ShortName: 'n', + LongName: "no-logo", + EnvironmentVariable: "NO_LOGO", + Type: typeof(bool), + Key: "slskd:nologo", + Description: "suppress logo on startup"), + new( + ShortName: 'x', + LongName: "no-auth", + EnvironmentVariable: "NO_AUTH", + Type: typeof(bool), + Key: "slskd:noauth", + Description: "disable authentication for web requests"), + new( + ShortName: 'i', + LongName: "instance-name", + EnvironmentVariable: "INSTANCE_NAME", + Type: typeof(string), + Key: "slskd:instancename", + Description: "optional; a unique name for this instance"), + new( + ShortName: 'm', + LongName: "prometheus", + EnvironmentVariable: "PROMETHEUS", + Type: typeof(bool), + Key: "slskd:feature:prometheus", + Description: "enable collection and publishing of prometheus metrics"), + new( + ShortName: 's', + LongName: "swagger", + EnvironmentVariable: "SWAGGER", + Type: typeof(bool), + Key: "slskd:feature:swagger", + Description: "enable swagger documentation and UI"), + new( + ShortName: 'l', + LongName: "loki", + EnvironmentVariable: "LOKI", + Type: typeof(string), + Key: "slskd:logger:loki", + Description: "optional; the url to a Grafana Loki instance to which to log"), + new( + ShortName: 'b', + LongName: "url-base", + EnvironmentVariable: "URL_BASE", + Type: typeof(string), + Key: "slskd:web:urlbase", + Description: "base url for web requests"), + new( + ShortName: 'c', + LongName: "content-path", + EnvironmentVariable: "CONTENT_PATH", + Type: typeof(string), + Key: "slskd:web:contentpath", + Description: "path to static web content"), + new( + ShortName: 'k', + LongName: "jwt-key", + EnvironmentVariable: "JWT_KEY", + Type: typeof(string), + Key: "slskd:web:jwt:key", + Description: "the key with which to sign JWTs"), + new( + ShortName: 't', + LongName: "jwt-ttl", + EnvironmentVariable: "JWT_TTL", + Type: typeof(int), + Key: "slskd:web:jwt:ttl", + Description: "the TTL for JWTs"), + new( + ShortName: 'u', + LongName: "username", + EnvironmentVariable: "USERNAME", + Type: typeof(string), + Key: "soulseek:username", + Description: "the username for the Soulseek network"), + new( + ShortName: 'p', + LongName: "password", + EnvironmentVariable: "PASSWORD", + Type: typeof(string), + Key: "soulseek:password", + Description: "the password for the Soulseek network") + }; + + public class slskd + { + public bool ShowHelp { get; private set; } = false; + public bool ShowVersion { get; private set; } = false; + public bool Debug { get; private set; } = false; + public bool NoLogo { get; private set; } = false; + public bool NoAuth { get; private set; } = false; + public string InstanceName { get; private set; } = "default"; + public FeatureOptions Feature { get; private set; } = new FeatureOptions(); + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + public WebOptions Web { get; private set; } = new WebOptions(); + + public class FeatureOptions + { + public bool Prometheus { get; private set; } = false; + public bool Swagger { get; private set; } = false; + } + + public class LoggerOptions + { + public string Loki { get; private set; } = null; + } + + public class WebOptions + { + public string UrlBase { get; private set; } = "/"; + public string ContentPath { get; private set; } = "wwwroot"; + public JwtOptions Jwt { get; private set; } = new JwtOptions(); + + public class JwtOptions + { + public int TTL { get; private set; } = 1234567890; + public string Key { get; private set; } = Guid.NewGuid().ToString(); + } + } + } + + public class Soulseek + { + public string Username { get; set; } + public string Password { get; set; } + public int ListenPort { get; set; } = 50000; + public DistributedNetworkOptions DistributedNetwork { get; set; } + public ConnectionOptions Connection { get; set; } + + public class DistributedNetworkOptions + { + public bool Enabled { get; set; } = true; + public int ChildLimit { get; set; } = 10; + } + + public class ConnectionOptions + { + public TimeoutOptions Timeout { get; set; } + public BufferOptions Buffer { get; set; } + + public class TimeoutOptions + { + public int Connect { get; set; } = 5000; + public int Inactivity { get; set; } = 15000; + } + + public class BufferOptions + { + public int Read { get; set; } = 16384; + public int Write { get; set; } = 16384; + } + } + } + + public class Authentication + { + public IEnumerable<User> Users { get; set; } + public IEnumerable<ApiKey> ApiKeys { get; set; } + + public class User + { + public string Name { get; set; } + public string Password { get; set; } + public Role Role { get; set; } + } + + public class ApiKey + { + public string Key { get; set; } + public Role Role { get; set; } + } + } + } +} |
