-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainForm.cs
535 lines (471 loc) · 20.1 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
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Xml;
namespace SimuCoins
{
public partial class MainForm : Form
{
// Create an HttpClient to handle HTTP requests and responses
private readonly HttpClient httpClient = new(new HttpClientHandler { CookieContainer = new CookieContainer() });
private bool isClosingDueToEscKey = false;
private bool isClaimed = false;
private static string xmlPath = Application.StartupPath;
private static readonly Regex BalancePatternRegex = new(PluginInfo.BalancePattern);
private static readonly Regex ClaimPatternRegex = new(PluginInfo.ClaimPattern);
private static readonly Regex TimePatternRegex = new(PluginInfo.TimePattern);
internal string UserName
{
get { return UserNameCB.Text; }
set { UserNameCB.Text = value; }
}
internal string Password
{
get { return PasswordTB.Text; }
set { PasswordTB.Text = value; }
}
public MainForm()
{
InitializeComponent();
httpClient.Timeout = TimeSpan.FromSeconds(30);
// Register the event handlers.
KeyDown += MainForm_KeyDown;
FormClosing += MainForm_FormClosing;
FormClosed += MainForm_FormClosed;
List<Button> buttons = new() { ClearBTN, RemoveBTN, LoginBTN };
foreach (Button button in buttons)
{
button.GotFocus += Button_GotFocus;
button.LostFocus += Button_LostFocus;
}
timeLBL.Text = "";
coinsLBL.Text = "";
xmlPath = Path.Combine(PluginInfo.Coin?.get_Variable("PluginPath") ?? "", "SimuCoins.xml");
if (File.Exists(xmlPath))
{
LoadXML();
}
else
{
var xmlDocument = new XmlDocument();
xmlDocument.AppendChild(xmlDocument.CreateElement("users"));
xmlDocument.Save(xmlPath);
}
}
private void SaveXML()
{
var xmlDocument = new XmlDocument();
xmlDocument.Load(xmlPath);
var root = xmlDocument.DocumentElement ?? xmlDocument.CreateElement("users");
xmlDocument.AppendChild(root);
var userName = UserNameCB.Text;
var password = PasswordTB.Text;
// Encrypt the password
string encryptedPassword = EncryptDecrypt.Encrypt(password);
// Check if the username already exists in the XML file
if (root.SelectSingleNode($"user[@username='{userName.ToUpper()}']") is XmlElement userNode)
{
// Replace the current password with the new generated password
userNode.SetAttribute("password", encryptedPassword);
}
else
{
// Create a new user node
userNode = xmlDocument.CreateElement("user");
userNode.SetAttribute("username", userName.ToUpper());
userNode.SetAttribute("password", encryptedPassword);
root.AppendChild(userNode);
// Add the username to the combo box
UserNameCB.Items.Add(userName.ToUpper());
}
// Save the selected item before clearing the combobox
var selectedItem = UserNameCB.SelectedItem;
xmlDocument.Save(xmlPath);
UserNameCB.Items.Clear();
LoadXML();
// Set the selected item again
if (selectedItem != null && UserNameCB.Items.Contains(selectedItem))
{
UserNameCB.SelectedItem = selectedItem;
}
}
private void LoadXML()
{
var xmlDocument = new XmlDocument();
xmlDocument.Load(xmlPath);
// Refactor the code that searches for user nodes
var userNodes = GetUserNodes(xmlDocument);
foreach (var userName in userNodes.Select(node => node.Attributes?.GetNamedItem("username")?.Value))
{
// Add the username to the combo box
UserNameCB.Items.Add(userName?.ToUpper());
}
}
private void UserNameCB_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedItem = UserNameCB.SelectedItem?.ToString();
if (!string.IsNullOrEmpty(selectedItem))
{
// Load the password for the selected user from the XML file
var xmlDocument = new XmlDocument();
xmlDocument.Load(xmlPath);
// Refactor the code that searches for user nodes
var userNodes = GetUserNodes(xmlDocument);
foreach (var password in userNodes.Where(node => node.Attributes?.GetNamedItem("username")?.Value == selectedItem)
.Select(node => node.Attributes?.GetNamedItem("password")?.Value))
{
if (password != null)
{
PasswordTB.Text = EncryptDecrypt.Decrypt(password);
break;
}
}
}
}
// Extract the code that searches for user nodes into a separate method
private static IEnumerable<XmlNode> GetUserNodes(XmlDocument xmlDocument)
{
if (xmlDocument.DocumentElement != null)
{
foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes)
{
// Add a null check before accessing the Attributes property
if (node.Attributes != null)
{
var userName = node.Attributes.GetNamedItem("username")?.Value;
var password = node.Attributes.GetNamedItem("password")?.Value;
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
yield return node;
}
}
}
}
}
internal async Task GUILogin()
{
try
{
SuspendLayout();
statusLBL.Text = "Status";
UserNameCB.Enabled = false;
PasswordTB.Enabled = false;
LoginBTN.Enabled = false;
RemoveBTN.Enabled = false;
ClearBTN.Enabled = false;
isClaimed = false;
string url = PluginInfo.LoginUrl; // URL for the login page
HttpResponseMessage response = await httpClient.GetAsync(url);
string token = PluginInfo.Token; // Extract the verification token from the page content
string username = UserNameCB.Text.ToUpper(); // Get the username from the text box
string password = PasswordTB.Text; // Get the password from the text box
var content = new FormUrlEncodedContent(new Dictionary<string, string> // Create the content object to send with the POST request
{
{ "__RequestVerificationToken", token },
{ "UserName", username },
{ "Password", password },
{ "RememberMe", "true" }
});
response = await httpClient.PostAsync(url, content); // Send POST request to the login page
_ = await response.Content.ReadAsStringAsync(); // Read the response content as a string
if (response.RequestMessage?.RequestUri?.ToString() == PluginInfo.StoreUrl) // Check if the login was successful
{
statusLBL.Text = $"Login Successful for {username}";
await UpdateLabels();
SaveXML();
if (!UserNameCB.Items.Contains(UserNameCB.Text.ToUpper()))
{
UserNameCB.Items.Add(UserNameCB.Text.ToUpper());
}
}
else
{
timeLBL.Text = "There is a problem with your account.";
statusLBL.Text = "Incorrect Username and/or Password";
}
}
catch (HttpRequestException)
{
statusLBL.Text = "No Connection available.";
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
// Handle timeout exception
statusLBL.Text = "The request timed out.";
}
catch (SocketException ex) when (ex.ErrorCode == 995)
{
// Handle the specific "SocketException (995)" error
PluginInfo.Coin?.EchoText($"SocketException (995): The I/O operation was aborted.");
}
catch (Exception ex)
{
// Handle other exceptions
PluginInfo.Coin?.EchoText($"An error occurred with store.play.net: {ex.Message}");
}
finally
{
// Re-enable GUI components
UserNameCB.Enabled = true;
UserNameCB.Focus();
PasswordTB.Enabled = true;
LoginBTN.Enabled = true;
RemoveBTN.Enabled = true;
ClearBTN.Enabled = true;
ResumeLayout();
}
}
private async Task UpdateLabels() // Update the labels and claim any available rewards
{
try
{
var response = await httpClient.GetAsync(PluginInfo.BalanceUrl);
var pageContent = await response.Content.ReadAsStringAsync();
UpdateTimeLBL(pageContent); // Update the time label
UpdateBalanceLBL(pageContent); // Update the balance label
var claimAmount = GetClaimAmount(pageContent); // Get the claim amount, if available
if (!string.IsNullOrEmpty(claimAmount))
{
await ClaimReward();
}
}
catch (Exception ex)
{
PluginInfo.Coin?.EchoText($"UpdateLabels: {ex.Message}");
}
await PluginInfo.SignOut();
}
private void UpdateTimeLBL(string pageContent)
{
var time = TimePatternRegex.Match(pageContent).Groups[1].Value;
timeLBL.Text = time;
}
private void UpdateBalanceLBL(string pageContent)
{
this.SuspendLayout();
var balance = BalancePatternRegex.Match(pageContent).Groups[1].Value;
if (isClaimed)
coinsLBL.Text = $"You Now Have {balance}";
else
coinsLBL.Text = $"You Have {balance}";
iconPIC.Visible = true;
iconPIC.Image = Properties.Resources.icon;
iconPIC.Location = new Point(coinsLBL.Right - 5, 30);
exclamationLBL.Location = new Point(iconPIC.Right - 2, 22);
exclamationLBL.Visible = true;
this.ResumeLayout();
}
private static string? GetClaimAmount(string pageContent)
{
var match = ClaimPatternRegex.Match(pageContent);
return match.Success ? match.Groups[1].Value : null;
}
private async Task<bool> ClaimReward()
{
try
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("game", "DR"),
new KeyValuePair<string, string>("filter", ""),
new KeyValuePair<string, string>("itemSearch", "")
});
var response = await httpClient.PostAsync(PluginInfo.ClaimUrl, formContent);
if (response.IsSuccessStatusCode)
{
var claimPageContent = await response.Content.ReadAsStringAsync();
var match = Regex.Match(claimPageContent, @"<h1 class=""RewardMessage centered sans_serif"">Claimed (\d+) SimuCoin reward!</h1>");
if (match.Success)
{
var claimAmount = match.Groups[1].Value;
timeLBL.Text = $"Subscription Reward: {claimAmount} Free SimuCoins";
statusLBL.Text = $"Claimed {claimAmount} SimuCoins";
isClaimed = true;
UpdateBalanceLBL(claimPageContent);
return true;
}
else
{
statusLBL.Text = "Claim Failed";
return false;
}
}
else
{
PluginInfo.Coin?.EchoText("Request failed: " + response.StatusCode);
return false;
}
}
catch (Exception ex)
{
PluginInfo.Coin?.EchoText($"ClaimReward: {ex.Message}");
return false;
}
}
private void Button_GotFocus(object? sender, EventArgs e)
{
if (sender is Button button)
{
button.BackColor = Color.LightBlue;
}
}
private void Button_LostFocus(object? sender, EventArgs e)
{
if (sender is Button button)
{
button.BackColor = DefaultBackColor;
}
}
// The ClearBTN_Click event handler clears the GUI.
private void ClearBTN_Click(object sender, EventArgs e)
{
this.SuspendLayout();
UserNameCB.Enabled = false;
PasswordTB.Enabled = false;
LoginBTN.Enabled = false;
RemoveBTN.Enabled = false;
ClearBTN.Enabled = false;
timeLBL.Text = "";
coinsLBL.Text = "";
iconPIC.Visible = false;
UserNameCB.Text = "";
PasswordTB.Text = "";
statusLBL.Text = "Cleared";
exclamationLBL.Visible = false;
UserNameCB.Enabled = true;
UserNameCB.Focus();
PasswordTB.Enabled = true;
LoginBTN.Enabled = true;
RemoveBTN.Enabled = true;
ClearBTN.Enabled = true;
this.ResumeLayout();
}
private async void LoginBTN_Click(object sender, EventArgs e)
{
this.SuspendLayout();
coinsLBL.Text = "";
timeLBL.Text = "";
iconPIC.Visible = false;
exclamationLBL.Visible = false;
this.ResumeLayout();
await GUILogin();
}
// If the Enter key is pressed, it suppresses the key press and performs a click on the login button.
private void PasswordTB_KeyDown(object sender, KeyEventArgs e)
{
var capsLockOn = Control.IsKeyLocked(Keys.CapsLock);
statusLBL.Text = $"Caps Lock is {(capsLockOn ? "on" : "off")}.";
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
LoginBTN.PerformClick();
}
}
// If the Enter key is pressed, it suppresses the key press and performs a click on the login button.
private void UserNameCB_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
LoginBTN.PerformClick();
}
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
e.SuppressKeyPress = true;
var currentIndex = UserNameCB.SelectedIndex;
var itemCount = UserNameCB.Items.Count;
if (e.KeyCode == Keys.Up)
{
currentIndex--;
if (currentIndex < 0)
{
currentIndex = itemCount - 1;
}
}
else if (e.KeyCode == Keys.Down)
{
currentIndex++;
if (currentIndex >= itemCount)
{
currentIndex = 0;
}
}
UserNameCB.SelectedIndex = currentIndex;
}
}
private void RemoveBTN_Click(object sender, EventArgs e)
{
// Get the selected user from the combo box
var selectedUser = UserNameCB.SelectedItem?.ToString();
UserNameCB.Enabled = false;
PasswordTB.Enabled = false;
LoginBTN.Enabled = false;
RemoveBTN.Enabled = false;
ClearBTN.Enabled = false;
if (!string.IsNullOrEmpty(selectedUser))
{
// Ask the user to confirm the deletion
var result = MessageBox.Show($"Are you sure you want to delete the user '{selectedUser}'?", "Confirm Deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// Load the XML document
var xmlDocument = new XmlDocument();
xmlDocument.Load(xmlPath);
// Find the XML node for the selected user
var userNode = xmlDocument.SelectSingleNode($"//user[@username='{selectedUser}']");
if (userNode != null)
{
UserNameCB.Text = "";
PasswordTB.Text = "";
statusLBL.Text = $"Removed: {selectedUser}";
// Remove the user node from the XML document
xmlDocument.DocumentElement?.RemoveChild(userNode);
// Save the updated XML file
xmlDocument.Save(xmlPath);
// Clear the combo box and reload the user list
UserNameCB.Items.Clear();
LoadXML();
}
}
}
UserNameCB.Enabled = true;
UserNameCB.Focus();
PasswordTB.Enabled = true;
LoginBTN.Enabled = true;
RemoveBTN.Enabled = true;
ClearBTN.Enabled = true;
}
// If the Escape key is pressed, it will close the plugin.
private void MainForm_KeyDown(object? sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
e.SuppressKeyPress = true;
isClosingDueToEscKey = true;
this.Close();
}
}
private void MainForm_FormClosing(object? sender, FormClosingEventArgs e)
{
if (isClosingDueToEscKey)
{
// Unregister the event handlers before closing the form.
this.KeyDown -= (s, ev) => MainForm_KeyDown(s, ev);
this.FormClosing -= (s, ev) => MainForm_FormClosing(s, ev);
}
else
{
isClosingDueToEscKey = true;
this.Close();
}
}
private void MainForm_FormClosed(object? sender, FormClosedEventArgs e)
{
// Unregister the event handlers after the form has closed.
this.KeyDown -= (s, ev) => MainForm_KeyDown(s, ev);
this.FormClosing -= (s, ev) => MainForm_FormClosing(s, ev);
this.FormClosed -= (s, ev) => MainForm_FormClosed(s, ev);
}
}
}