-
Notifications
You must be signed in to change notification settings - Fork 3
/
mainWindow.cs
3050 lines (2774 loc) · 132 KB
/
mainWindow.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 ALL_LEGIT.Download;
using Gma.System.MouseKeyHook;
using Microsoft.Graph.TermStore;
using Microsoft.VisualStudio.Services.CircuitBreaker;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Graph.Client;
using Microsoft.Web.Helpers;
using Newtonsoft.Json;
using RestSharp;
using SharpCompress.Archives.Rar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using static Azure.Core.HttpHeader;
using Directory = System.IO.Directory;
using Timer = System.Windows.Forms.Timer;
using ToolTip = System.Windows.Forms.ToolTip;
using System.Drawing.Text;
namespace ALL_LEGIT
{
public partial class MainWindow : Form
{// 1. Import InteropServices
/// 2. Declare DownloadsFolder KNOWNFOLDERID
private static Guid FolderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
/// 3. Import SHGetKnownFolderPath method
/// <summary>
/// Retrieves the full path of a known folder identified by the folder's KnownFolderID.
/// </summary>
/// <param name="id">A KnownFolderID that identifies the folder.</param>
/// <param name="flags">Flags that specify special retrieval options. This value can be
/// 0; otherwise, one or more of the KnownFolderFlag values.</param>
/// <param name="token">An access token that represents a particular user. If this
/// parameter is NULL, which is the most common usage, the function requests the known
/// folder for the current user. Assigning a value of -1 indicates the Default User.
/// The default user profile is duplicated when any new user account is created.
/// Note that access to the Default User folders requires administrator privileges.
/// </param>
/// <param name="path">When this method returns, contains the address of a string that
/// specifies the path of the known folder. The returned path does not include a
/// trailing backslash.</param>
/// <returns>Returns S_OK if successful, or an error value otherwise.</returns>
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHGetKnownFolderPath(ref Guid id, int flags, IntPtr token, out IntPtr path);
/// 4. Declare method that returns the Downloads Path as string
/// Returns the absolute downloads directory specified on the system.
/// </summary>
/// <returns></returns>
///
public static string FilecryptURL = "";
public static Dictionary<string, string> Dict = new Dictionary<string, string>();
public static string GetDownloadsPath()
{
if (Environment.OSVersion.Version.Major < 6) throw new NotSupportedException();
IntPtr pathPtr = IntPtr.Zero;
try
{
SHGetKnownFolderPath(ref FolderDownloads, 0, IntPtr.Zero, out pathPtr);
return Marshal.PtrToStringUni(pathPtr);
}
finally
{
Marshal.FreeCoTaskMem(pathPtr);
}
}
public static bool TrayExit = false;
private void menuItem1_Click(object Sender, EventArgs e)
{
// Close the form, which closes the application.
TrayExit = true;
this.Close();
}
void intToolTips()
{
try
{
ToolTip AutoDLBox = new ToolTip();
AutoDLBox.SetToolTip(this.AutoDLBox, "Automatically download added links.");
ToolTip HKTip = new ToolTip();
HKTip.SetToolTip(this.HotKeyBox, "Change global shortcut, global shortcut can be used from anywhere, even if All Legit! is minimized or closed to tray.\n" +
"Simply copy a link and press the global shortcut and All Legit! will parse the links.");
ToolTip listView1 = new ToolTip();
listView1.SetToolTip(this.listView1, "Right click or middle click to remove item.");
ToolTip StayOnTop = new ToolTip();
StayOnTop.SetToolTip(this.StayOnTopCheckbox, "Keep All Legit on top of other programs.");
ToolTip disableNotiesBox = new ToolTip();
disableNotiesBox.SetToolTip(this.disableNotiesBox, "Disable windows notifications.");
ToolTip OpenDirBox = new ToolTip();
OpenDirBox.SetToolTip(this.OpenDirBox, "Open download directory after downloads/extractions finish.");
ToolTip AutoUpdate = new ToolTip();
AutoUpdate.SetToolTip(this.autoUpdateBox, "If update is available install it autommatically at launch.");
ToolTip Close2Tray = new ToolTip();
Close2Tray.SetToolTip(this.Close2Tray, "Minimize All Legit to taskbar instead of exiting when you close the app.");
ToolTip RemDL = new ToolTip();
RemDL.SetToolTip(this.RemDL, "Remove downloaded/extracted/copied links.");
ToolTip AutoOverwrite = new ToolTip();
AutoOverwrite.SetToolTip(this.AutoOverwrite, "If file exists automatically overwrite it without asking.");
ToolTip autoDelZips = new ToolTip();
autoDelZips.SetToolTip(this.autoDelZips, "Delete zips after they have been successfully extracted.");
ToolTip AutoExtract = new ToolTip();
AutoExtract.SetToolTip(this.AutoExtract, "Automatically extract downloaded archives.");
ToolTip extractNested = new ToolTip();
extractNested.SetToolTip(this.extractNested, "If archives exist within extracted archives, extract them to a folder named after the archive.");
}
catch { }
}
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
public static string APIKEY;
public static string apiNAME;
public static bool waitingforkey = false;
public static Timer a = new Timer();
public static System.Windows.Forms.Keys hotkeyset = Properties.Settings.Default.HotKeyKeyData;
public MainWindow()
{
InitializeComponent();
intToolTips();
Utilities.GetMissingFiles();
this.components = new System.ComponentModel.Container();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
// Initialize contextMenu1
this.contextMenu1.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuItem2 });
// Initialize menuItem1
this.menuItem1.Index = 0;
this.menuItem1.Text = "E&xit";
this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
// Initialize menuItem1
this.menuItem2.Index = 1;
this.menuItem2.Text = "Diable notifications";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
// Create the NotifyIcon.
// The Icon property sets the icon that will appear
// in the systray for this application.
ALTrayIcon.Icon = new Icon("_bin\\AL.ico");
// The ContextMenu property sets the menu that will
// appear when the systray icon is right clicked.
ALTrayIcon.ContextMenu = this.contextMenu1;
// The Text property sets the text that will be displayed,
// in a tooltip, when the mouse hovers over the systray icon.
ALTrayIcon.Text = "All Legit";
ALTrayIcon.Visible = true;
this.Invoke(() =>
{
menuItem2.Checked = Properties.Settings.Default.DisableNotifies;
});
// Handle the DoubleClick event to activate the form.
var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
Microsoft.Win32.Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
appName, 11000, Microsoft.Win32.RegistryValueKind.DWord);
try
{
Hook.GlobalEvents().KeyDown += (sender, e) =>
{
if (e.KeyData == Properties.Settings.Default.HotKeyKeyData)
{
DoAsyncConversion();
}
};
}
catch { }
}
private void menuItem2_Click(object Sender, EventArgs e)
{
if (menuItem2.Checked)
{
disableNotiesBox.Checked = false;
menuItem2.Checked = false;
Properties.Settings.Default.DisableNotifies = false;
}
else
{
menuItem2.Checked = true;
disableNotiesBox.Checked = true;
Properties.Settings.Default.DisableNotifies = true;
}
Properties.Settings.Default.Save();
}
public static string patchNotes =
" • Added BULK UPLOAD option! If a site gives you 20 rapid gator links or whatever (unless its filecrypt), use this mode, it will count it all as one object and make auto extraction (usually) work better and download faster!\n" +
" • Fixed some instances of nested deletions, still a WIP so be careful with using delete extracted on massive downloads if you're worried about potentially needing to download the files again. Though please DO NOTE, when this " +
"happens it will go to your RECYCLE BIN, not full deletion, the vast majority of the time!\n\n\n";
public static bool endreached = false;
private async void MainWindow_Load(object sender, EventArgs e)
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile($"{Environment.CurrentDirectory}\\_bin\\ka1.ttf");
foreach (Control c in this.Controls)
{
if (c.Name.StartsWith("KA"))
{
c.Font = new Font(pfc.Families[0], 12, FontStyle.Regular);
}
}
extractNested.Checked = Properties.Settings.Default.extractNested;
autoUpdateBox.Checked = Properties.Settings.Default.AutoUpdate;
Updater.Update();
var cme = new System.Net.Configuration.ConnectionManagementElement();
cme.MaxConnection = 99999;
System.Net.ServicePointManager.DefaultConnectionLimit = 99999;
KA_changeLog_Label.Text = $"{Updater.LocalVersion} Change log:\n\n";
tipsText.Text = " • Click settings cog in top-right corner for auto downloads, auto extraction and more.\n" +
$" • Shortcut key works everywhere, even when app is minimized/closed to tray.";
SplashText.Text = $"{patchNotes}";
StayOnTopCheckbox.Checked = Properties.Settings.Default.TopMost;
var converter = new KeysConverter();
removeURLs.Checked = Properties.Settings.Default.ExcludeURLS;
HotKeyBox.Text = converter.ConvertToString(Properties.Settings.Default.HotKeyKeyData);
OpenDirBox.Checked = Properties.Settings.Default.OpenDir;
disableNotiesBox.Checked = Properties.Settings.Default.DisableNotifies;
Close2Tray.Checked = Properties.Settings.Default.Close2Tray;
RemDL.Checked = Properties.Settings.Default.RemDL;
AutoOverwrite.Checked = Properties.Settings.Default.AutoOverwrite;
AutoDLBox.Checked = Properties.Settings.Default.AutoDL;
autoDelZips.Checked = Properties.Settings.Default.DelZips;
AutoExtract.Checked = Properties.Settings.Default.AutoExtract;
if (!String.IsNullOrEmpty(Properties.Settings.Default.ZipPWS))
{
PWBox.Text = Properties.Settings.Default.ZipPWS;
PWLIST = PWBox.Text;
}
this.Invoke(() =>
{
DownloadingText.Text = $"";
});
KA_tipsHeader.Text = "Tips:\n\n";
RemDL.Checked = Properties.Settings.Default.RemDL;
if (!Properties.Settings.Default.RegistrySet || Properties.Settings.Default.DownloadDir == null || !Properties.Settings.Default.NoNag)
{
if (Properties.Settings.Default.DownloadDir.Length < 3 || String.IsNullOrWhiteSpace(Properties.Settings.Default.DownloadDir))
{
Properties.Settings.Default.NoNag = false;
Properties.Settings.Default.RegistrySet = false;
Properties.Settings.Default.DownloadDir = GetDownloadsPath() + "\\All Legit Downloads";
Properties.Settings.Default.Save();
}
DownloadDir.Text = Properties.Settings.Default.DownloadDir;
Process proc = new Process();
if (!Properties.Settings.Default.RegistrySet)
{
try
{
//check if we are running as administrator currently
if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
{
DialogResult yesnoQ = MessageBox.Show("Administrator rights are required to properly register your downloads path. Once it is registered then it is set until you change it. Please click YES to elevate All Legit and register your download directory.\n\nNOTE: If you click NO we will not ask you again and it might cause download conflicts in the future. For best results click yes or press cancel to be reminded on next launch.", "Relaunch as administrator?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (yesnoQ == DialogResult.Yes)
{
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
proc.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
//Start new process as administrator
proc.StartInfo.FileName = "All.Legit.exe";
proc.StartInfo.Verb = "runas";
proc.StartInfo.Arguments = "";
proc.Start();
//Exit current process
Environment.Exit(0);
}
else if (yesnoQ == DialogResult.No)
{
MessageBox.Show("OK we will not ask again.");
Properties.Settings.Default.RegistrySet = true;
Properties.Settings.Default.NoNag = true;
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.RegistrySet = false;
Properties.Settings.Default.Save();
}
}
else
{
Environment.SetEnvironmentVariable("ALDOWNLOADS", Properties.Settings.Default.DownloadDir,
EnvironmentVariableTarget.Machine);
Properties.Settings.Default.RegistrySet = true;
Properties.Settings.Default.Save();
try
{
Process.Start($"\"C:\\Windows\\explorer.exe\" \"{Environment.CurrentDirectory}\\All.Legit.exe\"");
await Task.Delay(3000);
File.WriteAllText(Environment.CurrentDirectory + "\\js", "");
Application.Exit();
}
catch { }
}
}
//if user selects "no" from adminstrator request.
catch
{
MessageBox.Show("Administrator access was denied, please allow All Legit to store your downloads directory by accepting the admin prompt.");
}
}
}
if (!Directory.Exists(Properties.Settings.Default.DownloadDir))
{
Directory.CreateDirectory(Properties.Settings.Default.DownloadDir);
}
if (File.Exists(Environment.CurrentDirectory + "\\js"))
{
File.Delete(Environment.CurrentDirectory + "\\js");
MessageBox.Show("All set!");
}
await ConnectViaAPIAsync();
while (!loginsuccess)
{
this.Invoke(() =>
{
this.Text = $"All-Legit {Updater.LocalVersion}: Not Connected";
});
}
if (loginsuccess)
{
this.Invoke(() =>
{
isloggingin = false;
this.Text = $"All-Legit {Updater.LocalVersion}: Connected";
});
}
}
public static dynamic getJson(string requestURL)
{
try
{
string BaseURL = "https://api.alldebrid.com/v4/";
var client = new RestClient(BaseURL);
Console.WriteLine($"Requesting: {BaseURL}{requestURL}");
var request = new RestRequest(requestURL, Method.Get);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
var obj = JsonConvert.DeserializeObject<dynamic>(queryResult.Content);
return obj;
}
catch
{
return null;
}
}
public static bool loginsuccess = false;
public static bool isloggingin = false;
public async Task ConnectViaAPIAsync(bool wasManual = false)
{
isloggingin = true;
Thread t1 = new Thread(() =>
{
try
{
apiNAME = Properties.Settings.Default.ApiNAME;
APIKEY = Properties.Settings.Default.ApiKEY;
if (!String.IsNullOrWhiteSpace(apiNAME) || !String.IsNullOrWhiteSpace(APIKEY))
{
apiNAME = Properties.Settings.Default.ApiNAME;
APIKEY = Properties.Settings.Default.ApiKEY;
var auth = getJson($"user?agent={apiNAME}&apikey={APIKEY}");
if (!auth.ToString().Contains("AUTH"))
{
loginsuccess = true;
}
else
{
if (!wasManual)
MessageBox.Show(new Form { TopMost = true }, "Previously set API key no longer working... you must reconnect!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (!loginsuccess)
{
Random random = new Random();
int randomNumber = random.Next(0, 1000);
apiNAME = $"AllLegit{randomNumber}";
Properties.Settings.Default.ApiNAME = apiNAME;
Properties.Settings.Default.Save();
var obj = getJson($"pin/get?agent={apiNAME}");
FilecryptURL = obj.data.user_url.ToString();
if (!wasManual)
{
this.Invoke(() =>
{
Form WebFormForm = new WebFormForm();
WebFormForm.ShowDialog();
this.Show();
});
}
string CheckURL = obj.data.check_url.ToString();
obj = getJson(CheckURL);
bool Activated;
Activated = bool.Parse(obj.data.activated.ToString());
while (!Activated)
{
obj = getJson(CheckURL);
Activated = bool.Parse(obj.data.activated.ToString());
Task.Delay(1000);
}
if (Activated)
{
obj = getJson(CheckURL);
APIKEY = obj.data.apikey.ToString();
Properties.Settings.Default.ApiKEY = APIKEY;
Properties.Settings.Default.Save();
}
var auth = getJson($"user?agent={apiNAME}&apikey={APIKEY}");
if (!auth.ToString().Contains("AUTH"))
{
loginsuccess = true;
}
else
{
MessageBox.Show(new Form { TopMost = true }, "Previously set API key no longer working... you must reconnect!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch
{
Program.mutex.Close();
Application.Exit();
}
});
t1.Start();
while (t1.IsAlive)
{
await Task.Delay(100);
}
}
public static string fileDownloading = ";";
public static bool warnedthisbatch = false;
public static bool overwrite = false;
public static string MagnetSubName = "";
public static bool NoNamesPresent = false;
public static int CheckedCount = 0;
public static int cancelledCount = 0;
public static int CurrentCount = 0;
public static int cancelGroupRuns = 0;
public static string FinishedDL = "";
public static string DIR = "";
public static string DLList = "";
public static string CurrentDLFileName = "";
public WebClient webClient = new WebClient();
string currentGroup = "";
public async Task downloadFiles(string URL, string FILENAME, string MagnetNAME)
{
bool hasgonethru = false;
if (dlsGoin.Contains($"{FILENAME};{MagnetNAME}"))
{
return;
}
dlsGoin += $"{FILENAME};{MagnetNAME}\n";
while (webClient.IsBusy)
{
await (Task.Delay(100));
}
currGroup = MagnetNAME;
CancelButton.Visible = true;
if (!String.IsNullOrEmpty(cancelledGroup))
{
cancelGroupRuns++;
if (MagnetNAME.Equals(cancelledGroup))
{
webClient.CancelAsync();
if (cancelGroupRuns == cancelledCount)
{
cancelledGroup = "";
cancelledCount = 0;
cancelGroupRuns = 1;
}
return;
}
else
{
cancelledGroup = "";
}
}
else
{
cancelledGroup = "";
}
webClient = new WebClient();
warnedthisbatch = false;
Stopwatch sw = new Stopwatch(); // The stopwatch which we will be using to calculate the download speed
DIR = Properties.Settings.Default.DownloadDir + "\\" + MagnetNAME;
DLList += $"{FILENAME};{DIR}\n";
if (!Directory.Exists(DIR))
{
Directory.CreateDirectory(DIR);
}
string DL = Properties.Settings.Default.DownloadDir + "\\" + MagnetNAME + "\\" + FILENAME;
if (File.Exists(DL))
{
if (!currentGroup.Contains(MagnetNAME) && !Properties.Settings.Default.AutoOverwrite)
{
currentGroup = MagnetNAME;
DialogResult Overwrite1 = MessageBox.Show(new Form { TopMost = true }, $"Files found, do you want to overwrite all files from this batch of links({MagnetNAME})", "Overwrite?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Overwrite1 == DialogResult.Yes)
{
overwrite = true;
}
else
{
cancelledGroup = "";
fileDownloading = "";
isDownloading = false;
}
}
if (Properties.Settings.Default.AutoOverwrite)
{
try
{
if (File.Exists(DL))
{
DL.FileRecycle();
}
}
catch { }
}
else if (!Properties.Settings.Default.AutoOverwrite)
{
try
{
listView1.BeginUpdate();
foreach (ListViewItem itemmm in listView1.Items)
{
if (itemmm.SubItems[2].Text.Contains(currGroup) && itemmm.Checked)
{
if (Properties.Settings.Default.RemDL)
{
listView1.Items.Remove(itemmm);
}
else
{
itemmm.Checked = false;
}
}
}
listView1.EndUpdate();
}
catch { }
return;
}
}
//
//
//
//
//DOWNLOAD AREA
//
//
//
//
string DLS = "";
sw.Start();
webClient.DownloadProgressChanged += (s, e) =>
{
isDownloading = true;
if (!hasgonethru)
{
this.Invoke(() =>
{
CancelButton.Visible = true;
});
if (listView1.Items.Count > 0)
{
CurrentDLFileName = listView1.TopItem.SubItems[1].Text;
}
var name = FILENAME;
const int MaxLength = 35;
if (name.Length > MaxLength)
{
FILENAME = name.Substring(0, MaxLength) + "..."; //
}
hasgonethru = true;
}
DLS = String.Format("{0:0.00}", (e.BytesReceived / 1024 / 1024 / sw.Elapsed.TotalSeconds).ToString("0.00"));
this.Invoke(() =>
{
DownloadingText.Text = $"{FILENAME} - {e.ProgressPercentage}% - {DLS}MB\\s";
dlProg.Value = e.ProgressPercentage;
});
};
webClient.DownloadFileCompleted += (s, e) =>
{
isDownloading = false;
fileDownloading = "";
FinishedDL = DL;
torrentDLING = false;
webClient.Dispose();
if (e.Cancelled)
{
if (File.Exists(DL))
{
DL.FileRecycle();
}
if (Directory.Exists(DIR))
{
string[] files = Directory.GetFiles(DIR, "*.*", SearchOption.AllDirectories);
if (files.Length == 0)
{
DIR.DirectoryRecycle();
}
}
if (webClient.IsBusy)
{
}
foreach (ListViewItem item in listView1.CheckedItems)
{
if (MagnetNAME == cancelledGroup)
{
cancelledCount++;
}
if (item.BackColor == Color.MediumSpringGreen)
{
item.BackColor = Color.FromArgb(0, 50, 42);
}
}
}
this.Invoke(() =>
{
CancelButton.Visible = false;
DownloadingText.Text = $"Download finished...";
});
sw.Stop();
this.Invoke(() =>
{
listView1.BeginUpdate();
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems[1].Text.Equals(URL))
{
if (Properties.Settings.Default.RemDL)
{
listView1.Items.Remove(item);
}
else
{
item.Checked = false;
}
}
}
listView1.EndUpdate();
});
this.Invoke(() =>
{
dlProg.Value = 0;
});
fileDownloading = "";
torrentDLING = false;
cancel = false;
webClient.Dispose();
};
await webClient.DownloadFileTaskAsync(new Uri(URL), $"{DL}");
}
public static bool notdone = false;
public static long total = 0;
public static long DLsofar = 0;
public static long ULsofar = 0;
public static double DownloadSpeed = 0;
public static double UploadSpeed = 0;
public static bool alertedonce = false;
public static string PWLIST = "";
public static string filecryptlist = "";
public static bool filecryptinprog = false;
/// <summary>
/// The URLMON library contains this function, URLDownloadToFile, which is a way
/// to download files without user prompts. The ExecWB( _SAVEAS ) function always
/// prompts the user, even if _DONTPROMPTUSER parameter is specified, for "internet
/// security reasons". This function gets around those reasons.
/// </summary>
/// <param name="callerPointer">Pointer to caller object (AX).</param>
/// <param name="url">String of the URL.</param>
/// <param name="filePathWithName">String of the destination filename/path.</param>
/// <param name="reserved">[reserved].</param>
/// <param name="callBack">A callback function to monitor progress or abort.</param>
/// <returns>0 for okay.</returns>
/// source: http://www.pinvoke.net/default.aspx/urlmon/URLDownloadToFile%20.html
[DllImport("urlmon.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern Int32 URLDownloadToFile(
[MarshalAs(UnmanagedType.IUnknown)] object callerPointer,
[MarshalAs(UnmanagedType.LPWStr)] string url,
[MarshalAs(UnmanagedType.LPWStr)] string filePathWithName,
Int32 reserved,
IntPtr callBack);
public static string currGroup = "";
/// <summary>
public static int CurrentlyShowingID = 0;
/// Download a file from the webpage and save it to the destination without promting the user
/// </summary>
/// <param name="url">the url with the file</param>
/// <param name="destinationFullPathWithName">the absolut full path with the filename as destination</param>
/// <returns></returns>
public FileInfo DownloadFile(string url, string destinationFullPathWithName)
{
URLDownloadToFile(null, url, destinationFullPathWithName, 0, IntPtr.Zero);
return new FileInfo(destinationFullPathWithName);
}
private Dictionary<string, string> CurrentPaste { get; set; } = new Dictionary<string, string>();
private List<string> pastedList { get; set; } = new List<string>();
public static string LinkType = "";
public static string currentLink = "";
public static bool convertingMag = false;
public static bool showingconversion = false;
public bool workingOnPaste { get; set; } = false;
public static Dictionary<string, Dictionary<string, string>> magnetList { get; set; }
public async void DoAsyncConversion(string pasted = "")
{
List<string> _pastedList = pastedList;
pasted = pasted.Trim();
if (pasted.Length == 0)
{
if (Clipboard.GetText().Length > 0)
{
pasted = Clipboard.GetText();
}
else
{
return;
}
}
int DLCCountLocal = 0;
fileDownloading += $"{pasted};";
bool _workingOnPaste = workingOnPaste;
while (_workingOnPaste)
{
await Task.Delay(100);
}
if (pasted.ToLower().StartsWith("magnet:?".ToLower()))
{
_workingOnPaste = true;
this.Invoke(() =>
{
splashPanel.Visible = false;
});
if (!Program.form.Focused && TrayNotify && !Properties.Settings.Default.DisableNotifies)
{
this.Invoke(() =>
{
ALTrayIcon.ShowBalloonTip(2000, "", "Adding magnet links...", ToolTipIcon.None);
});
}
else
{
this.Invoke(() =>
{
DownloadingText.Text = $"Adding magnet links...";
});
}
Thread t1 = new Thread(async () =>
{
pasted = pasted.Trim();
string[] output = new string[] { pasted };
output = pasted.Replace("\r\n", "\n").Replace(";", "\n").Replace("\n\n", "\n").Replace("\r", "\n").Trim().Split('\n');
bool isErrors = false;
int a = 0;
int b = 0;
int c = 0;
string a1 = "";
string b1 = "";
string c1 = "";
foreach (string link in output)
{
_pastedList.Add(link);
}
try
{
foreach (string s in _pastedList)
{
while (_workingOnPaste)
{
await Task.Delay(100);
}
_workingOnPaste = true;
var obj = getJson($"magnet/upload?agent={apiNAME}&apikey={APIKEY}&magnets[]={s}");
string status = obj.status.ToString();
if (obj.data.magnets[0].ToString().Contains("error"))
{
isErrors = true;
string error = obj.data.magnets[0].error.code.ToString();
if (error.Contains("MAGNET_INVALID_URI"))
{
a++;
a1 += $"{s}\n";
}
if (error.Contains("MAGNET_TOO_MANY_ACTIVE"))
{
b++;
b1 += $"{s}\n";
}
if (error.Contains("MAGNET_NO_SERVER"))
{
c++;
c1 += $"{s}\n";
}
}
if (isErrors)
{
continue;
}
else
{
LinkType = "M";
string magnetName = obj.data.magnets[0].name.ToString();
Dictionary<string, string> magnetDict = new Dictionary<string, string>();
magnetDict.Add("Name", magnetName);
string magnetID = obj.data.magnets[0].id.ToString();
magnetDict.Add("ID", magnetID);
string MagnetPoll = $"magnet/status?agent={apiNAME}&apikey={APIKEY}&id={magnetID}";
magnetDict.Add("StatusLink", MagnetPoll);
Dictionary<string, Dictionary<string, string>> magnetList = new Dictionary<string, Dictionary<string, string>>();
magnetList.Add(magnetName, magnetDict);
//WHILE LOOP START
if (notdone)
{
this.Invoke(() =>
{
Program.form.DownloadingText.Text = "Magnet already converting! Cannot add torrent until this finshes or it it cancelled first!";
});
_workingOnPaste = false;
return;
}
obj = getJson(MagnetPoll);
var key = obj.data.magnets;
magnetName = key.filename.ToString();
bool ready = false;
notdone = true;
bool secondalert = false;
while (notdone)
{
foreach (var MagnetList in magnetList)
{
magnetName = MagnetList.Key.ToString();
magnetID = MagnetList.Value["ID"];
obj = getJson(MagnetList.Value["StatusLink"]);
key = obj.data.magnets;
if (key.id.ToString().Equals(magnetID))
{
string seeders = key.seeders.ToString();
string MagnetStatus = key.status.ToString();
if (MagnetStatus.Equals("Ready"))
{
torrentDLING = false;
convertingMag = false;
notdone = false;
ready = true;
}
else
{
convertingMag = true;
if (cancel)
{
if (torrentDLING)
{
getJson($"magnet/delete?agent={apiNAME}&apikey={APIKEY}&id={magnetID}");
if (int.Parse(seeders) == 0)
{
if (!Program.form.Focused && TrayNotify && !Properties.Settings.Default.DisableNotifies)
{
ALTrayIcon.ShowBalloonTip(2000, "", $"Magnet removed from profile!", ToolTipIcon.None);
}
this.Invoke(() =>
{
Program.form.DownloadingText.Text = "Magnet removed from profile!";
});
this.Invoke(() =>
{
Program.form.DownloadingText.Text = $"";
});
this.Invoke(() =>
{
CancelButton.Visible = false;
DownloadingText.Text = $"";
dlProg.Value = 0;
});
torrentDLING = false;
fileDownloading = "";
CurrentlyShowingID = 0;
}
else
{
if (!Program.form.Focused && TrayNotify && !Properties.Settings.Default.DisableNotifies)
{
ALTrayIcon.ShowBalloonTip(2000, "", $"Cannot remove magnet that has already started downloading!", ToolTipIcon.None);
}
this.Invoke(() =>
{
Program.form.DownloadingText.Text = "Cannot remove magnet that has already started downloading!";
});
}
}
await Task.Delay(5000);
}
if (!alertedonce)
{
alertedonce = true;
this.Invoke(() =>
{
if (!Program.form.Focused && TrayNotify && !Properties.Settings.Default.DisableNotifies)
{
ALTrayIcon.ShowBalloonTip(2000, "", $"Torrent not cached, now converting!", ToolTipIcon.None);
}
DownloadingText.Text = $"Torrent not cached, now converting!";
});
}
MagnetStatus = key.status.ToString();