-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDownloader.axaml.cs
1443 lines (1337 loc) · 69.7 KB
/
Downloader.axaml.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 Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using MsBox.Avalonia;
using MsBox.Avalonia.Enums;
using System.IO;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using MsBox.Avalonia.Dto;
using MsBox.Avalonia.Models;
using Avalonia.Media.Imaging;
using System.IO.Compression;
using Avalonia.Threading;
using static Manga_Manager.Globals;
using MangaDex_Library;
using System.Linq;
using System.Xml;
using Avalonia.Platform.Storage;
using System.Threading;
using SkiaSharp;
namespace Manga_Manager;
public partial class Downloader : Window
{
private class MimicCheckBox
{
public string Content = string.Empty;
public bool Checked = false;
}
private class MimicProgressBar
{
public int Maximum = 0;
public int Value = 0;
}
private class QueuedManga
{
public List<string> Titles = new List<string>();
public int SelectedTitleIndex = -1;
public int Format = 0; // 0 = EPUB, 1 = CBZ
public string SavePath = Path.GetDirectoryName(Environment.ProcessPath);
public bool UpdateCover = true;
public bool OriginalQuality = true;
public List<MimicCheckBox> Chapters = new List<MimicCheckBox>();
public List<MimicProgressBar> ProgressBars = new List<MimicProgressBar>();
public List<string> ChapterIDs = new List<string>();
public List<int> ChapterPages = new List<int>();
public Manga TempManga = new Manga();
public bool Updating = false;
}
internal static List<string> addedMangas = new List<string>(); // This is to not add these to "Add from library"
private List<QueuedManga> mangaQueue = new List<QueuedManga>();
private List<TextBlock> mangaQueueStatuses = new List<TextBlock>();
private bool downloadError = false;
public Downloader()
{
InitializeComponent();
// More Avalonia weirdness, same issue as in Filtering, I think setting their states in the XAML triggers these methods before the QueueListBox "exists", so it's throwing the null reference error
UpdateCoverCheckBox.IsCheckedChanged += UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged += QualityComboBox_SelectionChanged;
FormatComboBox.SelectedIndex = downloaderLastUsedFormat;
if (MainWindow.openedByDownloadUpdatesButton == true)
{
MainWindow.openedByDownloadUpdatesButton = false;
AddMangaToQueue(mangaList[passIndex].ID, true);
QueueListBox.SelectedIndex = 0;
}
MDLGetData.DownloadError += MDLGetData_DownloadError;
}
private void MDLGetData_DownloadError(object sender, EventArgs e)
{
downloadError = true;
}
private void FormatComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
downloaderLastUsedFormat = FormatComboBox.SelectedIndex;
if (QueueListBox.SelectedIndex != -1)
mangaQueue[QueueListBox.SelectedIndex].Format = FormatComboBox.SelectedIndex;
}
private void TitleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (QueueListBox.SelectedIndex != -1)
mangaQueue[QueueListBox.SelectedIndex].SelectedTitleIndex = TitleComboBox.SelectedIndex;
}
private async void SavePathButton_Clicked(object sender, RoutedEventArgs args)
{
try
{
mangaQueue[QueueListBox.SelectedIndex].SavePath = (await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions()
{
AllowMultiple = false,
Title = "Select where to save the Manga"
}))[0].TryGetLocalPath();
ToolTip.SetTip(SavePathButton, mangaQueue[QueueListBox.SelectedIndex].SavePath);
}
catch { }
}
private void UpdateCoverCheckBox_Checked(object sender, RoutedEventArgs e)
{
mangaQueue[QueueListBox.SelectedIndex].UpdateCover = (bool)UpdateCoverCheckBox.IsChecked;
}
private void QualityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (QueueListBox.SelectedIndex != -1)
{
mangaQueue[QueueListBox.SelectedIndex].OriginalQuality = QualityComboBox.SelectedIndex == 0;
MDLParameters.DataSaving = QualityComboBox.SelectedIndex == 1;
}
}
private async void AddFromLinkButton_Clicked(object sender, RoutedEventArgs args)
{
QueueListBox.SelectedIndex = -1;
Downloader_AddFromLink downloader_AddFromLink = new Downloader_AddFromLink();
string result = await downloader_AddFromLink.ShowDialog<string>(this);
if (ValidateLink(result) == true)
{
StatusTextBox.Text = "Getting manga info...";
if (addedMangas.Contains(result.Split('/')[4]) == true)
{
await MessageBoxManager.GetMessageBoxStandard("Manga already added", "This manga is already in queue!").ShowAsync();
StatusTextBox.Text = "Add mangas to the queue!";
return;
}
foreach (Manga manga in mangaList)
if(manga.ID == result.Split('/')[4])
{
if (await MessageBoxManager.GetMessageBoxStandard("Manga already exists", "This manga is already in the library!\nWould you like to update it instead?", ButtonEnum.YesNo).ShowAsync() == ButtonResult.No)
{
StatusTextBox.Text = "Add mangas to the queue!";
return;
}
passIndex = mangaList.IndexOf(manga);
AddMangaToQueue(manga.ID, true);
StatusTextBox.Text = "Add mangas to the queue!";
return;
}
AddMangaToQueue(result.Split('/')[4], false);
StatusTextBox.Text = "Add mangas to the queue!";
QueueListBox.SelectedIndex = QueueListBox.Items.Count - 1;
}
}
private async void AddFromLibraryButton_Clicked(object sender, RoutedEventArgs args)
{
QueueListBox.SelectedIndex = -1;
Downloader_AddFromLibrary downloader_AddFromLibrary = new Downloader_AddFromLibrary();
List<int> result = await downloader_AddFromLibrary.ShowDialog<List<int>>(this);
if (result == null)
return;
StatusTextBox.Text = "Getting manga info...";
await Task.Run(() => Thread.Sleep(100));
foreach (int indexToAdd in result)
{
passIndex = indexToAdd;
AddMangaToQueue(mangaList[indexToAdd].ID, true);
}
StatusTextBox.Text = "Add mangas to the queue!";
if (result.Count == 1)
QueueListBox.SelectedIndex = QueueListBox.Items.Count - 1;
}
private async void RemoveFromQueueButton_Clicked(object sender, RoutedEventArgs args)
{
if (await MessageBoxManager.GetMessageBoxStandard("Confirmation", "Are you sure you want to remove this Manga from the queue?", ButtonEnum.YesNo).ShowAsync() == ButtonResult.No)
return;
int index = QueueListBox.SelectedIndex;
QueueListBox.SelectedIndex = -1;
QueueListBox.Items.RemoveAt(index);
addedMangas.RemoveAt(index);
mangaQueue.RemoveAt(index);
if (mangaQueue.Count == 0)
DownloadButton.IsEnabled = false;
}
private void QueueListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TitleComboBox.SelectionChanged -= TitleComboBox_SelectionChanged;
FormatComboBox.SelectionChanged -= FormatComboBox_SelectionChanged;
UpdateCoverCheckBox.IsCheckedChanged -= UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged -= QualityComboBox_SelectionChanged;
for (int i = ChaptersStackPanel.Children.Count - 1; i > 0; i--)
ChaptersStackPanel.Children.RemoveAt(i);
TitleComboBox.Items.Clear();
SavePathButton.IsEnabled = false;
UpdateCoverCheckBox.IsEnabled = false;
if (QueueListBox.SelectedIndex == -1)
{
RemoveFromQueueButton.IsVisible = false;
TitleComboBox.IsEnabled = false;
FormatComboBox.IsEnabled = true;
TitleComboBox.SelectionChanged += TitleComboBox_SelectionChanged;
FormatComboBox.SelectionChanged += FormatComboBox_SelectionChanged;
UpdateCoverCheckBox.IsCheckedChanged += UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged += QualityComboBox_SelectionChanged;
return;
}
RemoveFromQueueButton.IsVisible = true;
for (int i = 0; i < mangaQueue[QueueListBox.SelectedIndex].Chapters.Count; i++)
{
CheckBox checkBox = new CheckBox()
{
Foreground = new SolidColorBrush(Colors.White),
IsChecked = mangaQueue[QueueListBox.SelectedIndex].Chapters[i].Checked,
Content = mangaQueue[QueueListBox.SelectedIndex].Chapters[i].Content,
Margin = new Avalonia.Thickness(3, 0, 0, 0)
};
checkBox.IsCheckedChanged += ChapterCheckBox_Checked;
ProgressBar progressBar = new ProgressBar()
{
Minimum = 0,
Maximum = mangaQueue[QueueListBox.SelectedIndex].ProgressBars[i].Maximum,
Value = mangaQueue[QueueListBox.SelectedIndex].ProgressBars[i].Value,
IsVisible = false,
Foreground = new SolidColorBrush(Color.FromRgb(248, 200, 220)),
Background = new SolidColorBrush(Colors.White),
Margin = new Avalonia.Thickness(3, 0)
};
ChaptersStackPanel.Children.Add(new StackPanel()
{
Orientation = Avalonia.Layout.Orientation.Horizontal,
Spacing = 4,
Children = { checkBox, progressBar }
});
}
foreach (string title in mangaQueue[QueueListBox.SelectedIndex].Titles)
TitleComboBox.Items.Add(title);
TitleComboBox.IsEnabled = true;
TitleComboBox.SelectedIndex = mangaQueue[QueueListBox.SelectedIndex].SelectedTitleIndex;
FormatComboBox.IsEnabled = !mangaQueue[QueueListBox.SelectedIndex].Updating;
FormatComboBox.SelectedIndex = mangaQueue[QueueListBox.SelectedIndex].Format;
SavePathButton.IsEnabled = !mangaQueue[QueueListBox.SelectedIndex].Updating;
ToolTip.SetTip(SavePathButton, mangaQueue[QueueListBox.SelectedIndex].SavePath);
UpdateCoverCheckBox.IsEnabled = mangaQueue[QueueListBox.SelectedIndex].Updating;
UpdateCoverCheckBox.IsChecked = mangaQueue[QueueListBox.SelectedIndex].UpdateCover;
if (mangaQueue[QueueListBox.SelectedIndex].OriginalQuality == true)
QualityComboBox.SelectedIndex = 0;
else
QualityComboBox.SelectedIndex = 1;
TitleComboBox.SelectionChanged += TitleComboBox_SelectionChanged;
FormatComboBox.SelectionChanged += FormatComboBox_SelectionChanged;
UpdateCoverCheckBox.IsCheckedChanged += UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged += QualityComboBox_SelectionChanged;
}
private void ChapterCheckBox_Checked(object sender, RoutedEventArgs e)
{
for (int i = 1; i < ChaptersStackPanel.Children.Count; i++)
{
StackPanel parent = ChaptersStackPanel.Children[i] as StackPanel;
CheckBox checkBox = parent.Children[0] as CheckBox;
if (checkBox == (sender as CheckBox))
{
mangaQueue[QueueListBox.SelectedIndex].Chapters[i - 1].Checked = (bool)checkBox.IsChecked;
break;
}
}
}
private void AddMangaToQueue(string mangaID, bool isUpdate)
{
MDLParameters.MangaID = mangaID;
QueuedManga newManga = new QueuedManga();
MDLGetData.GetTitles();
if (apiError == true)
{
apiError = false;
return;
}
MDLGetData.GetChapterIDs();
if (apiError == true)
{
apiError = false;
return;
}
newManga.Titles = MDLGetData.GetTitles().ToList<string>();
newManga.SelectedTitleIndex = 0;
if (isUpdate == true)
{
newManga.Titles.Insert(0, mangaList[passIndex].Title);
if (Path.GetExtension(mangaList[passIndex].Path).ToLower() == ".epub")
newManga.Format = 0;
else
newManga.Format = 1;
newManga.SavePath = Path.GetDirectoryName(mangaList[passIndex].Path);
}
else
newManga.Format = FormatComboBox.SelectedIndex;
newManga.UpdateCover = (bool)UpdateCoverCheckBox.IsChecked;
newManga.OriginalQuality = QualityComboBox.SelectedIndex == 0;
List<decimal> chapterNumbers = MDLGetData.GetChapterNumbers();
Dictionary<decimal, int> chapterNumberAppearances = new Dictionary<decimal, int>();
foreach (decimal number in chapterNumbers)
if (chapterNumberAppearances.Count > 0 && chapterNumberAppearances.ElementAt(chapterNumberAppearances.Count - 1).Key == number)
chapterNumberAppearances[number]++;
else
chapterNumberAppearances[number] = 1;
for (int i = 0; i < chapterNumbers.Count; i++)
{
if (isUpdate == true && chapterNumbers[i] <= mangaList[passIndex].FileLastChapter)
continue;
newManga.Chapters.Add(new MimicCheckBox()
{
Checked = MDLGetData.GetAltCuratedChapterIndexes().Contains(i)
});
if (chapterNumberAppearances[chapterNumbers[i]] > 1) // If the current chapter number appears more than once, I also add the scanlator name to it
newManga.Chapters[newManga.Chapters.Count - 1].Content = $"Ch.{chapterNumbers[i]} by {MDLGetData.GetChapterGroups()[i]}";
else
newManga.Chapters[newManga.Chapters.Count - 1].Content = $"Ch.{chapterNumbers[i]}";
newManga.ProgressBars.Add(new MimicProgressBar()
{
Maximum = MDLGetData.GetChapterNrPages()[i],
Value = 0
});
}
newManga.ChapterIDs = MDLGetData.GetChapterIDs().ToList<string>();
newManga.ChapterPages = MDLGetData.GetChapterNrPages().ToList<int>();
while (newManga.Chapters.Count < newManga.ChapterIDs.Count) // Accounting for skipped chapters if it's an update
{
newManga.ChapterIDs.RemoveAt(0);
newManga.ChapterPages.RemoveAt(0);
}
newManga.TempManga = new Manga()
{
Title = newManga.Titles[0],
Description = MDLGetData.GetDescription().ToString(),
Path = newManga.SavePath,
OnlineLastChapter = MDLGetData.GetLastChapter(),
LastChecked = new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day),
OngoingStatus = MDLGetData.GetStatus().Substring(0, 1).ToUpper() + MDLGetData.GetStatus().Substring(1),
CheckInBulk = (MDLGetData.GetStatus().Substring(0, 1).ToUpper() + MDLGetData.GetStatus().Substring(1)) == "Ongoing" || (MDLGetData.GetStatus().Substring(0, 1).ToUpper() + MDLGetData.GetStatus().Substring(1)) == "Hiatus",
ID = mangaID,
ContentRating = MDLGetData.GetContentRating().Substring(0, 1).ToUpper() + MDLGetData.GetContentRating().Substring(1),
Tags = MDLGetData.GetTags().ToList<string>()
};
if (isUpdate == true)
newManga.TempManga.Tags = mangaList[passIndex].Tags;
newManga.Updating = isUpdate;
TextBlock title = new TextBlock()
{
Foreground = new SolidColorBrush(Colors.White),
FontWeight = FontWeight.Bold,
FontSize = 12,
Text = newManga.Titles[0],
Margin = new Avalonia.Thickness(2)
}, status = new TextBlock()
{
Foreground = new SolidColorBrush(Colors.LightGray),
FontSize = 9,
Margin = new Avalonia.Thickness(0),
Text = "In queue"
};
QueueListBox.Items.Add(new StackPanel()
{
Children = { title, status }
});
mangaQueue.Add(newManga);
addedMangas.Add(mangaID); // This is to not add these to "Add from library"
mangaQueueStatuses.Add(status);
DownloadButton.IsEnabled = true;
}
#region Downloading
private void AltQueueListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TitleComboBox.SelectionChanged -= TitleComboBox_SelectionChanged;
FormatComboBox.SelectionChanged -= FormatComboBox_SelectionChanged;
UpdateCoverCheckBox.IsCheckedChanged -= UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged -= QualityComboBox_SelectionChanged;
for (int i = ChaptersStackPanel.Children.Count - 1; i > 0; i--)
ChaptersStackPanel.Children.RemoveAt(i);
TitleComboBox.Items.Clear();
if (QueueListBox.SelectedIndex == -1)
{
TitleComboBox.SelectionChanged += TitleComboBox_SelectionChanged;
FormatComboBox.SelectionChanged += FormatComboBox_SelectionChanged;
UpdateCoverCheckBox.IsCheckedChanged += UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged += QualityComboBox_SelectionChanged;
return;
}
TitleComboBox.Items.Add(mangaQueue[QueueListBox.SelectedIndex].Titles[mangaQueue[QueueListBox.SelectedIndex].SelectedTitleIndex]);
TitleComboBox.SelectedIndex = 0;
FormatComboBox.SelectedIndex = mangaQueue[QueueListBox.SelectedIndex].Format;
UpdateCoverCheckBox.IsChecked = mangaQueue[QueueListBox.SelectedIndex].UpdateCover;
if (mangaQueue[QueueListBox.SelectedIndex].OriginalQuality == true)
QualityComboBox.SelectedIndex = 0;
else
QualityComboBox.SelectedIndex = 1;
for (int i = 0; i < mangaQueue[QueueListBox.SelectedIndex].Chapters.Count; i++)
{
CheckBox checkBox = new CheckBox()
{
Foreground = new SolidColorBrush(Colors.White),
IsChecked = mangaQueue[QueueListBox.SelectedIndex].Chapters[i].Checked,
Content = mangaQueue[QueueListBox.SelectedIndex].Chapters[i].Content,
Margin = new Avalonia.Thickness(3, 0, 0, 0),
IsEnabled = false
};
ProgressBar progressBar = new ProgressBar()
{
Minimum = 0,
Maximum = mangaQueue[QueueListBox.SelectedIndex].ProgressBars[i].Maximum,
Value = mangaQueue[QueueListBox.SelectedIndex].ProgressBars[i].Value,
IsVisible = (bool)checkBox.IsChecked,
Foreground = new SolidColorBrush(Color.FromRgb(248, 200, 220)),
Background = new SolidColorBrush(Colors.White),
Margin = new Avalonia.Thickness(3, 0)
};
ChaptersStackPanel.Children.Add(new StackPanel()
{
Orientation = Avalonia.Layout.Orientation.Horizontal,
Spacing = 4,
Children = { checkBox, progressBar }
});
}
TitleComboBox.SelectionChanged += TitleComboBox_SelectionChanged;
FormatComboBox.SelectionChanged += FormatComboBox_SelectionChanged;
UpdateCoverCheckBox.IsCheckedChanged += UpdateCoverCheckBox_Checked;
QualityComboBox.SelectionChanged += QualityComboBox_SelectionChanged;
}
private int queueIndex = 0;
private bool downloading = false;
CancellationTokenSource tokenSource = new CancellationTokenSource();
private CancellationToken cancelCheck;
private bool skip = false;
private async void DownloadButton_Clicked(object sender, RoutedEventArgs args)
{
if (downloading == true)
{
string result = await MessageBoxManager.GetMessageBoxCustom(new MessageBoxCustomParams
{
ButtonDefinitions = new List<ButtonDefinition>
{
new ButtonDefinition { Name = "Skip Manga" },
new ButtonDefinition { Name = "Stop all" },
new ButtonDefinition { Name = "Cancel" }
},
ContentTitle = "Skip or cancel",
ContentMessage = "Would you like to just skip this Manga, or stop all the downloads?",
CanResize = false,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
SizeToContent = SizeToContent.WidthAndHeight,
Topmost = true,
SystemDecorations = SystemDecorations.None
}).ShowAsync();
if (result == "Cancel")
return;
skip = result == "Skip Manga";
if (skip == false)
tokenSource.Cancel();
return;
}
if (await MessageBoxManager.GetMessageBoxStandard("Confirmation", "Are you sure you want to start downloading?", ButtonEnum.YesNo).ShowAsync() == ButtonResult.No)
return;
downloading = true;
QueueListBox.SelectionChanged -= QueueListBox_SelectionChanged;
QueueListBox.SelectionChanged += AltQueueListBox_SelectionChanged;
QueueListBox.SelectedIndex = -1;
foreach (TextBlock textBox in mangaQueueStatuses)
{
textBox.Text = "In queue";
textBox.Foreground = new SolidColorBrush(Colors.LightGray);
}
TitleComboBox.IsEnabled = false;
FormatComboBox.IsEnabled = false;
SavePathButton.IsEnabled = false;
UpdateCoverCheckBox.IsEnabled = false;
QualityComboBox.IsEnabled = false;
AddFromLinkButton.IsEnabled = false;
AddFromLibraryButton.IsEnabled = false;
RemoveFromQueueButton.IsEnabled = false;
DownloadButton.Content = "Skip or Stop download";
cancelCheck = tokenSource.Token;
_ = Task.Run(() =>
{
for (queueIndex = 0; queueIndex < mangaQueue.Count; queueIndex++)
{
skip = false;
int indexHere = queueIndex;
Dispatcher.UIThread.Post(() =>
{
StatusTextBox.Text = "Preparing files...";
StatusTextBox.Foreground = new SolidColorBrush(Colors.Yellow);
mangaQueueStatuses[indexHere].Text = "In progress";
mangaQueueStatuses[indexHere].Foreground = new SolidColorBrush(Colors.Yellow);
QueueListBox.SelectedIndex = indexHere;
});
QueuedManga currentManga = mangaQueue[queueIndex];
currentManga.TempManga.Title = currentManga.Titles[currentManga.SelectedTitleIndex];
Dictionary<string, int> chaptersToDownload = new Dictionary<string, int>(); // Chapter ID to Nr. of pages for the Progress Bars
List<string> selectedChapterNumbers = new List<string>();
for (int i = 0; i < currentManga.Chapters.Count; i++)
if (currentManga.Chapters[i].Checked == true)
{
chaptersToDownload[currentManga.ChapterIDs[i]] = currentManga.ChapterPages[i];
try
{
currentManga.TempManga.FileLastChapter = Convert.ToDecimal(currentManga.Chapters[i].Content.Split(' ')[0].Split("Ch.")[1]);
string sanitizedGroupName = new string(currentManga.Chapters[i].Content.Split(" by ")[1].Where(c => char.IsLetter(c)).ToArray()).ToLower();
selectedChapterNumbers.Add(currentManga.Chapters[i].Content.Split(' ')[0].Split("Ch.")[1] + "by" + sanitizedGroupName);
}
catch
{
currentManga.TempManga.FileLastChapter = Convert.ToDecimal(currentManga.Chapters[i].Content.Split("Ch.")[1]);
selectedChapterNumbers.Add(currentManga.Chapters[i].Content.Split("Ch.")[1]);
}
}
if (chaptersToDownload.Count == 0 && currentManga.Updating == true)
{
foreach (Manga manga in mangaList)
if (manga.ID == currentManga.TempManga.ID)
{
currentManga.TempManga.FileLastChapter = manga.FileLastChapter;
break;
}
}
if (currentManga.Updating == false && chaptersToDownload.Count == 0)
{
int indexHere2 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere2].Text = "Dropped: no chapters selected";
mangaQueueStatuses[indexHere2].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
}
int directoryName = 0;
while (Directory.Exists(Path.Combine(currentManga.SavePath, $"Temp Manga folder {directoryName}")))
directoryName++;
string tempFolderPath = Path.Combine(currentManga.SavePath, $"Temp Manga folder {directoryName}");
try
{
Directory.CreateDirectory(Path.Combine(currentManga.SavePath, $"Temp Manga folder {directoryName}"));
}
catch
{
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Error: could not create folder";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
}
if (FileSetup(tempFolderPath, chaptersToDownload.Count) == false) // Creates empty folder structure for new mangas or extracts the archives if it's an update
{
Dispatcher.UIThread.Post(() =>
{
int indexHere3 = queueIndex;
mangaQueueStatuses[indexHere3].Text = "Dropped: could not create files";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
}
string fileName = string.Empty;
if (currentManga.Updating == false)
fileName = currentManga.Titles[currentManga.SelectedTitleIndex];
else
{
foreach (Manga manga in mangaList)
if (manga.ID == currentManga.TempManga.ID)
{
fileName = Path.GetFileNameWithoutExtension(manga.Path);
break;
}
}
foreach (char c in Path.GetInvalidFileNameChars())
fileName = fileName.Replace(c.ToString(), string.Empty);
if (currentManga.Updating == false)
{
currentManga.SavePath = Path.Combine(currentManga.SavePath, fileName);
if (currentManga.SavePath.Contains(Path.GetDirectoryName(Environment.ProcessPath)))
currentManga.TempManga.Path = currentManga.SavePath.Substring(Path.GetDirectoryName(Environment.ProcessPath).Length);
else
currentManga.TempManga.Path = currentManga.SavePath;
if (currentManga.TempManga.Path[0] == Path.DirectorySeparatorChar)
currentManga.TempManga.Path = currentManga.TempManga.Path.Substring(1);
}
string cbzPrefix = string.Empty;
if (currentManga.Format == 1)
{
if (currentManga.Updating == true)
{
string[] files = Directory.GetFiles(tempFolderPath);
int i = 0;
while (Path.GetFileNameWithoutExtension(files[0]).Substring(i, 1) == Path.GetFileNameWithoutExtension(files.Last()).Substring(i, 1))
{
cbzPrefix += Path.GetFileNameWithoutExtension(files[0]).Substring(i, 1);
i++;
}
}
else
cbzPrefix = "pg-";
}
int offset = 0;
if (currentManga.Updating == true)
{
if (currentManga.Format == 0)
{
offset = 1; // The folders in the existing manga folder start with 1
while (Directory.Exists(Path.Combine(tempFolderPath, offset.ToString())) == true)
offset++;
offset--; // I need the last folder that was used
offset -= chaptersToDownload.Count; // The folders for the new chapters were already created, so gotta subtract those to get to the correct offset
} // No, I will not be fixing this atrocious.. thing. It works and it shows my thought process, leave me alone.
else
{
try
{
offset = Directory.GetFiles(tempFolderPath).Count() - 1;
}
catch
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: could not read files";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
}
}
}
int totalPages = 0;
foreach (KeyValuePair<string, int> chapter in chaptersToDownload)
totalPages += chapter.Value;
if (cancelCheck.IsCancellationRequested || skip == true) // Cancel check
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
if (skip == false)
{
Dispatcher.UIThread.Post(() => AbortAll());
return;
}
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: user skipped manga";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
} // Cancel check
MDLParameters.MangaID = currentManga.TempManga.ID;
MDLParameters.DataSaving = !currentManga.OriginalQuality;
List<List<string>> pageFileNames = new List<List<string>>();
#region Downloading
int cbzPageNumber = 1;
bool skipManga = false;
for (int chapterIndex = offset; chapterIndex < chaptersToDownload.Count + offset; chapterIndex++)
{
int pageFailures = 0;
string currentPath = Path.Combine(tempFolderPath, Convert.ToString(chapterIndex + 1), "img", string.Empty);
Retry:
if (pageFailures >= 5)
{
skipManga = true;
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: could not complete download";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
break;
}
if (cancelCheck.IsCancellationRequested || skip == true) // Cancel check
{
if (skip == false)
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
Dispatcher.UIThread.Post(() => AbortAll());
return;
}
break;
} // Cancel check
List<string> pageLinks = MDLGetData.GetPageLinks(chaptersToDownload.ElementAt(chapterIndex - offset).Key);
if (apiError == true)
{
apiError = false;
skipManga = true;
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: API error";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
break;
}
List<string> chapterPagePaths = new List<string>();
pageFileNames.Add(chapterPagePaths);
for (int pageNumber = 1; pageNumber <= pageLinks.Count; pageNumber++)
{
if (cancelCheck.IsCancellationRequested || skip == true) // Cancel check
{
if (skip == false)
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
Dispatcher.UIThread.Post(() => AbortAll());
return;
}
break;
} // Cancel check
using MemoryStream pageStream = new MemoryStream();
MDLGetData.GetPageImage(pageLinks[pageNumber - 1]).CopyTo(pageStream);
if (downloadError == true || pageStream == null)
{
pageFailures++;
downloadError = false;
goto Retry;
}
pageStream.Seek(0, SeekOrigin.Begin);
using SKBitmap page = SKBitmap.Decode(pageStream);
// Saving the page
try
{
if (currentManga.Format == 0)
{
string pageFileName = pageNumber.ToString("D" + chaptersToDownload.ElementAt(chapterIndex - offset).Value.ToString().Length) + ".jpg";
using FileStream fileStream = new FileStream(Path.Combine(currentPath, pageFileName), FileMode.Create);
SKImage.FromBitmap(page).Encode(SKEncodedImageFormat.Jpeg, 100).SaveTo(fileStream);
File.WriteAllText(Path.Combine(tempFolderPath, Convert.ToString(chapterIndex + 1), "xhtml", pageNumber - 1 + ".xhtml"), $"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n <link href=\"../css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\r\n <title>{pageFileName}</title>\r\n</head>\r\n<body>\r\n <div>\r\n <img alt=\"{pageFileName}\" src=\"../img/{pageFileName}\"/>\r\n </div>\r\n</body>\r\n</html>\r\n");
chapterPagePaths.Add(Path.Combine(currentPath, pageFileName));
}
else if (currentManga.Format == 1)
{
int currentPageNumber = offset + cbzPageNumber;
string pageFileName;
if (currentManga.Updating == false)
pageFileName = $"{cbzPrefix}{currentPageNumber.ToString("D" + totalPages.ToString().Length)}.jpg";
else
pageFileName = $"{cbzPrefix}{currentPageNumber.ToString("D" + (totalPages + offset).ToString().Length)}.jpg";
using FileStream fileStream = new FileStream(Path.Combine(tempFolderPath, pageFileName), FileMode.Create);
SKImage.FromBitmap(page).Encode(SKEncodedImageFormat.Jpeg, 100).SaveTo(fileStream);
cbzPageNumber++;
}
}
catch
{
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: could not create files";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
skipManga = true;
break;
}
// Reporting progress
currentManga.ProgressBars[chapterIndex - offset].Value++;
int indexHere2 = queueIndex, indexHere4 = chapterIndex;
Dispatcher.UIThread.Post(() =>
{
if (QueueListBox.SelectedIndex == indexHere2)
((ProgressBar)((StackPanel)ChaptersStackPanel.Children[mangaQueue[indexHere2].ChapterIDs.IndexOf(chaptersToDownload.ElementAt(indexHere4 - offset).Key) + 1]).Children[1]).Value = mangaQueue[indexHere2].ProgressBars[indexHere4 - offset].Value;
});
}
if (cancelCheck.IsCancellationRequested || skip == true) // Cancel check
{
if (skip == false)
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
Dispatcher.UIThread.Post(() => AbortAll());
return;
}
break;
} // Cancel check
}
if (skipManga == true)
{
skipManga = false;
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
continue;
}
if (cancelCheck.IsCancellationRequested || skip == true) // Cancel check
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
if (skip == false)
{
Dispatcher.UIThread.Post(() => AbortAll());
return;
}
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: user skipped manga";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
} // Cancel check
// Get the cover image
if (currentManga.Updating == false || (currentManga.Updating == true && currentManga.UpdateCover == true))
{
MemoryStream coverStream = new MemoryStream();
MDLGetData.GetCover().CopyTo(coverStream);
if (apiError == true)
{
apiError = false;
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: API error";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
}
coverStream.Seek(0, SeekOrigin.Begin);
using SKBitmap cover = SKBitmap.Decode(coverStream);
try
{
File.Delete(Path.Combine(tempFolderPath, "cover.jpg"));
}
catch { }
if (currentManga.Format == 0)
{
using FileStream fileStream = new FileStream(Path.Combine(tempFolderPath, "cover.jpg"), FileMode.Create);
SKImage.FromBitmap(cover).Encode(SKEncodedImageFormat.Jpeg, 100).SaveTo(fileStream);
}
else if (currentManga.Format == 1)
{
string coverFileName;
if (currentManga.Updating == false)
coverFileName = $"{cbzPrefix}{0.ToString("D" + totalPages.ToString().Length)}.jpg";
else
coverFileName = $"{cbzPrefix}{0.ToString("D" + (totalPages + offset).ToString().Length)}.jpg";
try
{
File.Delete(Path.Combine(tempFolderPath, coverFileName));
}
catch { }
using FileStream fileStream = new FileStream(Path.Combine(tempFolderPath, coverFileName), FileMode.Create);
SKImage.FromBitmap(cover).Encode(SKEncodedImageFormat.Jpeg, 100).SaveTo(fileStream);
}
cover.Dispose();
}
#endregion
if (cancelCheck.IsCancellationRequested || skip == true) // Cancel check
{
try
{
Directory.Delete(tempFolderPath, true);
}
catch
{
Dispatcher.UIThread.Post(() => _ = MessageBoxManager.GetMessageBoxStandard("Write error", "Could not delete the temporary folder, please delete it yourself.").ShowAsync());
}
if (skip == false)
{
Dispatcher.UIThread.Post(() => AbortAll());
return;
}
int indexHere3 = queueIndex;
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[indexHere3].Text = "Dropped: user skipped manga";
mangaQueueStatuses[indexHere3].Foreground = new SolidColorBrush(Color.FromRgb(130, 0, 0));
});
continue;
} // Cancel check
if (currentManga.Format == 1)
{
int hereIndex2 = queueIndex;
if (currentManga.Updating == true)
PackManga(tempFolderPath, Path.Combine(currentManga.TempManga.Path, fileName));
else
PackManga(tempFolderPath, currentManga.TempManga.Path);
Dispatcher.UIThread.Post(() =>
{
mangaQueueStatuses[hereIndex2].Text = "Completed";
mangaQueueStatuses[hereIndex2].Foreground = new SolidColorBrush(Colors.Lime);
});
continue;