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/slskd/Integrations | |
| 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/slskd/Integrations')
| -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 |
4 files changed, 270 insertions, 0 deletions
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); + } +} |
