ShareX/UploadersLib/FileUploaders/FTP.cs

416 lines
12 KiB
C#
Raw Normal View History

2013-11-03 23:53:49 +13:00
#region License Information (GPL v3)
/*
ShareX - A program that allows you to take screenshots and share any file type
2014-05-13 21:06:40 +12:00
Copyright (C) 2007-2014 ShareX Developers
2013-11-03 23:53:49 +13:00
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/
#endregion License Information (GPL v3)
using HelpersLib;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.FtpClient;
using System.Net.Security;
2013-11-03 23:53:49 +13:00
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace UploadersLib.FileUploaders
2013-11-03 23:53:49 +13:00
{
public sealed class FTP : FileUploader, IDisposable
2013-11-03 23:53:49 +13:00
{
public FTPAccount Account { get; private set; }
2013-11-03 23:53:49 +13:00
private FtpClient client;
2013-11-03 23:53:49 +13:00
public FTP(FTPAccount account)
2013-11-03 23:53:49 +13:00
{
Account = account;
client = new FtpClient()
{
Host = Account.Host,
Port = Account.Port,
Credentials = new NetworkCredential(Account.Username, Account.Password)
};
if (account.IsActive)
2013-11-03 23:53:49 +13:00
{
client.DataConnectionType = FtpDataConnectionType.AutoActive;
2013-11-03 23:53:49 +13:00
}
else
{
client.DataConnectionType = FtpDataConnectionType.AutoPassive;
}
2014-05-25 10:24:51 +12:00
if (account.Protocol == FTPProtocol.FTPS)
{
2014-05-25 10:24:51 +12:00
switch (Account.FTPSEncryption)
{
default:
case FTPSEncryption.Explicit:
client.EncryptionMode = FtpEncryptionMode.Explicit;
break;
case FTPSEncryption.Implicit:
client.EncryptionMode = FtpEncryptionMode.Implicit;
break;
}
client.DataConnectionEncryption = true;
2013-11-03 23:53:49 +13:00
2014-05-25 10:24:51 +12:00
if (!string.IsNullOrEmpty(account.FTPSCertificateLocation) && File.Exists(account.FTPSCertificateLocation))
2013-11-03 23:53:49 +13:00
{
2014-05-25 10:24:51 +12:00
X509Certificate cert = X509Certificate2.CreateFromSignedFile(Account.FTPSCertificateLocation);
client.ClientCertificates.Add(cert);
2013-11-03 23:53:49 +13:00
}
else
{
client.ValidateCertificate += (FtpClient control, FtpSslValidationEventArgs e) =>
{
if (e.PolicyErrors != SslPolicyErrors.None)
{
e.Accept = true;
}
};
2013-11-03 23:53:49 +13:00
}
}
}
2013-11-03 23:53:49 +13:00
public override UploadResult Upload(Stream stream, string fileName)
{
UploadResult result = new UploadResult();
2013-11-03 23:53:49 +13:00
fileName = Helpers.GetValidURL(fileName);
string path = Account.GetSubFolderPath(fileName);
try
{
IsUploading = true;
UploadData(stream, path);
}
finally
2013-11-03 23:53:49 +13:00
{
IsUploading = false;
}
2013-11-03 23:53:49 +13:00
if (!stopUpload && Errors.Count == 0)
{
result.URL = Account.GetUriPath(fileName);
2013-11-03 23:53:49 +13:00
}
return result;
2013-11-03 23:53:49 +13:00
}
public override void StopUpload()
2013-11-03 23:53:49 +13:00
{
if (IsUploading && !stopUpload)
2013-11-03 23:53:49 +13:00
{
stopUpload = true;
Disconnect();
2013-11-03 23:53:49 +13:00
}
}
public bool Connect()
2013-11-03 23:53:49 +13:00
{
if (!client.IsConnected)
2013-11-03 23:53:49 +13:00
{
client.Connect();
2013-11-03 23:53:49 +13:00
}
return client.IsConnected;
2013-11-03 23:53:49 +13:00
}
public void Disconnect()
{
if (client != null && client.IsConnected)
2013-11-03 23:53:49 +13:00
{
client.Disconnect();
2013-11-03 23:53:49 +13:00
}
}
public void UploadData(Stream localStream, string remotePath)
2013-11-03 23:53:49 +13:00
{
if (Connect())
{
try
{
using (Stream remoteStream = client.OpenWrite(remotePath))
{
TransferData(localStream, remoteStream);
}
2013-11-03 23:53:49 +13:00
}
catch (Exception e)
{
if (e.InnerException.Message.Contains("No such file or directory"))
{
MakeMultiDirectory(FTPHelpers.GetDirectoryName(remotePath));
using (Stream remoteStream = client.OpenWrite(remotePath))
{
TransferData(localStream, remoteStream);
}
2013-11-03 23:53:49 +13:00
}
else
{
throw e;
}
}
}
}
public void UploadData(byte[] data, string remotePath)
{
using (MemoryStream stream = new MemoryStream(data, false))
{
UploadData(stream, remotePath);
}
}
public void UploadFile(string localPath, string remotePath)
{
using (FileStream stream = new FileStream(localPath, FileMode.Open))
{
UploadData(stream, remotePath);
}
}
public void UploadImage(Image image, string remotePath)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, image.RawFormat);
UploadData(stream, remotePath);
}
}
public void UploadText(string text, string remotePath)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(text), false))
{
UploadData(stream, remotePath);
}
}
public void UploadFiles(string[] localPaths, string remotePath)
{
foreach (string file in localPaths)
{
if (!string.IsNullOrEmpty(file))
{
string filename = Path.GetFileName(file);
2013-11-03 23:53:49 +13:00
if (File.Exists(file))
{
UploadFile(file, Helpers.CombineURL(remotePath, filename));
}
else if (Directory.Exists(file))
{
List<string> filesList = new List<string>();
filesList.AddRange(Directory.GetFiles(file));
filesList.AddRange(Directory.GetDirectories(file));
string path = Helpers.CombineURL(remotePath, filename);
MakeDirectory(path);
UploadFiles(filesList.ToArray(), path);
}
}
}
}
public void DownloadFile(string remotePath, string localPath)
2013-11-03 23:53:49 +13:00
{
Connect();
using (FileStream fs = new FileStream(localPath, FileMode.Create))
2013-11-03 23:53:49 +13:00
{
DownloadFile(remotePath, fs);
2013-11-03 23:53:49 +13:00
}
}
public void DownloadFile(string remotePath, Stream localStream)
2013-11-03 23:53:49 +13:00
{
Connect();
using (Stream remoteStream = client.OpenRead(remotePath))
{
TransferData(remoteStream, localStream);
}
2013-11-03 23:53:49 +13:00
}
public void DownloadFiles(IEnumerable<FtpListItem> files, string localPath, bool recursive = true)
2013-11-03 23:53:49 +13:00
{
Connect();
foreach (FtpListItem file in files)
2013-11-03 23:53:49 +13:00
{
if (file != null && !string.IsNullOrEmpty(file.Name))
{
if (recursive && file.Type == FtpFileSystemObjectType.Directory)
2013-11-03 23:53:49 +13:00
{
FtpListItem[] newFiles = client.GetListing(file.FullName);
2013-11-03 23:53:49 +13:00
string directoryPath = Path.Combine(localPath, file.Name);
2013-11-03 23:53:49 +13:00
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
DownloadFiles(newFiles, directoryPath);
}
else if (file.Type == FtpFileSystemObjectType.File)
2013-11-03 23:53:49 +13:00
{
string filePath = Path.Combine(localPath, file.Name);
DownloadFile(file.FullName, filePath);
2013-11-03 23:53:49 +13:00
}
}
}
}
public bool ChangeDirectory(string remotePath, bool autoCreateDirectory = false)
{
if (Connect())
{
remotePath = FTPHelpers.AddSlash(remotePath, FTPHelpers.SlashType.Prefix);
try
{
client.SetWorkingDirectory(remotePath);
2013-11-03 23:53:49 +13:00
return true;
}
catch (Exception e)
{
if (autoCreateDirectory && e.Message.StartsWith("Could not change working directory to"))
{
MakeMultiDirectory(remotePath);
client.SetWorkingDirectory(remotePath);
2013-11-03 23:53:49 +13:00
return true;
}
throw e;
}
}
return false;
}
public bool MakeDirectory(string remotePath)
{
if (Connect())
{
try
{
client.CreateDirectory(remotePath);
2013-11-03 23:53:49 +13:00
return true;
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
return false;
}
public void MakeMultiDirectory(string remotePath)
{
List<string> paths = FTPHelpers.GetPaths(remotePath);
foreach (string path in paths)
{
if (MakeDirectory(path))
{
DebugHelper.WriteLine("FTP MakeDirectory: " + path);
}
}
}
public void Rename(string fromRemotePath, string toRemotePath)
{
Connect();
client.Rename(fromRemotePath, toRemotePath);
2013-11-03 23:53:49 +13:00
}
public void DeleteFile(string remotePath)
{
Connect();
client.DeleteFile(remotePath);
2013-11-03 23:53:49 +13:00
}
public void DeleteFiles(IEnumerable<FtpListItem> files)
2013-11-03 23:53:49 +13:00
{
foreach (FtpListItem file in files)
2013-11-03 23:53:49 +13:00
{
if (file != null && !string.IsNullOrEmpty(file.Name))
{
if (file.Type == FtpFileSystemObjectType.Directory)
2013-11-03 23:53:49 +13:00
{
DeleteDirectory(file.FullName);
2013-11-03 23:53:49 +13:00
}
else if (file.Type == FtpFileSystemObjectType.File)
2013-11-03 23:53:49 +13:00
{
DeleteFile(file.FullName);
2013-11-03 23:53:49 +13:00
}
}
}
}
public void DeleteDirectory(string remotePath)
{
Connect();
string filename = FTPHelpers.GetFileName(remotePath);
if (filename == "." || filename == "..")
{
return;
}
FtpListItem[] files = client.GetListing(remotePath);
2013-11-03 23:53:49 +13:00
DeleteFiles(files);
2013-11-03 23:53:49 +13:00
client.DeleteDirectory(remotePath);
2013-11-03 23:53:49 +13:00
}
public bool SendCommand(string command)
{
Connect();
try
{
client.Execute(command);
2013-11-03 23:53:49 +13:00
return true;
}
catch
{
return false;
}
}
public void Dispose()
{
if (client != null)
{
Disconnect();
client.Dispose();
}
2013-11-03 23:53:49 +13:00
}
}
}