-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectoryHandler.cs
602 lines (551 loc) · 21.7 KB
/
DirectoryHandler.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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Data;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections;
using System.Threading;
using System.ComponentModel;
namespace CSL
{
class DirectoryHandler : BackgroundWorker
{
static FileInfo ErrorLog = new FileInfo(Directory.GetCurrentDirectory() + "\\" + "errorlog.txt");
private object locker = new object();
public DirectoryHandler()
{
WorkerReportsProgress = true;
WorkerSupportsCancellation = true;
}
protected override void OnDoWork(DoWorkEventArgs e)
{
Type t = null;
if (e.Argument != null)
{
t = e.Argument.GetType();
if (t.Equals(typeof(String[])))
{
List<FileInfo> list = UnzipFiles((string[])e.Argument);
e.Result = list;
}
}
}
public static void CreateEmptyDirectories(List<String> paths)
{
foreach (string path in paths)
{
try
{
DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists) { di.Create(); }
}
catch { }
}
}
public static void LogError(string error)
{
/*
FileStream fs = null;
if (!ErrorLog.Exists)
ErrorLog.Create();
try
{
fs = ErrorLog.OpenWrite();
List<byte> bytes = new List<byte>();
foreach (char l in error.ToCharArray())
bytes.Add(Convert.ToByte(l));
fs.Write(bytes.ToArray(), 0, bytes.Count);
}
catch { }
finally { if(fs != null)fs.Close(); }*/
}
public static bool DeleteFile(FileInfo file)
{
try
{
file.Delete();
}
catch (IOException ioe)
{
LogError(ioe.Message + "\n" + ioe.StackTrace);
}
catch (System.Security.SecurityException soe)
{
LogError(soe.Message + "\n" + soe.StackTrace);
}
catch (UnauthorizedAccessException ue)
{
LogError(ue.Message + "\n" + ue.StackTrace);
}
if (file.Exists)
return false; //Didn't delete successfully
else
return true; //Deleted
}
public static bool DeleteFolder(DirectoryInfo folder)
{
try
{
folder.Delete(true);
}
catch (IOException ioe)
{
LogError(ioe.Message + "\n" + ioe.StackTrace);
}
catch (System.Security.SecurityException soe)
{
LogError(soe.Message + "\n" + soe.StackTrace);
}
if (folder.Exists)
return false; //Didn't delete successfully
else
return true; //Deleted
}
public static bool DeleteTempFolder()
{
if (Directory.Exists(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL]--Temp"))
Directory.Delete(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL]--Temp", true);
if (!Directory.Exists(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL]--Temp"))
return true;
else
return false;
}
public static void DeleteZipFiles()
{
string[] zipFiles = null;
zipFiles = Directory.GetFiles(SettingsHandler.GetTorrentSaveFolder(), "*.zip", SearchOption.TopDirectoryOnly);
for (int a = 0; a < zipFiles.Length; a++)
{
File.Delete(zipFiles[a]);
}
}
public static bool GetFileExists(string file)
{
FileInfo fi = new FileInfo(file);
if (fi.Exists)
return true;
else
return false;
}
public static string[] GetTorrentZips()
{
string[] files;
try
{
files = Directory.GetFiles(SettingsHandler.GetTorrentSaveFolder(), "*.zip", SearchOption.TopDirectoryOnly);
return (files.Length == 0) ? null : files;
}
catch { return null; }
}
public static string[] GetTorrents()
{
try
{
string[] files = Directory.GetFiles(SettingsHandler.GetTorrentSaveFolder(), "*.torrent", SearchOption.TopDirectoryOnly);
return (files.Length == 0) ? null : files;
}
catch { return null; }
}
public static FileInfo[] GetFileInfos(string[] files)
{
List<FileInfo> infos = new List<FileInfo>();
foreach (string file in files)
infos.Add(new FileInfo(file));
return infos.ToArray<FileInfo>();
}
public static string GetHTMLLookUp(string value)
{
StreamReader sr = null;
string[] ab = new string[2];
string a;
string b;
int c = 0;
string[] lines = null;
string replace;
if (value == null)
return value;
try
{
sr = new StreamReader(System.Windows.Forms.Application.StartupPath + @"\HTML-Look-Up.txt");
while (!sr.EndOfStream)
{
ab = sr.ReadLine().Split(' ');
a = ab[0];
b = ab[1];
if (value.Contains(a) || value.Contains(b))
{
while (value.Contains(a))
{
replace = sr.ReadLine();
value = value.Replace(a, replace);
}
while (value.Contains(b))
{
replace = sr.ReadLine();
value = value.Replace(b, replace);
}
}
else
{
sr.ReadLine();
}
}
}
catch (FileNotFoundException)
{
ErrorWindow ew = new ErrorWindow();
ew.IssueGeneralWarning("HTML replacing will not occur", "Could not find HTML-Look-Up.txt...", null);
}
catch (Exception e)
{
ErrorWindow ew = new ErrorWindow();
ew.IssueGeneralWarning("Error..", lines[c], e.Message);
}
finally
{
if (sr != null)
sr.Dispose();
}
return value;
}
public static bool MoveFile(FileInfo origin, DirectoryInfo dest)
{
if (File.Exists(dest.Name + origin.Name))
{
if (!origin.DirectoryName.Equals(dest.Name))
DirectoryHandler.DeleteFile(origin);
return true;
}
else
{
try
{
origin.MoveTo(dest.FullName + "\\" + origin.Name);
}
catch (Exception e)
{
LogError(e.Message + "\n" + e.StackTrace);
}
}
if (File.Exists(dest.Name + origin.Name))
return true;
else
return false;
}
public static string[] UnzipFile(string zipFile)
{
string destination;
string[] files;
FastZip fz = new FastZip();
FileInfo fi = new FileInfo(zipFile);
if (fi.Exists)
{
try
{
destination = SettingsHandler.GetTorrentSaveFolder() + @"\[CSL]--Temp\" + fi.Name;
Directory.CreateDirectory(destination);
fz.ExtractZip(zipFile, destination, ".torrent");
files = Directory.GetFiles(destination, "*.torrent", SearchOption.AllDirectories);
try
{
fi.MoveTo(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL] -- Processed Zips\" + fi.Name);
}
catch(Exception e) { }
return files;
}
catch (Exception)
{
return null;
}
}
else
{
return null;
}
}
//To be called only from DoWork
public List<FileInfo> UnzipFiles(string[] zipFiles)
{
List<FileInfo> items = new List<FileInfo>();
List<FileInfo> fileinfos = new List<FileInfo>();
foreach (string zipfile in zipFiles)
{
try
{
fileinfos.Add(new FileInfo(zipfile));
}
catch (Exception e)
{
LogError(e.Message + "\n" + e.StackTrace);
}
}
FastZip fz = new FastZip();
ErrorWindow ew = new ErrorWindow();
string[] files = null;
string filename;
DirectoryInfo destination;
int total = zipFiles.Length;
double progress = 0;
double count = 0;
foreach (FileInfo zipfile in fileinfos)
{
filename = zipfile.Name;
filename = filename.Replace(zipfile.Extension, "");
string dest = SettingsHandler.GetTorrentSaveFolder() + @"\[CSL]--Temp\" + filename + @"\";
destination = new DirectoryInfo(dest);
if (!destination.Exists)
{
try
{
destination.Create();
}
catch (Exception e)
{
LogError(e.Message + "\n" + e.StackTrace);
}
}
try
{
fz.ExtractZip(zipfile.FullName, destination.FullName, ".torrent");
}
catch (Exception) { ew.IssueGeneralWarning("No action necessary", "Warning: Could not unzip " + filename, zipfile.Name); }
try
{
files = Directory.GetFiles(destination.FullName,
"*.torrent", SearchOption.AllDirectories);
}
catch (DirectoryNotFoundException) { ew.IssueGeneralWarning("No action necessary", "Warning: " + filename + "was empty", zipfile.Name); }
finally
{
foreach (string file in files)
{
try
{
items.Add(new FileInfo(file));
}
catch (Exception e)
{
LogError(e.Message + "\n" + e.StackTrace);
}
}
}
try
{
zipfile.MoveTo(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL] -- Processed Zips\" + zipfile.Name);
}
catch { }
progress = (++count / total) * 100;
if (progress <= 100 && progress >= 0)
ReportProgress((int)progress);
}
return items;
}
public static void MoveZipFiles()
{
string[] zipFiles;
//MOVE ZIP FILES
zipFiles = Directory.GetFiles(SettingsHandler.GetTorrentSaveFolder(), "*.zip", SearchOption.TopDirectoryOnly);
List<FileInfo> zips = new List<FileInfo>();
foreach (string zipfile in zipFiles)
zips.Add(new FileInfo(zipfile));
if (zips != null && zips.Count > 0)
{
DirectoryInfo zipsavefolder = new DirectoryInfo(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL] -- Processed Zips");
if (!zipsavefolder.Exists)
zipsavefolder.Create();
foreach (FileInfo zip in zips)
{
if (!zip.DirectoryName.Equals(zipsavefolder.FullName))
{
try
{
zip.MoveTo(zipsavefolder.FullName + "\\" + zip.Name);
}
catch { zip.Delete(); }
}
}
}
//DELETE TEMP FOLDER
DirectoryHandler.DeleteTempFolder();
}
public static string MoveTorrentFile(Torrent t)
{
FileInfo fi;
DirectoryInfo cslSaveFolder = null;
string filename;
string file = t.GetPath();
string where = (t.GetDiscard()) ? "unhandled" : "handled";
try
{
fi = new FileInfo(file);
filename = fi.Name;
switch (where)
{
case "handled":
cslSaveFolder = new DirectoryInfo(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL] -- Handled Torrents\");
break;
case "unhandled":
cslSaveFolder = new DirectoryInfo(SettingsHandler.GetTorrentSaveFolder() + @"\[CSL] -- Unhandled Torrents\");
break;
default:
cslSaveFolder = new DirectoryInfo(SettingsHandler.GetTorrentSaveFolder() + '\\' + where + '\\');
break;
}
if (!cslSaveFolder.Exists)
cslSaveFolder.Create();
if (fi.FullName.Equals(cslSaveFolder + fi.Name)) //In handled directory already
return fi.FullName;
if (File.Exists(cslSaveFolder.FullName + fi.Name))
{
fi.Delete();
return cslSaveFolder.FullName + fi.Name;
}
else if (fi != null)
{
fi.MoveTo(cslSaveFolder.FullName + "\\" + fi.Name);
return fi.FullName;
}
else
{
return null;
}
}
catch (Exception e)
{
LogError(e.Message + "\n" + e.StackTrace);
return null;
}
}
#region Dead Methods (for reference)
/****DEAD
//To be called only from DoWork
public void MoveProcessedFiles()
{
string filepath;
bool skip = false;
int total = TorrentDataHandler.table.Rows.Count;
double progress = 0;
double count = 0;
List<DataRow> items = new List<DataRow>();
while (true)
{
DataTable copytable= null;
if (this.CancellationPending)
{
//lock (locker) { copytable = TorrentXMLHandler.GetProcessedRows(); }
}
//GET A COPY OF ALL NEWLY ADDED TORRENTS
//and work with the copied table to allow TorrentXMLHandler to properly add/remove
else
{
lock (locker) { copytable = TorrentDataHandler.table.GetChanges(DataRowState.Added); }
}
if (copytable != null && copytable.Rows.Count > 0)
{
foreach (DataRow dr in copytable.Rows)
{
if (dr["Processed"] != DBNull.Value && (bool)dr["Processed"])
{
if (!dr["File Path"].Equals(DBNull.Value))
{
int index = copytable.Rows.IndexOf(dr);
filepath = (string)dr["File Path"];
if (filepath.Contains("[CSL] -- Unhandled Torrents") && (bool)dr["Error"])
skip = true;
else
skip = false;
if (!skip)
{
switch ((bool)dr["Error"])
{
case true:
filepath = MoveTorrentFile((string)dr["File Path"], "unhandled");
if (filepath == null)
{
copytable.Rows[index]["File Path"] = "Problem moving file..";
copytable.Columns["Error"].ReadOnly = false;
copytable.Rows[index]["Error"] = true;
copytable.Columns["Error"].ReadOnly = true;
}
else
copytable.Rows[index]["File Path"] = filepath;
break;
case false:
try
{
filepath = MoveTorrentFile((string)dr["File Path"], "Sent");
if (filepath == null)
{
copytable.Rows[index]["File Path"] = "Problem moving file..";
copytable.Columns["Error"].ReadOnly = false;
copytable.Rows[index]["Error"] = true;
copytable.Columns["Error"].ReadOnly = true;
}
else
copytable.Rows[index]["File Path"] = filepath;
}
catch (Exception e) { LogError(e.Message + "\n" + e.StackTrace); }
break;
default:
filepath = MoveTorrentFile((string)dr["File Path"], "Sent");
if (filepath == null)
{
copytable.Rows[index]["File Path"] = "Problem moving file..";
copytable.Columns["Error"].ReadOnly = false;
copytable.Rows[index]["Error"] = true;
copytable.Columns["Error"].ReadOnly = true;
}
else
copytable.Rows[index]["File Path"] = filepath;
break;
}
}
}
progress = (++count / total) * 100;
if (progress <= 100 && progress >= 0)
ReportProgress((int)progress);
}
}//END FOREACH
//Load the copytable back into TorrentXMLHandler
lock (locker)
{
TorrentDataHandler.table.Columns["Error"].ReadOnly = false;
foreach (DataRow dr in copytable.Rows)
{
DataRow find = TorrentDataHandler.table.Rows.Find(dr["File"]);
if (find != null)
{
int index = TorrentDataHandler.table.Rows.IndexOf(find);
try
{
TorrentDataHandler.table.Rows[index]["File Path"] = dr["File Path"];
TorrentDataHandler.table.Rows[index]["Error"] = dr["Error"];
}
catch (Exception e) { DirectoryHandler.LogError(e.Message + "\n" + e.StackTrace); }
}
}
TorrentDataHandler.table.Columns["Error"].ReadOnly = true;
try
{
TorrentDataHandler.table.AcceptChanges();
}
catch (Exception e) { DirectoryHandler.LogError(e.Message + "\n" + e.StackTrace); }
}
}
if (this.CancellationPending)
{
//copytable = TorrentXMLHandler.GetProcessedRows();
if (copytable.Rows.Count == 0)
break; //Break out of while
}
else
Thread.Sleep(150);
}
* */
////
#endregion
}
}