-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFtpLib.cs
More file actions
564 lines (512 loc) · 19.9 KB
/
FtpLib.cs
File metadata and controls
564 lines (512 loc) · 19.9 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using EnterpriseDT.Net.Ftp;
namespace modsync
{
/// <summary>
/// Wrapper class around the EnterpriseDT Ftp library
/// </summary>
public class FtpLib
{
private FTPConnection FtpServer;
private long BytesTotal = 0;
private long BytesDone = 0;
private long BytesLast = 0;
private string LastFile = "";
public FtpLib(ref FTPConnection con)
{
this.FtpServer = con;
this.FtpServer.ReplyReceived += HandleMessages;
this.FtpServer.CommandSent += HandleMessages;
this.FtpServer.Downloaded += new FTPFileTransferEventHandler(FtpServer_Downloaded);
this.FtpServer.Uploaded += new FTPFileTransferEventHandler(FtpServer_Uploaded);
this.FtpServer.BytesTransferred += HandleProgress;
//this.FtpServer.TransferNotifyInterval = 1024;
}
// Handler for status indicator
private void ShowStatus(int lvl, string msg)
{
if (lvl <= 1)
{
Console.WriteLine(msg);
}
}
// Progress event handler
private void ShowProgress(int progress)
{
Console.Write("\r{0}% ", progress);
}
public void LogIn()
{
ShowStatus(2, "Connecting to " + this.FtpServer.ServerAddress);
this.FtpServer.Connect();
}
public void DisConnect()
{
if (IsConnected())
{
try
{
this.FtpServer.Close();
}
catch (Exception)
{
}
}
}
public bool IsConnected()
{
return this.FtpServer.IsConnected;
}
public string CurrentWorkingFolder()
{
return this.FtpServer.ServerDirectory;
}
/// <summary>
/// Compare local directory with remote directory
/// </summary>
/// <param name="localFolder">folder @ client</param>
/// <param name="remoteFolder">folder @ server</param>
/// <param name="recursive">Will we go into directories?</param>
/// <returns>List of modifications to make</returns>
public List<FTPSyncModification> CompareDirectory(string localFolder, string remoteFolder, FTPSyncSettings settings)
{
BytesTotal = 0;
BytesDone = 0;
BytesLast = 0;
LastFile = "";
// make list of local files
List<string> locals = new List<string>();
GetLocalFiles(ref locals, localFolder, settings.Recurse);
// check remote files
List<FTPSyncModification> mods = new List<FTPSyncModification>();
CheckRemoteFiles(ref locals, ref mods, localFolder, remoteFolder, settings);
if (settings.WhenMissingRemote != FTPAction.Noop)
{
// local files still in list have been added
FileInfo fi;
foreach (string LocalFile in locals)
{
fi = new FileInfo(LocalFile);
FTPSyncModification m = new FTPSyncModification();
m.Exists = false;
m.Upload = true;
m.Action = settings.WhenMissingRemote;
m.LocalFile = LocalFile;
m.ModifiedTime = fi.LastWriteTime;
m.RemoteFile = LocalFile.Replace(localFolder, remoteFolder).Replace('\\', '/');
if (settings.WhenMissingRemote == FTPAction.Copy)
{
BytesTotal += fi.Length;
}
mods.Add(m);
ShowMod(m);
}
}
return mods;
}
private void GetLocalFiles(ref List<string> files, string localFolder, bool recursive)
{
// create local dir if not present
CreateDirectoryLocal(new DirectoryInfo(localFolder));
// add files in current dir
foreach (string f in Directory.GetFiles(localFolder))
{
files.Add(Path.Combine(localFolder, f));
}
// recurse into directories
if (recursive)
{
foreach (string d in Directory.GetDirectories(localFolder))
{
if (d != "." && d != "..")
{
GetLocalFiles(ref files, d, recursive);
}
}
}
}
/// <summary>
/// Check all remote files for:
/// </summary>
/// <param name="locals"></param>
/// <param name="mods">List of modifications. Items are added when syncing is required</param>
/// <param name="localFolder">folder @ client</param>
/// <param name="remoteFolder">folder @ server</param>
/// <param name="recursive">if true, directories are also checked by recalling this function </param>
private void CheckRemoteFiles(ref List<string> locals, ref List<FTPSyncModification> mods, string localFolder, string remoteFolder, FTPSyncSettings settings)
{
this.FtpServer.ChangeWorkingDirectory(remoteFolder);
FTPFile[] FtpServerFileInfo = this.FtpServer.GetFileInfos();
string LocalTargetFolder = null;
string FtpTargetFolder = null;
bool AddModification = false;
FileInfo fi = default(FileInfo);
foreach (FTPFile CurrentFileOrDirectory in FtpServerFileInfo)
{
if (settings.Recurse)
{
if (CurrentFileOrDirectory.Dir && CurrentFileOrDirectory.Name != "." && CurrentFileOrDirectory.Name != "..")
{
LocalTargetFolder = Path.Combine(localFolder, CurrentFileOrDirectory.Name);
FtpTargetFolder = string.Format("{0}/{1}", remoteFolder, CurrentFileOrDirectory.Name);
CheckRemoteFiles(ref locals, ref mods, LocalTargetFolder, FtpTargetFolder, settings);
// set the ftp working folder back to the correct value
this.FtpServer.ChangeWorkingDirectory(remoteFolder);
}
}
if (!CurrentFileOrDirectory.Dir)
{
FTPSyncModification m = new FTPSyncModification();
AddModification = false;
DateTime RemoteStamp = TimeZone.CurrentTimeZone.ToLocalTime(CurrentFileOrDirectory.LastModified);
m.LocalFile = Path.Combine(localFolder, CurrentFileOrDirectory.Name);
m.RemoteFile = string.Format("{0}/{1}", remoteFolder, CurrentFileOrDirectory.Name);
// check file existence
if (!File.Exists(m.LocalFile))
{
if (settings.WhenMissingLocal != FTPAction.Noop)
{
AddModification = true;
m.Exists = false;
m.ModifiedTime = RemoteStamp;
m.Upload = false;
m.Action = settings.WhenMissingLocal;
if (settings.WhenMissingLocal == FTPAction.Copy)
{
BytesTotal += CurrentFileOrDirectory.Size;
}
}
}
else
{
// read file info
fi = new FileInfo(m.LocalFile);
DateTime LocalStamp = TimeZone.CurrentTimeZone.ToLocalTime(fi.LastWriteTime);
// check file size
if (CurrentFileOrDirectory.Size != fi.Length)
{
m.Exists = true;
if (CurrentFileOrDirectory.Size < fi.Length)
{
if (settings.WhenLargerLocal == FTPAction.Copy)
{
AddModification = true;
m.ModifiedTime = LocalStamp;
m.Upload = true;
m.Action = settings.WhenLargerLocal;
BytesTotal += fi.Length;
}
}
else
{
if (settings.WhenLargerRemote == FTPAction.Copy)
{
AddModification = true;
m.ModifiedTime = RemoteStamp;
m.Upload = false;
m.Action = settings.WhenLargerRemote;
BytesTotal += CurrentFileOrDirectory.Size;
}
}
}
// check modification time
TimeSpan TimeDiff = RemoteStamp - LocalStamp;
if ((TimeDiff < TimeSpan.FromMinutes(-1)) || (TimeDiff > TimeSpan.FromMinutes(1)))
{
m.Exists = true;
if (RemoteStamp < LocalStamp)
{
if (settings.WhenNewerLocal == FTPAction.Copy)
{
AddModification = true;
m.ModifiedTime = LocalStamp;
m.Upload = true;
m.Action = settings.WhenNewerLocal;
BytesTotal += fi.Length;
}
}
else
{
if (settings.WhenNewerRemote == FTPAction.Copy)
{
AddModification = true;
m.ModifiedTime = RemoteStamp;
m.Upload = false;
m.Action = settings.WhenNewerRemote;
BytesTotal += CurrentFileOrDirectory.Size;
}
}
}
// remove from local list
locals.Remove(m.LocalFile);
}
if (AddModification)
{
mods.Add(m);
ShowMod(m);
}
}
}
}
private void ShowMod(FTPSyncModification mod)
{
string LocalFile = mod.LocalFile.Replace(Locations.LocalFolderName_Minecraft + "\\", "");
string RemoteFile = mod.RemoteFile.Replace(Config.ftpsettings.FtpServerFolder + "/", "");
switch (mod.Action)
{
case FTPAction.Copy:
if (mod.Upload)
{
ShowStatus(1, string.Format("--> {0} ({1} {2})", LocalFile, (mod.Exists ? "Updated" : "Added"), mod.ModifiedTime.ToShortDateString()));
}
else
{
ShowStatus(1, string.Format("<-- {0} ({1} {2})", RemoteFile, (mod.Exists ? "Updated" : "Added"), mod.ModifiedTime.ToShortDateString()));
}
break;
case FTPAction.Delete:
if (mod.Upload)
{
ShowStatus(1, string.Format(" X {0}", LocalFile));
}
else
{
ShowStatus(1, string.Format(" X {0}", RemoteFile));
}
break;
}
}
/// <summary>
/// Synchronize local files with files on the server
/// </summary>
/// <param name="mods">List of modifications to make</param>
public void SynchronizeFiles(List<FTPSyncModification> mods, bool prompt)
{
foreach (FTPSyncModification mod in mods)
{
// ask user to delete or overwrite existing file
if (prompt && ((mod.Action == FTPAction.Delete) || mod.Exists))
{
if (!ConfirmModification(mod))
{
continue;
}
}
switch (mod.Action)
{
case FTPAction.Copy:
if (mod.Upload)
{
UploadModification(mod);
}
else
{
DownloadModification(mod);
}
break;
case FTPAction.Delete:
if (mod.Upload)
{
DeleteLocalMod(mod);
}
else
{
DeleteRemoteMod(mod);
}
break;
}
}
}
private bool ConfirmModification(FTPSyncModification mod)
{
while (true)
{
switch (mod.Action)
{
case FTPAction.Copy:
if (mod.Upload)
{
Console.WriteLine("Overwrite remote file: " + mod.LocalFile + "? Y/N");
}
else
{
Console.WriteLine("Overwrite local file: " + mod.RemoteFile + "? Y/N");
}
break;
case FTPAction.Delete:
if (mod.Upload)
{
Console.WriteLine("Delete local file: " + mod.LocalFile + "? Y/N");
}
else
{
Console.WriteLine("Delete remote file: " + mod.RemoteFile + "? Y/N");
}
break;
}
string overwrite = Console.ReadLine();
if (overwrite.ToUpper().Equals("Y"))
{
return true;
}
else if (overwrite.ToUpper().Equals("N"))
{
return false;
}
}
}
private void UploadModification(FTPSyncModification mod)
{
if (mod.Exists)
{
this.FtpServer.DeleteFile(mod.RemoteFile);
}
// check directory
string dir = mod.RemoteFile.Substring(0, mod.RemoteFile.LastIndexOf('/'));
CreateDirectoryRemote(dir);
// upload file
this.FtpServer.UploadFile(mod.LocalFile, mod.RemoteFile);
// update file properties
try
{
this.FtpServer.SetLastWriteTime(mod.RemoteFile, mod.ModifiedTime);
}
catch (Exception)
{
}
}
private void DownloadModification(FTPSyncModification mod)
{
FileInfo fi;
// delete old file
if (mod.Exists)
{
File.Delete(mod.LocalFile);
}
// check directory
string dir = Path.GetDirectoryName(mod.LocalFile);
CreateDirectoryLocal(new DirectoryInfo(dir));
// download file
this.FtpServer.DownloadFile(mod.LocalFile, mod.RemoteFile);
// update file properties
fi = new FileInfo(mod.LocalFile);
fi.CreationTime = mod.ModifiedTime;
fi.LastAccessTime = mod.ModifiedTime;
fi.LastWriteTime = mod.ModifiedTime;
}
private void DeleteLocalMod(FTPSyncModification mod)
{
File.Delete(mod.LocalFile);
}
private void DeleteRemoteMod(FTPSyncModification mod)
{
this.FtpServer.DeleteFile(mod.RemoteFile);
}
public void CreateDirectoryLocal(DirectoryInfo dirInfo)
{
if (!dirInfo.Exists)
{
if (dirInfo.Parent != null)
{
CreateDirectoryLocal(dirInfo.Parent);
}
ShowStatus(2, "FTP: Creating dir " + dirInfo.FullName);
dirInfo.Create();
}
}
public void CreateDirectoryRemote(string dirName)
{
if (!this.FtpServer.DirectoryExists(dirName))
{
string parent = "";
int index = dirName.LastIndexOf('/');
if (index > 0) parent = dirName.Substring(0, index);
if (parent != "")
{
CreateDirectoryRemote(parent);
}
ShowStatus(2, "FTP: Creating dir " + dirName);
this.FtpServer.CreateDirectory(dirName);
}
}
// status feedback
private void HandleMessages(object sender, FTPMessageEventArgs e)
{
ShowStatus(3, "FTP: " + e.Message);
}
// progress feedback
private void HandleProgress(object sender, BytesTransferredEventArgs e)
{
if (BytesTotal == 0)
{
return;
}
try
{
// bug in edtFTPnet: path incorrect, so we need to check filename as well as size
if ((e.RemoteFile != LastFile) || (e.ByteCount < BytesLast))
{
BytesDone += BytesLast;
}
LastFile = e.RemoteFile;
BytesLast = e.ByteCount;
int perc = (int)((long)100 * (BytesDone + BytesLast) / BytesTotal);
if (perc > 100) perc = 100;
ShowProgress(perc);
}
catch
{
}
}
private void FtpServer_Uploaded(object sender, FTPFileTransferEventArgs e)
{
ShowStatus(2, "FTP: Uploaded " + e.RemoteFile);
}
private void FtpServer_Downloaded(object sender, FTPFileTransferEventArgs e)
{
ShowStatus(2, "FTP: Downloaded " + e.RemoteFile);
}
}
/// <summary>
/// Modification record
/// </summary>
public class FTPSyncModification
{
public bool Upload; /*if true: upload modification, otherwise download modification*/
public bool Exists;
public string LocalFile;
public string RemoteFile;
public DateTime ModifiedTime;
public FTPAction Action;
}
public enum FTPAction
{
Noop,
Copy,
Delete
}
/// <summary>
/// Sync settings
/// </summary>
public class FTPSyncSettings
{
// go into directories
public bool Recurse;
// what to do when missing remote
public FTPAction WhenMissingRemote;
// what to do when missing local
public FTPAction WhenMissingLocal;
// what to do when newer remote
public FTPAction WhenNewerRemote;
// what to do when newer local
public FTPAction WhenNewerLocal;
// what to do when larger remote
public FTPAction WhenLargerRemote;
// what to do when larger local
public FTPAction WhenLargerLocal;
}
}