From c06c1d31d6b39d9e02b240995fbd15beb6ef3e7e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 19:00:31 -0600 Subject: move example config --- src/slskd/Properties/slskd.yml | 82 ------------------------------------------ src/slskd/slskd.csproj | 4 +-- 2 files changed, 2 insertions(+), 84 deletions(-) delete mode 100644 src/slskd/Properties/slskd.yml (limited to 'src') diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml deleted file mode 100644 index b8450d35..00000000 --- a/src/slskd/Properties/slskd.yml +++ /dev/null @@ -1,82 +0,0 @@ -# debug: false -# no_logo: false -# no_start: false -# no_connect: false -# no_share_scan: false -# no_version_check: false -# instance_name: default -# directories: -# app: ~ -# incomplete: ~ -# downloads: ~ -# shared: -# - ~ -# filters: -# share: -# - \.ini$ -# - Thumbs.db$ -# - \.DS_Store$ -# web: -# port: 5000 -# https: -# port: 5001 -# force: false -# certificate: -# pfx: ~ -# password: ~ -# url_base: / -# content_path: wwwroot -# authentication: -# disable: false -# username: slskd -# password: slskd -# jwt: -# key: ~ -# ttl: 604800000 -# logger: -# loki: ~ -# feature: -# prometheus: false -# swagger: false -# soulseek: -# username: ~ -# password: ~ -# listen_port: 50000 -# diagnostic_level: Info -# distributed_network: -# disabled: false -# child_limit: 25 -# connection: -# timeout: -# connect: 10000 -# inactivity: 15000 -# buffer: -# read: 16384 -# write: 16384 -# proxy: -# enabled: false -# address: ~ -# port: ~ -# username: ~ -# password: ~ -# integration: -# ftp: -# enabled: false -# address: ~ -# port: ~ -# encryption_mode: auto -# ignore_certificate_errors: false -# username: ~ -# password: ~ -# remote_path: / -# overwrite_existing: true -# connection_timeout: 5000 -# retry_attempts: 3 -# pushbullet: -# enabled: false -# access_token: ~ -# notification_prefix: "From slskd:" -# notify_on_private_message: true -# notify_on_room_mention: true -# retry_attempts: 3 -# cooldown_time: 900000 \ No newline at end of file diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 4c33e6f0..124238e4 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -32,12 +32,12 @@ - + - + -- cgit v1.2.3 From 583c8d351677a7f0e9b8129eece6f21e6b3ab1cf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 19:02:53 -0600 Subject: verify app directories --- src/slskd/Program.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index edecf4e8..db0f58b5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -230,6 +230,10 @@ namespace slskd try { VerifyDirectory(OptionsAtStartup.Directories.App, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "config"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "data"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "files"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(OptionsAtStartup.Directories.Incomplete, createIfMissing: true, verifyWriteable: true); VerifyDirectory(OptionsAtStartup.Directories.Downloads, createIfMissing: true, verifyWriteable: true); } -- cgit v1.2.3 From c62bb64823237ea7b413ff6e0b734e0eca30a870 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 19:36:27 -0600 Subject: copy example config to app dir --- src/slskd/Program.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index db0f58b5..f649ce40 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -61,7 +61,7 @@ namespace slskd /// /// The default configuration filename. /// - public static readonly string DefaultConfigurationFile = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.yml"); + public static readonly string DefaultConfigurationFile = Path.Combine(DefaultAppDirectory, $"{AppName}.yml"); /// /// The default incomplete download directory. @@ -230,9 +230,7 @@ namespace slskd try { VerifyDirectory(OptionsAtStartup.Directories.App, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "config"), createIfMissing: true, verifyWriteable: true); VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "data"), createIfMissing: true, verifyWriteable: true); - VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "files"), createIfMissing: true, verifyWriteable: true); VerifyDirectory(OptionsAtStartup.Directories.Incomplete, createIfMissing: true, verifyWriteable: true); VerifyDirectory(OptionsAtStartup.Directories.Downloads, createIfMissing: true, verifyWriteable: true); @@ -243,6 +241,20 @@ namespace slskd return; } + try + { + // for convenience, try to copy the example configuration file to the application directory + // if any part fails, just move on silently. + var exampleFileName = $"{AppName}.example.yml"; + var source = Path.Combine(AppContext.BaseDirectory, "config", exampleFileName); + var destination = Path.Combine(OptionsAtStartup.Directories.App, exampleFileName); + File.Copy(source, destination); + } + catch + { + // no-op + } + Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) -- cgit v1.2.3 From 61d2a0e2c1efe74e8e14ea867b30b3b948b3cd94 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 19:36:39 -0600 Subject: create .db files in /data/ --- src/slskd/Startup.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 0ac5c437..5e8cfb7b 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -218,12 +218,12 @@ namespace slskd services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "data", "search.db")}"); }); services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "users.db")}"); + options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "data", "users.db")}"); }); services.AddHttpClient(); -- cgit v1.2.3 From a56d632c01549af144041162763a8dae379b3a92 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 21:06:26 -0600 Subject: remove config option, move AppDir to top level --- config/slskd.example.yml | 1 - src/slskd/Options.cs | 21 ++++++--------------- 2 files changed, 6 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index b8450d35..643911e2 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -6,7 +6,6 @@ # no_version_check: false # instance_name: default # directories: -# app: ~ # incomplete: ~ # downloads: ~ # shared: diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 83844551..875b3e69 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -119,13 +119,14 @@ namespace slskd public bool GenerateCertificate { get; private set; } = false; /// - /// Gets the path to the application configuration file. + /// Gets the path where application data is saved. /// - [Argument('c', "config")] - [EnvironmentVariable("CONFIG")] - [Description("path to configuration file")] + [Argument(default, "appdir")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] [Obsolete("Used only for documentation; see Program for actual implementation")] - public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile; + public string AppDirectory { get; private set; } = Program.DefaultAppDirectory; + /// /// Gets a value indicating whether the application should run in debug mode. @@ -248,16 +249,6 @@ namespace slskd /// public class DirectoriesOptions : IValidatableObject { - /// - /// Gets the path where application data is saved. - /// - [Argument(default, "app")] - [EnvironmentVariable("APP_DIR")] - [Description("path where application data is saved")] - [DirectoryExists] - [RequiresRestart] - public string App { get; private set; } = Program.DefaultAppDirectory; - /// /// Gets the path where incomplete downloads are saved. /// -- cgit v1.2.3 From ca8fe2230ae16b6d507e6a0adeaf7c4807453e24 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 21:06:48 -0600 Subject: swap config option for AppDir --- src/slskd/Program.cs | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f649ce40..e4c15704 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -58,20 +58,15 @@ namespace slskd /// public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), AppName); - /// - /// The default configuration filename. - /// - public static readonly string DefaultConfigurationFile = Path.Combine(DefaultAppDirectory, $"{AppName}.yml"); - /// /// The default incomplete download directory. /// - public static readonly string DefaultIncompleteDirectory = Path.Combine(DefaultAppDirectory, "incomplete"); + public static string DefaultIncompleteDirectory => Path.Combine(AppDirectory, "incomplete"); /// /// The default downloads directory. /// - public static readonly string DefaultDownloadsDirectory = Path.Combine(DefaultAppDirectory, "downloads"); + public static string DefaultDownloadsDirectory => Path.Combine(AppDirectory, "downloads"); /// /// The global prefix for environment variables. @@ -93,6 +88,13 @@ namespace slskd /// public static event EventHandler LogEmitted; + /// + /// Gets the path where application data is saved. + /// + [Argument(default, "appdir", "path where application data is saved")] + [EnvironmentVariable("APP_DIR")] + public static string AppDirectory { get; private set; } = DefaultAppDirectory; + /// /// Gets the assembly version of the application. /// @@ -135,11 +137,9 @@ namespace slskd public static ConcurrentFixedSizeQueue LogBuffer { get; } = new ConcurrentFixedSizeQueue(size: 500); private static IConfigurationRoot Configuration { get; set; } + private static string ConfigurationFile => Path.Combine(AppDirectory, $"{AppName}.yml"); private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); - [EnvironmentVariable("CONFIG")] - [Argument('c', "config", "path to configuration file")] - private static string ConfigurationFile { get; set; } = DefaultConfigurationFile; [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -229,8 +229,8 @@ namespace slskd try { - VerifyDirectory(OptionsAtStartup.Directories.App, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(Path.Combine(OptionsAtStartup.Directories.App, "data"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(Path.Combine(AppDirectory, "data"), createIfMissing: true, verifyWriteable: true); VerifyDirectory(OptionsAtStartup.Directories.Incomplete, createIfMissing: true, verifyWriteable: true); VerifyDirectory(OptionsAtStartup.Directories.Downloads, createIfMissing: true, verifyWriteable: true); @@ -247,7 +247,7 @@ namespace slskd // if any part fails, just move on silently. var exampleFileName = $"{AppName}.example.yml"; var source = Path.Combine(AppContext.BaseDirectory, "config", exampleFileName); - var destination = Path.Combine(OptionsAtStartup.Directories.App, exampleFileName); + var destination = Path.Combine(AppDirectory, exampleFileName); File.Copy(source, destination); } catch @@ -268,7 +268,7 @@ namespace slskd outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.File( - Path.Combine(OptionsAtStartup.Directories.App, "logs", $"{AppName}-.log"), + Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( @@ -298,9 +298,9 @@ namespace slskd PrintLogo(Version); } - if (ConfigurationFile != DefaultConfigurationFile && !IOFile.Exists(ConfigurationFile)) + if (!IOFile.Exists(ConfigurationFile)) { - logger.Warning($"Specified configuration file '{ConfigurationFile}' could not be found and was not loaded."); + logger.Warning($"Configuration file '{ConfigurationFile}' could not be found and was not loaded."); } logger.Information("Version: {Version}", Version); -- cgit v1.2.3 From 7b2088171f56ff63f5892087cd10983f2686d95e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Nov 2021 21:07:00 -0600 Subject: reference AppDir at Program --- src/slskd/Startup.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 5e8cfb7b..98deac0d 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -218,12 +218,12 @@ namespace slskd services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "data", "search.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Program.AppDirectory, "data", "search.db")}"); }); services.AddDbContextFactory(options => { - options.UseSqlite($"Data Source={Path.Combine(OptionsAtStartup.Directories.App, "data", "users.db")}"); + options.UseSqlite($"Data Source={Path.Combine(Program.AppDirectory, "data", "users.db")}"); }); services.AddHttpClient(); -- cgit v1.2.3 From d0ef56835155e0c93393eee660297cddfb3f9cca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 8 Nov 2021 18:55:36 -0600 Subject: add ToYaml() --- src/slskd/Common/Extensions.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 30b35d14..03bec7fe 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -25,6 +25,8 @@ namespace slskd using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; + using YamlDotNet.Serialization; + using YamlDotNet.Serialization.NamingConventions; /// /// Extensions. @@ -213,6 +215,16 @@ namespace slskd /// A string containing the serialized object. public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions()); + /// + /// Serializes this object to yaml. + /// + /// The object to serialize. + /// A string containing the serialized object. + public static string ToYaml(this object obj) => new SerializerBuilder() + .WithNamingConvention(UnderscoredNamingConvention.Instance) + .Build() + .Serialize(obj); + /// /// Converts a fully qualified remote filename to a local filename based in the provided /// , swapping directory characters for those specific to the local OS, removing any -- cgit v1.2.3 From 7d936c12da1587961c22caf5dded805bcbba53de Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 8 Nov 2021 18:56:26 -0600 Subject: tweak options for yaml compatibility --- src/slskd/Integrations/FTP/FTPClientFactory.cs | 8 +++--- src/slskd/Integrations/FTP/FTPService.cs | 20 +++++++-------- src/slskd/Options.cs | 29 +++++++++++++--------- .../API/Controllers/TransfersController.cs | 2 +- 4 files changed, 32 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index e9ee0721..2e41ab03 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -37,7 +37,7 @@ namespace slskd.Integrations.FTP OptionsMonitor = optionsMonitor; } - private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP; + private FtpOptions FtpOptions => OptionsMonitor.CurrentValue.Integration.Ftp; private IOptionsMonitor OptionsMonitor { get; set; } /// @@ -46,9 +46,9 @@ namespace slskd.Integrations.FTP /// The created instance. public FtpClient CreateFtpClient() { - var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); - client.EncryptionMode = ParseFtpEncryptionMode(FTPOptions.EncryptionMode); - client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; + var client = new FtpClient(FtpOptions.Address, FtpOptions.Port, FtpOptions.Username, FtpOptions.Password); + client.EncryptionMode = ParseFtpEncryptionMode(FtpOptions.EncryptionMode); + client.ValidateAnyCertificate = FtpOptions.IgnoreCertificateErrors; return client; } diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index becf1a12..dd1b340f 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -49,7 +49,7 @@ namespace slskd.Integrations.FTP } private IFTPClientFactory Factory { get; set; } - private FTPOptions FTPOptions => OptionsMonitor.CurrentValue.Integration.FTP; + private FtpOptions FtpOptions => OptionsMonitor.CurrentValue.Integration.Ftp; private ILogger Log { get; set; } private IOptionsMonitor OptionsMonitor { get; } @@ -60,7 +60,7 @@ namespace slskd.Integrations.FTP /// The operation context. public async Task UploadAsync(string filename) { - if (!FTPOptions.Enabled) + if (!FtpOptions.Enabled) { Log.LogDebug("Skipping FTP upload of {filename}; FTP integration is disabled"); return; @@ -74,7 +74,7 @@ namespace slskd.Integrations.FTP task: () => AttemptUploadAsync(filename), isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => Log.LogInformation("Failed attempt {Attempts} to upload {Filename} to FTP: {Message}", attempts, fileAndParentDirectory, ex.Message), - maxAttempts: FTPOptions.RetryAttempts, + maxAttempts: FtpOptions.RetryAttempts, maxDelayInMilliseconds: 30000); } catch (RetryException ex) @@ -84,7 +84,7 @@ namespace slskd.Integrations.FTP } catch (Exception ex) { - Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FTPOptions.RetryAttempts, ex.Message); + Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FtpOptions.RetryAttempts, ex.Message); throw; } } @@ -92,15 +92,15 @@ namespace slskd.Integrations.FTP private async Task AttemptUploadAsync(string filename) { var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); - var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + var remotePath = FtpOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; - var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; + var existsMode = FtpOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; using var client = Factory.CreateFtpClient(); var timeoutTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); + using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FtpOptions.ConnectionTimeout)); using var timeoutCancellationTokenRegistration = timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); @@ -111,7 +111,7 @@ namespace slskd.Integrations.FTP if (completedTask == timeoutTaskCompletionSource.Task) { - throw new TimeoutException($"Failed to connect to server after {FTPOptions.ConnectionTimeout}ms"); + throw new TimeoutException($"Failed to connect to server after {FtpOptions.ConnectionTimeout}ms"); } if (connectTask.Exception != null) @@ -119,7 +119,7 @@ namespace slskd.Integrations.FTP throw connectTask.Exception; } - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); + Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FtpOptions.Address, FtpOptions.Port, remoteFilename); var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); if (status == FtpStatus.Failed) @@ -127,7 +127,7 @@ namespace slskd.Integrations.FTP throw new FtpException("FTP client reported a failed transfer"); } - Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); + Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FtpOptions.Address, FtpOptions.Port); } private string GetFileAndParentDirectoryFromFilename(string filename) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 875b3e69..71c341e9 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -34,6 +34,7 @@ namespace slskd using Soulseek.Diagnostics; using Utility.CommandLine; using Utility.EnvironmentVariables; + using YamlDotNet.Serialization; /// /// Disambiguates options derived at startup from options that may update at run time. @@ -92,6 +93,7 @@ namespace slskd [Argument('v', "version")] [Description("display version information")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool ShowVersion { get; private set; } = false; /// @@ -100,6 +102,7 @@ namespace slskd [Argument('h', "help")] [Description("display command line usage")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool ShowHelp { get; private set; } = false; /// @@ -108,6 +111,7 @@ namespace slskd [Argument('e', "envars")] [Description("display environment variables")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool ShowEnvironmentVariables { get; private set; } = false; /// @@ -116,18 +120,9 @@ namespace slskd [Argument('g', "generate-cert")] [Description("generate X509 certificate and password for HTTPs")] [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] public bool GenerateCertificate { get; private set; } = false; - /// - /// Gets the path where application data is saved. - /// - [Argument(default, "appdir")] - [EnvironmentVariable("APP_DIR")] - [Description("path where application data is saved")] - [Obsolete("Used only for documentation; see Program for actual implementation")] - public string AppDirectory { get; private set; } = Program.DefaultAppDirectory; - - /// /// Gets a value indicating whether the application should run in debug mode. /// @@ -191,6 +186,16 @@ namespace slskd [RequiresRestart] public string InstanceName { get; private set; } = "default"; + /// + /// Gets the path where application data is saved. + /// + [Argument(default, "app")] + [EnvironmentVariable("APP_DIR")] + [Description("path where application data is saved")] + [Obsolete("Used only for documentation; see Program for actual implementation")] + [YamlIgnore] + public string AppDirectory { get; private set; } = Program.DefaultAppDirectory; + /// /// Gets directory options. /// @@ -828,7 +833,7 @@ namespace slskd /// Gets FTP options. /// [Validate] - public FTPOptions FTP { get; private set; } = new FTPOptions(); + public FtpOptions Ftp { get; private set; } = new FtpOptions(); /// /// Gets Pushbullet options. @@ -839,7 +844,7 @@ namespace slskd /// /// FTP options. /// - public class FTPOptions : IValidatableObject + public class FtpOptions : IValidatableObject { /// /// Gets a value indicating whether the FTP integration is enabled. diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index b912bbda..12d6bfcf 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -137,7 +137,7 @@ namespace slskd.Transfers.API MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); - if (Options.Integration.FTP.Enabled) + if (Options.Integration.Ftp.Enabled) { _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); } -- cgit v1.2.3 From 80748ef499215a5b39532b9500b277494e1119be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 8 Nov 2021 18:57:05 -0600 Subject: wip --- src/slskd/Program.cs | 93 ++++++++++++++++++++++++++-------------------------- 1 file changed, 47 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e4c15704..3aba9ec3 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -54,46 +54,24 @@ namespace slskd public static readonly string AppName = "slskd"; /// - /// The default application data directory. - /// - public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), AppName); - - /// - /// The default incomplete download directory. - /// - public static string DefaultIncompleteDirectory => Path.Combine(AppDirectory, "incomplete"); - - /// - /// The default downloads directory. + /// The url to the issues/support site. /// - public static string DefaultDownloadsDirectory => Path.Combine(AppDirectory, "downloads"); + public static readonly string IssuesUrl = "https://github.com/slskd/slskd/issues"; /// /// The global prefix for environment variables. /// public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; - /// - /// The url to the issues/support site. - /// - public static readonly string IssuesUrl = "https://github.com/slskd/slskd/issues"; - /// /// The default XML documentation filename. /// public static readonly string XmlDocumentationFile = Path.Combine(AppContext.BaseDirectory, "etc", $"{AppName}.xml"); /// - /// Occurs when a new log event is emitted. - /// - public static event EventHandler LogEmitted; - - /// - /// Gets the path where application data is saved. + /// The default application data directory. /// - [Argument(default, "appdir", "path where application data is saved")] - [EnvironmentVariable("APP_DIR")] - public static string AppDirectory { get; private set; } = DefaultAppDirectory; + public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), AppName); /// /// Gets the assembly version of the application. @@ -101,7 +79,7 @@ namespace slskd /// /// Inaccurate when running locally. /// - public static Version AssemblyVersion { get; } = Assembly.GetExecutingAssembly().GetName().Version.Equals(new Version(1, 0, 0, 0)) ? new Version(0, 0, 0, 0) : Assembly.GetExecutingAssembly().GetName().Version; + public static readonly Version AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.Equals(new Version(1, 0, 0, 0)) ? new Version(0, 0, 0, 0) : Assembly.GetExecutingAssembly().GetName().Version; /// /// Gets the informational version of the application, including the git sha at the latest commit. @@ -109,27 +87,49 @@ namespace slskd /// /// Inaccurate when running locally. /// - public static string InformationalVersion { get; } = Assembly.GetExecutingAssembly().GetCustomAttribute().InformationalVersion == "1.0.0" ? "0.0.0" : Assembly.GetExecutingAssembly().GetCustomAttribute().InformationalVersion; + public static readonly string InformationalVersion = Assembly.GetExecutingAssembly().GetCustomAttribute().InformationalVersion == "1.0.0" ? "0.0.0" : Assembly.GetExecutingAssembly().GetCustomAttribute().InformationalVersion; + + /// + /// Gets the full application version, including both assembly and informational versions. + /// + public static readonly string Version = $"{AssemblyVersion} ({InformationalVersion})"; + + /// + /// Gets a value indicating whether the current version is a Canary build. + /// + public static readonly bool IsCanary = AssemblyVersion.Revision == 65534; /// /// Gets the unique Id of this application invocation. /// - public static Guid InvocationId { get; } = Guid.NewGuid(); + public static readonly Guid InvocationId = Guid.NewGuid(); /// /// Gets the Id of the current application process. /// - public static int ProcessId { get; } = Environment.ProcessId; + public static readonly int ProcessId = Environment.ProcessId; /// - /// Gets the full application version, including both assembly and informational versions. + /// Occurs when a new log event is emitted. /// - public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; + public static event EventHandler LogEmitted; /// - /// Gets a value indicating whether the current version is a Canary build. + /// Gets the path where application data is saved. + /// + [Argument(default, "app", "path where application data is saved")] + [EnvironmentVariable("APP_DIR")] + public static string AppDirectory { get; private set; } = DefaultAppDirectory; + + /// + /// Gets the default downloads directory. /// - public static bool IsCanary { get; } = AssemblyVersion.Revision == 65534; + public static string DefaultDownloadsDirectory => Path.Combine(AppDirectory, "downloads"); + + /// + /// Gets the default incomplete download directory. + /// + public static string DefaultIncompleteDirectory => Path.Combine(AppDirectory, "incomplete"); /// /// Gets a buffer containing the last few log events. @@ -140,7 +140,6 @@ namespace slskd private static string ConfigurationFile => Path.Combine(AppDirectory, $"{AppName}.yml"); private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); - [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -241,18 +240,20 @@ namespace slskd return; } - try - { - // for convenience, try to copy the example configuration file to the application directory - // if any part fails, just move on silently. - var exampleFileName = $"{AppName}.example.yml"; - var source = Path.Combine(AppContext.BaseDirectory, "config", exampleFileName); - var destination = Path.Combine(AppDirectory, exampleFileName); - File.Copy(source, destination); - } - catch + // for convenience, try to copy the example configuration file to the application directory if no configuration + // file exists. if any part fails, just move on silently. + if (!IOFile.Exists(ConfigurationFile)) { - // no-op + try + { + var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); + var destination = ConfigurationFile; + IOFile.Copy(source, destination); + } + catch + { + // no-op + } } Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) -- cgit v1.2.3 From 86f5e46c2dfe595d8a970cc2f9e49d2520f14b55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Nov 2021 08:52:59 -0600 Subject: verify directories before config --- src/slskd/Program.cs | 76 ++++++++++++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 38 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 3aba9ec3..2403dbbf 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -198,8 +198,23 @@ namespace slskd return; } - // the application isn't being run in command mode. load all configuration values and proceed - // with bootstrapping. + // the application isn't being run in command mode. verify (create if needed) default application + // directories. if the downloads or complete directories are overridden in config, those will be + // validated after the config is loaded. + try + { + VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(Path.Combine(AppDirectory, "data"), createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DefaultDownloadsDirectory, createIfMissing: true, verifyWriteable: true); + VerifyDirectory(DefaultIncompleteDirectory, createIfMissing: true, verifyWriteable: true); + } + catch (Exception ex) + { + Console.WriteLine($"Filesystem exception: {ex.Message}"); + return; + } + + // load and validate the configuration try { Configuration = new ConfigurationBuilder() @@ -226,36 +241,6 @@ namespace slskd return; } - try - { - VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(Path.Combine(AppDirectory, "data"), createIfMissing: true, verifyWriteable: true); - - VerifyDirectory(OptionsAtStartup.Directories.Incomplete, createIfMissing: true, verifyWriteable: true); - VerifyDirectory(OptionsAtStartup.Directories.Downloads, createIfMissing: true, verifyWriteable: true); - } - catch (Exception ex) - { - Console.WriteLine($"Filesystem exception: {ex.Message}"); - return; - } - - // for convenience, try to copy the example configuration file to the application directory if no configuration - // file exists. if any part fails, just move on silently. - if (!IOFile.Exists(ConfigurationFile)) - { - try - { - var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); - var destination = ConfigurationFile; - IOFile.Copy(source, destination); - } - catch - { - // no-op - } - } - Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) @@ -299,11 +284,6 @@ namespace slskd PrintLogo(Version); } - if (!IOFile.Exists(ConfigurationFile)) - { - logger.Warning($"Configuration file '{ConfigurationFile}' could not be found and was not loaded."); - } - logger.Information("Version: {Version}", Version); if (IsCanary) @@ -313,9 +293,29 @@ namespace slskd logger.Warning($"Please report any issues here: {IssuesUrl}"); } - logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); + logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); + + logger.Information("Using application directory {AppDirectory}", AppDirectory); + logger.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); + + // for convenience, try to copy the example configuration file to the application directory if no configuration + // file exists. if any part fails, just move on silently. + if (!IOFile.Exists(ConfigurationFile)) + { + try + { + logger.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", ConfigurationFile); + var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); + var destination = ConfigurationFile; + IOFile.Copy(source, destination); + } + catch (Exception ex) + { + logger.Error("Failed to create configuration file {ConfigurationFile}: {Message}", ConfigurationFile, ex.Message); + } + } if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { -- cgit v1.2.3