From 343712527943431dcb03e5d22293f77b8803b22a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 12:00:39 -0500 Subject: add EnumAttribute --- src/slskd/Common/Validation/EnumAttribute.cs | 47 ++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/slskd/Common/Validation/EnumAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/EnumAttribute.cs b/src/slskd/Common/Validation/EnumAttribute.cs new file mode 100644 index 00000000..ad9b393c --- /dev/null +++ b/src/slskd/Common/Validation/EnumAttribute.cs @@ -0,0 +1,47 @@ +// +// 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.Validation +{ + using System; + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the value is a valid nember of the specified . + /// + public class EnumAttribute : ValidationAttribute + { + public EnumAttribute(Type targetType, bool ignoreCase = true) + { + TargetType = targetType; + IgnoreCase = ignoreCase; + } + + private Type TargetType { get; set; } + private bool IgnoreCase { get; set; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + } + + return ValidationResult.Success; + } + } +} \ No newline at end of file -- cgit v1.2.3 From 949d158c07bd4ef595876725a509f0f71b3a5f10 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 12:04:48 -0500 Subject: add FTP options --- src/slskd/Options.cs | 75 ++++++++++++++++++++++++++++++++++++++++++ src/slskd/Properties/slskd.yml | 10 +++++- 2 files changed, 84 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 485619bc..73678df0 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -21,6 +21,7 @@ namespace slskd using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; + using FluentFTP; using slskd.Validation; using Soulseek.Diagnostics; using Utility.CommandLine; @@ -121,6 +122,12 @@ namespace slskd [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. /// @@ -547,5 +554,73 @@ namespace slskd } } } + + /// + /// Options for external integrations. + /// + public class IntegrationOptions + { + /// + /// Gets FTP options. + /// + [Validate] + public FTPOptions FTP { get; private set; } = new FTPOptions(); + + /// + /// FTP options. + /// + public class FTPOptions + { + /// + /// 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 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 number of times failing uploads will be retried. + /// + [Argument(default, "ftp-retry-attempts")] + [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] + [Description("The number of times failing uploads will be retried")] + public int RetryAttempts { get; private set; } = 5; + } + } } } \ No newline at end of file diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index ccfe60f9..492fb01c 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -48,4 +48,12 @@ # address: ~ # port: ~ # username: ~ -# password: ~ \ No newline at end of file +# password: ~ +# integration: +# ftp: +# address: ~ +# port: ~ +# encryption_mode: auto +# username: ~ +# password: ~ +# retry_attempts: 5 \ No newline at end of file -- cgit v1.2.3 From 9b6a378671ffcda6c42d4592d9e8cfddf50fb5f0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 12:04:58 -0500 Subject: disable casing rule --- src/slskd/Properties/analysis.ruleset | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset index d6a504ff..db01a09c 100644 --- a/src/slskd/Properties/analysis.ruleset +++ b/src/slskd/Properties/analysis.ruleset @@ -31,6 +31,7 @@ + -- cgit v1.2.3 From 7d3432f1e1b290cfafd007fea1372be968881301 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 12:05:11 -0500 Subject: add FluentFTP --- src/slskd/slskd.csproj | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 6ac3da83..c2873938 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -42,6 +42,7 @@ + -- cgit v1.2.3 From 5a663143c92215262f02aa40eae9b36b32c26ff2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 12:05:52 -0500 Subject: stub FTPService --- src/slskd/Integrations/FTP/FTPService.cs | 61 +++++++++++++++++++++++++++++++ src/slskd/Integrations/FTP/IFTPService.cs | 26 +++++++++++++ src/slskd/Startup.cs | 2 + 3 files changed, 89 insertions(+) create mode 100644 src/slskd/Integrations/FTP/FTPService.cs create mode 100644 src/slskd/Integrations/FTP/IFTPService.cs (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs new file mode 100644 index 00000000..b704063c --- /dev/null +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -0,0 +1,61 @@ +// +// 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.Integrations.FTP +{ + using System; + using System.Threading.Tasks; + using FluentFTP; + using Microsoft.Extensions.Logging; + using static slskd.Options.IntegrationOptions; + + public class FTPService : IFTPService + { + public FTPService( + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + ILogger log) + { + Options = optionsMonitor.CurrentValue; + Log = log; + + FtpEncryptionMode encryptionMode; + + try + { + encryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); + } + catch (Exception ex) + { + // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. + throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); + } + + Client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); + Client.EncryptionMode = encryptionMode; + } + + private Options Options { get; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private ILogger Log { get; set; } + private FtpClient Client { get; set; } + + public Task UploadAsync(string filename) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/slskd/Integrations/FTP/IFTPService.cs b/src/slskd/Integrations/FTP/IFTPService.cs new file mode 100644 index 00000000..11c12073 --- /dev/null +++ b/src/slskd/Integrations/FTP/IFTPService.cs @@ -0,0 +1,26 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Integrations.FTP +{ + using System.Threading.Tasks; + + public interface IFTPService + { + Task UploadAsync(string filename); + } +} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index dd44fd87..ddf2f637 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -35,6 +35,7 @@ namespace slskd using Serilog; using slskd.Authentication; using slskd.Cryptography; + using slskd.Integrations.FTP; using slskd.Management; using slskd.Messaging; using slskd.Peer; @@ -186,6 +187,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddHostedService(); services.AddSingleton(_ => Service.SoulseekClient); -- cgit v1.2.3 From 7cd62baa4501b9dbedfee2f13d5902555116a587 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 18:18:20 -0500 Subject: add additional FTP options --- src/slskd/Options.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 73678df0..0993fa12 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -613,12 +613,28 @@ namespace slskd [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 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")] + public bool OverwriteExisting { get; private set; } = true; + /// /// Gets the number of times failing uploads will be retried. /// [Argument(default, "ftp-retry-attempts")] [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] - [Description("The number of times failing uploads will be retried")] + [Description("number of times failing uploads will be retried")] public int RetryAttempts { get; private set; } = 5; } } -- cgit v1.2.3 From 9035870600587b6bf2c689e148d2f5c77e85a9e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 18:19:35 -0500 Subject: implement upload --- .../API/Controllers/TransfersController.cs | 12 ++- src/slskd/Integrations/FTP/FTPClient.cs | 105 +++++++++++++++++++++ src/slskd/Integrations/FTP/FTPClientFactory.cs | 53 +++++++++++ src/slskd/Integrations/FTP/FTPService.cs | 61 ------------ src/slskd/Integrations/FTP/IFTPClient.cs | 27 ++++++ src/slskd/Integrations/FTP/IFTPClientFactory.cs | 26 +++++ src/slskd/Integrations/FTP/IFTPService.cs | 26 ----- src/slskd/Startup.cs | 4 +- 8 files changed, 225 insertions(+), 89 deletions(-) create mode 100644 src/slskd/Integrations/FTP/FTPClient.cs create mode 100644 src/slskd/Integrations/FTP/FTPClientFactory.cs delete mode 100644 src/slskd/Integrations/FTP/FTPService.cs create mode 100644 src/slskd/Integrations/FTP/IFTPClient.cs create mode 100644 src/slskd/Integrations/FTP/IFTPClientFactory.cs delete mode 100644 src/slskd/Integrations/FTP/IFTPService.cs (limited to 'src') diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index f7274157..8131aa8c 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -25,6 +25,7 @@ namespace slskd.Transfer.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using slskd.Integrations.FTP; using Soulseek; /// @@ -43,19 +44,23 @@ namespace slskd.Transfer.API /// /// /// + /// public TransfersController( Microsoft.Extensions.Options.IOptionsSnapshot options, ISoulseekClient client, - ITransferTracker tracker) + ITransferTracker tracker, + IFTPClient ftpClient) { Client = client; Tracker = tracker; Options = options.Value; + FTP = ftpClient; } private Options Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } + private IFTPClient FTP { get; } /// /// Cancels the specified download. @@ -129,6 +134,11 @@ namespace slskd.Transfer.API }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token); MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); + + if (FTP.Enabled) + { + _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); + } }); // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the diff --git a/src/slskd/Integrations/FTP/FTPClient.cs b/src/slskd/Integrations/FTP/FTPClient.cs new file mode 100644 index 00000000..6f23ffc6 --- /dev/null +++ b/src/slskd/Integrations/FTP/FTPClient.cs @@ -0,0 +1,105 @@ +// +// 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.Integrations.FTP +{ + using System; + using System.IO; + using System.Threading.Tasks; + using FluentFTP; + using Microsoft.Extensions.Logging; + using static slskd.Options.IntegrationOptions; + + public class FTPClient : IFTPClient + { + public FTPClient( + IFTPClientFactory ftpClientFactory, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + ILogger log) + { + Factory = ftpClientFactory; + Options = optionsMonitor.CurrentValue; + Log = log; + + try + { + EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); + } + catch (Exception ex) + { + // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. + throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); + } + } + + public bool Enabled => !string.IsNullOrEmpty(Options.Integration.FTP.Address); + + private Options Options { get; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private ILogger Log { get; set; } + private IFTPClientFactory Factory { get; set; } + private FtpEncryptionMode EncryptionMode { get; set; } + + public FtpClient CreateFtpClient() + { + var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); + client.EncryptionMode = EncryptionMode; + + return client; + } + + public async Task UploadAsync(string filename) + { + if (!Enabled) + { + Log.LogDebug("Skipping FTP upload of {filename}; FTP integration is disabled"); + return; + } + + try + { + var fileOnly = Path.GetFileName(filename); + var fileAndParentDirectory = Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); + + var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; + + var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; + + using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read); + + Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); + var client = Factory.CreateFtpClient(); + await client.ConnectAsync(); + var status = await client.UploadAsync(stream, remoteFilename, existsMode, createRemoteDir: true); + + if (status == FtpStatus.Failed) + { + throw new FtpException("FTP client reported a failed transfer"); + } + + Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); + Console.WriteLine($"========================DONE: {filename}, {status}"); + } + catch (Exception ex) + { + Log.LogWarning(ex, "Failed to upload {Filename} to FTP: {Message}", ex.Message); + throw; + } + } + } +} diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs new file mode 100644 index 00000000..887623a2 --- /dev/null +++ b/src/slskd/Integrations/FTP/FTPClientFactory.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.Integrations.FTP +{ + using System; + using FluentFTP; + using static slskd.Options.IntegrationOptions; + + public class FTPClientFactory : IFTPClientFactory + { + public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) + { + Options = optionsMonitor.CurrentValue; + + try + { + EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); + } + catch (Exception ex) + { + // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. + throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); + } + } + + private Options Options { get; set; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private FtpEncryptionMode EncryptionMode { get; set; } + + public FtpClient CreateFtpClient() + { + var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); + client.EncryptionMode = EncryptionMode; + + return client; + } + } +} diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs deleted file mode 100644 index b704063c..00000000 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ /dev/null @@ -1,61 +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.Integrations.FTP -{ - using System; - using System.Threading.Tasks; - using FluentFTP; - using Microsoft.Extensions.Logging; - using static slskd.Options.IntegrationOptions; - - public class FTPService : IFTPService - { - public FTPService( - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, - ILogger log) - { - Options = optionsMonitor.CurrentValue; - Log = log; - - FtpEncryptionMode encryptionMode; - - try - { - encryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); - } - catch (Exception ex) - { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. - throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); - } - - Client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); - Client.EncryptionMode = encryptionMode; - } - - private Options Options { get; } - private FTPOptions FTPOptions => Options.Integration.FTP; - private ILogger Log { get; set; } - private FtpClient Client { get; set; } - - public Task UploadAsync(string filename) - { - throw new NotImplementedException(); - } - } -} diff --git a/src/slskd/Integrations/FTP/IFTPClient.cs b/src/slskd/Integrations/FTP/IFTPClient.cs new file mode 100644 index 00000000..b556ea3b --- /dev/null +++ b/src/slskd/Integrations/FTP/IFTPClient.cs @@ -0,0 +1,27 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Integrations.FTP +{ + using System.Threading.Tasks; + + public interface IFTPClient + { + Task UploadAsync(string filename); + bool Enabled { get; } + } +} diff --git a/src/slskd/Integrations/FTP/IFTPClientFactory.cs b/src/slskd/Integrations/FTP/IFTPClientFactory.cs new file mode 100644 index 00000000..760db612 --- /dev/null +++ b/src/slskd/Integrations/FTP/IFTPClientFactory.cs @@ -0,0 +1,26 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Integrations.FTP +{ + using FluentFTP; + + public interface IFTPClientFactory + { + public FtpClient CreateFtpClient(); + } +} diff --git a/src/slskd/Integrations/FTP/IFTPService.cs b/src/slskd/Integrations/FTP/IFTPService.cs deleted file mode 100644 index 11c12073..00000000 --- a/src/slskd/Integrations/FTP/IFTPService.cs +++ /dev/null @@ -1,26 +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.Integrations.FTP -{ - using System.Threading.Tasks; - - public interface IFTPService - { - Task UploadAsync(string filename); - } -} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index ddf2f637..f802a56a 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -187,7 +187,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + + services.AddSingleton(); + services.AddTransient(); services.AddHostedService(); services.AddSingleton(_ => Service.SoulseekClient); -- cgit v1.2.3 From 49b4b712e59e1591f636201988e45b3ff87c2406 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 18:34:19 -0500 Subject: use UploadFileAsync --- src/slskd/Integrations/FTP/FTPClient.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClient.cs b/src/slskd/Integrations/FTP/FTPClient.cs index 6f23ffc6..e6a748a9 100644 --- a/src/slskd/Integrations/FTP/FTPClient.cs +++ b/src/slskd/Integrations/FTP/FTPClient.cs @@ -70,22 +70,25 @@ namespace slskd.Integrations.FTP return; } + // todo: add retries up to configured count with exponential backoff try { var fileOnly = Path.GetFileName(filename); var fileAndParentDirectory = Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + // todo: sanitize filename var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; - using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read); - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); var client = Factory.CreateFtpClient(); + + // todo: add cancellation token for timeout await client.ConnectAsync(); - var status = await client.UploadAsync(stream, remoteFilename, existsMode, createRemoteDir: true); + + var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); if (status == FtpStatus.Failed) { @@ -93,7 +96,6 @@ namespace slskd.Integrations.FTP } Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); - Console.WriteLine($"========================DONE: {filename}, {status}"); } catch (Exception ex) { -- cgit v1.2.3 From 695ec2a026efe87423cce1f3a6c737fac82a9cf0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Jun 2021 08:44:02 -0500 Subject: stub Retry lib --- src/slskd/Common/Retry.cs | 73 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/slskd/Common/Retry.cs (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs new file mode 100644 index 00000000..c0e1bd83 --- /dev/null +++ b/src/slskd/Common/Retry.cs @@ -0,0 +1,73 @@ +// +// 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.Threading.Tasks; + + public class Retry + { + public static async Task Do(Func task, TimeSpan retryInterval, int maxAttemptCount = 3) + { + var exceptions = new List(); + for (int attempted = 0; attempted < maxAttemptCount; attempted++) + { + try + { + if (attempted > 0) + { + await Task.Delay(retryInterval); + } + + await task(); + return; + } + catch (Exception ex) + { + exceptions.Add(ex); + } + } + + throw new AggregateException(exceptions); + } + + public static async Task Do(Func> task, TimeSpan retryInterval, int maxAttemptCount = 3) + { + var exceptions = new List(); + for (int attempted = 0; attempted < maxAttemptCount; attempted++) + { + try + { + if (attempted > 0) + { + await Task.Delay(retryInterval); + } + + return await task(); + } + catch (Exception ex) + { + exceptions.Add(ex); + } + } + + throw new AggregateException(exceptions); + } + } +} \ No newline at end of file -- cgit v1.2.3 From b92588f1f9f5678970fdc05460b70e31ad47cdb5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Jun 2021 21:45:17 -0500 Subject: improve Retry --- src/slskd/Common/Retry.cs | 64 +++++++++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index c0e1bd83..f18b7459 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -21,42 +21,51 @@ namespace slskd using System.Collections.Generic; using System.Threading.Tasks; - public class Retry + /// + /// Retry logic. + /// + public static class Retry { - public static async Task Do(Func task, TimeSpan retryInterval, int maxAttemptCount = 3) + /// + /// Executes logic with the specified retry parameters. + /// + /// The logic to execute. + /// A function returning a value indicating whether the last Exception is retryable. + /// The maximum number of retry attempts. + /// The maximum delay in milliseconds. + /// The execution context. + public static async Task Do(Func task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { - var exceptions = new List(); - for (int attempted = 0; attempted < maxAttemptCount; attempted++) + await Do(async () => { - try - { - if (attempted > 0) - { - await Task.Delay(retryInterval); - } - - await task(); - return; - } - catch (Exception ex) - { - exceptions.Add(ex); - } - } - - throw new AggregateException(exceptions); + await task(); + return Task.FromResult(null); + }, isRetryable, maxAttempts, maxDelayInMilliseconds); } - public static async Task Do(Func> task, TimeSpan retryInterval, int maxAttemptCount = 3) + /// + /// Executes logic with the specified retry parameters. + /// + /// The logic to execute. + /// A function returning a value indicating whether the last Exception is retryable. + /// The maximum number of retry attempts. + /// The maximum delay in miliseconds. + /// The Type of the logic return value. + /// The execution context. + public static async Task Do(Func> task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { + isRetryable ??= (_, _) => true; + var exceptions = new List(); - for (int attempted = 0; attempted < maxAttemptCount; attempted++) + + for (int attempts = 0; attempts < maxAttempts; attempts++) { try { - if (attempted > 0) + if (attempts > 0) { - await Task.Delay(retryInterval); + var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, maxDelayInMilliseconds); + await Task.Delay(delay + jitter); } return await task(); @@ -64,6 +73,11 @@ namespace slskd catch (Exception ex) { exceptions.Add(ex); + + if (!isRetryable(attempts + 1, ex)) + { + throw new AggregateException(exceptions); + } } } -- cgit v1.2.3 From 750ce2d4672ec387523217eb2b5caab85873e0c3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Jun 2021 21:49:24 -0500 Subject: add ConnectionTimeout for FTP --- src/slskd/Options.cs | 12 +++++++++++- src/slskd/Properties/slskd.yml | 3 +++ 2 files changed, 14 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 0993fa12..74125297 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -629,13 +629,23 @@ namespace slskd [Description("overwrite existing files")] 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 uploads will be retried")] - public int RetryAttempts { get; private set; } = 5; + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; } } } diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index 492fb01c..8cb1c04a 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -56,4 +56,7 @@ # encryption_mode: auto # username: ~ # password: ~ +# remote_path: / +# overwrite_existing: true +# connection_timeout: 5000 # retry_attempts: 5 \ No newline at end of file -- cgit v1.2.3 From bb08368d27bee40f16e847ed95e87e602238172c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 28 Jun 2021 21:49:32 -0500 Subject: implement retry, clean up a bit --- src/slskd/Integrations/FTP/FTPClient.cs | 48 ++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClient.cs b/src/slskd/Integrations/FTP/FTPClient.cs index e6a748a9..105863ea 100644 --- a/src/slskd/Integrations/FTP/FTPClient.cs +++ b/src/slskd/Integrations/FTP/FTPClient.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -19,6 +19,7 @@ namespace slskd.Integrations.FTP { using System; using System.IO; + using System.Threading; using System.Threading.Tasks; using FluentFTP; using Microsoft.Extensions.Logging; @@ -70,36 +71,41 @@ namespace slskd.Integrations.FTP return; } - // todo: add retries up to configured count with exponential backoff - try - { - var fileOnly = Path.GetFileName(filename); - var fileAndParentDirectory = Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); + var fileOnly = Path.GetFileName(filename); + var fileAndParentDirectory = Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); - var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); - // todo: sanitize filename - var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; + 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; - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); - var client = Factory.CreateFtpClient(); + try + { + await Retry.Do(async () => + { + Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); + var client = Factory.CreateFtpClient(); - // todo: add cancellation token for timeout - await client.ConnectAsync(); + var cts = new CancellationTokenSource(FTPOptions.ConnectionTimeout); + await client.ConnectAsync(cts.Token); - var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); + var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); - if (status == FtpStatus.Failed) - { - throw new FtpException("FTP client reported a failed transfer"); - } + if (status == FtpStatus.Failed) + { + 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); + }, (attempts, ex) => + { + Log.LogWarning("Failed attempt {Attempts} to upload {Filename} to FTP: {Message}", attempts, ex.Message); + return true; + }, maxAttempts: FTPOptions.RetryAttempts, maxDelayInMilliseconds: 30000); } catch (Exception ex) { - Log.LogWarning(ex, "Failed to upload {Filename} to FTP: {Message}", ex.Message); + Log.LogWarning(ex, "Failed to upload {Filename} to FTP after {Attempts}: {Message}", FTPOptions.RetryAttempts, ex.Message); throw; } } -- cgit v1.2.3 From 5680bdf76da6c17b3bb2c7501fe2aea8cf456a59 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 29 Jun 2021 09:48:36 -0500 Subject: add action on failure, trap errors executing delegates --- src/slskd/Common/Retry.cs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index f18b7459..eccb6b62 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -31,16 +31,17 @@ namespace slskd /// /// The logic to execute. /// A function returning a value indicating whether the last Exception is retryable. + /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in milliseconds. /// The execution context. - public static async Task Do(Func task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { await Do(async () => { await task(); return Task.FromResult(null); - }, isRetryable, maxAttempts, maxDelayInMilliseconds); + }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds); } /// @@ -48,13 +49,15 @@ namespace slskd /// /// The logic to execute. /// A function returning a value indicating whether the last Exception is retryable. + /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in miliseconds. /// The Type of the logic return value. /// The execution context. - public static async Task Do(Func> task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { isRetryable ??= (_, _) => true; + onFailure ??= (_, _) => { }; var exceptions = new List(); @@ -74,9 +77,18 @@ namespace slskd { exceptions.Add(ex); - if (!isRetryable(attempts + 1, ex)) + try { - throw new AggregateException(exceptions); + onFailure(attempts + 1, ex); + + if (!isRetryable(attempts + 1, ex)) + { + break; + } + } + catch (Exception retryEx) + { + throw new RetryException($"Failed to retry operation: {retryEx.Message}", ex); } } } -- cgit v1.2.3 From 47f073655985259de957d34e2d55efea02cb1be1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 29 Jun 2021 09:48:48 -0500 Subject: add RetryException --- src/slskd/Application/Exceptions/RetryException.cs | 72 ++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/slskd/Application/Exceptions/RetryException.cs (limited to 'src') diff --git a/src/slskd/Application/Exceptions/RetryException.cs b/src/slskd/Application/Exceptions/RetryException.cs new file mode 100644 index 00000000..c688f377 --- /dev/null +++ b/src/slskd/Application/Exceptions/RetryException.cs @@ -0,0 +1,72 @@ +// +// 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.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents erorrs that originate while attempting to execute retry logic. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class RetryException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public RetryException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public RetryException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public RetryException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected RetryException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file -- cgit v1.2.3 From a911ff7f153547d8fa1abb24a43fc6b852cde30c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 29 Jun 2021 10:02:53 -0500 Subject: add option to ignore certificate errors --- src/slskd/Options.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 74125297..a2a9d707 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -618,7 +618,7 @@ namespace slskd /// [Argument(default, "ftp-remote-path")] [EnvironmentVariable("FTP_REMOTE_PATH")] - [Description("remote path for uploads")] + [Description("remote path for FTP uploads")] public string RemotePath { get; private set; } = "/"; /// @@ -626,7 +626,7 @@ namespace slskd /// [Argument(default, "ftp-overwrite-existing")] [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] - [Description("overwrite existing files")] + [Description("overwrite existing files when uploading to FTP")] public bool OverwriteExisting { get; private set; } = true; /// @@ -643,9 +643,14 @@ namespace slskd /// [Argument(default, "ftp-retry-attempts")] [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] - [Description("number of times failing uploads will be retried")] + [Description("number of times failing FTP uploads will be retried")] [Range(0, 5)] public int RetryAttempts { get; private set; } = 3; + + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; private set; } = false; } } } -- cgit v1.2.3 From 3093c4ad7362809deb1de2a98b36a0390d08e44b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 29 Jun 2021 10:03:12 -0500 Subject: make retries work --- src/slskd/Integrations/FTP/FTPClient.cs | 85 ++++++++++++++++++++++----------- 1 file changed, 58 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClient.cs b/src/slskd/Integrations/FTP/FTPClient.cs index 105863ea..141bc10c 100644 --- a/src/slskd/Integrations/FTP/FTPClient.cs +++ b/src/slskd/Integrations/FTP/FTPClient.cs @@ -71,43 +71,74 @@ namespace slskd.Integrations.FTP return; } - var fileOnly = Path.GetFileName(filename); - var fileAndParentDirectory = Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); + var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); + + try + { + await Retry.Do( + 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, + maxDelayInMilliseconds: 30000); + } + catch (RetryException ex) + { + Log.LogError(ex, "Fatal error retrying upload of {Filename} to FTP: {Message}", fileAndParentDirectory, ex.Message); + throw; + } + catch (Exception ex) + { + Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FTPOptions.RetryAttempts, ex.Message); + throw; + } + } + private async Task AttemptUploadAsync(string filename) + { + var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; - try + Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); + var client = Factory.CreateFtpClient(); + client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; + + var timeoutTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); + using var timeoutCancellationTokenRegistration = + timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); + + var connectTask = client.ConnectAsync(); + + var completedTask = await Task.WhenAny(connectTask, timeoutTaskCompletionSource.Task); + + if (completedTask == timeoutTaskCompletionSource.Task) { - await Retry.Do(async () => - { - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); - var client = Factory.CreateFtpClient(); - - var cts = new CancellationTokenSource(FTPOptions.ConnectionTimeout); - await client.ConnectAsync(cts.Token); - - var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); - - if (status == FtpStatus.Failed) - { - throw new FtpException("FTP client reported a failed transfer"); - } - - Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); - }, (attempts, ex) => - { - Log.LogWarning("Failed attempt {Attempts} to upload {Filename} to FTP: {Message}", attempts, ex.Message); - return true; - }, maxAttempts: FTPOptions.RetryAttempts, maxDelayInMilliseconds: 30000); + throw new TimeoutException($"Failed to connect to server after {FTPOptions.ConnectionTimeout}ms"); } - catch (Exception ex) + + if (connectTask.Exception != null) { - Log.LogWarning(ex, "Failed to upload {Filename} to FTP after {Attempts}: {Message}", FTPOptions.RetryAttempts, ex.Message); - throw; + throw connectTask.Exception; } + + var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); + + if (status == FtpStatus.Failed) + { + throw new FtpException("FTP client reported a failed transfer"); + } + + Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); + } + + private string GetFileAndParentDirectoryFromFilename(string filename) + { + var fileOnly = Path.GetFileName(filename); + return Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); } } } -- cgit v1.2.3 From e141476ef5b6e13ec8de6cfe0d599595326ed28f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 29 Jun 2021 22:14:57 -0500 Subject: cleanup --- .../API/Controllers/TransfersController.cs | 4 +- src/slskd/Integrations/FTP/FTPClient.cs | 144 --------------------- src/slskd/Integrations/FTP/FTPClientFactory.cs | 20 ++- src/slskd/Integrations/FTP/FTPService.cs | 144 +++++++++++++++++++++ src/slskd/Integrations/FTP/IFTPClient.cs | 27 ---- src/slskd/Integrations/FTP/IFTPClientFactory.cs | 7 + src/slskd/Integrations/FTP/IFTPService.cs | 31 +++++ src/slskd/Startup.cs | 2 +- 8 files changed, 201 insertions(+), 178 deletions(-) delete mode 100644 src/slskd/Integrations/FTP/FTPClient.cs create mode 100644 src/slskd/Integrations/FTP/FTPService.cs delete mode 100644 src/slskd/Integrations/FTP/IFTPClient.cs create mode 100644 src/slskd/Integrations/FTP/IFTPService.cs (limited to 'src') diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index 8131aa8c..d0bff636 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -49,7 +49,7 @@ namespace slskd.Transfer.API Microsoft.Extensions.Options.IOptionsSnapshot options, ISoulseekClient client, ITransferTracker tracker, - IFTPClient ftpClient) + IFTPService ftpClient) { Client = client; Tracker = tracker; @@ -60,7 +60,7 @@ namespace slskd.Transfer.API private Options Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } - private IFTPClient FTP { get; } + private IFTPService FTP { get; } /// /// Cancels the specified download. diff --git a/src/slskd/Integrations/FTP/FTPClient.cs b/src/slskd/Integrations/FTP/FTPClient.cs deleted file mode 100644 index 141bc10c..00000000 --- a/src/slskd/Integrations/FTP/FTPClient.cs +++ /dev/null @@ -1,144 +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.Integrations.FTP -{ - using System; - using System.IO; - using System.Threading; - using System.Threading.Tasks; - using FluentFTP; - using Microsoft.Extensions.Logging; - using static slskd.Options.IntegrationOptions; - - public class FTPClient : IFTPClient - { - public FTPClient( - IFTPClientFactory ftpClientFactory, - Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, - ILogger log) - { - Factory = ftpClientFactory; - Options = optionsMonitor.CurrentValue; - Log = log; - - try - { - EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); - } - catch (Exception ex) - { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. - throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); - } - } - - public bool Enabled => !string.IsNullOrEmpty(Options.Integration.FTP.Address); - - private Options Options { get; } - private FTPOptions FTPOptions => Options.Integration.FTP; - private ILogger Log { get; set; } - private IFTPClientFactory Factory { get; set; } - private FtpEncryptionMode EncryptionMode { get; set; } - - public FtpClient CreateFtpClient() - { - var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); - client.EncryptionMode = EncryptionMode; - - return client; - } - - public async Task UploadAsync(string filename) - { - if (!Enabled) - { - Log.LogDebug("Skipping FTP upload of {filename}; FTP integration is disabled"); - return; - } - - var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); - - try - { - await Retry.Do( - 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, - maxDelayInMilliseconds: 30000); - } - catch (RetryException ex) - { - Log.LogError(ex, "Fatal error retrying upload of {Filename} to FTP: {Message}", fileAndParentDirectory, ex.Message); - throw; - } - catch (Exception ex) - { - Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FTPOptions.RetryAttempts, ex.Message); - throw; - } - } - - private async Task AttemptUploadAsync(string filename) - { - var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); - var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); - var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; - - var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; - - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); - var client = Factory.CreateFtpClient(); - client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; - - var timeoutTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); - using var timeoutCancellationTokenRegistration = - timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); - - var connectTask = client.ConnectAsync(); - - var completedTask = await Task.WhenAny(connectTask, timeoutTaskCompletionSource.Task); - - if (completedTask == timeoutTaskCompletionSource.Task) - { - throw new TimeoutException($"Failed to connect to server after {FTPOptions.ConnectionTimeout}ms"); - } - - if (connectTask.Exception != null) - { - throw connectTask.Exception; - } - - var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); - - if (status == FtpStatus.Failed) - { - throw new FtpException("FTP client reported a failed transfer"); - } - - Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); - } - - private string GetFileAndParentDirectoryFromFilename(string filename) - { - var fileOnly = Path.GetFileName(filename); - return Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); - } - } -} diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index 887623a2..7e6f948e 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -21,8 +21,15 @@ namespace slskd.Integrations.FTP using FluentFTP; using static slskd.Options.IntegrationOptions; + /// + /// FTP client factory. + /// public class FTPClientFactory : IFTPClientFactory { + /// + /// Initializes a new instance of the class. + /// + /// The options monitor used to derive application options. public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor) { Options = optionsMonitor.CurrentValue; @@ -33,15 +40,20 @@ namespace slskd.Integrations.FTP } catch (Exception ex) { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. + // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this + // throws there's a bug somewhere. throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); } } - private Options Options { get; set; } - private FTPOptions FTPOptions => Options.Integration.FTP; private FtpEncryptionMode EncryptionMode { get; set; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private Options Options { get; set; } + /// + /// Creates an instance of . + /// + /// The created instance. public FtpClient CreateFtpClient() { var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); @@ -50,4 +62,4 @@ namespace slskd.Integrations.FTP return client; } } -} +} \ No newline at end of file diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs new file mode 100644 index 00000000..f9f9de66 --- /dev/null +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -0,0 +1,144 @@ +// +// 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.Integrations.FTP +{ + using System; + using System.IO; + using System.Threading; + using System.Threading.Tasks; + using FluentFTP; + using Microsoft.Extensions.Logging; + using static slskd.Options.IntegrationOptions; + + public class FTPService : IFTPService + { + public FTPService( + IFTPClientFactory ftpClientFactory, + Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, + ILogger log) + { + Factory = ftpClientFactory; + Options = optionsMonitor.CurrentValue; + Log = log; + + try + { + EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); + } + catch (Exception ex) + { + // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. + throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); + } + } + + public bool Enabled => !string.IsNullOrEmpty(Options.Integration.FTP.Address); + + private Options Options { get; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private ILogger Log { get; set; } + private IFTPClientFactory Factory { get; set; } + private FtpEncryptionMode EncryptionMode { get; set; } + + public FtpClient CreateFtpClient() + { + var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); + client.EncryptionMode = EncryptionMode; + + return client; + } + + public async Task UploadAsync(string filename) + { + if (!Enabled) + { + Log.LogDebug("Skipping FTP upload of {filename}; FTP integration is disabled"); + return; + } + + var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); + + try + { + await Retry.Do( + 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, + maxDelayInMilliseconds: 30000); + } + catch (RetryException ex) + { + Log.LogError(ex, "Fatal error retrying upload of {Filename} to FTP: {Message}", fileAndParentDirectory, ex.Message); + throw; + } + catch (Exception ex) + { + Log.LogWarning("Failed to upload {Filename} to FTP after {Attempts} attempts: {Message}", fileAndParentDirectory, FTPOptions.RetryAttempts, ex.Message); + throw; + } + } + + private async Task AttemptUploadAsync(string filename) + { + var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); + var remotePath = FTPOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; + + var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; + + Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); + var client = Factory.CreateFtpClient(); + client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; + + var timeoutTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); + using var timeoutCancellationTokenRegistration = + timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); + + var connectTask = client.ConnectAsync(); + + var completedTask = await Task.WhenAny(connectTask, timeoutTaskCompletionSource.Task); + + if (completedTask == timeoutTaskCompletionSource.Task) + { + throw new TimeoutException($"Failed to connect to server after {FTPOptions.ConnectionTimeout}ms"); + } + + if (connectTask.Exception != null) + { + throw connectTask.Exception; + } + + var status = await client.UploadFileAsync(filename, remoteFilename, existsMode, createRemoteDir: true); + + if (status == FtpStatus.Failed) + { + throw new FtpException("FTP client reported a failed transfer"); + } + + Log.LogInformation("FTP upload of {Filename} to {Address}:{Port} complete", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port); + } + + private string GetFileAndParentDirectoryFromFilename(string filename) + { + var fileOnly = Path.GetFileName(filename); + return Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); + } + } +} diff --git a/src/slskd/Integrations/FTP/IFTPClient.cs b/src/slskd/Integrations/FTP/IFTPClient.cs deleted file mode 100644 index b556ea3b..00000000 --- a/src/slskd/Integrations/FTP/IFTPClient.cs +++ /dev/null @@ -1,27 +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.Integrations.FTP -{ - using System.Threading.Tasks; - - public interface IFTPClient - { - Task UploadAsync(string filename); - bool Enabled { get; } - } -} diff --git a/src/slskd/Integrations/FTP/IFTPClientFactory.cs b/src/slskd/Integrations/FTP/IFTPClientFactory.cs index 760db612..2ab729d1 100644 --- a/src/slskd/Integrations/FTP/IFTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/IFTPClientFactory.cs @@ -19,8 +19,15 @@ namespace slskd.Integrations.FTP { using FluentFTP; + /// + /// FTP client factory. + /// public interface IFTPClientFactory { + /// + /// Creates an instance of . + /// + /// The created instance. public FtpClient CreateFtpClient(); } } diff --git a/src/slskd/Integrations/FTP/IFTPService.cs b/src/slskd/Integrations/FTP/IFTPService.cs new file mode 100644 index 00000000..5841e0b2 --- /dev/null +++ b/src/slskd/Integrations/FTP/IFTPService.cs @@ -0,0 +1,31 @@ +// +// 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.Integrations.FTP +{ + using System.Threading.Tasks; + + /// + /// FTP Integration service. + /// + public interface IFTPService + { + + Task UploadAsync(string filename); + bool Enabled { get; } + } +} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index f802a56a..65781e6e 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -189,7 +189,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); - services.AddTransient(); + services.AddTransient(); services.AddHostedService(); services.AddSingleton(_ => Service.SoulseekClient); -- cgit v1.2.3 From a59657daf526e85adad34e63a4b236f07cb53079 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jul 2021 09:16:10 -0500 Subject: add enabled flag --- src/slskd/Options.cs | 21 ++++++++++++++++----- src/slskd/Properties/slskd.yml | 2 ++ 2 files changed, 18 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index a2a9d707..e32ef522 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -571,6 +571,14 @@ namespace slskd /// public class FTPOptions { + /// + /// 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. /// @@ -597,6 +605,14 @@ namespace slskd [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. /// @@ -646,11 +662,6 @@ namespace slskd [Description("number of times failing FTP uploads will be retried")] [Range(0, 5)] public int RetryAttempts { get; private set; } = 3; - - [Argument(default, "ftp-ignore-certificate-errors")] - [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] - [Description("ignore FTP certificate errors")] - public bool IgnoreCertificateErrors { get; private set; } = false; } } } diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index 8cb1c04a..a0356e6f 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -51,9 +51,11 @@ # password: ~ # integration: # ftp: +# enabled: false # address: ~ # port: ~ # encryption_mode: auto +# ignore_certificate_errors: false # username: ~ # password: ~ # remote_path: / -- cgit v1.2.3 From af0c79be657bd4dd56dc2ef3ccc6bb64c4328162 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jul 2021 09:18:03 -0500 Subject: use option enabled flag to determine whether to attempt FTP uploads --- src/slskd/Application/Transfer/API/Controllers/TransfersController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index d0bff636..97b86689 100644 --- a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs +++ b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs @@ -135,7 +135,7 @@ namespace slskd.Transfer.API MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); - if (FTP.Enabled) + if (Options.Integration.FTP.Enabled) { _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); } -- cgit v1.2.3 From 34a25f488eecee202cbed8d8c2ee64bd60439ab4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jul 2021 10:02:37 -0500 Subject: add validator to ensure Address if FTP is Enabled --- src/slskd/Options.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index e32ef522..f8190fc7 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -18,6 +18,7 @@ namespace slskd { using System; + using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; @@ -569,7 +570,7 @@ namespace slskd /// /// FTP options. /// - public class FTPOptions + public class FTPOptions : IValidatableObject { /// /// Gets a value indicating whether the FTP integration is enabled. @@ -662,6 +663,18 @@ namespace slskd [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; + } } } } -- cgit v1.2.3 From 5df50ddb3bb537b30ed1f86f7834b0ee17569585 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jul 2021 10:08:49 -0500 Subject: docs, remove Enabled --- src/slskd/Integrations/FTP/FTPService.cs | 43 +++++++++++++------------------ src/slskd/Integrations/FTP/IFTPService.cs | 7 +++-- 2 files changed, 23 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index f9f9de66..bffc5244 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -25,8 +25,17 @@ namespace slskd.Integrations.FTP using Microsoft.Extensions.Logging; using static slskd.Options.IntegrationOptions; + /// + /// FTP Integration service. + /// public class FTPService : IFTPService { + /// + /// Initializes a new instance of the class. + /// + /// The FTP client factory to use. + /// The options monitor used to derive application options. + /// The logger. public FTPService( IFTPClientFactory ftpClientFactory, Microsoft.Extensions.Options.IOptionsMonitor optionsMonitor, @@ -35,37 +44,21 @@ namespace slskd.Integrations.FTP Factory = ftpClientFactory; Options = optionsMonitor.CurrentValue; Log = log; - - try - { - EncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), FTPOptions.EncryptionMode, ignoreCase: true); - } - catch (Exception ex) - { - // Options should validate that the given string is parsable to FtpEncryptionMode through EnumAttribute; if this throws there's a bug somewhere. - throw new ArgumentException($"Failed to parse {typeof(FtpEncryptionMode).Name} from application Options. This is most likely a programming error; please file a GitHub issue and include your FTP configuration.", ex); - } } - public bool Enabled => !string.IsNullOrEmpty(Options.Integration.FTP.Address); - - private Options Options { get; } + private IFTPClientFactory Factory { get; set; } private FTPOptions FTPOptions => Options.Integration.FTP; private ILogger Log { get; set; } - private IFTPClientFactory Factory { get; set; } - private FtpEncryptionMode EncryptionMode { get; set; } - - public FtpClient CreateFtpClient() - { - var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); - client.EncryptionMode = EncryptionMode; - - return client; - } + private Options Options { get; } + /// + /// Uploads the specified to the configured FTP server. + /// + /// The fully qualified name of the file to upload. + /// The operation context. public async Task UploadAsync(string filename) { - if (!Enabled) + if (!FTPOptions.Enabled) { Log.LogDebug("Skipping FTP upload of {filename}; FTP integration is disabled"); return; @@ -141,4 +134,4 @@ namespace slskd.Integrations.FTP return Path.Combine(Path.GetDirectoryName(filename).Replace(Path.GetDirectoryName(Path.GetDirectoryName(filename)), string.Empty), fileOnly).TrimStart('/').TrimStart('\\'); } } -} +} \ No newline at end of file diff --git a/src/slskd/Integrations/FTP/IFTPService.cs b/src/slskd/Integrations/FTP/IFTPService.cs index 5841e0b2..543138f3 100644 --- a/src/slskd/Integrations/FTP/IFTPService.cs +++ b/src/slskd/Integrations/FTP/IFTPService.cs @@ -24,8 +24,11 @@ namespace slskd.Integrations.FTP /// public interface IFTPService { - + /// + /// Uploads the specified to the configured FTP server. + /// + /// The fully qualified name of the file to upload. + /// The operation context. Task UploadAsync(string filename); - bool Enabled { get; } } } -- cgit v1.2.3 From dfd8015a0727d2074282d93d7911f988195b20f9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jul 2021 08:02:06 -0500 Subject: set cert validation option --- src/slskd/Integrations/FTP/FTPClientFactory.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs index 7e6f948e..cc076ca1 100644 --- a/src/slskd/Integrations/FTP/FTPClientFactory.cs +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -58,6 +58,7 @@ namespace slskd.Integrations.FTP { var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); client.EncryptionMode = EncryptionMode; + client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; return client; } -- cgit v1.2.3 From 32cd804dd3e13967a14316ae76ae2ce71c3de936 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jul 2021 08:06:39 -0500 Subject: dispose FTP client --- src/slskd/Integrations/FTP/FTPService.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index bffc5244..a5fe6a8f 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -95,17 +95,16 @@ namespace slskd.Integrations.FTP var existsMode = FTPOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; - Log.LogInformation("Uploading {Filename} to FTP {Address}:{Port} as {RemoteFilename}", fileAndParentDirectory, FTPOptions.Address, FTPOptions.Port, remoteFilename); - var client = Factory.CreateFtpClient(); - client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; + using var client = Factory.CreateFtpClient(); var timeoutTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); using var timeoutCancellationTokenRegistration = timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); - var connectTask = client.ConnectAsync(); + Log.LogDebug("Connecting to FTP at {Address}:{Port} using encryption mode {EncryptionMode}", client.Host, client.Port, client.EncryptionMode); + var connectTask = client.ConnectAsync(); var completedTask = await Task.WhenAny(connectTask, timeoutTaskCompletionSource.Task); if (completedTask == timeoutTaskCompletionSource.Task) @@ -118,6 +117,7 @@ namespace slskd.Integrations.FTP throw connectTask.Exception; } + 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) -- cgit v1.2.3