This repository has been archived by the owner on May 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
MainForm.cs
1119 lines (983 loc) · 46.8 KB
/
MainForm.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 RookiePCVR.Models;
using RookiePCVR.Utilities;
using JR.Utils.GUI.Forms;
using Newtonsoft.Json;
using SergeUtils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RookiePCVR
{
public partial class MainForm : Form
{
private readonly ListViewColumnSorter lvwColumnSorter;
#if DEBUG
public static bool debugMode = true;
public bool DeviceConnected = false;
public bool keyheld;
public bool keyheld2;
public static string CurrAPK;
public static string CurrPCKG;
List<UploadGame> gamesToUpload = new List<UploadGame>();
public static string currremotesimple = "";
#else
public bool keyheld;
public static string CurrAPK;
public static string CurrPCKG;
public static bool debugMode = false;
public bool DeviceConnected = false;
public static string currremotesimple = "";
#endif
private bool isLoading = true;
public static bool hasPublicPCVRConfig = false;
public static PublicConfig PublicConfigFile;
public static string PublicMirrorExtraArgs = " --tpslimit 1.0 --tpslimit-burst 3";
private System.Windows.Forms.Timer _debounceTimer;
private CancellationTokenSource _cts;
private List<ListViewItem> _allItems;
public MainForm()
{
InitializeComponent();
_debounceTimer = new System.Windows.Forms.Timer
{
Interval = 1000, // 1 second delay
Enabled = false
};
_debounceTimer.Tick += async (sender, e) => await RunSearch();
gamesQueListBox.DataSource = gamesQueueList;
//Time for debuglog
string launchtime = DateTime.Now.ToString("hh:mmtt(UTC)");
_ = Logger.Log($"\n------\n------\nProgram Launched at: {launchtime}\n------\n------");
if (string.IsNullOrEmpty(Properties.Settings.Default.CurrentLogPath))
{
Properties.Settings.Default.CurrentLogPath = $"{Environment.CurrentDirectory}\\debuglog.txt";
}
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer
{
Interval = 840000 // 14 mins between wakeup commands
};
t.Start();
System.Windows.Forms.Timer t2 = new System.Windows.Forms.Timer
{
Interval = 300 // 30ms
};
t2.Tick += new EventHandler(timer_Tick2);
t2.Start();
lvwColumnSorter = new ListViewColumnSorter();
gamesListView.ListViewItemSorter = lvwColumnSorter;
}
public static string DonorApps = "";
private string oldTitle = "";
public static bool updatesnotified = false;
public static string BackupFolder;
private async void Form1_Load(object sender, EventArgs e)
{
Splash splash = new Splash();
splash.Show();
if (File.Exists($"{Environment.CurrentDirectory}\\vrp-public-pcvr.json"))
{
Thread worker = new Thread(() =>
{
SideloaderRCLONE.updatePublicConfig();
});
worker.Start();
while (worker.IsAlive)
{
Thread.Sleep(10);
}
try
{
string configFileData =
File.ReadAllText($"{Environment.CurrentDirectory}\\vrp-public-pcvr.json");
PublicConfig config = JsonConvert.DeserializeObject<PublicConfig>(configFileData);
if (config != null
&& !string.IsNullOrWhiteSpace(config.BaseUri)
&& !string.IsNullOrWhiteSpace(config.Password))
{
PublicConfigFile = config;
hasPublicPCVRConfig = true;
}
}
catch
{
hasPublicPCVRConfig = false;
}
if (!hasPublicPCVRConfig)
{
_ = FlexibleMessageBox.Show(Program.form, "Failed to fetch public mirror config, and the current one is unreadable.\r\nPlease ensure you can access https://vrpirates.wiki/ in your browser.", "Config Update Failed", MessageBoxButtons.OK);
}
if (Directory.Exists(@"C:\RSL\EBWebView"))
{
Directory.Delete(@"C:\RSL\EBWebView", true);
}
}
Properties.Settings.Default.MainDir = Environment.CurrentDirectory;
Properties.Settings.Default.Save();
FetchDependencies.downloadFiles();
await Task.Delay(100);
if (Directory.Exists(FetchDependencies.TempFolder))
{
Directory.Delete(FetchDependencies.TempFolder, true);
_ = Directory.CreateDirectory(FetchDependencies.TempFolder);
}
//Delete the Debug file if it is more than 5MB
if (File.Exists($"{Properties.Settings.Default.CurrentLogPath}"))
{
long length = new System.IO.FileInfo(Properties.Settings.Default.CurrentLogPath).Length;
if (length > 5000000)
{
File.Delete($"{Properties.Settings.Default.CurrentLogPath}");
}
}
RCLONE.Init();
if (Properties.Settings.Default.CallUpgrade)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.CallUpgrade = false;
Properties.Settings.Default.Save();
}
CenterToScreen();
gamesListView.View = View.Details;
gamesListView.FullRowSelect = true;
gamesListView.GridLines = false;
etaLabel.Text = "";
speedLabel.Text = "";
if (File.Exists("crashlog.txt"))
{
if (File.Exists(Properties.Settings.Default.CurrentCrashPath))
{
File.Delete(Properties.Settings.Default.CurrentCrashPath);
}
DialogResult dialogResult = FlexibleMessageBox.Show(Program.form, $"Sideloader crashed during your last use.\nPress OK if you'd like to send us your crash log.\n\n NOTE: THIS CAN TAKE UP TO 30 SECONDS.", "Crash Detected", MessageBoxButtons.OKCancel);
if (dialogResult == DialogResult.OK)
{
if (File.Exists($"{Environment.CurrentDirectory}\\crashlog.txt"))
{
string UUID = SideloaderUtilities.UUID();
System.IO.File.Move("crashlog.txt", $"{Environment.CurrentDirectory}\\{UUID}.log");
Properties.Settings.Default.CurrentCrashPath = $"{Environment.CurrentDirectory}\\{UUID}.log";
Properties.Settings.Default.CurrentCrashName = UUID;
Properties.Settings.Default.Save();
Clipboard.SetText(UUID);
_ = RCLONE.runRcloneCommand_UploadConfig($"copy \"{Properties.Settings.Default.CurrentCrashPath}\" RSL-gameuploads:CrashLogs");
_ = FlexibleMessageBox.Show(Program.form, $"Your CrashLog has been copied to the server.\nPlease mention your CrashLogID ({Properties.Settings.Default.CurrentCrashName}) to the Mods.\nIt has been automatically copied to your clipboard.");
Clipboard.SetText(Properties.Settings.Default.CurrentCrashName);
}
}
else
{
File.Delete($"{Environment.CurrentDirectory}\\crashlog.txt");
}
}
if (hasPublicPCVRConfig)
{
lblMirror.Text = " Public Mirror";
remotesList.Size = Size.Empty;
}
splash.Close();
}
private async void Form1_Shown(object sender, EventArgs e)
{
new Thread(() =>
{
Thread.Sleep(10000);
freeDisclaimer.Invoke(() => { freeDisclaimer.Dispose(); });
}).Start();
progressBar.Style = ProgressBarStyle.Marquee;
Thread t1 = new Thread(() =>
{
if (!debugMode && Properties.Settings.Default.checkForUpdates)
{
Updater.AppName = "Rookie-PCVR";
Updater.Repostory = "VRPirates/rookie-pcvr";
Updater.Update();
}
progressBar.Invoke(() => { progressBar.Style = ProgressBarStyle.Marquee; });
progressBar.Style = ProgressBarStyle.Marquee;
ChangeTitle("Initializing Servers...");
initMirrors(true);
if (Properties.Settings.Default.autoUpdateConfig)
{
ChangeTitle("Checking for a new Configuration File...");
SideloaderRCLONE.updateDownloadConfig();
}
SideloaderRCLONE.updateUploadConfig();
if (!hasPublicPCVRConfig)
{
ChangeTitle("Grabbing the Games List...");
SideloaderRCLONE.initGames(currentRemote);
}
else
{
ChangeTitle("Offline mode enabled, no Rclone");
}
});
t1.SetApartmentState(ApartmentState.STA);
t1.IsBackground = true;
t1.Start();
while (t1.IsAlive)
{
await Task.Delay(100);
}
if (hasPublicPCVRConfig)
{
remotesList.Visible = false;
Thread t2 = new Thread(() =>
{
ChangeTitle("Updating Metadata...");
SideloaderRCLONE.UpdateMetadataFromPublic();
ChangeTitle("Processing Metadata...");
SideloaderRCLONE.ProcessMetadataFromPublic();
})
{
IsBackground = true
};
t2.Start();
while (t2.IsAlive)
{
await Task.Delay(50);
}
}
progressBar.Style = ProgressBarStyle.Marquee;
ChangeTitle("Populating Game Update List, Almost There!");
downloadInstallGameButton.Enabled = true;
isLoading = false;
initListPCVRView();
string[] files = Directory.GetFiles(Environment.CurrentDirectory);
foreach (string file in files)
{
string fileName = file;
while (fileName.Contains("\\"))
{
fileName = fileName.Substring(fileName.IndexOf("\\") + 1);
}
if (!fileName.Contains(Properties.Settings.Default.CurrentLogName) && !fileName.Contains(Properties.Settings.Default.CurrentCrashName))
{
if (!fileName.Contains("debuglog") && fileName.EndsWith(".txt"))
{
System.IO.File.Delete(fileName);
}
}
}
}
private void initMirrors(bool random)
{
int index = 0;
remotesList.Invoke(() => { index = remotesList.SelectedIndex; remotesList.Items.Clear(); });
string[] mirrors = RCLONE.runRcloneCommand_DownloadConfig("listremotes").Output.Split('\n');
_ = Logger.Log("Loaded following mirrors: ");
int itemsCount = 0;
foreach (string mirror in mirrors)
{
if (mirror.Contains("mirror"))
{
_ = Logger.Log(mirror.Remove(mirror.Length - 1));
remotesList.Invoke(() => { _ = remotesList.Items.Add(mirror.Remove(mirror.Length - 1).Replace("VRP-mirror", "")); });
itemsCount++;
}
}
if (itemsCount > 0)
{
Random rand = new Random();
// Code that implements a randomized mirror. The rotation logic (the rotation) is reported as being bugged so I just disabled as a workaround ~pmow
// if (random == true && index < itemsCount)
// index = rand.Next(0, itemsCount);
// remotesList.Invoke(() =>
// {
// remotesList.SelectedIndex = index;
// remotesList.SelectedIndex = 0;
// currentRemote = "VRP-mirror" + remotesList.SelectedItem.ToString();
// });
remotesList.Invoke(() =>
{
remotesList.SelectedIndex = 0; // Set mirror to first item in array.
currentRemote = "VRP-mirror" + remotesList.SelectedItem.ToString(); ;
});
};
}
public static string processError = string.Empty;
public static string currentRemote = string.Empty;
private void timer_Tick2(object sender, EventArgs e)
{
keyheld = false;
}
public async void ChangeTitle(string txt, bool reset = true)
{
try
{
this.Invoke(() => { oldTitle = txt; Text = "Rookie PCVR v" + Updater.LocalVersion + " | " + txt; });
if (!reset)
{
return;
}
await Task.Delay(TimeSpan.FromSeconds(5));
this.Invoke(() => { Text = "Rookie PCVR v" + Updater.LocalVersion + " | " + oldTitle; });
}
catch
{
}
}
private void ShowSubMenu(Panel subMenu)
{
subMenu.Visible = subMenu.Visible == false;
}
public void ShowPrcOutput(ProcessOutput prcout)
{
string message = $"Output: {prcout.Output}";
if (prcout.Error.Length != 0)
{
message += $"\nError: {prcout.Error}";
}
_ = FlexibleMessageBox.Show(Program.form, message);
}
public List<string> Devices = new List<string>();
private List<string> newGamesList = new List<string>();
private List<string> newGamesToUploadList = new List<string>();
private readonly List<UpdateGameData> gamesToAskForUpdate = new List<UpdateGameData>();
public static bool loaded = false;
public static string rookienamelist;
public static string rookienamelist2;
private bool errorOnList;
public static bool updates = false;
public static bool newapps = false;
public static int newint = 0;
public static int updint = 0;
public static bool nodeviceonstart = false;
public static bool either = false;
private bool _allItemsInitialized = false;
private async void initListPCVRView()
{
rookienamelist = "";
loaded = false;
char[] delims = new[] { '\r', '\n' };
List<ListViewItem> GameList = new List<ListViewItem>();
GameList.Clear();
List<string> rookieList = new List<string>();
errorOnList = false;
//This is for black list, but temporarly will be whitelist
//this list has games that we are actually going to upload
progressBar.Style = ProgressBarStyle.Marquee;
if (SideloaderRCLONE.games.Count > 5)
{
Thread t1 = new Thread(() =>
{
foreach (string[] release in SideloaderRCLONE.games)
{
if (!rookienamelist.Contains(release[SideloaderRCLONE.GameNameIndex].ToString()))
{
rookienamelist += release[SideloaderRCLONE.GameNameIndex].ToString() + "\n";
rookienamelist2 += release[SideloaderRCLONE.GameNameIndex].ToString() + ", ";
}
ListViewItem Game = new ListViewItem(release);
GameList.Add(Game);
}
})
{
IsBackground = true
};
t1.Start();
while (t1.IsAlive)
{
await Task.Delay(100);
}
}
else
{
SwitchMirrors();
initListPCVRView();
}
progressBar.Style = ProgressBarStyle.Continuous;
ChangeTitle("Populating game list... \n\n");
ListViewItem[] arr = GameList.ToArray();
gamesListView.BeginUpdate();
gamesListView.Items.Clear();
gamesListView.Items.AddRange(arr);
gamesListView.EndUpdate();
if (!_allItemsInitialized)
{
_allItems = gamesListView.Items.Cast<ListViewItem>().ToList();
_allItemsInitialized = true; // Set the flag to true after initialization
}
ChangeTitle(" \n\n");
loaded = true;
}
private void settingsButton_Click(object sender, EventArgs e)
{
SettingsForm settingsForm = new SettingsForm();
settingsForm.Show(Program.form);
}
private void aboutBtn_Click(object sender, EventArgs e)
{
string about = $@"Version: {Updater.LocalVersion}
- Software orignally coded by rookie.wtf
- Fork of AndroidSideloader made by Chax to work with PCVR
";
_ = FlexibleMessageBox.Show(Program.form, about);
}
private static readonly HttpClient client = new HttpClient();
public static bool reset = false;
public static bool updatedConfig = false;
public static int steps = 0;
public static bool gamesAreDownloading = false;
private readonly BindingList<string> gamesQueueList = new BindingList<string>();
public static int quotaTries = 0;
public static bool timerticked = false;
public static bool skiponceafterremove = false;
public void SwitchMirrors()
{
try
{
quotaTries++;
remotesList.Invoke(() =>
{
if (quotaTries > remotesList.Items.Count)
{
ShowError_QuotaExceeded();
RCLONE.killRclone();
Application.Exit();
return;
}
if (remotesList.SelectedIndex + 1 == remotesList.Items.Count)
{
reset = true;
for (int i = 0; i < steps; i++)
{
remotesList.SelectedIndex--;
}
}
if (reset)
{
remotesList.SelectedIndex--;
}
if (remotesList.Items.Count > remotesList.SelectedIndex && !reset)
{
remotesList.SelectedIndex++;
steps++;
}
});
}
catch { }
}
private static void ShowError_QuotaExceeded()
{
string errorMessage =
$@"Unable to connect to Remote Server. Rookie is unable to connect to our Servers.
First time launching Rookie-PCVR? Please relaunch and try again.
Things you can try:
1) Move the Rookie-PCVR directory (Folder containing Rookie-PCVR.exe) into {Path.GetPathRoot(Environment.SystemDirectory)}RSL
2) Try changing your systems DNS to either Cloudflare/Google/OpenDNS
3) Try using a systemwide VPN like ProtonVPN
4) Sponsor a private server (https://vrpirates.wiki/en/Howto/sponsored-mirrors)
";
_ = FlexibleMessageBox.Show(Program.form, errorMessage, "Unable to connect to Remote Server");
}
public void cleanupActiveDownloadStatus()
{
speedLabel.Text = "";
etaLabel.Text = "";
progressBar.Value = 0;
gamesQueueList.RemoveAt(0);
}
public bool isinstalling = false;
public static bool removedownloading = false;
public async void downloadInstallGameButton_Click(object sender, EventArgs e)
{
{
if (!Properties.Settings.Default.customDownloadDir)
{
Properties.Settings.Default.downloadDir = Environment.CurrentDirectory.ToString();
}
progressBar.Style = ProgressBarStyle.Marquee;
if (gamesListView.SelectedItems.Count == 0)
{
progressBar.Style = ProgressBarStyle.Continuous;
ChangeTitle("You must select a game from the Game List!");
return;
}
string namebox = gamesListView.SelectedItems[0].ToString();
int count = 0;
string[] gamesToDownload;
if (gamesListView.SelectedItems.Count > 0)
{
count = gamesListView.SelectedItems.Count;
gamesToDownload = new string[count];
for (int i = 0; i < count; i++)
{
gamesToDownload[i] = gamesListView.SelectedItems[i].SubItems[SideloaderRCLONE.GameNameIndex].Text;
}
}
else
{
return;
}
progressBar.Value = 0;
progressBar.Style = ProgressBarStyle.Continuous;
string game = gamesToDownload.Length == 1 ? $"\"{gamesToDownload[0]}\"" : "the selected games";
isinstalling = true;
//Add games to the queue
for (int i = 0; i < gamesToDownload.Length; i++)
{
gamesQueueList.Add(gamesToDownload[i]);
}
if (gamesAreDownloading)
{
return;
}
gamesAreDownloading = true;
ProcessOutput output = new ProcessOutput("", "");
string gameName = "";
while (gamesQueueList.Count > 0)
{
gameName = gamesQueueList.ToArray()[0];
string dir = Path.GetDirectoryName(gameName);
string gameDirectory = Properties.Settings.Default.downloadDir + "\\" + gameName;
string downloadDirectory = Path.Combine(Properties.Settings.Default.downloadDir, gameName);
string path = gameDirectory;
string gameNameHash = string.Empty;
using (MD5 md5 = MD5.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(gameName + "\n");
byte[] hash = md5.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
{
_ = sb.Append(b.ToString("x2"));
}
gameNameHash = sb.ToString();
}
ProcessOutput gameDownloadOutput = new ProcessOutput("", "");
_ = Logger.Log($"Starting Game Download");
Thread t1;
string extraArgs = string.Empty;
string virtualFilesystemCompatibilityArg = string.Empty;
if (Properties.Settings.Default.singleThreadMode)
{
extraArgs = "--transfers 1 --multi-thread-streams 0";
}
if (hasPublicPCVRConfig)
{
bool doDownload = true;
if (Directory.Exists(gameDirectory))
{
DialogResult res = FlexibleMessageBox.Show(
$"{gameName} exists in destination directory.\r\nWould you like to overwrite it?",
"Download again?", MessageBoxButtons.YesNo);
doDownload = res == DialogResult.Yes;
if (doDownload)
{
// only delete after extraction; allows for resume if the fetch fails midway.
if (Directory.Exists($"{Properties.Settings.Default.downloadDir}\\{gameName}"))
{
Directory.Delete($"{Properties.Settings.Default.downloadDir}\\{gameName}", true);
}
}
}
if (doDownload)
{
downloadDirectory = $"{Properties.Settings.Default.downloadDir}\\{gameNameHash}";
_ = Logger.Log($"rclone copy \"Public:{SideloaderRCLONE.RcloneGamesFolder}/{gameName}\"");
t1 = new Thread(() =>
{
string rclonecommand =
$"copy \":http:/{gameNameHash}/\" \"{downloadDirectory}\" {extraArgs} {virtualFilesystemCompatibilityArg} --progress --rc --check-first --fast-list";
gameDownloadOutput = RCLONE.runRcloneCommand_PublicConfig(rclonecommand, true);
});
}
else
{
t1 = new Thread(() => { gameDownloadOutput = new ProcessOutput("Download skipped."); });
}
}
else
{
_ = Directory.CreateDirectory(gameDirectory);
downloadDirectory = $"{SideloaderRCLONE.RcloneGamesFolder}/{gameName}";
_ = Logger.Log($"rclone copy \"{currentRemote}:{downloadDirectory}\"");
t1 = new Thread(() =>
{
gameDownloadOutput = RCLONE.runRcloneCommand_DownloadConfig($"copy \"{currentRemote}:{SideloaderRCLONE.RcloneGamesFolder}/{gameName}\" \"{Properties.Settings.Default.downloadDir}\\{gameName}\" {extraArgs} {virtualFilesystemCompatibilityArg} --progress --rc --retries 1 --low-level-retries 1 --check-first");
});
}
if (Directory.Exists(downloadDirectory))
{
string[] partialFiles = Directory.GetFiles($"{downloadDirectory}", "*.partial");
foreach (string file in partialFiles)
{
File.Delete(file);
Logger.Log($"Deleted partial file: {file}");
}
}
t1.IsBackground = true;
t1.Start();
ChangeTitle("Downloading game " + gameName, false);
speedLabel.Text = "Starting download..."; etaLabel.Text = "Please wait...";
//Download
while (t1.IsAlive)
{
try
{
HttpResponseMessage response = await client.PostAsync("http://127.0.0.1:5572/core/stats", null);
string foo = await response.Content.ReadAsStringAsync();
//Debug.WriteLine("RESP CONTENT " + foo);
dynamic results = JsonConvert.DeserializeObject<dynamic>(foo);
if (results["transferring"] != null)
{
double totalSize = 0;
double downloadedSize = 0;
long fileCount = 0;
long transfersComplete = 0;
long totalChecks = 0;
long globalEta = 0;
float speed = 0;
float downloadSpeed = 0;
double estimatedFileCount = 0;
totalSize = results["totalBytes"];
downloadedSize = results["bytes"];
fileCount = results["totalTransfers"];
totalChecks = results["totalChecks"];
transfersComplete = results["transfers"];
globalEta = results["eta"];
speed = results["speed"];
estimatedFileCount = Math.Ceiling(totalSize / 524288000); // maximum part size
if (totalChecks > fileCount) {
fileCount = totalChecks;
}
if (estimatedFileCount > fileCount) {
fileCount = (long)estimatedFileCount;
}
downloadSpeed = speed / 1000000;
totalSize /= 1000000;
downloadedSize /= 1000000;
// Logger.Log("Files: " + transfersComplete.ToString() + "/" + fileCount.ToString() + " (" + Convert.ToInt32((downloadedSize / totalSize) * 100).ToString() + "% Complete)");
// Logger.Log("Downloaded: " + downloadedSize.ToString() + " of " + totalSize.ToString());
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Value = Convert.ToInt32((downloadedSize / totalSize) * 100);
TimeSpan time = TimeSpan.FromSeconds(globalEta);
etaLabel.Text = etaLabel.Text = "ETA: " + time.ToString(@"hh\:mm\:ss") + " left";
speedLabel.Text = "DLS: " + transfersComplete.ToString() + "/" + fileCount.ToString() + " files - " + string.Format("{0:0.00}", downloadSpeed) + " MB/s";
}
}
catch {
}
await Task.Delay(100);
}
if (removedownloading)
{
ChangeTitle("Deleting game files", false);
try
{
cleanupActiveDownloadStatus();
DialogResult res = FlexibleMessageBox.Show(
$"{gameName} already has some downloaded files, do you want to delete them?\n\nClick NO to keep the files if you wish to resume your download later.",
"Delete Temporary Files?", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes) {
if (hasPublicPCVRConfig)
{
if (Directory.Exists($"{Properties.Settings.Default.downloadDir}\\{gameNameHash}"))
{
Directory.Delete($"{Properties.Settings.Default.downloadDir}\\{gameNameHash}", true);
}
if (Directory.Exists($"{Properties.Settings.Default.downloadDir}\\{gameName}"))
{
Directory.Delete($"{Properties.Settings.Default.downloadDir}\\{gameName}", true);
}
}
else
{
Directory.Delete(Properties.Settings.Default.downloadDir + "\\" + gameName, true);
}
}
}
catch (Exception ex)
{
_ = FlexibleMessageBox.Show($"Error deleting game files: {ex.Message}");
}
ChangeTitle("");
break;
}
{
//Quota Errors
bool quotaError = false;
bool otherError = false;
if (gameDownloadOutput.Error.Length > 0)
{
string err = gameDownloadOutput.Error.ToLower();
err += gameDownloadOutput.Output.ToLower();
if ((err.Contains("quota") && err.Contains("exceeded")) || err.Contains("directory not found"))
{
quotaError = true;
SwitchMirrors();
cleanupActiveDownloadStatus();
}
else if (!gameDownloadOutput.Error.Contains("Serving remote control on http://127.0.0.1:5572/"))
{
otherError = true;
//Remove current game
cleanupActiveDownloadStatus();
_ = FlexibleMessageBox.Show($"Rclone error: {gameDownloadOutput.Error}");
output += new ProcessOutput("", "Download Failed");
}
}
if (hasPublicPCVRConfig && otherError == false && gameDownloadOutput.Output != "Download skipped.")
{
Thread extractionThread = new Thread(() =>
{
try
{
Invoke(new Action(() =>
{
speedLabel.Text = "Extracting..."; etaLabel.Text = "Please wait...";
}));
ChangeTitle("Extracting " + gameName, false);
Zip.ExtractFile($"{Properties.Settings.Default.downloadDir}\\{gameNameHash}\\{gameNameHash}.7z.001", $"{Properties.Settings.Default.downloadDir}", PublicConfigFile.Password);
Program.form.ChangeTitle("");
}
catch (Exception ex)
{
Invoke(new Action(() =>
{
cleanupActiveDownloadStatus();
}));
otherError = true;
_ = FlexibleMessageBox.Show($"7zip error: {ex.Message}");
output += new ProcessOutput("", "Extract Failed");
}
})
{
IsBackground = true
};
extractionThread.Start();
while (extractionThread.IsAlive)
{
await Task.Delay(100);
}
string[] partFiles = Directory.GetFiles($"{Properties.Settings.Default.downloadDir}\\{gameName}", "*.001");
string[] sevenZipFiles = Directory.GetFiles($"{Properties.Settings.Default.downloadDir}\\{gameName}", "*.7z");
string[] zipFiles = Directory.GetFiles($"{Properties.Settings.Default.downloadDir}\\{gameName}", "*.zip");
bool extracted = false; // Flag to track if any zip file has been extracted
if (Properties.Settings.Default.autoExtract)
{
if (partFiles != null && partFiles.Length > 0)
{
// Extract the first part file
Zip.ExtractFile(partFiles.First(), $"{Properties.Settings.Default.downloadDir}\\{gameName}");
extracted = true;
string[] allPartFiles = Directory.GetFiles($"{Properties.Settings.Default.downloadDir}\\{gameName}", "*.7z.*");
foreach (string part in allPartFiles)
{
File.Delete(part);
}
}
else if (sevenZipFiles != null && sevenZipFiles.Length > 0)
{
// If there are no part files, extract the 7z file
Zip.ExtractFile(sevenZipFiles.First(), $"{Properties.Settings.Default.downloadDir}\\{gameName}");
File.Delete(sevenZipFiles.First());
extracted = true;
}
else if (zipFiles != null && zipFiles.Length > 0)
{
// If there are no part or 7z files, extract the zip file
Zip.ExtractFile(zipFiles.First(), $"{Properties.Settings.Default.downloadDir}\\{gameName}");
File.Delete(zipFiles.First());
extracted = true;
}
}
if (Directory.Exists($"{Properties.Settings.Default.downloadDir}\\{gameNameHash}"))
{
Directory.Delete($"{Properties.Settings.Default.downloadDir}\\{gameNameHash}", true);
}
}
if (quotaError == false && otherError == false)
{
ChangeTitle($"Installation of {gameName} completed.");
//Remove current game
cleanupActiveDownloadStatus();
}
}
}
}
if (removedownloading)
{
removedownloading = false;
gamesAreDownloading = false;
isinstalling = false;
return;
}
ChangeTitle("Refreshing games list, please wait... \n");
progressBar.Style = ProgressBarStyle.Continuous;
etaLabel.Text = "ETA: Finished Queue";
speedLabel.Text = "DLS: Finished Queue";
gamesAreDownloading = false;
isinstalling = false;
ChangeTitle(" \n\n");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (isinstalling)
{
DialogResult res1 = FlexibleMessageBox.Show(Program.form, "There are downloads and/or installations in progress,\nif you exit now you'll have to start the entire process over again.\nAre you sure you want to exit?", "Still downloading/installing.",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (res1 != DialogResult.Yes)
{
e.Cancel = true;
return;
}
else
{
RCLONE.killRclone();
}
}
else
{
RCLONE.killRclone();
}
}
private void disPosed(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void gamesQueListBox_MouseClick(object sender, MouseEventArgs e)
{
if (gamesQueListBox.SelectedIndex == 0 && gamesQueueList.Count == 1)
{
removedownloading = true;
RCLONE.killRclone();
}
if (gamesQueListBox.SelectedIndex != -1 && gamesQueListBox.SelectedIndex != 0)
{
_ = gamesQueueList.Remove(gamesQueListBox.SelectedItem.ToString());
}
}
private void remotesList_SelectedIndexChanged(object sender, EventArgs e)
{
if (remotesList.SelectedItem != null)
{
remotesList.Invoke(() => { currentRemote = "VRP-mirror" + remotesList.SelectedItem.ToString(); });
}
}
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.SortColumn)
{
// Reverse the current sort direction for this column.
lvwColumnSorter.Order = lvwColumnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
}
else