forked from SuperGouge/ChanThreadWatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
frmChanThreadWatch.cs
1519 lines (1397 loc) · 67.1 KB
/
frmChanThreadWatch.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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using JDP.Properties;
namespace JDP {
public partial class frmChanThreadWatch : Form {
private Dictionary<long, DownloadProgressInfo> _downloadProgresses = new Dictionary<long, DownloadProgressInfo>();
private frmDownloads _downloadForm;
private object _startupPromptSync = new object();
private bool _isExiting;
private bool _saveThreadList;
private int _itemAreaY;
private int[] _columnWidths;
private object _cboCheckEveryLastValue;
private bool _isLoadingThreadsFromFile;
private static Dictionary<string, int> _categories = new Dictionary<string, int>();
private static Dictionary<string, ThreadWatcher> _watchers = new Dictionary<string, ThreadWatcher>();
private static HashSet<string> _blacklist = new HashSet<string>();
// ReleaseDate property and version in AssemblyInfo.cs should be updated for each release.
public frmChanThreadWatch() {
InitializeComponent();
Icon = Resources.ChanThreadWatchIcon;
niTrayIcon.Icon = Resources.ChanThreadWatchIcon;
Settings.Load();
string logPath = Path.Combine(Settings.GetSettingsDirectory(), Settings.LogFileName);
if (!File.Exists(logPath)) {
try { File.Create(logPath); }
catch { }
}
int initialWidth = ClientSize.Width;
GUI.SetFontAndScaling(this);
float scaleFactorX = (float)ClientSize.Width / initialWidth;
if (Settings.ClientSize != null) {
Size newSize = Settings.ClientSize.Value + Size - ClientSize;
if (newSize.Width >= MinimumSize.Width && newSize.Height >= MinimumSize.Height) {
ClientSize = Settings.ClientSize.Value;
}
}
_columnWidths = new int[lvThreads.Columns.Count];
for (int iColumn = 0; iColumn < lvThreads.Columns.Count; iColumn++) {
ColumnHeader column = lvThreads.Columns[iColumn];
if (iColumn < Settings.ColumnWidths.Length) {
column.Width = Settings.ColumnWidths[iColumn] > 0 ? Settings.ColumnWidths[iColumn] : 0;
}
else {
column.Width = Convert.ToInt32(column.Width * scaleFactorX);
}
_columnWidths[iColumn] = column.Width != 0 ? column.Width : Settings.DefaultColumnWidths[iColumn];
if (iColumn < Settings.ColumnIndices.Length && Settings.ColumnIndices[iColumn] > 0 && Settings.ColumnIndices[iColumn] < lvThreads.Columns.Count) {
column.DisplayIndex = Settings.ColumnIndices[iColumn];
}
}
GUI.EnableDoubleBuffering(lvThreads);
BindCheckEveryList();
BuildCheckEverySubMenu();
BuildColumnHeaderMenu();
if ((Settings.DownloadFolder == null) || !Directory.Exists(Settings.AbsoluteDownloadDirectory)) {
Settings.DownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Watched Threads");
Settings.DownloadFolderIsRelative = false;
}
if (Settings.CheckEvery == 1) {
Settings.CheckEvery = 0;
}
chkPageAuth.Checked = Settings.UsePageAuth ?? false;
txtPageAuth.Text = Settings.PageAuth ?? String.Empty;
chkImageAuth.Checked = Settings.UseImageAuth ?? false;
txtImageAuth.Text = Settings.ImageAuth ?? String.Empty;
chkOneTime.Checked = Settings.OneTimeDownload ?? false;
chkAutoFollow.Checked = Settings.AutoFollow ?? false;
if (Settings.CheckEvery != null) {
foreach (ListItemInt32 item in cboCheckEvery.Items) {
if (item.Value != Settings.CheckEvery) continue;
cboCheckEvery.SelectedValue = Settings.CheckEvery;
break;
}
if ((int)cboCheckEvery.SelectedValue != Settings.CheckEvery) txtCheckEvery.Text = Settings.CheckEvery.ToString();
}
else {
cboCheckEvery.SelectedValue = 3;
}
OnThreadDoubleClick = Settings.OnThreadDoubleClick ?? ThreadDoubleClickAction.OpenFolder;
if ((Settings.CheckForUpdates == true) && (Settings.LastUpdateCheck ?? DateTime.MinValue) < DateTime.Now.Date) {
CheckForUpdates();
}
niTrayIcon.Visible = Settings.MinimizeToTray ?? false;
}
public Dictionary<long, DownloadProgressInfo> DownloadProgresses {
get { return _downloadProgresses; }
}
private ThreadDoubleClickAction OnThreadDoubleClick {
get {
if (rbEdit.Checked)
return ThreadDoubleClickAction.Edit;
else if (rbOpenURL.Checked)
return ThreadDoubleClickAction.OpenURL;
else
return ThreadDoubleClickAction.OpenFolder;
}
set {
if (value == ThreadDoubleClickAction.Edit)
rbEdit.Checked = true;
else if (value == ThreadDoubleClickAction.OpenURL)
rbOpenURL.Checked = true;
else
rbOpenFolder.Checked = true;
}
}
private void frmChanThreadWatch_Shown(object sender, EventArgs e) {
UseWaitCursor = true;
btnAdd.Enabled = false;
btnAddFromClipboard.Enabled = false;
btnRemoveCompleted.Enabled = false;
btnDownloads.Enabled = false;
btnSettings.Enabled = false;
btnAbout.Enabled = false;
btnHelp.Enabled = false;
lvThreads.Enabled = false;
Application.DoEvents();
lvThreads.Items.Add(new ListViewItem());
_itemAreaY = lvThreads.GetItemRect(0).Y;
lvThreads.Items.RemoveAt(0);
Thread thread = new Thread(() => {
LoadThreadList();
LoadBlacklist();
Invoke(() => {
UseWaitCursor = false;
btnAdd.Enabled = true;
btnAddFromClipboard.Enabled = true;
btnRemoveCompleted.Enabled = true;
btnDownloads.Enabled = true;
btnSettings.Enabled = true;
btnAbout.Enabled = true;
btnHelp.Enabled = true;
lvThreads.Enabled = true;
lvThreads.ListViewItemSorter = new ListViewItemSorter(Settings.SortColumn ?? (int)ColumnIndex.AddedOn) { Ascending = Settings.SortAscending ?? true };
lvThreads.Sort();
FocusLastThread();
});
});
thread.Start();
}
private void frmChanThreadWatch_FormClosed(object sender, FormClosedEventArgs e) {
if (IsDisposed) return;
Settings.UsePageAuth = chkPageAuth.Checked;
Settings.PageAuth = txtPageAuth.Text;
Settings.UseImageAuth = chkImageAuth.Checked;
Settings.ImageAuth = txtImageAuth.Text;
Settings.OneTimeDownload = chkOneTime.Checked;
Settings.AutoFollow = chkAutoFollow.Checked;
Settings.CheckEvery = pnlCheckEvery.Enabled ? (cboCheckEvery.Enabled ? (int)cboCheckEvery.SelectedValue : Int32.Parse(txtCheckEvery.Text)) : 0;
Settings.OnThreadDoubleClick = OnThreadDoubleClick;
if (WindowState == FormWindowState.Normal) {
Settings.ClientSize = ClientSize;
}
int[] columnWidths = new int[lvThreads.Columns.Count];
int[] columnIndices = new int[lvThreads.Columns.Count];
for (int i = 0; i < lvThreads.Columns.Count; i++) {
columnWidths[i] = lvThreads.Columns[i].Width;
columnIndices[i] = lvThreads.Columns[i].DisplayIndex;
}
Settings.ColumnWidths = columnWidths;
Settings.ColumnIndices = columnIndices;
ListViewItemSorter sorter = (ListViewItemSorter)lvThreads.ListViewItemSorter;
if (sorter != null) {
Settings.SortColumn = sorter.Column;
Settings.SortAscending = sorter.Ascending;
}
Settings.Save();
foreach (ThreadWatcher watcher in ThreadWatchers) {
watcher.Stop(StopReason.Exiting);
}
// Save before waiting in addition to after in case the wait hangs or is interrupted
SaveThreadList();
_isExiting = true;
foreach (ThreadWatcher watcher in ThreadWatchers) {
while (!watcher.WaitUntilStopped(10) || !watcher.WaitReparse(10)) {
Application.DoEvents();
}
}
SaveThreadList();
Program.ReleaseMutex();
}
private void frmChanThreadWatch_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent("UniformResourceLocatorW") ||
e.Data.GetDataPresent("UniformResourceLocator"))
{
if ((e.AllowedEffect & DragDropEffects.Copy) != 0) {
e.Effect = DragDropEffects.Copy;
}
else if ((e.AllowedEffect & DragDropEffects.Link) != 0) {
e.Effect = DragDropEffects.Link;
}
}
}
private void frmChanThreadWatch_DragDrop(object sender, DragEventArgs e) {
if (_isExiting) return;
string url = null;
if (e.Data.GetDataPresent("UniformResourceLocatorW")) {
byte[] data = ((MemoryStream)e.Data.GetData("UniformResourceLocatorW")).ToArray();
url = Encoding.Unicode.GetString(data, 0, General.StrLenW(data) * 2);
}
else if (e.Data.GetDataPresent("UniformResourceLocator")) {
byte[] data = ((MemoryStream)e.Data.GetData("UniformResourceLocator")).ToArray();
url = Encoding.Default.GetString(data, 0, General.StrLen(data));
}
url = General.CleanPageURL(url);
if (url != null) {
AddThread(url);
FocusThread(url);
_saveThreadList = true;
}
}
private void frmChanThreadWatch_Resize(object sender, EventArgs e) {
if (WindowState == FormWindowState.Minimized && Settings.MinimizeToTray == true) {
Hide();
}
}
private void frmChanThreadWatch_ResizeEnd(object sender, EventArgs e) {
if (WindowState == FormWindowState.Normal) {
Settings.ClientSize = ClientSize;
}
}
private void txtPageURL_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
btnAdd_Click(txtPageURL, null);
e.SuppressKeyPress = true;
}
}
private void btnAdd_Click(object sender, EventArgs e) {
if (_isExiting) return;
if (txtPageURL.Text.Trim().Length == 0) return;
string pageURL = General.CleanPageURL(txtPageURL.Text);
if (pageURL == null) {
MessageBox.Show(this, "The specified URL is invalid.", "Invalid URL", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!AddThread(pageURL)) {
MessageBox.Show(this, "The same thread is already being watched, downloaded or has been blacklisted.", "Cannot Add Thread", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPageURL.Clear();
FocusThread(pageURL);
return;
}
FocusThread(pageURL);
txtPageURL.Clear();
txtPageURL.Focus();
_saveThreadList = true;
}
private void btnAddFromClipboard_Click(object sender, EventArgs e) {
if (_isExiting) return;
string text;
try {
text = Clipboard.GetText();
}
catch {
return;
}
string[] urls = text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
if (urls.Length > 0) {
lvThreads.SelectedItems.Clear();
lvThreads.Select();
}
for (int iURL = 0; iURL < urls.Length; iURL++) {
string url = General.CleanPageURL(urls[iURL]);
if (url == null) continue;
AddThread(url);
if (urls.Length == 1) {
FocusThread(url);
}
else {
SiteHelper siteHelper = SiteHelpers.GetInstance((new Uri(url)).Host);
siteHelper.SetURL(url);
ThreadWatcher watcher;
if (_watchers.TryGetValue(siteHelper.GetPageID(), out watcher)) {
(((WatcherExtraData)watcher.Tag).ListViewItem).Selected = true;
}
}
}
_saveThreadList = true;
}
private void btnRemoveCompleted_Click(object sender, EventArgs e) {
if (Settings.MoveToCompletedFolder != true) {
RemoveThreads(true, false);
}
else {
if (!Directory.Exists(Settings.AbsoluteCompletedDirectory)) {
Settings.CompletedFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Completed Threads");
Settings.CompletedFolderIsRelative = false;
}
RemoveThreads(true, false,
(watcher) => {
string destDir = Path.Combine(Settings.AbsoluteCompletedDirectory,
General.GetRelativeDirectoryPath(watcher.ThreadDownloadDirectory, watcher.MainDownloadDirectory));
if (Directory.Exists(watcher.ThreadDownloadDirectory)) {
if (Directory.Exists(destDir)) {
Directory.Delete(destDir);
}
if (watcher.Category.Length != 0) {
Directory.CreateDirectory(General.RemoveLastDirectory(destDir));
}
Directory.Move(watcher.ThreadDownloadDirectory, destDir);
}
string categoryPath = General.RemoveLastDirectory(watcher.ThreadDownloadDirectory);
if (categoryPath != watcher.MainDownloadDirectory && Directory.GetFiles(categoryPath).Length == 0 && Directory.GetDirectories(categoryPath).Length == 0) {
Directory.Delete(categoryPath);
}
});
}
}
private void miStop_Click(object sender, EventArgs e) {
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
watcher.Stop(StopReason.UserRequest);
}
_saveThreadList = true;
}
private void miStart_Click(object sender, EventArgs e) {
if (_isExiting) return;
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
if (!watcher.IsRunning && !watcher.IsReparsing) {
watcher.Start();
}
}
_saveThreadList = true;
}
private void miEdit_Click(object sender, EventArgs e) {
if (_isExiting) return;
var selectedThreadWatchers = new List<ThreadWatcher>(SelectedThreadWatchers);
if (selectedThreadWatchers.Count == 0) return;
using (frmThreadEdit editForm = new frmThreadEdit(selectedThreadWatchers, _categories)) {
if (editForm.ShowDialog(this) == DialogResult.OK && editForm.IsDirty) {
foreach (ThreadWatcher watcher in selectedThreadWatchers) {
if (editForm.Description.IsDirty) {
watcher.Description = editForm.Description.Value;
}
if (editForm.Category.IsDirty) {
UpdateCategories(watcher.Category, true);
UpdateCategories(editForm.Category.Value);
watcher.Category = editForm.Category.Value;
}
if (editForm.CheckIntervalSeconds.IsDirty) {
watcher.CheckIntervalSeconds = editForm.CheckIntervalSeconds.Value;
}
if (!watcher.IsRunning) {
if (editForm.PageAuth.IsDirty) {
watcher.PageAuth = editForm.PageAuth.Value;
}
if (editForm.ImageAuth.IsDirty) {
watcher.ImageAuth = editForm.ImageAuth.Value;
}
if (editForm.OneTimeDownload.IsDirty) {
watcher.OneTimeDownload = editForm.OneTimeDownload.Value;
}
if (editForm.AutoFollow.IsDirty) {
watcher.AutoFollow = editForm.AutoFollow.Value;
}
}
DisplayData(watcher);
}
_saveThreadList = true;
}
}
}
private void miOpenFolder_Click(object sender, EventArgs e) {
int selectedCount = lvThreads.SelectedItems.Count;
if (selectedCount > 5 && MessageBox.Show(this, "Do you want to open the folders of all " + selectedCount + " selected items?",
"Open Folders", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
string dir = watcher.ThreadDownloadDirectory;
ThreadWatcher tmpWatcher = watcher;
ThreadPool.QueueUserWorkItem((s) => {
try {
if (!Directory.Exists(dir)) {
tmpWatcher.Stop(StopReason.Other);
BeginInvoke(() => {
MessageBox.Show(this, "The folder " + dir + " does not exists. The watcher has been stopped to let you fix this, in case of an unwanted deletion or rename. If the thread file cannot be found for the next check, it won't include possible deleted posts.",
"Folder Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
});
}
else {
Process.Start(dir);
}
}
catch (Exception ex) {
Logger.Log(ex.ToString());
}
});
}
}
private void miOpenURL_Click(object sender, EventArgs e) {
int selectedCount = lvThreads.SelectedItems.Count;
if (selectedCount > 5 && MessageBox.Show(this, "Do you want to open the URLs of all " + selectedCount + " selected items?",
"Open URLs", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
string url = watcher.PageURL;
ThreadPool.QueueUserWorkItem((s) => {
try {
Process.Start(url);
}
catch (Exception ex) {
Logger.Log(ex.ToString());
}
});
}
}
private void miCopyURL_Click(object sender, EventArgs e) {
StringBuilder sb = new StringBuilder();
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
if (sb.Length != 0) sb.Append(Environment.NewLine);
sb.Append(watcher.PageURL);
}
try {
Clipboard.Clear();
Clipboard.SetText(sb.ToString());
}
catch (Exception ex) {
MessageBox.Show(this, "Unable to copy to clipboard: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void miRemove_Click(object sender, EventArgs e) {
RemoveThreads(false, true);
}
private void miRemoveAndDeleteFolder_Click(object sender, EventArgs e) {
if (MessageBox.Show(this, "Are you sure you want to delete the selected threads and all associated files from disk?",
"Delete From Disk", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
RemoveThreads(false, true,
(watcher) => {
if (Directory.Exists(watcher.ThreadDownloadDirectory)) Directory.Delete(watcher.ThreadDownloadDirectory, true);
string categoryPath = General.RemoveLastDirectory(watcher.ThreadDownloadDirectory);
if (categoryPath != watcher.MainDownloadDirectory && Directory.GetFiles(categoryPath).Length == 0 && Directory.GetDirectories(categoryPath).Length == 0) {
Directory.Delete(categoryPath);
}
});
}
private void miBlacklist_Click(object sender, EventArgs e) {
if (_isExiting) return;
List<string> lines = new List<string>();
foreach (string rule in _blacklist) {
lines.Add(rule);
}
HashSet<string> blacklist = new HashSet<string>();
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
if (!_blacklist.Contains(watcher.PageID) && blacklist.Add(watcher.PageID)) {
lines.Add(watcher.PageID);
}
}
try {
string path = Path.Combine(Settings.GetSettingsDirectory(), Settings.BlacklistFileName);
File.WriteAllLines(path, lines.ToArray());
foreach (string pageID in blacklist) {
_blacklist.Add(pageID);
}
}
catch (Exception ex) {
Logger.Log(ex.ToString());
}
}
private void miCheckNow_Click(object sender, EventArgs e) {
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
watcher.MillisecondsUntilNextCheck = 0;
}
}
private void miCheckEvery_Click(object sender, EventArgs e) {
MenuItem menuItem = sender as MenuItem;
if (menuItem != null) {
int checkIntervalSeconds = Convert.ToInt32(menuItem.Tag) * 60;
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
watcher.CheckIntervalSeconds = checkIntervalSeconds;
}
UpdateWaitingWatcherStatuses();
}
_saveThreadList = true;
}
private void miReparse_Click(object sender, EventArgs e) {
if (_isExiting) return;
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
if (!watcher.IsRunning && !watcher.IsReparsing && Settings.SaveThumbnails != false) {
watcher.BeginReparse();
}
}
_saveThreadList = true;
}
private void btnDownloads_Click(object sender, EventArgs e) {
if (_downloadForm != null && !_downloadForm.IsDisposed) {
_downloadForm.Activate();
}
else {
_downloadForm = new frmDownloads(this);
GUI.CenterChildForm(this, _downloadForm);
_downloadForm.Show(this);
}
}
private void btnSettings_Click(object sender, EventArgs e) {
if (_isExiting) return;
using (frmSettings settingsForm = new frmSettings()) {
GUI.CenterChildForm(this, settingsForm);
settingsForm.ShowDialog(this);
}
niTrayIcon.Visible = Settings.MinimizeToTray ?? false;
tmrBackupThreadList.Interval = (Settings.BackupEvery ?? 1) * 60 * 1000;
UpdateWindowTitle(GetMonitoringInfo());
}
private void btnAbout_Click(object sender, EventArgs e) {
MessageBox.Show(this, String.Format("Chan Thread Watch{0}Version {1} ({2}){0}{0}Original Author: JDP ([email protected]){0}http://sites.google.com/site/chanthreadwatch/" +
"{0}{0}Maintained by: SuperGouge (https://github.com/SuperGouge){0}{3}",
Environment.NewLine, General.Version, General.ReleaseDate, General.ProgramURL), "About",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnHelp_Click(object sender, EventArgs e) {
Process.Start(General.WikiURL);
}
private void lvThreads_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Delete) {
RemoveThreads(false, true);
}
else if (e.Control && e.KeyCode == Keys.A) {
foreach (ListViewItem item in lvThreads.Items) {
item.Selected = true;
}
}
else if (e.Control && e.KeyCode == Keys.I) {
foreach (ListViewItem item in lvThreads.Items) {
item.Selected = !item.Selected;
}
}
}
private void lvThreads_MouseClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Right) {
int selectedCount = lvThreads.SelectedItems.Count;
if (selectedCount != 0) {
bool anyRunning = false;
bool anyStopped = false;
bool anyNotReparsing = false;
foreach (ThreadWatcher watcher in SelectedThreadWatchers) {
bool isRunning = watcher.IsRunning;
anyRunning |= isRunning;
anyStopped |= !isRunning;
anyNotReparsing |= !watcher.IsReparsing;
}
miStop.Visible = anyRunning;
miStart.Visible = anyStopped && anyNotReparsing;
miCheckNow.Visible = anyRunning;
miCheckEvery.Visible = anyRunning;
miRemove.Visible = anyStopped && anyNotReparsing;
miRemoveAndDeleteFolder.Visible = anyStopped && anyNotReparsing;
miReparse.Visible = anyStopped && anyNotReparsing;
cmThreads.Show(lvThreads, e.Location);
}
}
}
private void lvThreads_MouseDoubleClick(object sender, MouseEventArgs e) {
if (OnThreadDoubleClick == ThreadDoubleClickAction.Edit) {
miEdit_Click(null, null);
}
else if (OnThreadDoubleClick == ThreadDoubleClickAction.OpenFolder) {
miOpenFolder_Click(null, null);
}
else {
miOpenURL_Click(null, null);
}
}
private void lvThreads_ColumnClick(object sender, ColumnClickEventArgs e) {
ListViewItemSorter sorter = (ListViewItemSorter)lvThreads.ListViewItemSorter;
if (sorter == null) {
sorter = new ListViewItemSorter(e.Column);
lvThreads.ListViewItemSorter = sorter;
}
else if (e.Column != sorter.Column) {
sorter.Column = e.Column;
sorter.Ascending = true;
}
else {
sorter.Ascending = !sorter.Ascending;
}
lvThreads.Sort();
}
private void chkOneTime_CheckedChanged(object sender, EventArgs e) {
pnlCheckEvery.Enabled = !chkOneTime.Checked;
}
private void chkPageAuth_CheckedChanged(object sender, EventArgs e) {
txtPageAuth.Enabled = chkPageAuth.Checked;
}
private void chkImageAuth_CheckedChanged(object sender, EventArgs e) {
txtImageAuth.Enabled = chkImageAuth.Checked;
}
private void txtCheckEvery_TextChanged(object sender, EventArgs e) {
int checkEvery;
if (Int32.TryParse(txtCheckEvery.Text, out checkEvery)) {
cboCheckEvery.SelectedIndex = -1;
cboCheckEvery.Enabled = false;
}
else {
if (cboCheckEvery.SelectedIndex == -1) cboCheckEvery.SelectedValue = _cboCheckEveryLastValue;
cboCheckEvery.Enabled = true;
}
}
private void cboCheckEvery_SelectedIndexChanged(object sender, EventArgs e) {
if (cboCheckEvery.SelectedIndex == -1) return;
if (cboCheckEvery.Focused) txtCheckEvery.Clear();
if (_cboCheckEveryLastValue == null && (int)cboCheckEvery.SelectedValue == 0 && (int)cboCheckEvery.SelectedValue != Settings.CheckEvery) {
_cboCheckEveryLastValue = 3;
}
else {
_cboCheckEveryLastValue = cboCheckEvery.SelectedValue;
}
}
private void tmrSaveThreadList_Tick(object sender, EventArgs e) {
if (_saveThreadList && !_isExiting) {
SaveThreadList();
_saveThreadList = false;
}
}
private void tmrUpdateWaitStatus_Tick(object sender, EventArgs e) {
UpdateWaitingWatcherStatuses();
}
private void tmrMaintenance_Tick(object sender, EventArgs e) {
lock (_downloadProgresses) {
if (_downloadProgresses.Count == 0) return;
List<long> oldDownloadIDs = new List<long>();
long ticksNow = TickCount.Now;
foreach (DownloadProgressInfo info in _downloadProgresses.Values) {
if (info.EndTicks != null && ticksNow - info.EndTicks.Value > 5000) {
oldDownloadIDs.Add(info.DownloadID);
}
}
foreach (long downloadID in oldDownloadIDs) {
_downloadProgresses.Remove(downloadID);
}
}
}
private void tmrMonitor_Tick(object sender, EventArgs e) {
MonitoringInfo monitoringInfo = GetMonitoringInfo();
UpdateWindowTitle(monitoringInfo);
miMonitorTotal.Text = String.Format("Watching {0} thread{1}", monitoringInfo.TotalThreads, monitoringInfo.TotalThreads != 1 ? "s" : String.Empty);
miMonitorRunning.Text = String.Format(" {0} running", monitoringInfo.RunningThreads);
miMonitorDead.Text = String.Format(" {0} dead", monitoringInfo.DeadThreads);
miMonitorStopped.Text = String.Format(" {0} stopped", monitoringInfo.StoppedThreads);
}
private void tmrBackupThreadList_Tick(object sender, EventArgs e) {
if (Settings.BackupThreadList == true) {
General.BackupThreadList(Settings.BackupCheckSize ?? false);
}
}
private void niTrayIcon_Click(object sender, EventArgs e) {
// Nothing for now
}
private void niTrayIcon_DoubleClick(object sender, EventArgs e) {
Show();
WindowState = FormWindowState.Normal;
}
private void miExit_Click(object sender, EventArgs e) {
Close();
}
private void ThreadWatcher_DownloadStatus(ThreadWatcher watcher, DownloadStatusEventArgs args) {
WatcherExtraData extraData = (WatcherExtraData)watcher.Tag;
bool isInitialPageDownload = false;
bool isFirstImageUpdate = false;
if (args.DownloadType == DownloadType.Page) {
if (!extraData.HasDownloadedPage) {
extraData.HasDownloadedPage = true;
isInitialPageDownload = true;
}
extraData.PreviousDownloadWasPage = true;
}
if (args.DownloadType == DownloadType.Image && extraData.PreviousDownloadWasPage) {
extraData.LastImageOn = DateTime.Now;
extraData.PreviousDownloadWasPage = false;
isFirstImageUpdate = true;
}
BeginInvoke(() => {
SetDownloadStatus(watcher, args.DownloadType, args.CompleteCount, args.TotalCount);
if (isInitialPageDownload) {
DisplayDescription(watcher);
_saveThreadList = true;
}
if (isFirstImageUpdate) {
DisplayLastImageOn(watcher);
_saveThreadList = true;
}
SetupWaitTimer();
});
}
private void ThreadWatcher_WaitStatus(ThreadWatcher watcher, EventArgs args) {
BeginInvoke(() => {
SetWaitStatus(watcher);
SetupWaitTimer();
});
}
private void ThreadWatcher_StopStatus(ThreadWatcher watcher, StopStatusEventArgs args) {
BeginInvoke(() => {
SetStopStatus(watcher, args.StopReason);
SetupWaitTimer();
if (args.StopReason != StopReason.UserRequest && args.StopReason != StopReason.Exiting) {
_saveThreadList = true;
}
});
}
private void ThreadWatcher_ReparseStatus(ThreadWatcher watcher, ReparseStatusEventArgs args) {
BeginInvoke(() => {
SetReparseStatus(watcher, args.ReparseType, args.CompleteCount, args.TotalCount);
SetupWaitTimer();
});
}
private void ThreadWatcher_ThreadDownloadDirectoryRename(ThreadWatcher watcher, EventArgs args) {
BeginInvoke(() => {
_saveThreadList = true;
});
}
private void ThreadWatcher_DownloadStart(ThreadWatcher watcher, DownloadStartEventArgs args) {
DownloadProgressInfo info = new DownloadProgressInfo();
info.DownloadID = args.DownloadID;
info.URL = args.URL;
info.TryNumber = args.TryNumber;
info.StartTicks = TickCount.Now;
info.TotalSize = args.TotalSize;
lock (_downloadProgresses) {
_downloadProgresses[args.DownloadID] = info;
}
}
private void ThreadWatcher_DownloadProgress(ThreadWatcher watcher, DownloadProgressEventArgs args) {
lock (_downloadProgresses) {
DownloadProgressInfo info;
if (!_downloadProgresses.TryGetValue(args.DownloadID, out info)) return;
info.DownloadedSize = args.DownloadedSize;
_downloadProgresses[args.DownloadID] = info;
}
}
private void ThreadWatcher_DownloadEnd(ThreadWatcher watcher, DownloadEndEventArgs args) {
lock (_downloadProgresses) {
DownloadProgressInfo info;
if (!_downloadProgresses.TryGetValue(args.DownloadID, out info)) return;
info.EndTicks = TickCount.Now;
info.DownloadedSize = args.DownloadedSize;
info.TotalSize = args.DownloadedSize;
_downloadProgresses[args.DownloadID] = info;
}
}
private void ThreadWatcher_AddThread(ThreadWatcher watcher, AddThreadEventArgs args) {
BeginInvoke(() => {
ThreadInfo thread = new ThreadInfo {
URL = args.PageURL,
PageAuth = watcher.PageAuth,
ImageAuth = watcher.ImageAuth,
CheckIntervalSeconds = watcher.CheckIntervalSeconds,
OneTimeDownload = watcher.OneTimeDownload,
SaveDir = null,
Description = String.Empty,
StopReason = null,
ExtraData = new WatcherExtraData {
AddedOn = DateTime.Now,
AddedFrom = watcher.PageID
},
Category = watcher.Category,
AutoFollow = Settings.RecursiveAutoFollow != false
};
SiteHelper siteHelper = SiteHelpers.GetInstance((new Uri(thread.URL)).Host);
siteHelper.SetURL(thread.URL);
if (_watchers.ContainsKey(siteHelper.GetPageID())) return;
if (AddThread(thread)) {
_saveThreadList = true;
}
});
}
private bool AddThread(string pageURL) {
ThreadInfo thread = new ThreadInfo {
URL = pageURL,
PageAuth = (chkPageAuth.Checked && (txtPageAuth.Text.IndexOf(':') != -1)) ? txtPageAuth.Text : String.Empty,
ImageAuth = (chkImageAuth.Checked && (txtImageAuth.Text.IndexOf(':') != -1)) ? txtImageAuth.Text : String.Empty,
CheckIntervalSeconds = pnlCheckEvery.Enabled ? (cboCheckEvery.Enabled ? (int)cboCheckEvery.SelectedValue * 60 : Int32.Parse(txtCheckEvery.Text) * 60) : 0,
OneTimeDownload = chkOneTime.Checked,
SaveDir = null,
Description = String.Empty,
StopReason = null,
ExtraData = null,
Category = cboCategory.Text,
AutoFollow = chkAutoFollow.Checked
};
return AddThread(thread);
}
private bool AddThread(ThreadInfo thread) {
ThreadWatcher watcher = null;
ThreadWatcher parentThread = null;
ListViewItem newListViewItem = null;
SiteHelper siteHelper = SiteHelpers.GetInstance((new Uri(thread.URL)).Host);
siteHelper.SetURL(thread.URL);
string pageID = siteHelper.GetPageID();
if (IsBlacklisted(pageID)) return false;
if (_watchers.ContainsKey(pageID)) {
watcher = _watchers[pageID];
if (watcher.IsRunning) return false;
}
if (watcher == null) {
watcher = new ThreadWatcher(thread.URL);
watcher.ThreadDownloadDirectory = thread.SaveDir;
watcher.Description = thread.Description;
if (_isLoadingThreadsFromFile) watcher.DoNotRename = true;
watcher.Category = thread.Category;
watcher.DoNotRename = false;
if (thread.ExtraData != null && !String.IsNullOrEmpty(thread.ExtraData.AddedFrom)) {
_watchers.TryGetValue(thread.ExtraData.AddedFrom, out parentThread);
watcher.ParentThread = parentThread;
}
watcher.DownloadStatus += ThreadWatcher_DownloadStatus;
watcher.WaitStatus += ThreadWatcher_WaitStatus;
watcher.StopStatus += ThreadWatcher_StopStatus;
watcher.ReparseStatus += ThreadWatcher_ReparseStatus;
watcher.ThreadDownloadDirectoryRename += ThreadWatcher_ThreadDownloadDirectoryRename;
watcher.DownloadStart += ThreadWatcher_DownloadStart;
watcher.DownloadProgress += ThreadWatcher_DownloadProgress;
watcher.DownloadEnd += ThreadWatcher_DownloadEnd;
watcher.AddThread += ThreadWatcher_AddThread;
newListViewItem = new ListViewItem(String.Empty);
for (int i = 1; i < lvThreads.Columns.Count; i++) {
newListViewItem.SubItems.Add(String.Empty);
}
newListViewItem.Tag = watcher;
lvThreads.Items.Add(newListViewItem);
lvThreads.Sort();
UpdateCategories(watcher.Category);
}
watcher.PageAuth = thread.PageAuth;
watcher.ImageAuth = thread.ImageAuth;
watcher.CheckIntervalSeconds = thread.CheckIntervalSeconds;
watcher.OneTimeDownload = thread.OneTimeDownload;
watcher.AutoFollow = thread.AutoFollow;
if (thread.ExtraData == null) {
thread.ExtraData = watcher.Tag as WatcherExtraData ?? new WatcherExtraData { AddedOn = DateTime.Now };
}
if (newListViewItem != null) {
thread.ExtraData.ListViewItem = newListViewItem;
}
watcher.Tag = thread.ExtraData;
if (parentThread != null) parentThread.ChildThreads.Add(watcher.PageID, watcher);
if (!_watchers.ContainsKey(watcher.PageID)) {
_watchers.Add(watcher.PageID, watcher);
}
else {
_watchers[watcher.PageID] = watcher;
}
DisplayData(watcher);
if (thread.StopReason == null && !_isLoadingThreadsFromFile) {
watcher.Start();
}
else if (thread.StopReason != null) {
watcher.Stop(thread.StopReason.Value);
}
return true;
}
private void RemoveThreads(bool removeCompleted, bool removeSelected) {
RemoveThreads(removeCompleted, removeSelected, null);
}
private void RemoveThreads(bool removeCompleted, bool removeSelected, Action<ThreadWatcher> preRemoveAction) {
int i = 0;
while (i < lvThreads.Items.Count) {
ThreadWatcher watcher = (ThreadWatcher)lvThreads.Items[i].Tag;
if ((removeCompleted || (removeSelected && lvThreads.Items[i].Selected)) && !watcher.IsRunning && !watcher.IsReparsing) {
if (preRemoveAction != null) {
try { preRemoveAction(watcher); }
catch (Exception ex) {
Logger.Log(ex.ToString());
}
}
UpdateCategories(watcher.Category, true);
lvThreads.Items.RemoveAt(i);
_watchers.Remove(watcher.PageID);
}
else {
i++;
}
}
_saveThreadList = true;
}
private void BindCheckEveryList() {
cboCheckEvery.ValueMember = "Value";
cboCheckEvery.DisplayMember = "Text";
cboCheckEvery.DataSource = new[] {
new ListItemInt32(0, "1 or <"),
new ListItemInt32(2, "2"),
new ListItemInt32(3, "3"),
new ListItemInt32(5, "5"),
new ListItemInt32(10, "10"),
new ListItemInt32(60, "60")
};
}
private void BuildCheckEverySubMenu() {
for (int i = 0; i < cboCheckEvery.Items.Count; i++) {
int minutes = ((ListItemInt32)cboCheckEvery.Items[i]).Value;
MenuItem menuItem = new MenuItem {
Index = i,
Tag = minutes,
Text = minutes > 0 ? minutes + " Minutes" : "1 Minute or <"
};
menuItem.Click += miCheckEvery_Click;
miCheckEvery.MenuItems.Add(menuItem);
}
}
private void BuildColumnHeaderMenu() {
ContextMenu contextMenu = new ContextMenu();
contextMenu.Popup += (s, e) => {
for (int i = 0; i < lvThreads.Columns.Count; i++) {