-
Notifications
You must be signed in to change notification settings - Fork 34
/
Main.cs
1321 lines (1159 loc) · 47.9 KB
/
Main.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 Microsoft.Win32;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Reflection;
using YuukiPS_Launcher.Json;
using YuukiPS_Launcher.Json.GameClient;
using YuukiPS_Launcher.Yuuki;
using YuukiPS_Launcher.Utils;
using System.Security.Cryptography.X509Certificates;
namespace YuukiPS_Launcher
{
public partial class Main : Form
{
// Main Function
private Proxy? proxy;
private Process? progress;
Config ConfigData = new();
Profile DefaultProfile = new();
// Stats default
public string WatchFile = "";
public string WatchCheat = "melon123";
public string HostName = "YuukiPS"; // host name
public bool isGameRunning = false;
public bool DoneCheck = true;
// Config basic game
public string VersionGame = "";
public int GameChannel = 0;
public string PathfileGame = "";
// Extra
readonly Extra.Discord discord = new();
// Game
public Game.Genshin.Settings? settingsGenshin = null;
// Patch
Patch? getPatch = null;
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
OperatingSystem os = Environment.OSVersion;
string logFileName = $"log_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.txt";
string logsFolderPath = Path.Combine(Application.StartupPath, "logs");
string logFilePath = Path.Combine(logsFolderPath, logFileName);
Directory.CreateDirectory(logsFolderPath);
Logger.InitLogging($"Platform: {os.Platform}\nPlatform Version: {os.Version}\nService pack: {os.ServicePack}\n\n", logFilePath);
Logger.Info("Boot", "Loading....");
// Before starting make sure proxy is turned off
CheckProxy(true);
// Check Update
CheckUpdate();
LoadConfig("Boot"); // if found config
// Load Profile by profile_default
LoadProfile(ConfigData.profile_default);
// Extra
if (Enable_RPC.Checked)
{
Logger.Info("Boot", "Discord RPC enabled");
discord.Ready();
}
else
{
Logger.Info("Boot", "Discord RPC disabled");
}
}
private void BTLoadClick(object? sender, EventArgs e)
{
var getSelectProfile = GetProfileServer.Text;
LoadProfile(getSelectProfile);
}
private void SetLASaveClick(object? sender, EventArgs e)
{
var getSelectProfile = GetProfileServer.Text;
SaveProfile(getSelectProfile);
}
private void GetProfileServer_SelectedIndexChanged(object? sender, EventArgs e)
{
var getSelectProfile = GetProfileServer.Text;
Logger.Info("Profiles", "GetProfileServer_SelectedIndexChanged " + getSelectProfile);
LoadProfile(getSelectProfile);
}
private void GetTypeGame_SelectedIndexChanged(object? sender, EventArgs e)
{
DefaultProfile.GameConfig.type = (GameType)GetTypeGame.SelectedItem;
}
public void LoadConfig(string LoadBy)
{
ConfigData = Config.LoadConfig();
Logger.Info("Config", $"Configuration loaded by: {LoadBy}");
// Unsubscribe from SelectedIndexChanged event
GetProfileServer.SelectedIndexChanged -= GetProfileServer_SelectedIndexChanged;
// Profile
GetProfileServer.DisplayMember = "name";
GetProfileServer.DataSource = ConfigData.Profile;
// GameType
GetTypeGame.DataSource = Enum.GetValues(typeof(GameType));
// Find the index of the desired profile
for (int i = 0; i < GetProfileServer.Items.Count; i++)
{
Profile profile = (Profile)GetProfileServer.Items[i];
if (profile.name == ConfigData.profile_default)
{
Logger.Info("Profiles", $"Setting selected profile: '{ConfigData.profile_default}' at index {i}");
GetProfileServer.SelectedIndex = i;
break;
}
}
// Subscribe back to SelectedIndexChanged event
GetProfileServer.SelectedIndexChanged += GetProfileServer_SelectedIndexChanged;
}
public void LoadProfile(string loadProfile = "")
{
if (string.IsNullOrEmpty(loadProfile))
{
Logger.Info("Profiles", "No profile specified. Using default settings.");
return;
}
Logger.Info("Profiles", $"Loading profile: '{loadProfile}'");
try
{
var tmpProfile = ConfigData.Profile.Find(p => p.name == loadProfile);
if (tmpProfile != null)
{
DefaultProfile = tmpProfile;
}
else
{
// use default data
}
Logger.Info("Profiles", $"Server URL: {DefaultProfile.ServerConfig.url}");
}
catch (Exception e)
{
Logger.Error("Profiles", $"Failed to load profile: {e.Message}. Using default data.");
}
// Data Set
// Game
Set_LA_GameFolder.Text = DefaultProfile.GameConfig.path;
GetTypeGame.SelectedIndex = Array.IndexOf(Enum.GetValues(typeof(GameType)), DefaultProfile.GameConfig.type);
// Server
CheckProxyEnable.Checked = DefaultProfile.ServerConfig.proxy.enable;
GetServerHost.Text = DefaultProfile.ServerConfig.url;
// Extra
ExtraCheat.Checked = DefaultProfile.GameConfig.extra.Akebi;
Enable_RPC.Checked = DefaultProfile.GameConfig.extra.RPC;
// Get Data Game
if (!CheckVersionGame(DefaultProfile.GameConfig.type))
{
var message = "No game folder detected. Please manually input the game folder before playing.";
Logger.Warning("Game", message);
MessageBox.Show(message, "Game Folder Not Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void SaveProfile(string NameSave = "Default")
{
try
{
var tmpProfile = new Profile();
// Game
tmpProfile.GameConfig.path = Set_LA_GameFolder.Text;
tmpProfile.GameConfig.type = (GameType)GetTypeGame.SelectedItem;
tmpProfile.GameConfig.wipeLogin = Enable_WipeLoginCache.Checked;
// Server
tmpProfile.ServerConfig.url = GetServerHost.Text;
bool isValid = int.TryParse(GetProxyPort.Text, out int myInt);
if (isValid)
{
tmpProfile.ServerConfig.proxy.port = myInt;
}
// Extra
tmpProfile.GameConfig.extra.Akebi = ExtraCheat.Checked;
tmpProfile.GameConfig.extra.RPC = Enable_RPC.Checked;
// Nama Profile
tmpProfile.name = NameSave;
try
{
int indexToUpdate = ConfigData.Profile.FindIndex(profile => profile.name == NameSave);
if (indexToUpdate != -1)
{
Logger.Info("Profiles", $"Updating existing profile: {NameSave}");
ConfigData.Profile[indexToUpdate] = tmpProfile;
}
else
{
Logger.Info("Profiles", $"Creating new profile: {NameSave}");
ConfigData.Profile.Add(tmpProfile);
}
}
catch (Exception ex)
{
Logger.Error("Profiles", $"Failed to save profile '{NameSave}'. Error: {ex.Message}. Reinitializing configuration.");
ConfigData = new Config() { Profile = new List<Profile>() { tmpProfile } };
}
ConfigData.profile_default = NameSave;
File.WriteAllText(Config.ConfigPath, JsonConvert.SerializeObject(ConfigData));
Logger.Info("Config", "Configuration saved successfully.");
LoadConfig("SaveProfile");
}
catch (Exception ex)
{
Logger.Error("Profiles", $"Failed to save profile: {ex.Message}. Reverting to default configuration.");
}
}
private void BTStartOfficialServer_Click(object sender, EventArgs e)
{
GetServerHost.Text = "official";
CheckProxyEnable.Checked = false;
DoStart();
}
private void BTStartYuukiServer_Click(object sender, EventArgs e)
{
GetServerHost.Text = API.WebLink;
CheckProxyEnable.Checked = true;
DoStart();
}
private void BTStartNormal_Click(object sender, EventArgs e)
{
DoStart();
}
public void DoStart()
{
// Jika game berjalan...
if (isGameRunning)
{
AllStop();
return;
}
// Setup
bool isCheat = ExtraCheat.Checked;
bool isProxyNeed = CheckProxyEnable.Checked;
bool isSendLog = EnableSendLog.Checked;
bool isShowLog = EnableShowLog.Checked;
GameType selectedGame = (GameType)GetTypeGame.SelectedItem;
// Get Host
string setServerHost = GetServerHost.Text;
if (string.IsNullOrEmpty(setServerHost))
{
MessageBox.Show("Please select a server first, you can click on one in server list");
return;
}
// Get Proxy
int setProxyPort = int.Parse(GetProxyPort.Text);
// Get Game
var cstGameFile = PathfileGame;
if (string.IsNullOrEmpty(cstGameFile))
{
MessageBox.Show("No game file config found");
return;
}
if (!File.Exists(cstGameFile))
{
MessageBox.Show("Please find game install folder!");
return;
}
bool patch = true;
// Check progress
if (!isGameRunning)
{
// if game is not running
if (progress != null)
{
Logger.Info("Game", "progress tes");
}
// if server is official
if (setServerHost == "official")
{
patch = false;
}
else
{
if (getPatch != null && getPatch.NoSupport != "")
{
MessageBox.Show(getPatch.NoSupport, "Game version not supported");
Process.Start(new ProcessStartInfo(API.WebLink) { UseShellExecute = true });
return;
}
}
// run patch
var startPatch = PatchGame(patch);
if (!startPatch)
{
MessageBox.Show("Failed to patch a game file. See console for more details.");
return;
}
}
// For Proxy
if (proxy == null)
{
// skip proxy if official server
if (setServerHost != "official")
{
if (isProxyNeed)
{
proxy = new Proxy(setProxyPort, setServerHost, isSendLog, isShowLog);
if (!proxy.Start())
{
MessageBox.Show($"Unable to start proxy on port {setProxyPort}. Possible reasons:\n\n" +
"1. The port is already in use by another application.\n" +
"2. Windows Firewall is blocking access to this port.\n" +
"3. Windows Update may be using ports in this range.\n\n" +
"Please try the following:\n" +
"- Close any applications that might be using this port.\n" +
"- Check your firewall settings.\n" +
"- Try restarting the application.\n" +
"- If the issue persists, consider using a different port.",
"Proxy Port Error");
try
{
Process.Start(new ProcessStartInfo("cmd", $"/c net stop winnat") { CreateNoWindow = true, UseShellExecute = false });
}
catch (Exception ex)
{
Logger.Error("Proxy", $"Error stopping WinNAT service: {ex.Message}");
}
proxy.Stop();
return;
}
else
{
if (setServerHost.Contains("yuuki.me"))
{
if (!API.IsYuuki(setProxyPort))
{
proxy.Stop();
InstallCert();
MessageBox.Show("Unable to connect to YuukiPS server. Please try the following steps:\n\n1. Close this program completely\n2. Reopen the program and try again\n\nIf the issue persists, please report it to an admin and include a screenshot of the console.", "Connection Error");
return;
}
}
}
}
else
{
Logger.Info("Proxy", "Proxy is disabled as per user settings");
}
}
else
{
Logger.Info("Proxy", "Proxy is bypassed when using the official server");
}
}
else
{
Logger.Info("Proxy", "Proxy is currently active and running");
}
// For Cheat (tmp)
if (isCheat)
{
Logger.Info("Cheat", "Cheat enabled");
try
{
var getFileCheat = API.GetCheat(selectedGame, GameChannel, VersionGame, cstGameFile);
if (getFileCheat == null)
{
MessageBox.Show("No cheats are available for this game version. Please disable the cheat feature in the settings to launch the game.", "Cheat Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Information);
ExtraCheat.Checked = false;
return;
}
cstGameFile = getFileCheat.Launcher;
WatchCheat = Path.GetFileNameWithoutExtension(cstGameFile);
Logger.Info("Cheat", $"RUN: Monitor {WatchCheat} at {cstGameFile}");
}
catch (Exception x)
{
Logger.Error("Cheat", $"Error: {x.Message}");
}
}
// For Game
if (progress == null)
{
progress = new()
{
StartInfo = new ProcessStartInfo
{
FileName = cstGameFile,
//UseShellExecute = true,
Arguments = "-server=" + setServerHost, // TODO: custom mod
WorkingDirectory = Path.GetDirectoryName(cstGameFile),
}
};
try
{
progress.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
AllStop();
}
}
else
{
Logger.Info("Game", "Game process is already running. Skipping launch.");
}
}
public static void InstallCert()
{
bool installationSucceeded = false;
while (!installationSucceeded)
{
try
{
// Load the certificate from the file
X509Certificate2 certificate = new X509Certificate2("rootCert.pfx");
// Open the Root certificate store for the current user
X509Store store = new(StoreName.Root, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
// Add the certificate to the store
store.Add(certificate);
// Close the store
store.Close();
Logger.Info("Certificate", "Certificate installed successfully.");
installationSucceeded = true; // Set flag to true to exit the loop
}
catch (Exception ex)
{
Logger.Error("Certificate", "Error: " + ex.Message);
}
}
}
public bool CheckVersionGame(GameType gameType)
{
var cstFolderGame = Set_LA_GameFolder.Text;
// If user doesn't have a game config folder, try searching for it automatically
if (string.IsNullOrEmpty(cstFolderGame))
{
var getLauncher = GetLauncherPath(gameType);
Logger.Info("Launcher", "Folder Launcher: " + (getLauncher == "" ? "Not Found" : getLauncher));
if (string.IsNullOrEmpty(getLauncher))
{
// If there is no launcher
Logger.Info("Game", "Please find game install folder!");
return false;
}
else
{
// If there is no launcher, try searching the game folder
cstFolderGame = GetGamePath(getLauncher);
}
}
// Check one more time
if (string.IsNullOrEmpty(cstFolderGame))
{
Logger.Info("Game", "Please find game install folder!");
return false;
}
if (!Directory.Exists(cstFolderGame))
{
Logger.Info("Game", "Please find game install folder! (2)"); // TODO
return false;
}
Logger.Info("Game", "Folder Game: " + cstFolderGame);
string cn = Path.Combine(cstFolderGame, "YuanShen.exe");
string os = Path.Combine(cstFolderGame, "GenshinImpact.exe");
if (gameType == GameType.StarRail)
{
cn = Path.Combine(cstFolderGame, "StarRail.exe"); // todo
os = Path.Combine(cstFolderGame, "StarRail.exe");
}
// Path
if (gameType == GameType.GenshinImpact)
{
// Pilih Channel
if (File.Exists(cn))
{
// Jika game versi cina
WatchFile = "YuanShen";
GameChannel = 2;
PathfileGame = cn;
}
else if (File.Exists(os))
{
// jika game versi global
WatchFile = "GenshinImpact";
GameChannel = 1;
PathfileGame = os;
}
else
{
// jika game versi tidak di dukung atau tidak ada file
Logger.Error("Game", $"No game executable found in the specified folder: {cstFolderGame}. Please ensure the game is properly installed.");
return false;
}
// Settings
try
{
settingsGenshin = new Game.Genshin.Settings(GameChannel);
if (settingsGenshin != null)
{
Logger.Info("Game", $"Game Settings - Text Language: {settingsGenshin.GetGameLanguage()}, Voice Language: {settingsGenshin.GetVoiceLanguageID()}, Server: {settingsGenshin.GetRegServerNameID()}");
}
}
catch (Exception ex)
{
Logger.Warning("Game", "Error getting game settings: " + ex.ToString());
}
}
else
{
// jika game versi global
WatchFile = "StarRail";
GameChannel = 1;
PathfileGame = os;
}
// Check MD5 Game
string gameLOCOriginalMD5 = Tool.CalculateMD5(PathfileGame);
// Check MD5 in Server API
getPatch = API.GetMD5Game(gameLOCOriginalMD5, gameType);
if (getPatch == null)
{
Logger.Error("Game", $"Unsupported game version detected. MD5: {gameLOCOriginalMD5}. Please report this to the admin.");
return false;
}
VersionGame = getPatch.Version;
if (VersionGame == "0.0.0")
{
Logger.Error("Game", $"Unsupported game version detected. MD5: {gameLOCOriginalMD5}.");
Get_LA_Version.Text = "Version: Unknown";
Get_LA_CH.Text = "Channel: Unknown";
Get_LA_REL.Text = "Release: Unknown";
Get_LA_MD5.Text = "MD5: Unknown";
return false;
}
var get_channel = getPatch.Channel;
// IF ALL OK
Set_LA_GameFolder.Text = cstFolderGame;
// Set Version
Get_LA_Version.Text = "Version: " + getPatch.Version;
Get_LA_CH.Text = "Channel: " + get_channel;
Get_LA_REL.Text = "Release: " + getPatch.Release;
Logger.Info("Game", $"Game version: {VersionGame}");
Logger.Info("Game", $"Game executable path: {PathfileGame}");
Logger.Info("Game", $"Game executable MD5 hash: {gameLOCOriginalMD5}");
Get_LA_MD5.Text = "MD5: " + gameLOCOriginalMD5;
return true;
}
public bool PatchGame(bool patchIt = true)
{
// check folder game (root)
var rootFolder = Set_LA_GameFolder.Text;
if (string.IsNullOrEmpty(rootFolder))
{
Logger.Error("PatchGame", "Game folder path is empty or null");
return false;
}
if (!Directory.Exists(rootFolder))
{
Logger.Error("PatchGame", $"Game folder not found at path: {rootFolder}");
return false;
}
// check version
if (getPatch == null)
{
Logger.Error("PatchGame", "Unable to determine game version. Please click 'Get Key' in the config tab to retrieve version information.");
return false;
}
if (VersionGame == "0.0.0")
{
Logger.Error("PatchGame", "The current game version is not compatible with this patching method. Please ensure you have a supported game version.");
return false;
}
if (patchIt)
{
// for patch
if (getPatch.Patched != null && getPatch.Patched.Any())
{
foreach (var data in getPatch.Patched)
{
var iss = PatchCopy(rootFolder, data.File, data.Location, data.MD5, "patch", getPatch.Version);
if (!string.IsNullOrEmpty(iss))
{
Logger.Error("PatchGame", $"Failed to patch file: {data.File}. Error: {iss}");
return false;
}
}
Logger.Info("PatchGame", "Successfully patched all files");
}
else
{
Logger.Info("PatchGame", "No files needed patching");
}
}
else
{
// for unpatch
if (getPatch.Patched != null && getPatch.Patched.Any())
{
foreach (var data in getPatch.Patched)
{
var iss = PatchCopy(rootFolder, data.File, data.Location, data.MD5, "unpatch", getPatch.Version);
if (!string.IsNullOrEmpty(iss))
{
Logger.Error("PatchGame", $"Failed to unpatch file: {data.File}. Error: {iss}");
return false;
}
}
Logger.Info("PatchGame", "Successfully unpatched all files");
}
else
{
Logger.Info("PatchGame", "No files needed unpatching");
}
if (getPatch.Original != null && getPatch.Original.Any())
{
foreach (var data in getPatch.Original)
{
var iss = PatchCopy(rootFolder, data.File, data.Location, data.MD5, "original", getPatch.Version);
if (!string.IsNullOrEmpty(iss))
{
Logger.Error("PatchGame", $"Failed to restore original file: {data.File}. Error: {iss}");
return false;
}
}
Logger.Info("PatchGame", "Successfully restored all original files");
}
else
{
Logger.Info("PatchGame", "No original files needed restoring");
}
}
Logger.Info("PatchGame", $"Game {(patchIt ? "patched" : "unpatched")} successfully");
return true;
}
private void Set_LA_Select_Click(object sender, EventArgs e)
{
var selectedGameFolder = SelectGamePath();
if (!string.IsNullOrEmpty(selectedGameFolder))
{
Set_LA_GameFolder.Text = selectedGameFolder;
Logger.Info("Game Folder", $"Selected game folder: {selectedGameFolder}");
if (!CheckVersionGame(DefaultProfile.GameConfig.type))
{
string message = $"The game version in {selectedGameFolder} may not be supported. Please check the console for more details.";
Logger.Warning("Game Version", message);
MessageBox.Show(message, "Game Version", MessageBoxButtons.OK, MessageBoxIcon.Error);
string url = API.WebLink + "/game/" + DefaultProfile.GameConfig.type.SEOUrl();
Logger.Info("Browser", $"Opening URL for game support: {url}");
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else
{
Logger.Info("Game Version", "Game version check passed successfully.");
}
}
else
{
Logger.Error("Game Folder", "No game folder was selected or found.");
MessageBox.Show("No game folder found. Please select a valid game folder.");
}
}
public static string PatchCopy(string rootFolder, string urlFile, string fileName, string fileMD5, string isCopy, string version)
{
string fileSave = Path.Combine(rootFolder, fileName);
if (isCopy == "unpatch")
{
try
{
File.Delete(fileSave);
Logger.Info("Patch", $"Successfully removed file: {fileSave}");
return "";
}
catch (Exception e)
{
Logger.Error("Patch", $"Failed to remove file: {fileSave}. Error: {e.Message}");
return e.Message;
}
}
if (File.Exists(fileSave))
{
var md5_file_raw = Tool.CalculateMD5(fileSave);
if (md5_file_raw == fileMD5)
{
Logger.Info("Patch", $"File '{fileSave}' already exists with matching MD5. No action needed for '{isCopy}' operation.");
return "";
}
}
var backupPatch = Path.Combine(Config.Modfolder, "i", version, isCopy, fileName);
if (File.Exists(backupPatch))
{
var backupPatchMd5 = Tool.CalculateMD5(backupPatch);
if (backupPatchMd5 == fileMD5)
{
Logger.Info("Patch", $"Found backup {isCopy} > {backupPatch} > {fileSave}");
string saveDir = Path.GetDirectoryName(fileSave) ?? string.Empty;
if (!string.IsNullOrEmpty(saveDir) && !Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
File.Copy(backupPatch, fileSave, overwrite: true);
return "";
}
else
{
// skip ?
}
}
Logger.Info("Patch", $"Initiating download for {isCopy}: URL: {urlFile}, Destination: {fileSave}");
var CEKDL1 = new Download(urlFile, fileSave);
if (CEKDL1.ShowDialog() != DialogResult.OK)
{
return $"Error download ${isCopy} file: {urlFile} to {fileSave}";
}
else
{
var md5_file = Tool.CalculateMD5(fileSave);
if (md5_file == fileMD5)
{
string backupDir = Path.GetDirectoryName(backupPatch) ?? string.Empty;
if (!string.IsNullOrEmpty(backupDir) && !Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
Logger.Info("Game", $"MD5 Patch File {urlFile}: " + md5_file);
File.Copy(fileSave, backupPatch, overwrite: true);
}
else
{
return $"Error patch file {urlFile}, md5 file mismatch {md5_file}";
}
}
// OK
return "";
}
public void CheckUpdate()
{
try
{
Logger.Info("Game", "Checking for launcher updates...");
var version = Assembly.GetExecutingAssembly().GetName().Version;
var versionLauncher = "";
if (version == null)
{
Text = "YuukiPS Launcher " + "(Version: Unknown)";
return;
}
string ver = version.ToString();
versionLauncher = "Version: " + ver;
Text = "YuukiPS Launcher " + versionLauncher;
var getDataUpdate = API.GetUpdate();
if (getDataUpdate == null) return;
var nameVersion = getDataUpdate.TagName;
if (!Version.TryParse(nameVersion, out var version1) || !Version.TryParse(ver, out var version2))
{
Logger.Error("Update", "Unable to compare version numbers. This might be due to an unexpected version format.");
MessageBox.Show("We encountered an issue while checking for updates. The version numbers couldn't be compared correctly.", "Update Check Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var result = version1.CompareTo(version2);
if (result > 0)
{
versionLauncher = $"Version: {ver} (New Update: {nameVersion})";
var tes = MessageBox.Show(getDataUpdate.Body, $"New Update: {getDataUpdate.Name}", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (tes == DialogResult.Yes)
{
PerformUpdate(getDataUpdate.Assets);
}
}
else if (result < 0)
{
versionLauncher = $"Version: {ver} (latest nightly) (Official: {nameVersion})";
}
else
{
versionLauncher = $"Version: {ver} (latest public)";
}
Text = "YuukiPS Launcher " + versionLauncher;
}
catch (Exception ex)
{
Logger.Error("Update", $"Error checking for updates: {ex.Message}");
MessageBox.Show($"An error occurred while checking for updates: {ex.Message}", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private static void PerformUpdate(IEnumerable<Assets> assets)
{
try
{
var url_dl = assets.FirstOrDefault(file =>
file.Name == "YuukiPSLauncherPC.zip" ||
file.Name == "YuukiPS.zip" ||
file.Name == "update.zip")?.BrowserDownloadUrl;
if (string.IsNullOrEmpty(url_dl))
{
MessageBox.Show("Update file not found.", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var updateZipPath = Path.Combine(Config.CurrentlyPath, "update.zip");
var DL1 = new Download(url_dl, updateZipPath);
if (DL1.ShowDialog() != DialogResult.OK) return;
var fileUpdate = Path.Combine(Config.CurrentlyPath, "update.bat");
using (var w = new StreamWriter(fileUpdate))
{
w.WriteLine("@echo off");
w.WriteLine("Taskkill /IM YuukiPS.exe /F");
Logger.Info("Update", "Extracting update files...");
w.WriteLine("tar -xf update.zip");
Logger.Info("Update", "Removing temporary update file...");
w.WriteLine("del update.zip");
Logger.Info("Update", "Update completed. Restarting application...");
w.WriteLine("timeout 5 > NUL");
w.WriteLine("start YuukiPS.exe");
w.WriteLine("del Update.bat");
}
Process.Start(fileUpdate);
}
catch (Exception ex)
{
Logger.Error("Update", $"Error performing update: {ex.Message}");
MessageBox.Show($"An error occurred during the update process: {ex.Message}", "Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Check Launcher
private static string GetLauncherPath(GameType version)
{
Logger.Info("Launcher", "GetLauncherPath: " + version.GetStringValue());
RegistryKey key = Registry.LocalMachine;
if (key != null)
{
var subKey = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + version.GetStringValue());
if (subKey != null)
{
var installPathValue = subKey.GetValue("InstallPath");
if (installPathValue != null)
{
var installPathString = installPathValue.ToString();
if (installPathString != null)
{
return installPathString;
}
}
}
}
return "";
}
// Check Game Install
private static string GetGamePath(string launcherPath = "")
{
string startPath = "";
if (launcherPath == "")
{
return "";
}
string cfgPath = Path.Combine(launcherPath, "config.ini");
if (File.Exists(launcherPath) || File.Exists(cfgPath))
{
// baca file config
using StreamReader reader = new(cfgPath);
string[] abc = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (var item in abc)
{
// cari line install patch
if (item.Contains("game_install_path", StringComparison.CurrentCulture))
{
startPath += item[(item.IndexOf("=") + 1)..];
}
}
}
return startPath;
}
// Pilih Folder
private static string SelectGamePath()
{
string foldPath = "";
FolderBrowserDialog dialog = new()
{
Description = "Select Game Folder"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
foldPath = dialog.SelectedPath;
}
return foldPath;
}