diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-07-02 08:26:14 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-07-02 08:26:14 -0500 |
| commit | 6e4166314c7cb9ce51f5c6ecff72258be26524b0 (patch) | |
| tree | 3f67ea09cfb52e4108bf2f00dc8b40744b66964e /src | |
| parent | 2ea8ed330d13c972c4cc36b13327701e6f4762d9 (diff) | |
| parent | 32cd804dd3e13967a14316ae76ae2ce71c3de936 (diff) | |
| download | slskd-6e4166314c7cb9ce51f5c6ecff72258be26524b0.tar.gz | |
Merge pull request #109 from slskd/ftp
Add the ability to upload files to an FTP after downloads complete
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application/Exceptions/RetryException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Application/Transfer/API/Controllers/TransfersController.cs | 12 | ||||
| -rw-r--r-- | src/slskd/Common/Retry.cs | 99 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/EnumAttribute.cs | 47 | ||||
| -rw-r--r-- | src/slskd/Integrations/FTP/FTPClientFactory.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Integrations/FTP/FTPService.cs | 137 | ||||
| -rw-r--r-- | src/slskd/Integrations/FTP/IFTPClientFactory.cs | 33 | ||||
| -rw-r--r-- | src/slskd/Integrations/FTP/IFTPService.cs | 34 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 130 | ||||
| -rw-r--r-- | src/slskd/Properties/analysis.ruleset | 1 | ||||
| -rw-r--r-- | src/slskd/Properties/slskd.yml | 15 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 4 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 1 |
13 files changed, 649 insertions, 2 deletions
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 file="RetryException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents erorrs that originate while attempting to execute retry logic. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class RetryException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class. + /// </summary> + public RetryException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public RetryException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public RetryException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RetryException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected RetryException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs b/src/slskd/Application/Transfer/API/Controllers/TransfersController.cs index f7274157..97b86689 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; /// <summary> @@ -43,19 +44,23 @@ namespace slskd.Transfer.API /// <param name="options"></param> /// <param name="client"></param> /// <param name="tracker"></param> + /// <param name="ftpClient"></param> public TransfersController( Microsoft.Extensions.Options.IOptionsSnapshot<Options> options, ISoulseekClient client, - ITransferTracker tracker) + ITransferTracker tracker, + IFTPService ftpClient) { Client = client; Tracker = tracker; Options = options.Value; + FTP = ftpClient; } private Options Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } + private IFTPService FTP { get; } /// <summary> /// 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 (Options.Integration.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/Common/Retry.cs b/src/slskd/Common/Retry.cs new file mode 100644 index 00000000..eccb6b62 --- /dev/null +++ b/src/slskd/Common/Retry.cs @@ -0,0 +1,99 @@ +// <copyright file="Retry.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + + /// <summary> + /// Retry logic. + /// </summary> + public static class Retry + { + /// <summary> + /// Executes logic with the specified retry parameters. + /// </summary> + /// <param name="task">The logic to execute.</param> + /// <param name="isRetryable">A function returning a value indicating whether the last Exception is retryable.</param> + /// <param name="onFailure">An action to execute on failure.</param> + /// <param name="maxAttempts">The maximum number of retry attempts.</param> + /// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param> + /// <returns>The execution context.</returns> + public static async Task Do(Func<Task> task, Func<int, Exception, bool> isRetryable = null, Action<int, Exception> onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + { + await Do<object>(async () => + { + await task(); + return Task.FromResult<object>(null); + }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds); + } + + /// <summary> + /// Executes logic with the specified retry parameters. + /// </summary> + /// <param name="task">The logic to execute.</param> + /// <param name="isRetryable">A function returning a value indicating whether the last Exception is retryable.</param> + /// <param name="onFailure">An action to execute on failure.</param> + /// <param name="maxAttempts">The maximum number of retry attempts.</param> + /// <param name="maxDelayInMilliseconds">The maximum delay in miliseconds.</param> + /// <typeparam name="T">The Type of the logic return value.</typeparam> + /// <returns>The execution context.</returns> + public static async Task<T> Do<T>(Func<Task<T>> task, Func<int, Exception, bool> isRetryable = null, Action<int, Exception> onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + { + isRetryable ??= (_, _) => true; + onFailure ??= (_, _) => { }; + + var exceptions = new List<Exception>(); + + for (int attempts = 0; attempts < maxAttempts; attempts++) + { + try + { + if (attempts > 0) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, maxDelayInMilliseconds); + await Task.Delay(delay + jitter); + } + + return await task(); + } + catch (Exception ex) + { + exceptions.Add(ex); + + try + { + onFailure(attempts + 1, ex); + + if (!isRetryable(attempts + 1, ex)) + { + break; + } + } + catch (Exception retryEx) + { + throw new RetryException($"Failed to retry operation: {retryEx.Message}", ex); + } + } + } + + throw new AggregateException(exceptions); + } + } +}
\ No newline at end of file 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 file="EnumAttribute.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Validation +{ + using System; + using System.ComponentModel.DataAnnotations; + + /// <summary> + /// Validates that the value is a valid nember of the specified <see cref="Enum"/>. + /// </summary> + 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 diff --git a/src/slskd/Integrations/FTP/FTPClientFactory.cs b/src/slskd/Integrations/FTP/FTPClientFactory.cs new file mode 100644 index 00000000..cc076ca1 --- /dev/null +++ b/src/slskd/Integrations/FTP/FTPClientFactory.cs @@ -0,0 +1,66 @@ +// <copyright file="FTPClientFactory.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Integrations.FTP +{ + using System; + using FluentFTP; + using static slskd.Options.IntegrationOptions; + + /// <summary> + /// FTP client factory. + /// </summary> + public class FTPClientFactory : IFTPClientFactory + { + /// <summary> + /// Initializes a new instance of the <see cref="FTPClientFactory"/> class. + /// </summary> + /// <param name="optionsMonitor">The options monitor used to derive application options.</param> + public FTPClientFactory(Microsoft.Extensions.Options.IOptionsMonitor<Options> 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 FtpEncryptionMode EncryptionMode { get; set; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private Options Options { get; set; } + + /// <summary> + /// Creates an instance of <see cref="FtpClient"/>. + /// </summary> + /// <returns>The created instance.</returns> + public FtpClient CreateFtpClient() + { + var client = new FtpClient(FTPOptions.Address, FTPOptions.Port, FTPOptions.Username, FTPOptions.Password); + client.EncryptionMode = EncryptionMode; + client.ValidateAnyCertificate = FTPOptions.IgnoreCertificateErrors; + + 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..a5fe6a8f --- /dev/null +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -0,0 +1,137 @@ +// <copyright file="FTPService.cs" company="slskd Team"> +// 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/. +// </copyright> + +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; + + /// <summary> + /// FTP Integration service. + /// </summary> + public class FTPService : IFTPService + { + /// <summary> + /// Initializes a new instance of the <see cref="FTPService"/> class. + /// </summary> + /// <param name="ftpClientFactory">The FTP client factory to use.</param> + /// <param name="optionsMonitor">The options monitor used to derive application options.</param> + /// <param name="log">The logger.</param> + public FTPService( + IFTPClientFactory ftpClientFactory, + Microsoft.Extensions.Options.IOptionsMonitor<Options> optionsMonitor, + ILogger<FTPService> log) + { + Factory = ftpClientFactory; + Options = optionsMonitor.CurrentValue; + Log = log; + } + + private IFTPClientFactory Factory { get; set; } + private FTPOptions FTPOptions => Options.Integration.FTP; + private ILogger<FTPService> Log { get; set; } + private Options Options { get; } + + /// <summary> + /// Uploads the specified <paramref name="filename"/> to the configured FTP server. + /// </summary> + /// <param name="filename">The fully qualified name of the file to upload.</param> + /// <returns>The operation context.</returns> + public async Task UploadAsync(string filename) + { + if (!FTPOptions.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; + + using var client = Factory.CreateFtpClient(); + + var timeoutTaskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); + using var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(FTPOptions.ConnectionTimeout)); + using var timeoutCancellationTokenRegistration = + timeoutCancellationTokenSource.Token.Register(() => timeoutTaskCompletionSource.TrySetResult(true)); + + 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) + { + throw new TimeoutException($"Failed to connect to server after {FTPOptions.ConnectionTimeout}ms"); + } + + if (connectTask.Exception != null) + { + 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) + { + 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('\\'); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Integrations/FTP/IFTPClientFactory.cs b/src/slskd/Integrations/FTP/IFTPClientFactory.cs new file mode 100644 index 00000000..2ab729d1 --- /dev/null +++ b/src/slskd/Integrations/FTP/IFTPClientFactory.cs @@ -0,0 +1,33 @@ +// <copyright file="IFTPClientFactory.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Integrations.FTP +{ + using FluentFTP; + + /// <summary> + /// FTP client factory. + /// </summary> + public interface IFTPClientFactory + { + /// <summary> + /// Creates an instance of <see cref="FtpClient"/>. + /// </summary> + /// <returns>The created instance.</returns> + 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..543138f3 --- /dev/null +++ b/src/slskd/Integrations/FTP/IFTPService.cs @@ -0,0 +1,34 @@ +// <copyright file="IFTPService.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Integrations.FTP +{ + using System.Threading.Tasks; + + /// <summary> + /// FTP Integration service. + /// </summary> + public interface IFTPService + { + /// <summary> + /// Uploads the specified <paramref name="filename"/> to the configured FTP server. + /// </summary> + /// <param name="filename">The fully qualified name of the file to upload.</param> + /// <returns>The operation context.</returns> + Task UploadAsync(string filename); + } +} diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 485619bc..f8190fc7 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -18,9 +18,11 @@ namespace slskd { using System; + using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; + using FluentFTP; using slskd.Validation; using Soulseek.Diagnostics; using Utility.CommandLine; @@ -122,6 +124,12 @@ namespace slskd public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); /// <summary> + /// Gets options for external integrations. + /// </summary> + [Validate] + public IntegrationOptions Integration { get; private set; } = new IntegrationOptions(); + + /// <summary> /// Directory options. /// </summary> public class DirectoriesOptions @@ -547,5 +555,127 @@ namespace slskd } } } + + /// <summary> + /// Options for external integrations. + /// </summary> + public class IntegrationOptions + { + /// <summary> + /// Gets FTP options. + /// </summary> + [Validate] + public FTPOptions FTP { get; private set; } = new FTPOptions(); + + /// <summary> + /// FTP options. + /// </summary> + public class FTPOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether the FTP integration is enabled. + /// </summary> + [Argument(default, "ftp")] + [EnvironmentVariable("FTP_ENABLED")] + [Description("enable FTP integration")] + public bool Enabled { get; private set; } + + /// <summary> + /// Gets the FTP address. + /// </summary> + [Argument(default, "ftp-address")] + [EnvironmentVariable("FTP_ADDRESS")] + [Description("FTP address")] + public string Address { get; private set; } + + /// <summary> + /// Gets the FTP port. + /// </summary> + [Argument(default, "ftp-port")] + [EnvironmentVariable("FTP_PORT")] + [Description("FTP port")] + [Range(1, 65535)] + public int Port { get; private set; } = 21; + + /// <summary> + /// Gets the FTP encryption mode. + /// </summary> + [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"; + + /// <summary> + /// Gets a value indicating whether FTP certificate errors should be ignored. + /// </summary> + [Argument(default, "ftp-ignore-certificate-errors")] + [EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")] + [Description("ignore FTP certificate errors")] + public bool IgnoreCertificateErrors { get; private set; } = false; + + /// <summary> + /// Gets the FTP username. + /// </summary> + [Argument(default, "ftp-username")] + [EnvironmentVariable("FTP_USERNAME")] + [Description("FTP username")] + public string Username { get; private set; } + + /// <summary> + /// Gets the FTP password. + /// </summary> + [Argument(default, "ftp-password")] + [EnvironmentVariable("FTP_PASSWORD")] + [Description("FTP password")] + public string Password { get; private set; } + + /// <summary> + /// Gets the remote path for uploads. + /// </summary> + [Argument(default, "ftp-remote-path")] + [EnvironmentVariable("FTP_REMOTE_PATH")] + [Description("remote path for FTP uploads")] + public string RemotePath { get; private set; } = "/"; + + /// <summary> + /// Gets a value indicating whether existing files should be overwritten. + /// </summary> + [Argument(default, "ftp-overwrite-existing")] + [EnvironmentVariable("FTP_OVERWRITE_EXISTING")] + [Description("overwrite existing files when uploading to FTP")] + public bool OverwriteExisting { get; private set; } = true; + + /// <summary> + /// Gets the connection timeout value, in milliseconds. + /// </summary> + [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; + + /// <summary> + /// Gets the number of times failing uploads will be retried. + /// </summary> + [Argument(default, "ftp-retry-attempts")] + [EnvironmentVariable("FTP_RETRY_ATTEMPTS")] + [Description("number of times failing FTP uploads will be retried")] + [Range(0, 5)] + public int RetryAttempts { get; private set; } = 3; + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (Enabled && string.IsNullOrWhiteSpace(Address)) + { + results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified.")); + } + + return results; + } + } + } } }
\ No newline at end of file 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 @@ <Rule Id="CA2008" Action="None" /> </Rules> <Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp"> + <Rule Id="S101" Action="None" /> <Rule Id="S2219" Action="None" /> <Rule Id="S2589" Action="None" /> <Rule Id="S3011" Action="None" /> diff --git a/src/slskd/Properties/slskd.yml b/src/slskd/Properties/slskd.yml index ccfe60f9..a0356e6f 100644 --- a/src/slskd/Properties/slskd.yml +++ b/src/slskd/Properties/slskd.yml @@ -48,4 +48,17 @@ # address: ~ # port: ~ # username: ~ -# password: ~
\ No newline at end of file +# 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: 5
\ No newline at end of file diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index dd44fd87..65781e6e 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; @@ -187,6 +188,9 @@ namespace slskd services.AddSingleton<IPeerService, PeerService>(); services.AddSingleton<IManagementService, ManagementService>(); + services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); + services.AddTransient<IFTPService, FTPService>(); + services.AddHostedService<Service>(); services.AddSingleton(_ => Service.SoulseekClient); } 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 @@ </Target> <ItemGroup> + <PackageReference Include="FluentFTP" Version="34.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.7" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.0.0" /> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="5.0.3"> |
