-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploader.cs
129 lines (103 loc) · 3.24 KB
/
Uploader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
using Renci.SshNet;
using System;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace ExpressBackup
{
public abstract class Uploader
{
public string
Host,
User,
Password,
Path;
[XmlAttribute]
public bool
Disabled = false;
public abstract void Upload(string file);
public abstract void Delete(string file);
public abstract string[] GetFileList(string path);
protected void PrintProgress(long uploaded, long total)
{
string
progress = string.Format("{0:0.0}%", (float)uploaded / total * 100);
Console.Write(progress);
foreach (var c in progress)
Console.Write("\b");
}
}
public class FtpUploader : Uploader
{
public override void Upload(string file)
{
var
helper = new FtpHelper(this.Host, this.User, this.Password, this.Path);
helper.Progress += (uploaded, total) => PrintProgress(uploaded, total);
Log.Entry(LogSeverity.Debug, "ftp upload {0}.7z to {1}", file, this.Host);
Console.Write("done ");
helper.UploadFile(file + ".7z");
Console.WriteLine();
}
public override void Delete(string file)
{
new FtpHelper(this.Host, this.User, this.Password, this.Path).DeleteFile(file);
}
public override string[] GetFileList(string path)
{
return new FtpHelper(this.Host, this.User, this.Password, this.Path).GetFileList(path);
}
}
public class SftpUploader : Uploader
{
public int
Port = 22;
public override void Upload(string file)
{
var
fi = new FileInfo(file + ".7z");
Log.Entry(LogSeverity.Debug, "sftp upload {0} to {1}", fi.FullName, this.Host);
Execute(sftp =>
{
sftp.ChangeDirectory(this.Path);
Console.Write("done ");
using (var fs = File.OpenRead(fi.FullName))
sftp.UploadFile(fs, fi.Name, true, uploaded => PrintProgress((long)uploaded, fs.Length));
Console.WriteLine();
});
}
public override void Delete(string file)
{
Execute(sftp =>
{
sftp.ChangeDirectory(this.Path);
sftp.DeleteFile(file);
});
}
public override string[] GetFileList(string path)
{
var
temp = new string[0];
Execute(sftp =>
{
temp = sftp.ListDirectory(path).Where(e => e.IsRegularFile).Select(e => e.Name).ToArray();
});
return temp;
}
void Execute(Action<SftpClient> action)
{
using (var client = new SftpClient(this.Host, this.Port, this.User, this.Password))
{
client.Connect();
try
{
action(client);
}
finally
{
client.Disconnect();
}
}
}
}
}