From 9035870600587b6bf2c689e148d2f5c77e85a9e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Jun 2021 18:19:35 -0500 Subject: implement upload --- .../Transfer/API/Controllers/TransfersController.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'src/slskd/Application/Transfer/API/Controllers/TransfersController.cs') 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 -- 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/slskd/Application/Transfer/API/Controllers/TransfersController.cs') 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 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/slskd/Application/Transfer/API/Controllers/TransfersController.cs') 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