From eaa6a1be21747f46370b5b1d545b31513eeb3ed8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jul 2021 00:01:42 -0500 Subject: add OptionsController --- .../API/Controllers/OptionsController.cs | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/slskd/Application/Management/API/Controllers/OptionsController.cs (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs new file mode 100644 index 00000000..b75adc97 --- /dev/null +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -0,0 +1,53 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Management.API +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Options. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class OptionsController : ControllerBase + { + public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + { + OptionsMonitor = optionsMonitor; + } + + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Options Options => OptionsMonitor.CurrentValue; + + /// + /// Gets the current application options. + /// + /// + [HttpGet] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Get() + { + return Ok(Options); + } + } +} -- cgit v1.2.3 From 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/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index b75adc97..578b6b4c 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -30,13 +30,13 @@ namespace slskd.Management.API [Consumes("application/json")] public class OptionsController : ControllerBase { - public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { OptionsMonitor = optionsMonitor; } - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } - private Options Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Configuration Options => OptionsMonitor.CurrentValue; /// /// Gets the current application options. @@ -44,7 +44,7 @@ namespace slskd.Management.API /// [HttpGet] [Authorize] - [ProducesResponseType(typeof(Options), 200)] + [ProducesResponseType(typeof(Configuration), 200)] public IActionResult Get() { return Ok(Options); diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 09a95c24..1721f3f2 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,7 +37,7 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, + Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, SymmetricSecurityKey jwtSigningKey) { Options = optionsSnapshot.Value; @@ -45,7 +45,7 @@ namespace slskd.Management.API } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; set; } + private Configuration Options { get; set; } /// /// Checks whether the provided authentication is valid. diff --git a/src/slskd/Application/Management/IManagementService.cs b/src/slskd/Application/Management/IManagementService.cs index 5ece698b..d4f7ff51 100644 --- a/src/slskd/Application/Management/IManagementService.cs +++ b/src/slskd/Application/Management/IManagementService.cs @@ -42,7 +42,7 @@ namespace slskd.Management /// Gets the current application options. /// /// - Options GetOptions(); + Configuration GetOptions(); /// /// Gets the current state of the connection to the Soulseek server. diff --git a/src/slskd/Application/Management/ManagementService.cs b/src/slskd/Application/Management/ManagementService.cs index 4a385cff..a1d807a0 100644 --- a/src/slskd/Application/Management/ManagementService.cs +++ b/src/slskd/Application/Management/ManagementService.cs @@ -32,7 +32,7 @@ namespace slskd.Management /// The options monitor used to derive application options. /// The Soulseek client. public ManagementService( - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient) { OptionsMonitor = optionsMonitor; @@ -40,8 +40,8 @@ namespace slskd.Management } private ISoulseekClient Client { get; } - private Options Options => OptionsMonitor.CurrentValue; - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } + private Configuration Options => OptionsMonitor.CurrentValue; + private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } /// /// Connects the Soulseek client to the server using the configured username and password. @@ -62,7 +62,7 @@ namespace slskd.Management /// Gets the current application options. /// /// - public Options GetOptions() => Options; + public Configuration GetOptions() => Options; /// /// Gets the current state of the connection to the Soulseek server. diff --git a/src/slskd/Application/Service.cs b/src/slskd/Application/Service.cs index d9b682fc..9a65ae37 100644 --- a/src/slskd/Application/Service.cs +++ b/src/slskd/Application/Service.cs @@ -44,7 +44,7 @@ namespace slskd private (int Directories, int Files) sharedCounts = (0, 0); public Service( - IOptionsMonitor optionMonitor, + IOptionsMonitor optionMonitor, ITransferTracker transferTracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -55,7 +55,7 @@ namespace slskd OptionsMonitor = optionMonitor; OptionsMonitor.OnChange(options => OptionsChanged(options)); - Options = OptionsMonitor.CurrentValue; + Configuration = OptionsMonitor.CurrentValue; TransferTracker = transferTracker; BrowseTracker = browseTracker; @@ -69,26 +69,26 @@ namespace slskd if (UsingProxy) { proxyOptions = new ProxyOptions( - address: Options.Soulseek.Connection.Proxy.Address, - port: Options.Soulseek.Connection.Proxy.Port.Value, - username: Options.Soulseek.Connection.Proxy.Username, - password: Options.Soulseek.Connection.Proxy.Password); + address: Configuration.Soulseek.Connection.Proxy.Address, + port: Configuration.Soulseek.Connection.Proxy.Port.Value, + username: Configuration.Soulseek.Connection.Proxy.Username, + password: Configuration.Soulseek.Connection.Proxy.Password); } var connectionOptions = new ConnectionOptions( - readBufferSize: Options.Soulseek.Connection.Buffer.Read, - writeBufferSize: Options.Soulseek.Connection.Buffer.Write, - connectTimeout: Options.Soulseek.Connection.Timeout.Connect, - inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity, + readBufferSize: Configuration.Soulseek.Connection.Buffer.Read, + writeBufferSize: Configuration.Soulseek.Connection.Buffer.Write, + connectTimeout: Configuration.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: Configuration.Soulseek.Connection.Timeout.Inactivity, proxyOptions: proxyOptions); var clientOptions = new SoulseekClientOptions( - listenPort: Options.Soulseek.ListenPort, + listenPort: Configuration.Soulseek.ListenPort, enableListener: true, userEndPointCache: new UserEndPointCache(), - distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, - enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, - minimumDiagnosticLevel: Options.Soulseek.DiagnosticLevel, + distributedChildLimit: Configuration.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !Configuration.Soulseek.DistributedNetwork.Disabled, + minimumDiagnosticLevel: Configuration.Soulseek.DiagnosticLevel, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, serverConnectionOptions: connectionOptions, @@ -137,31 +137,31 @@ namespace slskd private IConversationTracker ConversationTracker { get; set; } private ILogger Logger { get; set; } = Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); - private IOptionsMonitor OptionsMonitor { get; set; } - private Options Options { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } + private Configuration Configuration { get; set; } private IRoomTracker RoomTracker { get; set; } private ISharedFileCache SharedFileCache { get; set; } private ITransferTracker TransferTracker { get; set; } - private bool UsingProxy => !string.IsNullOrWhiteSpace(Options.Soulseek.Connection.Proxy.Address) && Options.Soulseek.Connection.Proxy.Port.HasValue; + private bool UsingProxy => !string.IsNullOrWhiteSpace(Configuration.Soulseek.Connection.Proxy.Address) && Configuration.Soulseek.Connection.Proxy.Port.HasValue; private IPushbulletService Pushbullet { get; } public async Task StartAsync(CancellationToken cancellationToken) { if (UsingProxy) { - Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); + Logger.Information($"Using Proxy {Configuration.Soulseek.Connection.Proxy.Address}:{Configuration.Soulseek.Connection.Proxy.Port}"); } Logger.Information("Client started"); - Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); + Logger.Information("Listening on port {Port}", Configuration.Soulseek.ListenPort); - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + if (string.IsNullOrEmpty(Configuration.Soulseek.Username) || string.IsNullOrEmpty(Configuration.Soulseek.Password)) { Logger.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } else { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); + await Client.ConnectAsync(Configuration.Soulseek.Username, Configuration.Soulseek.Password).ConfigureAwait(false); } } @@ -173,12 +173,12 @@ namespace slskd return Task.CompletedTask; } - private void OptionsChanged(Options options) + private void OptionsChanged(Configuration configuration) { Console.WriteLine($"Options changed. Old options:"); - Console.WriteLine(JsonSerializer.Serialize(Options)); + Console.WriteLine(JsonSerializer.Serialize(Configuration)); Console.WriteLine($"\tNew options:"); - Console.WriteLine(JsonSerializer.Serialize(options)); + Console.WriteLine(JsonSerializer.Serialize(configuration)); // todo: did options really change? // todo: if options did change, create a patch and ReconfigureOptionsAsync // todo: if ReconfigureOptionsAsync = true, find some way to let the user know a reconnect is pending @@ -202,7 +202,7 @@ namespace slskd private Task BrowseResponseResolver(string username, IPEndPoint endpoint) { var directories = System.IO.Directory - .GetDirectories(Options.Directories.Shared, "*", SearchOption.AllDirectories) + .GetDirectories(Configuration.Directories.Shared, "*", SearchOption.AllDirectories) .Select(dir => new Soulseek.Directory(dir.Replace("/", @"\"), System.IO.Directory.GetFiles(dir) .Select(f => new Soulseek.File(1, Path.GetFileName(f), new FileInfo(f).Length, Path.GetExtension(f))))); @@ -237,7 +237,7 @@ namespace slskd private void Client_LoggedIn(object sender, EventArgs e) { - Logger.Information("Logged in to the Soulseek server as {Username}", Options.Soulseek.Username); + Logger.Information("Logged in to the Soulseek server as {Username}", Configuration.Soulseek.Username); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) @@ -256,13 +256,13 @@ namespace slskd } else if (args.Exception is KickedFromServerException) { - Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Options.Soulseek.Username); + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Configuration.Soulseek.Username); } else { Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) + if (string.IsNullOrEmpty(Configuration.Soulseek.Username) || string.IsNullOrEmpty(Configuration.Soulseek.Password)) { Logger.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); return; @@ -284,7 +284,7 @@ namespace slskd try { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + await Client.ConnectAsync(Configuration.Soulseek.Username, Configuration.Soulseek.Password); break; } catch (Exception ex) @@ -300,7 +300,7 @@ namespace slskd { ConversationTracker.AddOrUpdate(args.Username, PrivateMessage.FromEventArgs(args)); - if (Options.Integration.Pushbullet.Enabled && !args.Replayed) + if (Configuration.Integration.Pushbullet.Enabled && !args.Replayed) { Console.WriteLine("Pushing..."); _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); @@ -311,7 +311,7 @@ namespace slskd { Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); - if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) + if (Configuration.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message); } @@ -320,7 +320,7 @@ namespace slskd private void Client_RoomJoined(object sender, RoomJoinedEventArgs args) { // this will fire when we join a room; track that through the join operation. - if (args.Username != Options.Soulseek.Username) + if (args.Username != Configuration.Soulseek.Username) { RoomTracker.TryAddUser(args.RoomName, args.UserData); } @@ -336,7 +336,7 @@ namespace slskd var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow); RoomTracker.AddOrUpdateMessage(args.RoomName, message); - if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) + if (Configuration.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username)) { _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message); } diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index 97b86689..b28e5b1a 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -46,7 +46,7 @@ namespace slskd.Transfer.API /// /// public TransfersController( - Microsoft.Extensions.Options.IOptionsSnapshot options, + Microsoft.Extensions.Options.IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker, IFTPService ftpClient) @@ -57,7 +57,7 @@ namespace slskd.Transfer.API FTP = ftpClient; } - private Options Options { get; } + private Configuration Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } private IFTPService FTP { get; } diff --git a/src/slskd/Common/Validation/Extensions.cs b/src/slskd/Common/Validation/Extensions.cs index b7e396a3..cc2e3c12 100644 --- a/src/slskd/Common/Validation/Extensions.cs +++ b/src/slskd/Common/Validation/Extensions.cs @@ -28,15 +28,15 @@ namespace slskd.Validation /// /// Validates options. /// - /// The options instance to validate. + /// The configuration instance to validate. /// The result of the validation, if invalid. /// A value indicating whether the instance is valid. - public static bool TryValidate(this Options options, out CompositeValidationResult result) + public static bool TryValidate(this Configuration configuration, out CompositeValidationResult result) { result = null; var results = new List(); - if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true)) + if (!Validator.TryValidateObject(configuration, new ValidationContext(configuration), results, true)) { result = new CompositeValidationResult("Invalid configuration", results); return false; diff --git a/src/slskd/Common/Validation/X509CertificateAttribute.cs b/src/slskd/Common/Validation/X509CertificateAttribute.cs index 7a080882..87cd776b 100644 --- a/src/slskd/Common/Validation/X509CertificateAttribute.cs +++ b/src/slskd/Common/Validation/X509CertificateAttribute.cs @@ -19,7 +19,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using slskd.Cryptography; - using static slskd.Options.WebOptions.HttpsOptions; + using static slskd.Configuration.WebOptions.HttpsOptions; /// /// Validates X509 certificate parameters specified through . diff --git a/src/slskd/Configuration.cs b/src/slskd/Configuration.cs new file mode 100644 index 00000000..b1620632 --- /dev/null +++ b/src/slskd/Configuration.cs @@ -0,0 +1,769 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using FluentFTP; + using slskd.Validation; + using Soulseek.Diagnostics; + using Utility.CommandLine; + using Utility.EnvironmentVariables; + + /// + /// Application options. + /// + public class Configuration + { + /// + /// Gets a value indicating whether to display the application version. + /// + [Argument('v', "version")] + [Description("display version information")] + public bool ShowVersion { get; private set; } = false; + + /// + /// Gets a value indicating whether to display a list of command line arguments. + /// + [Argument('h', "help")] + [Description("display command line usage")] + public bool ShowHelp { get; private set; } = false; + + /// + /// Gets a value indicating whether to display a list of configuration environment variables. + /// + [Argument('e', "envars")] + [Description("display environment variables")] + public bool ShowEnvironmentVariables { get; private set; } = false; + + /// + /// Gets a value indicating whether to generate an X509 certificate and password. + /// + [Argument('g', "generate-cert")] + [Description("generate X509 certificate and password for HTTPs")] + public bool GenerateCertificate { get; private set; } = false; + + /// + /// Gets the path to the application configuration file. + /// + [Argument('c', "config")] + [EnvironmentVariable("CONFIG")] + [Description("path to configuration file")] + public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; + + /// + /// Gets a value indicating whether the application should run in debug mode. + /// + [Argument('d', "debug")] + [EnvironmentVariable("DEBUG")] + [Description("run in debug mode")] + public bool Debug { get; private set; } = Debugger.IsAttached; + + /// + /// Gets a value indicating whether the logo should be suppressed on startup. + /// + [Argument('n', "no-logo")] + [EnvironmentVariable("NO_LOGO")] + [Description("suppress logo on startup")] + public bool NoLogo { get; private set; } = false; + + /// + /// Gets a value indicating whether the application should quit after initialization. + /// + [Argument('x', "no-start")] + [EnvironmentVariable("NO_START")] + [Description("quit the application after initialization")] + public bool NoStart { get; private set; } = false; + + /// + /// Gets the unique name for this instance. + /// + [Argument('i', "instance-name")] + [EnvironmentVariable("INSTANCE_NAME")] + [Description("optional; a unique name for this instance")] + public string InstanceName { get; private set; } = "default"; + + /// + /// Gets directory options. + /// + [Validate] + public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); + + /// + /// Gets options for the web UI. + /// + [Validate] + public WebOptions Web { get; private set; } = new WebOptions(); + + /// + /// Gets logger options. + /// + [Validate] + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + + /// + /// Gets feature options. + /// + [Validate] + public FeatureOptions Feature { get; private set; } = new FeatureOptions(); + + /// + /// Gets options for the Soulseek client. + /// + [Validate] + public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); + + /// + /// Gets options for external integrations. + /// + [Validate] + public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); + + /// + /// Directory options. + /// + public class DirectoriesOptions + { + /// + /// Gets the path where application data is saved. + /// + [Argument(default, "app")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] + [DirectoryExists] + public string App { get; private set; } = Program.DefaultAppDirectory; + + /// + /// Gets the path where incomplete downloads are saved. + /// + [Argument(default, "incomplete")] + [EnvironmentVariable("INCOMPLETE_DIR")] + [Description("path where incomplete downloads are saved")] + [DirectoryExists] + public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; + + /// + /// Gets the path where downloaded files are saved. + /// + [Argument('o', "downloads")] + [EnvironmentVariable("DOWNLOADS_DIR")] + [Description("path where downloaded files are saved")] + [DirectoryExists] + public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; + + /// + /// Gets the path to shared files. + /// + [Argument('s', "shared")] + [EnvironmentVariable("SHARED_DIR")] + [Description("path to shared files")] + [DirectoryExists] + public string Shared { get; private set; } = Program.DefaultSharedDirectory; + } + + /// + /// Feature options. + /// + public class FeatureOptions + { + /// + /// Gets a value indicating whether prometheus metrics should be collected and published. + /// + [Argument(default, "prometheus")] + [EnvironmentVariable("PROMETHEUS")] + [Description("enable collection and publishing of prometheus metrics")] + public bool Prometheus { get; private set; } = false; + + /// + /// Gets a value indicating whether swagger documentation and UI should be enabled. + /// + [Argument(default, "swagger")] + [EnvironmentVariable("SWAGGER")] + [Description("enable swagger documentation and UI")] + public bool Swagger { get; private set; } = false; + } + + /// + /// Logger options. + /// + public class LoggerOptions + { + /// + /// Gets the URL to a Grafana Loki instance to which to log. + /// + [Argument(default, "loki")] + [EnvironmentVariable("LOKI")] + [Description("optional; url to a Grafana Loki instance to which to log")] + public string Loki { get; private set; } = null; + } + + /// + /// Soulseek client options. + /// + public class SoulseekOptions + { + /// + /// Gets the username for the Soulseek network. + /// + [Argument(default, "slsk-username")] + [EnvironmentVariable("SLSK_USERNAME")] + [Description("username for the Soulseek network")] + public string Username { get; private set; } = null; + + /// + /// Gets the password for the Soulseek network. + /// + [Argument(default, "slsk-password")] + [EnvironmentVariable("SLSK_PASSWORD")] + [Description("password for the Soulseek network")] + public string Password { get; private set; } = null; + + /// + /// Gets the port on which to listen for incoming connections. + /// + [Argument(default, "slsk-listen-port")] + [EnvironmentVariable("SLSK_LISTEN_PORT")] + [Description("port on which to listen for incoming connections")] + [Range(1024, 65535)] + public int ListenPort { get; private set; } = 50000; + + /// + /// Gets the minimum diagnostic level. + /// + [Argument(default, "slsk-diag-level")] + [EnvironmentVariable("SLSK_DIAG_LEVEL")] + [Description("minimum diagnostic level (None, Warning, Info, Debug)")] + public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; + + /// + /// Gets options for the distributed network. + /// + [Validate] + public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions(); + + /// + /// Gets connection options. + /// + [Validate] + public ConnectionOptions Connection { get; private set; } = new ConnectionOptions(); + + /// + /// Connection options. + /// + public class ConnectionOptions + { + /// + /// Gets connection timeout options. + /// + [Validate] + public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions(); + + /// + /// Gets connection buffer options. + /// + [Validate] + public BufferOptions Buffer { get; private set; } = new BufferOptions(); + + /// + /// Gets connection proxy options. + /// + [Validate] + public ProxyOptions Proxy { get; private set; } = new ProxyOptions(); + + /// + /// Connection buffer options. + /// + public class BufferOptions + { + /// + /// Gets the connection read buffer size. + /// + [Argument(default, "slsk-read-buffer")] + [EnvironmentVariable("SLSK_READ_BUFFER")] + [Description("read buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Read { get; private set; } = 16384; + + /// + /// Gets the connection write buffer size. + /// + [Argument(default, "slsk-write-buffer")] + [EnvironmentVariable("SLSK_WRITE_BUFFER")] + [Description("write buffer size for connections")] + [Range(1024, int.MaxValue)] + public int Write { get; private set; } = 16384; + } + + /// + /// Connection timeout options. + /// + public class TimeoutOptions + { + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "slsk-connection-timeout")] + [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] + [Description("connection timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Connect { get; private set; } = 10000; + + /// + /// Gets the connection inactivity timeout, in milliseconds. + /// + [Argument(default, "slsk-inactivity-timeout")] + [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] + [Description("connection inactivity timeout, in milliseconds")] + [Range(1000, int.MaxValue)] + public int Inactivity { get; private set; } = 15000; + } + + /// + /// Connection proxy options. + /// + public class ProxyOptions + { + /// + /// Gets the proxy address. + /// + [Argument(default, "slsk-proxy-address")] + [EnvironmentVariable("SLSK_PROXY_ADDRESS")] + [Description("connection proxy address")] + [StringLength(255, MinimumLength = 1)] + public string Address { get; private set; } + + /// + /// Gets the proxy port. + /// + [Argument(default, "slsk-proxy-port")] + [EnvironmentVariable("SLSK_PROXY_PORT")] + [Description("connection proxy port")] + [Range(1, 65535)] + public int? Port { get; private set; } + + /// + /// Gets the proxy username, if applicable. + /// + [Argument(default, "slsk-proxy-username")] + [EnvironmentVariable("SLSK_PROXY_USERNAME")] + [Description("connection proxy username")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; private set; } + + /// + /// Gets the proxy password, if applicable. + /// + [Argument(default, "slsk-proxy-password")] + [EnvironmentVariable("SLSK_PROXY_PASSWORD")] + [Description("connection proxy password")] + [StringLength(255, MinimumLength = 1)] + public string Password { get; private set; } + } + } + + /// + /// Distributed network options. + /// + public class DistributedNetworkOptions + { + /// + /// Gets a value indicating whether the distributed network should be disabled. + /// + [Argument(default, "slsk-no-dnet")] + [EnvironmentVariable("SLSK_NO_DNET")] + [Description("disable the distributed network")] + public bool Disabled { get; private set; } = false; + + /// + /// Gets the distributed child connection limit. + /// + [Argument(default, "slsk-dnet-children")] + [EnvironmentVariable("SLSK_DNET_CHILDREN")] + [Description("max number of distributed children")] + [Range(1, int.MaxValue)] + public int ChildLimit { get; private set; } = 25; + } + } + + /// + /// Web server options. + /// + public class WebOptions + { + /// + /// Gets the HTTP listen port. + /// + [Argument('l', "http-port")] + [EnvironmentVariable("HTTP_PORT")] + [Description("HTTP listen port for web UI")] + [Range(1, 65535)] + public int Port { get; private set; } = 5000; + + /// + /// Gets HTTPS options. + /// + [Validate] + public HttpsOptions Https { get; private set; } = new HttpsOptions(); + + /// + /// Gets the base url for web requests. + /// + [Argument(default, "url-base")] + [EnvironmentVariable("URL_BASE")] + [Description("base url for web requests")] + public string UrlBase { get; private set; } = "/"; + + /// + /// Gets the path to static web content. + /// + [Argument(default, "content-path")] + [EnvironmentVariable("CONTENT_PATH")] + [Description("path to static web content")] + [StringLength(255, MinimumLength = 1)] + public string ContentPath { get; private set; } = "wwwroot"; + + /// + /// Gets authentication options. + /// + [Validate] + public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); + + /// + /// Authentication options. + /// + public class AuthenticationOptions + { + /// + /// Gets a value indicating whether authentication should be disabled. + /// + [Argument('x', "no-auth")] + [EnvironmentVariable("NO_AUTH")] + [Description("disable authentication for web requests")] + public bool Disable { get; private set; } = false; + + /// + /// Gets the username for the web UI. + /// + [Argument('u', "username")] + [EnvironmentVariable("USERNAME")] + [Description("username for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Username { get; private set; } = Program.AppName; + + /// + /// Gets the password for the web UI. + /// + [Argument('p', "password")] + [EnvironmentVariable("PASSWORD")] + [Description("password for web UI")] + [StringLength(255, MinimumLength = 1)] + public string Password { get; private set; } = Program.AppName; + + /// + /// Gets JWT options. + /// + [Validate] + public JwtOptions Jwt { get; private set; } = new JwtOptions(); + + /// + /// JWT options. + /// + public class JwtOptions + { + /// + /// Gets the key with which to sign JWTs. + /// + [Argument(default, "jwt-key")] + [EnvironmentVariable("JWT_KEY")] + [Description("JWT signing key")] + [StringLength(255, MinimumLength = 1)] + public string Key { get; private set; } = Guid.NewGuid().ToString(); + + /// + /// Gets the TTL for JWTs. + /// + [Argument(default, "jwt-ttl")] + [EnvironmentVariable("JWT_TTL")] + [Description("TTL for JWTs")] + [Range(3600, int.MaxValue)] + public int Ttl { get; private set; } = 604800000; + } + } + + /// + /// HTTPS options. + /// + public class HttpsOptions + { + /// + /// Gets the HTTPS listen port. + /// + [Argument('L', "https-port")] + [EnvironmentVariable("HTTPS_PORT")] + [Description("HTTPS listen port for web UI")] + [Range(1, 65535)] + public int Port { get; private set; } = 5001; + + /// + /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. + /// + [Argument('f', "force-https")] + [EnvironmentVariable("HTTPS_FORCE")] + [Description("redirect HTTP to HTTPS")] + public bool Force { get; private set; } = false; + + /// + /// Gets certificate options. + /// + [Validate] + public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); + + /// + /// Certificate options. + /// + [X509Certificate] + public class CertificateOptions + { + /// + /// Gets the path to the the X509 certificate .pfx file. + /// + [Argument(default, "https-cert-pfx")] + [EnvironmentVariable("HTTPS_CERT_PFX")] + [Description("path to X509 certificate .pfx")] + [FileExists] + public string Pfx { get; private set; } + + /// + /// Gets the password for the X509 certificate. + /// + [Argument(default, "https-cert-password")] + [EnvironmentVariable("HTTPS_CERT_PASSWORD")] + [Description("X509 certificate password")] + public string Password { get; private set; } + } + } + } + + /// + /// Options for external integrations. + /// + public class IntegrationOptions + { + /// + /// Gets FTP options. + /// + [Validate] + public FTPOptions FTP { get; private set; } = new FTPOptions(); + + /// + /// Gets Pushbullet options. + /// + [Validate] + public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); + + /// + /// FTP options. + /// + public class FTPOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the FTP integration is enabled. + /// + [Argument(default, "ftp")] + [EnvironmentVariable("FTP_ENABLED")] + [Description("enable FTP integration")] + public bool Enabled { get; private set; } + + /// + /// Gets the FTP address. + /// + [Argument(default, "ftp-address")] + [EnvironmentVariable("FTP_ADDRESS")] + [Description("FTP address")] + public string Address { get; private set; } + + /// + /// Gets the FTP port. + /// + [Argument(default, "ftp-port")] + [EnvironmentVariable("FTP_PORT")] + [Description("FTP port")] + [Range(1, 65535)] + public int Port { get; private set; } = 21; + + /// + /// Gets the FTP encryption mode. + /// + [Argument(default, "ftp-encryption-mode")] + [EnvironmentVariable("FTP_ENCRYPTION_MODE")] + [Description("FTP encryption mode; none, implicit, explicit, auto")] + [Enum(typeof(FtpEncryptionMode))] + public string EncryptionMode { get; private set; } = "auto"; + + /// + /// Gets a value indicating whether FTP certificate errors should be ignored. + /// + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; private set; } = false; + + /// + /// Gets the FTP username. + /// + [Argument(default, "ftp-username")] + [EnvironmentVariable("FTP_USERNAME")] + [Description("FTP username")] + public string Username { get; private set; } + + /// + /// Gets the FTP password. + /// + [Argument(default, "ftp-password")] + [EnvironmentVariable("FTP_PASSWORD")] + [Description("FTP password")] + public string Password { get; private set; } + + /// + /// Gets the remote path for uploads. + /// + [Argument(default, "ftp-remote-path")] + [EnvironmentVariable("FTP_REMOTE_PATH")] + [Description("remote path for FTP uploads")] + public string RemotePath { get; private set; } = "/"; + + /// + /// Gets a value indicating whether existing files should be overwritten. + /// + [Argument(default, "ftp-overwrite-existing")] + [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] + [Description("overwrite existing files when uploading to FTP")] + public bool OverwriteExisting { get; private set; } = true; + + /// + /// Gets the connection timeout value, in milliseconds. + /// + [Argument(default, "ftp-connection-timeout")] + [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] + [Description("FTP connection timeout, in milliseconds")] + [Range(0, int.MaxValue)] + public int ConnectionTimeout { get; private set; } = 5000; + + /// + /// Gets the number of times failing uploads will be retried. + /// + [Argument(default, "ftp-retry-attempts")] + [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] + [Description("number of times failing FTP uploads will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + return results; + } + } + + /// + /// Pushbullet options. + /// + public class PushbulletOptions : IValidatableObject + { + /// + /// Gets a value indicating whether the Pushbullet integration is enabled. + /// + [Argument(default, "pushbullet")] + [EnvironmentVariable("PUSHBULLET_ENABLED")] + [Description("enable Pushbullet integration")] + public bool Enabled { get; private set; } = false; + + /// + /// Gets the Pushbullet API access token. + /// + [Argument(default, "pushbullet-token")] + [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] + [Description("Pushbullet access token")] + public string AccessToken { get; private set; } + + /// + /// Gets the prefix for Pushbullet notification titles. + /// + [Argument(default, "pushbullet-prefix")] + [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] + [Description("prefix for Pushbullet notification titles")] + public string NotificationPrefix { get; private set; } = "From slskd:"; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. + /// + [Argument(default, "pushbullet-notify-on-pm")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] + [Description("send Pushbullet notifications when private messages are received")] + public bool NotifyOnPrivateMessage { get; private set; } = true; + + /// + /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged + /// in user's username is mentioned in a room. + /// + [Argument(default, "pushbullet-notify-on-room-mention")] + [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] + [Description("send Pushbullet notifications when your username is mentioned in a room")] + public bool NotifyOnRoomMention { get; private set; } = true; + + /// + /// Gets the number of times failing Pushbullet notifications will be retried. + /// + [Argument(default, "pushbullet-retry-attempts")] + [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] + [Description("number of times failing Pushbullet notifications will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + /// + /// Gets the cooldown time for Pushbullet notifications, in milliseconds. + /// + [Argument(default, "pushbullet-cooldown")] + [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] + [Description("cooldown time for Pushbullet notifications, in milliseconds")] + public int CooldownTime { get; private set; } = 900000; // 15 minutes + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); + } + + return results; + } + } + } + } +} \ No newline at end of file diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index cc076ca1..5b8639dc 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -19,7 +19,7 @@ namespace slskd.Integrations.FTP { using System; using FluentFTP; - using static slskd.Options.IntegrationOptions; + using static slskd.Configuration.IntegrationOptions; /// /// FTP client factory. @@ -30,7 +30,7 @@ namespace slskd.Integrations.FTP /// Initializes a new instance of the class. /// /// The options monitor used to derive application options. - public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { Options = optionsMonitor.CurrentValue; @@ -48,7 +48,7 @@ namespace slskd.Integrations.FTP private FtpEncryptionMode EncryptionMode { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; - private Options Options { get; set; } + private Configuration Options { get; set; } /// /// Creates an instance of . diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index a5fe6a8f..f7fd1ddd 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -23,7 +23,7 @@ namespace slskd.Integrations.FTP using System.Threading.Tasks; using FluentFTP; using Microsoft.Extensions.Logging; - using static slskd.Options.IntegrationOptions; + using static slskd.Configuration.IntegrationOptions; /// /// FTP Integration service. @@ -38,7 +38,7 @@ namespace slskd.Integrations.FTP /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ILogger log) { Factory = ftpClientFactory; @@ -49,7 +49,7 @@ namespace slskd.Integrations.FTP private IFTPClientFactory Factory { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; private ILogger Log { get; set; } - private Options Options { get; } + private Configuration Options { get; } /// /// Uploads the specified to the configured FTP server. diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index cb31e6dc..8bf94af9 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -24,7 +24,7 @@ namespace slskd.Integrations.Pushbullet using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; - using static slskd.Options.IntegrationOptions; + using static slskd.Configuration.IntegrationOptions; /// /// Pushbullet integration service. @@ -41,7 +41,7 @@ namespace slskd.Integrations.Pushbullet /// The logger. public PushbulletService( IHttpClientFactory httpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, ILogger log) { HttpClientFactory = httpClientFactory; @@ -52,7 +52,7 @@ namespace slskd.Integrations.Pushbullet } private IHttpClientFactory HttpClientFactory { get; } - private Options Options { get; } + private Configuration Options { get; } private ILogger Log { get; } private PushbulletOptions PushbulletOptions => Options.Integration.Pushbullet; private IMemoryCache RecentlySent { get; } diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs deleted file mode 100644 index 7e4880c6..00000000 --- a/src/slskd/Options.cs +++ /dev/null @@ -1,769 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.ComponentModel.DataAnnotations; - using System.Diagnostics; - using FluentFTP; - using slskd.Validation; - using Soulseek.Diagnostics; - using Utility.CommandLine; - using Utility.EnvironmentVariables; - - /// - /// Application options. - /// - public class Options - { - /// - /// Gets a value indicating whether to display the application version. - /// - [Argument('v', "version")] - [Description("display version information")] - public bool ShowVersion { get; private set; } = false; - - /// - /// Gets a value indicating whether to display a list of command line arguments. - /// - [Argument('h', "help")] - [Description("display command line usage")] - public bool ShowHelp { get; private set; } = false; - - /// - /// Gets a value indicating whether to display a list of configuration environment variables. - /// - [Argument('e', "envars")] - [Description("display environment variables")] - public bool ShowEnvironmentVariables { get; private set; } = false; - - /// - /// Gets a value indicating whether to generate an X509 certificate and password. - /// - [Argument('g', "generate-cert")] - [Description("generate X509 certificate and password for HTTPs")] - public bool GenerateCertificate { get; private set; } = false; - - /// - /// Gets the path to the application configuration file. - /// - [Argument('c', "config")] - [EnvironmentVariable("CONFIG")] - [Description("path to configuration file")] - public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; - - /// - /// Gets a value indicating whether the application should run in debug mode. - /// - [Argument('d', "debug")] - [EnvironmentVariable("DEBUG")] - [Description("run in debug mode")] - public bool Debug { get; private set; } = Debugger.IsAttached; - - /// - /// Gets a value indicating whether the logo should be suppressed on startup. - /// - [Argument('n', "no-logo")] - [EnvironmentVariable("NO_LOGO")] - [Description("suppress logo on startup")] - public bool NoLogo { get; private set; } = false; - - /// - /// Gets a value indicating whether the application should quit after initialization. - /// - [Argument('x', "no-start")] - [EnvironmentVariable("NO_START")] - [Description("quit the application after initialization")] - public bool NoStart { get; private set; } = false; - - /// - /// Gets the unique name for this instance. - /// - [Argument('i', "instance-name")] - [EnvironmentVariable("INSTANCE_NAME")] - [Description("optional; a unique name for this instance")] - public string InstanceName { get; private set; } = "default"; - - /// - /// Gets directory options. - /// - [Validate] - public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); - - /// - /// Gets options for the web UI. - /// - [Validate] - public WebOptions Web { get; private set; } = new WebOptions(); - - /// - /// Gets logger options. - /// - [Validate] - public LoggerOptions Logger { get; private set; } = new LoggerOptions(); - - /// - /// Gets feature options. - /// - [Validate] - public FeatureOptions Feature { get; private set; } = new FeatureOptions(); - - /// - /// Gets options for the Soulseek client. - /// - [Validate] - public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); - - /// - /// Gets options for external integrations. - /// - [Validate] - public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); - - /// - /// Directory options. - /// - public class DirectoriesOptions - { - /// - /// Gets the path where application data is saved. - /// - [Argument(default, "app")] - [EnvironmentVariable("APP_DIR")] - [Description("path where application data is saved")] - [DirectoryExists] - public string App { get; private set; } = Program.DefaultAppDirectory; - - /// - /// Gets the path where incomplete downloads are saved. - /// - [Argument(default, "incomplete")] - [EnvironmentVariable("INCOMPLETE_DIR")] - [Description("path where incomplete downloads are saved")] - [DirectoryExists] - public string Incomplete { get; private set; } = Program.DefaultIncompleteDirectory; - - /// - /// Gets the path where downloaded files are saved. - /// - [Argument('o', "downloads")] - [EnvironmentVariable("DOWNLOADS_DIR")] - [Description("path where downloaded files are saved")] - [DirectoryExists] - public string Downloads { get; private set; } = Program.DefaultDownloadsDirectory; - - /// - /// Gets the path to shared files. - /// - [Argument('s', "shared")] - [EnvironmentVariable("SHARED_DIR")] - [Description("path to shared files")] - [DirectoryExists] - public string Shared { get; private set; } = Program.DefaultSharedDirectory; - } - - /// - /// Feature options. - /// - public class FeatureOptions - { - /// - /// Gets a value indicating whether prometheus metrics should be collected and published. - /// - [Argument(default, "prometheus")] - [EnvironmentVariable("PROMETHEUS")] - [Description("enable collection and publishing of prometheus metrics")] - public bool Prometheus { get; private set; } = false; - - /// - /// Gets a value indicating whether swagger documentation and UI should be enabled. - /// - [Argument(default, "swagger")] - [EnvironmentVariable("SWAGGER")] - [Description("enable swagger documentation and UI")] - public bool Swagger { get; private set; } = false; - } - - /// - /// Logger options. - /// - public class LoggerOptions - { - /// - /// Gets the URL to a Grafana Loki instance to which to log. - /// - [Argument(default, "loki")] - [EnvironmentVariable("LOKI")] - [Description("optional; url to a Grafana Loki instance to which to log")] - public string Loki { get; private set; } = null; - } - - /// - /// Soulseek client options. - /// - public class SoulseekOptions - { - /// - /// Gets the username for the Soulseek network. - /// - [Argument(default, "slsk-username")] - [EnvironmentVariable("SLSK_USERNAME")] - [Description("username for the Soulseek network")] - public string Username { get; private set; } = null; - - /// - /// Gets the password for the Soulseek network. - /// - [Argument(default, "slsk-password")] - [EnvironmentVariable("SLSK_PASSWORD")] - [Description("password for the Soulseek network")] - public string Password { get; private set; } = null; - - /// - /// Gets the port on which to listen for incoming connections. - /// - [Argument(default, "slsk-listen-port")] - [EnvironmentVariable("SLSK_LISTEN_PORT")] - [Description("port on which to listen for incoming connections")] - [Range(1024, 65535)] - public int ListenPort { get; private set; } = 50000; - - /// - /// Gets the minimum diagnostic level. - /// - [Argument(default, "slsk-diag-level")] - [EnvironmentVariable("SLSK_DIAG_LEVEL")] - [Description("minimum diagnostic level (None, Warning, Info, Debug)")] - public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info; - - /// - /// Gets options for the distributed network. - /// - [Validate] - public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions(); - - /// - /// Gets connection options. - /// - [Validate] - public ConnectionOptions Connection { get; private set; } = new ConnectionOptions(); - - /// - /// Connection options. - /// - public class ConnectionOptions - { - /// - /// Gets connection timeout options. - /// - [Validate] - public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions(); - - /// - /// Gets connection buffer options. - /// - [Validate] - public BufferOptions Buffer { get; private set; } = new BufferOptions(); - - /// - /// Gets connection proxy options. - /// - [Validate] - public ProxyOptions Proxy { get; private set; } = new ProxyOptions(); - - /// - /// Connection buffer options. - /// - public class BufferOptions - { - /// - /// Gets the connection read buffer size. - /// - [Argument(default, "slsk-read-buffer")] - [EnvironmentVariable("SLSK_READ_BUFFER")] - [Description("read buffer size for connections")] - [Range(1024, int.MaxValue)] - public int Read { get; private set; } = 16384; - - /// - /// Gets the connection write buffer size. - /// - [Argument(default, "slsk-write-buffer")] - [EnvironmentVariable("SLSK_WRITE_BUFFER")] - [Description("write buffer size for connections")] - [Range(1024, int.MaxValue)] - public int Write { get; private set; } = 16384; - } - - /// - /// Connection timeout options. - /// - public class TimeoutOptions - { - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "slsk-connection-timeout")] - [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")] - [Description("connection timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Connect { get; private set; } = 10000; - - /// - /// Gets the connection inactivity timeout, in milliseconds. - /// - [Argument(default, "slsk-inactivity-timeout")] - [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")] - [Description("connection inactivity timeout, in milliseconds")] - [Range(1000, int.MaxValue)] - public int Inactivity { get; private set; } = 15000; - } - - /// - /// Connection proxy options. - /// - public class ProxyOptions - { - /// - /// Gets the proxy address. - /// - [Argument(default, "slsk-proxy-address")] - [EnvironmentVariable("SLSK_PROXY_ADDRESS")] - [Description("connection proxy address")] - [StringLength(255, MinimumLength = 1)] - public string Address { get; private set; } - - /// - /// Gets the proxy port. - /// - [Argument(default, "slsk-proxy-port")] - [EnvironmentVariable("SLSK_PROXY_PORT")] - [Description("connection proxy port")] - [Range(1, 65535)] - public int? Port { get; private set; } - - /// - /// Gets the proxy username, if applicable. - /// - [Argument(default, "slsk-proxy-username")] - [EnvironmentVariable("SLSK_PROXY_USERNAME")] - [Description("connection proxy username")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; private set; } - - /// - /// Gets the proxy password, if applicable. - /// - [Argument(default, "slsk-proxy-password")] - [EnvironmentVariable("SLSK_PROXY_PASSWORD")] - [Description("connection proxy password")] - [StringLength(255, MinimumLength = 1)] - public string Password { get; private set; } - } - } - - /// - /// Distributed network options. - /// - public class DistributedNetworkOptions - { - /// - /// Gets a value indicating whether the distributed network should be disabled. - /// - [Argument(default, "slsk-no-dnet")] - [EnvironmentVariable("SLSK_NO_DNET")] - [Description("disable the distributed network")] - public bool Disabled { get; private set; } = false; - - /// - /// Gets the distributed child connection limit. - /// - [Argument(default, "slsk-dnet-children")] - [EnvironmentVariable("SLSK_DNET_CHILDREN")] - [Description("max number of distributed children")] - [Range(1, int.MaxValue)] - public int ChildLimit { get; private set; } = 25; - } - } - - /// - /// Web server options. - /// - public class WebOptions - { - /// - /// Gets the HTTP listen port. - /// - [Argument('l', "http-port")] - [EnvironmentVariable("HTTP_PORT")] - [Description("HTTP listen port for web UI")] - [Range(1, 65535)] - public int Port { get; private set; } = 5000; - - /// - /// Gets HTTPS options. - /// - [Validate] - public HttpsOptions Https { get; private set; } = new HttpsOptions(); - - /// - /// Gets the base url for web requests. - /// - [Argument(default, "url-base")] - [EnvironmentVariable("URL_BASE")] - [Description("base url for web requests")] - public string UrlBase { get; private set; } = "/"; - - /// - /// Gets the path to static web content. - /// - [Argument(default, "content-path")] - [EnvironmentVariable("CONTENT_PATH")] - [Description("path to static web content")] - [StringLength(255, MinimumLength = 1)] - public string ContentPath { get; private set; } = "wwwroot"; - - /// - /// Gets authentication options. - /// - [Validate] - public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); - - /// - /// Authentication options. - /// - public class AuthenticationOptions - { - /// - /// Gets a value indicating whether authentication should be disabled. - /// - [Argument('x', "no-auth")] - [EnvironmentVariable("NO_AUTH")] - [Description("disable authentication for web requests")] - public bool Disable { get; private set; } = false; - - /// - /// Gets the username for the web UI. - /// - [Argument('u', "username")] - [EnvironmentVariable("USERNAME")] - [Description("username for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Username { get; private set; } = Program.AppName; - - /// - /// Gets the password for the web UI. - /// - [Argument('p', "password")] - [EnvironmentVariable("PASSWORD")] - [Description("password for web UI")] - [StringLength(255, MinimumLength = 1)] - public string Password { get; private set; } = Program.AppName; - - /// - /// Gets JWT options. - /// - [Validate] - public JwtOptions Jwt { get; private set; } = new JwtOptions(); - - /// - /// JWT options. - /// - public class JwtOptions - { - /// - /// Gets the key with which to sign JWTs. - /// - [Argument(default, "jwt-key")] - [EnvironmentVariable("JWT_KEY")] - [Description("JWT signing key")] - [StringLength(255, MinimumLength = 1)] - public string Key { get; private set; } = Guid.NewGuid().ToString(); - - /// - /// Gets the TTL for JWTs. - /// - [Argument(default, "jwt-ttl")] - [EnvironmentVariable("JWT_TTL")] - [Description("TTL for JWTs")] - [Range(3600, int.MaxValue)] - public int Ttl { get; private set; } = 604800000; - } - } - - /// - /// HTTPS options. - /// - public class HttpsOptions - { - /// - /// Gets the HTTPS listen port. - /// - [Argument('L', "https-port")] - [EnvironmentVariable("HTTPS_PORT")] - [Description("HTTPS listen port for web UI")] - [Range(1, 65535)] - public int Port { get; private set; } = 5001; - - /// - /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. - /// - [Argument('f', "force-https")] - [EnvironmentVariable("HTTPS_FORCE")] - [Description("redirect HTTP to HTTPS")] - public bool Force { get; private set; } = false; - - /// - /// Gets certificate options. - /// - [Validate] - public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); - - /// - /// Certificate options. - /// - [X509Certificate] - public class CertificateOptions - { - /// - /// Gets the path to the the X509 certificate .pfx file. - /// - [Argument(default, "https-cert-pfx")] - [EnvironmentVariable("HTTPS_CERT_PFX")] - [Description("path to X509 certificate .pfx")] - [FileExists] - public string Pfx { get; private set; } - - /// - /// Gets the password for the X509 certificate. - /// - [Argument(default, "https-cert-password")] - [EnvironmentVariable("HTTPS_CERT_PASSWORD")] - [Description("X509 certificate password")] - public string Password { get; private set; } - } - } - } - - /// - /// Options for external integrations. - /// - public class IntegrationOptions - { - /// - /// Gets FTP options. - /// - [Validate] - public FTPOptions FTP { get; private set; } = new FTPOptions(); - - /// - /// Gets Pushbullet options. - /// - [Validate] - public PushbulletOptions Pushbullet { get; private set; } = new PushbulletOptions(); - - /// - /// FTP options. - /// - public class FTPOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the FTP integration is enabled. - /// - [Argument(default, "ftp")] - [EnvironmentVariable("FTP_ENABLED")] - [Description("enable FTP integration")] - public bool Enabled { get; private set; } - - /// - /// Gets the FTP address. - /// - [Argument(default, "ftp-address")] - [EnvironmentVariable("FTP_ADDRESS")] - [Description("FTP address")] - public string Address { get; private set; } - - /// - /// Gets the FTP port. - /// - [Argument(default, "ftp-port")] - [EnvironmentVariable("FTP_PORT")] - [Description("FTP port")] - [Range(1, 65535)] - public int Port { get; private set; } = 21; - - /// - /// Gets the FTP encryption mode. - /// - [Argument(default, "ftp-encryption-mode")] - [EnvironmentVariable("FTP_ENCRYPTION_MODE")] - [Description("FTP encryption mode; none, implicit, explicit, auto")] - [Enum(typeof(FtpEncryptionMode))] - public string EncryptionMode { get; private set; } = "auto"; - - /// - /// Gets a value indicating whether FTP certificate errors should be ignored. - /// - [Argument(default, "ftp-ignore-certificate-errors")] - [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] - [Description("ignore FTP certificate errors")] - public bool IgnoreCertificateErrors { get; private set; } = false; - - /// - /// Gets the FTP username. - /// - [Argument(default, "ftp-username")] - [EnvironmentVariable("FTP_USERNAME")] - [Description("FTP username")] - public string Username { get; private set; } - - /// - /// Gets the FTP password. - /// - [Argument(default, "ftp-password")] - [EnvironmentVariable("FTP_PASSWORD")] - [Description("FTP password")] - public string Password { get; private set; } - - /// - /// Gets the remote path for uploads. - /// - [Argument(default, "ftp-remote-path")] - [EnvironmentVariable("FTP_REMOTE_PATH")] - [Description("remote path for FTP uploads")] - public string RemotePath { get; private set; } = "/"; - - /// - /// Gets a value indicating whether existing files should be overwritten. - /// - [Argument(default, "ftp-overwrite-existing")] - [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] - [Description("overwrite existing files when uploading to FTP")] - public bool OverwriteExisting { get; private set; } = true; - - /// - /// Gets the connection timeout value, in milliseconds. - /// - [Argument(default, "ftp-connection-timeout")] - [EnvironmentVariable("FTP_CONNECTION_TIMEOUT")] - [Description("FTP connection timeout, in milliseconds")] - [Range(0, int.MaxValue)] - public int ConnectionTimeout { get; private set; } = 5000; - - /// - /// Gets the number of times failing uploads will be retried. - /// - [Argument(default, "ftp-retry-attempts")] - [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] - [Description("number of times failing FTP uploads will be retried")] - [Range(0, 5)] - public int RetryAttempts { get; private set; } = 3; - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(Address)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); - } - - return results; - } - } - - /// - /// Pushbullet options. - /// - public class PushbulletOptions : IValidatableObject - { - /// - /// Gets a value indicating whether the Pushbullet integration is enabled. - /// - [Argument(default, "pushbullet")] - [EnvironmentVariable("PUSHBULLET_ENABLED")] - [Description("enable Pushbullet integration")] - public bool Enabled { get; private set; } = false; - - /// - /// Gets the Pushbullet API access token. - /// - [Argument(default, "pushbullet-token")] - [EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")] - [Description("Pushbullet access token")] - public string AccessToken { get; private set; } - - /// - /// Gets the prefix for Pushbullet notification titles. - /// - [Argument(default, "pushbullet-prefix")] - [EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")] - [Description("prefix for Pushbullet notification titles")] - public string NotificationPrefix { get; private set; } = "From slskd:"; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received. - /// - [Argument(default, "pushbullet-notify-on-pm")] - [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")] - [Description("send Pushbullet notifications when private messages are received")] - public bool NotifyOnPrivateMessage { get; private set; } = true; - - /// - /// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged - /// in user's username is mentioned in a room. - /// - [Argument(default, "pushbullet-notify-on-room-mention")] - [EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")] - [Description("send Pushbullet notifications when your username is mentioned in a room")] - public bool NotifyOnRoomMention { get; private set; } = true; - - /// - /// Gets the number of times failing Pushbullet notifications will be retried. - /// - [Argument(default, "pushbullet-retry-attempts")] - [EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")] - [Description("number of times failing Pushbullet notifications will be retried")] - [Range(0, 5)] - public int RetryAttempts { get; private set; } = 3; - - /// - /// Gets the cooldown time for Pushbullet notifications, in milliseconds. - /// - [Argument(default, "pushbullet-cooldown")] - [EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")] - [Description("cooldown time for Pushbullet notifications, in milliseconds")] - public int CooldownTime { get; private set; } = 900000; // 15 minutes - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (Enabled && string.IsNullOrWhiteSpace(AccessToken)) - { - results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified.")); - } - - return results; - } - } - } - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 01618efb..b83a9d8c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -119,8 +119,8 @@ namespace slskd /// public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; - private static IConfigurationRoot Configuration { get; set; } - private static Options Options { get; } = new Options(); + private static IConfigurationRoot ConfigurationRoot { get; set; } + private static Configuration Configuration { get; } = new Configuration(); [EnvironmentVariable("CONFIG")] [Argument('c', "config", "path to configuration file")] @@ -167,12 +167,12 @@ namespace slskd if (ShowHelp) { - PrintCommandLineArguments(typeof(Options)); + PrintCommandLineArguments(typeof(Configuration)); } if (ShowEnvironmentVariables) { - PrintEnvironmentVariables(typeof(Options), EnvironmentVariablePrefix); + PrintEnvironmentVariables(typeof(Configuration), EnvironmentVariablePrefix); } return; @@ -188,19 +188,19 @@ namespace slskd // with bootstrapping. try { - Configuration = new ConfigurationBuilder() + ConfigurationRoot = new ConfigurationBuilder() .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile) .Build(); - Configuration.GetSection(AppName) - .Bind(Options, (o) => { o.BindNonPublicProperties = true; }); + ConfigurationRoot.GetSection(AppName) + .Bind(Configuration, (o) => { o.BindNonPublicProperties = true; }); - if (Options.Debug) + if (Configuration.Debug) { - Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}"); + Console.WriteLine($"Configuration:\n{ConfigurationRoot.GetDebugView()}"); } - if (!Options.TryValidate(out var result)) + if (!Configuration.TryValidate(out var result)) { Console.WriteLine(result.GetResultView()); return; @@ -208,16 +208,16 @@ namespace slskd } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {(!Options.Debug ? ex : ex.Message)}"); + Console.WriteLine($"Invalid configuration: {(!Configuration.Debug ? ex : ex.Message)}"); return; } try { - VerifyOrCreateDirectory(Options.Directories.App); - VerifyOrCreateDirectory(Options.Directories.Incomplete); - VerifyOrCreateDirectory(Options.Directories.Downloads); - VerifyOrCreateDirectory(Options.Directories.Shared, verifyWriteable: false); + VerifyOrCreateDirectory(Configuration.Directories.App); + VerifyOrCreateDirectory(Configuration.Directories.Incomplete); + VerifyOrCreateDirectory(Configuration.Directories.Downloads); + VerifyOrCreateDirectory(Configuration.Directories.Shared, verifyWriteable: false); } catch (Exception ex) { @@ -225,31 +225,31 @@ namespace slskd return; } - Log.Logger = (Options.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + Log.Logger = (Configuration.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", Options.InstanceName) + .Enrich.WithProperty("InstanceName", Configuration.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( - outputTemplate: (Options.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + outputTemplate: (Configuration.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (Options.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (Configuration.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => !string.IsNullOrEmpty(Options.Logger.Loki), + e => !string.IsNullOrEmpty(Configuration.Logger.Loki), config => config.GrafanaLoki( - Options.Logger.Loki ?? string.Empty, + Configuration.Logger.Loki ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); var logger = Log.ForContext(typeof(Program)); - if (!Options.NoLogo) + if (!Configuration.NoLogo) { PrintLogo(Version); } @@ -260,18 +260,18 @@ namespace slskd } logger.Information("Version: {Version}", Version); - logger.Information("Instance Name: {InstanceName}", Options.InstanceName); + logger.Information("Instance Name: {InstanceName}", Configuration.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); - if (!string.IsNullOrEmpty(Options.Logger.Loki)) + if (!string.IsNullOrEmpty(Configuration.Logger.Loki)) { - logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Options.Logger.Loki); + logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Configuration.Logger.Loki); } try { - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } @@ -287,13 +287,13 @@ namespace slskd .UseUrls() .UseKestrel(options => { - logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Options.Web.Port}/"); - options.Listen(IPAddress.Any, Options.Web.Port); + logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Configuration.Web.Port}/"); + options.Listen(IPAddress.Any, Configuration.Web.Port); - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Options.Web.Https.Port}/"); - options.Listen(IPAddress.Any, Options.Web.Https.Port, listenOptions => + logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Configuration.Web.Https.Port}/"); + options.Listen(IPAddress.Any, Configuration.Web.Https.Port, listenOptions => { - var cert = Options.Web.Https.Certificate; + var cert = Configuration.Web.Https.Certificate; if (!string.IsNullOrEmpty(cert.Pfx)) { @@ -310,7 +310,7 @@ namespace slskd .UseStartup() .Build(); - if (Options.NoStart) + if (Configuration.NoStart) { logger.Information("Qutting because 'no-start' option is enabled"); return; @@ -334,18 +334,18 @@ namespace slskd return builder .AddDefaultValues( - targetType: typeof(Options)) + targetType: typeof(Configuration)) .AddEnvironmentVariables( - targetType: typeof(Options), + targetType: typeof(Configuration), prefix: environmentVariablePrefix) .AddYamlFile( path: Path.GetFileName(configurationFile), - targetType: typeof(Options), + targetType: typeof(Configuration), optional: true, reloadOnChange: false, provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory .AddCommandLine( - targetType: typeof(Options), + targetType: typeof(Configuration), commandLine: Environment.CommandLine); } diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 635a6890..07216937 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -51,29 +51,29 @@ namespace slskd /// /// Initializes a new instance of the class. /// - /// The application configuration. - public Startup(IConfiguration configuration) + /// The application configuration root. + public Startup(IConfiguration configurationRoot) { - Configuration = configuration; + ConfigurationRoot = configurationRoot; - Options = new Options(); - Configuration.GetSection(Program.AppName).Bind(Options, (o) => + Configuration = new Configuration(); + ConfigurationRoot.GetSection(Program.AppName).Bind(Configuration, (o) => { o.BindNonPublicProperties = true; }); - UrlBase = Options.Web.UrlBase; + UrlBase = Configuration.Web.UrlBase; UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - ContentPath = Path.GetFullPath(Options.Web.ContentPath); + ContentPath = Path.GetFullPath(Configuration.Web.ContentPath); - JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Options.Web.Authentication.Jwt.Key)); + JwtSigningKey = new SymmetricSecurityKey(Pbkdf2.GetKey(Configuration.Web.Authentication.Jwt.Key)); } - private IConfiguration Configuration { get; } + private IConfiguration ConfigurationRoot { get; } private string ContentPath { get; set; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; } + private Configuration Configuration { get; } private string UrlBase { get; set; } /// @@ -84,14 +84,14 @@ namespace slskd { var logger = Log.ForContext(); - services.AddOptions() - .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); + services.AddOptions() + .Bind(ConfigurationRoot.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }); services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddSingleton(JwtSigningKey); - if (!Options.Web.Authentication.Disable) + if (!Configuration.Web.Authentication.Disable) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => @@ -139,7 +139,7 @@ namespace slskd options.SubstituteApiVersionInUrl = true; }); - if (Options.Feature.Swagger) + if (Configuration.Feature.Swagger) { services.AddSwaggerGen(options => { @@ -163,19 +163,19 @@ namespace slskd }); } - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { services.AddSystemMetrics(); } services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Configuration.Directories.App, "search.db")}"); }); services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(Options.Directories.App, "peer.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Configuration.Directories.App, "peer.db")}"); }); services.AddHttpClient(); @@ -185,7 +185,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton(_ => - new SharedFileCache(Options.Directories.Shared, 3600000)); + new SharedFileCache(Configuration.Directories.Shared, 3600000)); services.AddSingleton(); services.AddSingleton(); @@ -213,7 +213,7 @@ namespace slskd app.UseCors("AllowAll"); - if (Options.Web.Https.Force) + if (Configuration.Web.Https.Force) { app.UseHttpsRedirection(); app.UseHsts(); @@ -258,7 +258,7 @@ namespace slskd logger.Information("Serving static content from {ContentPath}", ContentPath); } - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { app.UseHttpMetrics(); logger.Information("Publishing Prometheus metrics to /metrics"); @@ -275,13 +275,13 @@ namespace slskd endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); - if (Options.Feature.Prometheus) + if (Configuration.Feature.Prometheus) { endpoints.MapMetrics(); } }); - if (Options.Feature.Swagger) + if (Configuration.Feature.Swagger) { app.UseSwagger(); app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList() -- cgit v1.2.3 From e05b98574e6da694924163674353f836fcafb180 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jul 2021 08:14:14 -0500 Subject: fix bug restarting app --- .../Application/Management/API/Controllers/ApplicationController.cs | 4 ---- 1 file changed, 4 deletions(-) (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs index f0121af9..ddac832a 100644 --- a/src/slskd/Application/Management/API/Controllers/ApplicationController.cs +++ b/src/slskd/Application/Management/API/Controllers/ApplicationController.cs @@ -51,8 +51,6 @@ namespace slskd.Management.API [Authorize] public IActionResult Shutdown() { - Client.Disconnect("Shut down via API"); - Lifetime.StopApplication(); return NoContent(); } @@ -65,8 +63,6 @@ namespace slskd.Management.API [Authorize] public IActionResult Restart() { - Client.Disconnect("Restarted via API"); - Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); Lifetime.StopApplication(); -- cgit v1.2.3 From 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/Application/Management/API/Controllers') 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 d1637bafbff1d9cbf64bb8702ed48513b7edfcc6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 13 Jul 2021 18:14:02 -0500 Subject: use startup options --- src/slskd/Application/Management/API/Controllers/SessionController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 09a95c24..511643a6 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,10 +37,10 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Microsoft.Extensions.Options.IOptionsSnapshot optionsSnapshot, + Options optionsSnapshotAtStartup, SymmetricSecurityKey jwtSigningKey) { - Options = optionsSnapshot.Value; + Options = optionsSnapshotAtStartup; JwtSigningKey = jwtSigningKey; } -- cgit v1.2.3 From c10a01c6d58ca71ec629d08998bea47698a1d3c2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 14 Jul 2021 08:33:45 -0500 Subject: add endpoint to retrieve startup options --- .../API/Controllers/OptionsController.cs | 28 ++++++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index b75adc97..7bc93724 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Management.API { using Microsoft.AspNetCore.Authorization; @@ -30,13 +32,16 @@ namespace slskd.Management.API [Consumes("application/json")] public class OptionsController : ControllerBase { - public OptionsController(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + public OptionsController( + Options optionsSnapshotAtStartup, + IOptionsMonitor optionsMonitor) { + OptionsSnapshotAtStartup = optionsSnapshotAtStartup; OptionsMonitor = optionsMonitor; } - private Microsoft.Extensions.Options.IOptionsMonitor OptionsMonitor { get; } - private Options Options => OptionsMonitor.CurrentValue; + private IOptionsMonitor OptionsMonitor { get; } + private Options OptionsSnapshotAtStartup { get; } /// /// Gets the current application options. @@ -45,9 +50,22 @@ namespace slskd.Management.API [HttpGet] [Authorize] [ProducesResponseType(typeof(Options), 200)] - public IActionResult Get() + public IActionResult Current() + { + return Ok(OptionsMonitor.CurrentValue); + } + + /// + /// Gets the application options provided at startup. + /// + /// + [HttpGet] + [Route("startup")] + [Authorize] + [ProducesResponseType(typeof(Options), 200)] + public IActionResult Startup() { - return Ok(Options); + return Ok(OptionsSnapshotAtStartup); } } } -- cgit v1.2.3 From 2c772284155b99cbe16707e8f990466a868c3af6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 16 Jul 2021 08:10:31 -0500 Subject: inject OptionsAtStartup --- .../Management/API/Controllers/OptionsController.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/OptionsController.cs b/src/slskd/Application/Management/API/Controllers/OptionsController.cs index 7bc93724..6f6275d1 100644 --- a/src/slskd/Application/Management/API/Controllers/OptionsController.cs +++ b/src/slskd/Application/Management/API/Controllers/OptionsController.cs @@ -33,15 +33,15 @@ namespace slskd.Management.API public class OptionsController : ControllerBase { public OptionsController( - Options optionsSnapshotAtStartup, - IOptionsMonitor optionsMonitor) + OptionsAtStartup optionsAtStartup, + IOptionsSnapshot optionsSnapshot) { - OptionsSnapshotAtStartup = optionsSnapshotAtStartup; - OptionsMonitor = optionsMonitor; + OptionsAtStartup = optionsAtStartup; + OptionsSnapshot = optionsSnapshot; } - private IOptionsMonitor OptionsMonitor { get; } - private Options OptionsSnapshotAtStartup { get; } + private IOptionsSnapshot OptionsSnapshot { get; } + private OptionsAtStartup OptionsAtStartup { get; } /// /// Gets the current application options. @@ -52,7 +52,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(Options), 200)] public IActionResult Current() { - return Ok(OptionsMonitor.CurrentValue); + return Ok(OptionsSnapshot.Value); } /// @@ -65,7 +65,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(Options), 200)] public IActionResult Startup() { - return Ok(OptionsSnapshotAtStartup); + return Ok(OptionsAtStartup); } } } -- cgit v1.2.3 From 98c2f99198ecc48f8d4d0de1342a455a844e6c44 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 13:21:59 -0500 Subject: use OptionsAtStartup --- .../Management/API/Controllers/SessionController.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 511643a6..442970b9 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -37,15 +37,15 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( - Options optionsSnapshotAtStartup, + OptionsAtStartup optionsAtStartup, SymmetricSecurityKey jwtSigningKey) { - Options = optionsSnapshotAtStartup; + OptionsAtStartup = optionsAtStartup; JwtSigningKey = jwtSigningKey; } private SymmetricSecurityKey JwtSigningKey { get; set; } - private Options Options { get; set; } + private OptionsAtStartup OptionsAtStartup { get; set; } /// /// Checks whether the provided authentication is valid. @@ -75,7 +75,7 @@ namespace slskd.Management.API [ProducesResponseType(typeof(bool), 200)] public IActionResult Enabled() { - return Ok(!Options.Web.Authentication.Disable); + return Ok(!OptionsAtStartup.Web.Authentication.Disable); } /// @@ -106,7 +106,7 @@ namespace slskd.Management.API } // only admin login for now - if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password) + if (OptionsAtStartup.Web.Authentication.Username == login.Username && OptionsAtStartup.Web.Authentication.Password == login.Password) { return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); } @@ -117,7 +117,7 @@ namespace slskd.Management.API private JwtSecurityToken GetJwtSecurityToken(string username, Role role) { var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl); + var expiresUtc = DateTime.UtcNow.AddMilliseconds(OptionsAtStartup.Web.Authentication.Jwt.Ttl); var claims = new List() { -- cgit v1.2.3 From f210cb335277b17a18ca01591223adad53e60e2d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jul 2021 13:25:17 -0500 Subject: allow web un/pw to be changed at runtime --- .../Application/Management/API/Controllers/SessionController.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src/slskd/Application/Management/API/Controllers') diff --git a/src/slskd/Application/Management/API/Controllers/SessionController.cs b/src/slskd/Application/Management/API/Controllers/SessionController.cs index 442970b9..02e8257e 100644 --- a/src/slskd/Application/Management/API/Controllers/SessionController.cs +++ b/src/slskd/Application/Management/API/Controllers/SessionController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Management.API { using System; @@ -37,14 +39,17 @@ namespace slskd.Management.API public class SessionController : ControllerBase { public SessionController( + IOptionsSnapshot optionsSnapshot, OptionsAtStartup optionsAtStartup, SymmetricSecurityKey jwtSigningKey) { + OptionsSnapshot = optionsSnapshot; OptionsAtStartup = optionsAtStartup; JwtSigningKey = jwtSigningKey; } private SymmetricSecurityKey JwtSigningKey { get; set; } + private IOptionsSnapshot OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } /// @@ -106,7 +111,7 @@ namespace slskd.Management.API } // only admin login for now - if (OptionsAtStartup.Web.Authentication.Username == login.Username && OptionsAtStartup.Web.Authentication.Password == login.Password) + if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password) { return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); } -- cgit v1.2.3