This repository has been archived by the owner on Jun 10, 2023. It is now read-only.
/
FormMain.cs
508 lines (448 loc) · 17.9 KB
/
FormMain.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using MonkeModManager.Internals;
using System.Diagnostics;
using System.Runtime.InteropServices;
using MonkeModManager.Internals.SimpleJSON;
namespace MonkeModManager
{
public partial class FormMain : Form
{
private const string BaseEndpoint = "https://api.github.com/repos/";
private const Int16 CurrentVersion = 3;
private List<ReleaseInfo> releases;
private string InstallDirectory = @"";
public bool isSteam = true;
public bool platformDetected = false;
public FormMain()
{
InitializeComponent();
}
private void FormMain_Load(object sender, EventArgs e)
{
LocationHandler();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
releases = new List<ReleaseInfo>();
new Thread(() =>
{
LoadRequiredPlugins();
}).Start();
}
#region ReleaseHandling
private void LoadReleases()
{
var decoded = JSON.Parse(DownloadSite("https://raw.githubusercontent.com/DeadlyKitten/MonkeModManager/master/mods.json"));
var allMods = decoded["mods"].AsArray;
for (int i = 0; i < allMods.Count; i++)
{
JSONNode current = allMods[i];
ReleaseInfo release = new ReleaseInfo(current["name"], current["author"], current["gitPath"], current["releaseId"], current["tag"], current["dependencies"].AsArray);
UpdateReleaseInfo(ref release);
releases.Add(release);
}
foreach (ReleaseInfo release in releases)
{
foreach (string dep in release.Dependencies)
{
releases.Where(x => x.Name == dep).FirstOrDefault()?.Dependents.Add(release.Name);
}
}
//WriteReleasesToDisk();
}
private void LoadRequiredPlugins()
{
CheckVersion();
UpdateStatus("Getting latest version info...");
LoadReleases();
this.Invoke((MethodInvoker)(() =>
{//Invoke so we can call from current thread
//Update checkbox's text
foreach (ReleaseInfo release in releases)
{
ListViewItem item = new ListViewItem();
item.Text = $"{release.Name} - {release.Version}";
if (release.Tag != string.Empty) { item.Text = string.Format("{0} - ({1})",release.Name, release.Tag); };
item.SubItems.Add(release.Author);
item.Tag = release;
if (release.Install)
{
listViewMods.Items.Add(item);
}
CheckDefaultMod(release, item);
}
tabControlMain.Enabled = true;
buttonInstall.Enabled = true;
}));
UpdateStatus("Release info updated!");
}
private void UpdateReleaseInfo(ref ReleaseInfo release)
{
Thread.Sleep(500); //So we don't get rate limited by github
string releaseFormatted = BaseEndpoint + release.GitPath + "/releases";
var rootNode = JSON.Parse(DownloadSite(releaseFormatted))[0];
release.Version = rootNode["tag_name"];
var assetsNode = rootNode["assets"];
var downloadReleaseNode = assetsNode[release.ReleaseId];
release.Link = downloadReleaseNode["browser_download_url"];
var uploaderNode = downloadReleaseNode["uploader"];
if (release.Author.Equals(String.Empty)) release.Author = uploaderNode["login"];
}
#endregion
#region Installation
private void Install()
{
ChangeInstallButtonState(false);
UpdateStatus("Starting install sequence...");
foreach (ReleaseInfo release in releases)
{
if (release.Install)
{
UpdateStatus(string.Format("Downloading...{0}", release.Name));
byte[] file = DownloadFile(release.Link);
UpdateStatus(string.Format("Moving...{0}", release.Name));
string fileName = Path.GetFileName(release.Link);
if (release.Link.Contains(".dll"))
{
File.WriteAllBytes(InstallDirectory + @"\BepInEx\plugins\" + fileName, file);
}
else
{
UnzipFile(file, InstallDirectory);
}
UpdateStatus(string.Format("Moved!{0}", release.Name));
}
}
UpdateStatus("Install complete!");
ChangeInstallButtonState(true);
}
#endregion
#region UIEvents
private void buttonInstall_Click(object sender, EventArgs e)
{
new Thread(() =>
{
Install();
}).Start();
}
private void buttonFolderBrowser_Click(object sender, EventArgs e)
{
using (var fileDialog = new OpenFileDialog())
{
fileDialog.FileName = "Gorilla Tag.exe";
fileDialog.Filter = "Exe Files (.exe)|*.exe|All Files (*.*)|*.*";
fileDialog.FilterIndex = 1;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string path = fileDialog.FileName;
if (Path.GetFileName(path).Equals("Gorilla Tag.exe"))
{
InstallDirectory = Path.GetDirectoryName(path);
textBoxDirectory.Text = InstallDirectory;
}
else
{
MessageBox.Show("That's not Gorilla Tag.exe! please try again!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void listViewMods_ItemChecked(object sender, ItemCheckedEventArgs e)
{
ReleaseInfo release = (ReleaseInfo)e.Item.Tag;
if (release.Dependencies.Count > 0)
{
foreach (ListViewItem item in listViewMods.Items)
{
var plugin = (ReleaseInfo)item.Tag;
if (plugin.Name == release.Name) continue;
// if this depends on plugin
if (release.Dependencies.Contains(plugin.Name))
{
if (e.Item.Checked)
{
item.Checked = true;
item.ForeColor = System.Drawing.Color.DimGray;
}
else
{
release.Install = false;
if (releases.Count(x => plugin.Dependents.Contains(x.Name) && x.Install) <= 1)
{
item.Checked = false;
item.ForeColor = System.Drawing.Color.Black;
}
}
}
}
}
// don't allow user to uncheck if a dependent is checked
if (release.Dependents.Count > 0)
{
if (releases.Count(x => release.Dependents.Contains(x.Name) && x.Install) > 0)
{
e.Item.Checked = true;
}
}
if (release.Name.Contains("BepInEx")) { e.Item.Checked = true; };
release.Install = e.Item.Checked;
}
private void listViewMods_DoubleClick(object sender, EventArgs e)
{
OpenLinkFromRelease();
}
private void buttonModInfo_Click(object sender, EventArgs e)
{
OpenLinkFromRelease();
}
private void viewInfoToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenLinkFromRelease();
}
private void listViewMods_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (listViewMods.SelectedItems.Count > 0)
{
buttonModInfo.Enabled = true;
}
else
{
buttonModInfo.Enabled = false;
}
}
#endregion
#region Helpers
private CookieContainer PermCookie;
private string DownloadSite(string URL)
{
try
{
if (PermCookie == null) { PermCookie = new CookieContainer(); }
HttpWebRequest RQuest = (HttpWebRequest)HttpWebRequest.Create(URL);
RQuest.Method = "GET";
RQuest.KeepAlive = true;
RQuest.CookieContainer = PermCookie;
RQuest.ContentType = "application/x-www-form-urlencoded";
RQuest.Referer = "";
RQuest.UserAgent = "Monke-Mod-Manager";
RQuest.Proxy = null;
HttpWebResponse Response = (HttpWebResponse)RQuest.GetResponse();
StreamReader Sr = new StreamReader(Response.GetResponseStream());
string Code = Sr.ReadToEnd();
Sr.Close();
return Code;
}
catch (Exception ex)
{
if (ex.Message.Contains("403"))
{
MessageBox.Show("Failed to update version info, GitHub has rate limited you, please check back in 15 - 30 minutes", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Failed to update version info, please check your internet connection", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Process.GetCurrentProcess().Kill();
return null;
}
}
private void UnzipFile(byte[] data, string directory)
{
using (MemoryStream ms = new MemoryStream(data))
{
using (var unzip = new Unzip(ms))
{
unzip.ExtractToDirectory(directory);
}
}
}
private byte[] DownloadFile(string url)
{
WebClient client = new WebClient();
client.Proxy = null;
return client.DownloadData(url);
}
private void UpdateStatus(string status)
{
string formattedText = string.Format("Status: {0}", status);
this.Invoke((MethodInvoker)(() =>
{ //Invoke so we can call from any thread
labelStatus.Text = formattedText;
}));
}
private void NotFoundHandler()
{
bool found = false;
while (found == false)
{
using (var fileDialog = new OpenFileDialog())
{
fileDialog.FileName = "Gorilla Tag.exe";
fileDialog.Filter = "Exe Files (.exe)|*.exe|All Files (*.*)|*.*";
fileDialog.FilterIndex = 1;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string path = fileDialog.FileName;
if (Path.GetFileName(path).Equals("Gorilla Tag.exe"))
{
InstallDirectory = Path.GetDirectoryName(path);
textBoxDirectory.Text = InstallDirectory;
found = true;
}
else
{
MessageBox.Show("That's not Gorilla Tag.exe! please try again!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
Process.GetCurrentProcess().Kill();
}
}
}
}
private void CheckVersion()
{
UpdateStatus("Checking for updates...");
Int16 version = Convert.ToInt16(DownloadSite("https://raw.githubusercontent.com/DeadlyKitten/MonkeModManager/master/update.txt"));
if (version > CurrentVersion)
{
this.Invoke((MethodInvoker)(() =>
{
MessageBox.Show("Your version of the mod installer is outdated! Please download the new one!", "Update available!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Process.Start("https://github.com/DeadlyKitten/MonkeModManager/releases/latest");
Process.GetCurrentProcess().Kill();
Environment.Exit(0);
}));
}
}
private void ChangeInstallButtonState(bool enabled)
{
this.Invoke((MethodInvoker)(() =>
{
buttonInstall.Enabled = enabled;
}));
}
private void OpenLinkFromRelease()
{
if (listViewMods.SelectedItems.Count > 0)
{
ReleaseInfo release = (ReleaseInfo)listViewMods.SelectedItems[0].Tag;
Process.Start(string.Format("https://github.com/{0}", release.GitPath));
}
}
#endregion
#region Registry
private void LocationHandler()
{
string steam = GetSteamLocation();
if (steam != null)
{
if (Directory.Exists(steam))
{
if (File.Exists(steam + @"\Gorilla Tag.exe"))
{
textBoxDirectory.Text = steam;
InstallDirectory = steam;
platformDetected = true;
return;
}
}
}
ShowErrorFindingDirectoryMessage();
}
private void ShowErrorFindingDirectoryMessage()
{
MessageBox.Show("We couldn't seem to find your Gorilla Tag installation, please press \"OK\" and point us to it", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
NotFoundHandler();
this.TopMost = true;
}
private string GetSteamLocation()
{
string path = RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 1533390", @"InstallLocation");
if (path != null)
{
path = path + @"\";
}
return path;
}
private void CheckDefaultMod(ReleaseInfo release, ListViewItem item)
{
if (release.Name.Contains("BepInEx"))
{
item.Checked = true;
item.ForeColor = System.Drawing.Color.DimGray;
}
else
{
release.Install = false;
}
}
#endregion
#region RegHelper
enum RegSAM
{
QueryValue = 0x0001,
SetValue = 0x0002,
CreateSubKey = 0x0004,
EnumerateSubKeys = 0x0008,
Notify = 0x0010,
CreateLink = 0x0020,
WOW64_32Key = 0x0200,
WOW64_64Key = 0x0100,
WOW64_Res = 0x0300,
Read = 0x00020019,
Write = 0x00020006,
Execute = 0x00020019,
AllAccess = 0x000f003f
}
static class RegHive
{
public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
public static UIntPtr HKEY_CURRENT_USER = new UIntPtr(0x80000001u);
}
static class RegistryWOW6432
{
[DllImport("Advapi32.dll")]
static extern uint RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, out int phkResult);
[DllImport("Advapi32.dll")]
static extern uint RegCloseKey(int hKey);
[DllImport("advapi32.dll", EntryPoint = "RegQueryValueEx")]
public static extern int RegQueryValueEx(int hKey, string lpValueName, int lpReserved, ref uint lpType, System.Text.StringBuilder lpData, ref uint lpcbData);
static public string GetRegKey64(UIntPtr inHive, String inKeyName, string inPropertyName)
{
return GetRegKey64(inHive, inKeyName, RegSAM.WOW64_64Key, inPropertyName);
}
static public string GetRegKey32(UIntPtr inHive, String inKeyName, string inPropertyName)
{
return GetRegKey64(inHive, inKeyName, RegSAM.WOW64_32Key, inPropertyName);
}
static public string GetRegKey64(UIntPtr inHive, String inKeyName, RegSAM in32or64key, string inPropertyName)
{
//UIntPtr HKEY_LOCAL_MACHINE = (UIntPtr)0x80000002;
int hkey = 0;
try
{
uint lResult = RegOpenKeyEx(RegHive.HKEY_LOCAL_MACHINE, inKeyName, 0, (int)RegSAM.QueryValue | (int)in32or64key, out hkey);
if (0 != lResult) return null;
uint lpType = 0;
uint lpcbData = 1024;
StringBuilder AgeBuffer = new StringBuilder(1024);
RegQueryValueEx(hkey, inPropertyName, 0, ref lpType, AgeBuffer, ref lpcbData);
string Age = AgeBuffer.ToString();
return Age;
}
finally
{
if (0 != hkey) RegCloseKey(hkey);
}
}
}
#endregion
}
}