-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMainForm.cs
694 lines (591 loc) · 25.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
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
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using SteamAuth;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Net;
using Newtonsoft.Json;
using System.Threading;
namespace Steam_Desktop_Authenticator
{
public partial class MainForm : Form
{
private SteamGuardAccount currentAccount = null;
private SteamGuardAccount[] allAccounts;
private List<string> updatedSessions = new List<string>();
private Manifest manifest;
private static SemaphoreSlim confirmationsSemaphore = new SemaphoreSlim(1, 1);
private long steamTime = 0;
private long currentSteamChunk = 0;
private string passKey = null;
// Forms
private TradePopupForm popupFrm = new TradePopupForm();
public MainForm()
{
InitializeComponent();
}
// Form event handlers
private void MainForm_Shown(object sender, EventArgs e)
{
this.labelVersion.Text = String.Format("v{0}", Application.ProductVersion);
this.manifest = Manifest.GetManifest();
// Make sure we don't show that welcome dialog again
this.manifest.FirstRun = false;
this.manifest.Save();
// Tick first time manually to sync time
timerSteamGuard_Tick(new object(), EventArgs.Empty);
if (manifest.Encrypted)
{
passKey = manifest.PromptForPassKey();
if (passKey == null)
{
Application.Exit();
}
btnManageEncryption.Text = "Manage Encryption";
}
else
{
btnManageEncryption.Text = "Setup Encryption";
}
btnManageEncryption.Enabled = manifest.Entries.Count > 0;
loadSettings();
loadAccountsList();
checkForUpdates();
}
private void MainForm_Load(object sender, EventArgs e)
{
trayIcon.Icon = this.Icon;
}
private void MainForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
// UI Button handlers
private void btnSteamLogin_Click(object sender, EventArgs e)
{
var loginForm = new LoginForm();
loginForm.ShowDialog();
this.loadAccountsList();
}
private async void btnTradeConfirmations_Click(object sender, EventArgs e)
{
if (currentAccount == null) return;
string oText = btnTradeConfirmations.Text;
btnTradeConfirmations.Text = "Loading...";
await RefreshAccountSession(currentAccount);
btnTradeConfirmations.Text = oText;
try
{
ConfirmationFormWeb confirms = new ConfirmationFormWeb(currentAccount);
confirms.Show();
}
catch (Exception)
{
DialogResult res = MessageBox.Show("You are missing a dependency required to view your trade confirmations.\nWould you like to install it now?", "Trade confirmations failed to open", MessageBoxButtons.YesNo);
if (res == DialogResult.Yes)
{
new InstallRedistribForm(true).ShowDialog();
}
}
}
private void btnManageEncryption_Click(object sender, EventArgs e)
{
if (manifest.Encrypted)
{
InputForm currentPassKeyForm = new InputForm("Enter current passkey", true);
currentPassKeyForm.ShowDialog();
if (currentPassKeyForm.Canceled)
{
return;
}
string curPassKey = currentPassKeyForm.txtBox.Text;
InputForm changePassKeyForm = new InputForm("Enter new passkey, or leave blank to remove encryption.");
changePassKeyForm.ShowDialog();
if (changePassKeyForm.Canceled && !string.IsNullOrEmpty(changePassKeyForm.txtBox.Text))
{
return;
}
InputForm changePassKeyForm2 = new InputForm("Confirm new passkey, or leave blank to remove encryption.");
changePassKeyForm2.ShowDialog();
if (changePassKeyForm2.Canceled && !string.IsNullOrEmpty(changePassKeyForm.txtBox.Text))
{
return;
}
string newPassKey = changePassKeyForm.txtBox.Text;
string confirmPassKey = changePassKeyForm2.txtBox.Text;
if (newPassKey != confirmPassKey)
{
MessageBox.Show("Passkeys do not match.");
return;
}
if (newPassKey.Length == 0)
{
newPassKey = null;
}
string action = newPassKey == null ? "remove" : "change";
if (!manifest.ChangeEncryptionKey(curPassKey, newPassKey))
{
MessageBox.Show("Unable to " + action + " passkey.");
}
else
{
MessageBox.Show("Passkey successfully " + action + "d.");
this.loadAccountsList();
}
}
else
{
passKey = manifest.PromptSetupPassKey();
this.loadAccountsList();
}
}
private void labelUpdate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (newVersion == null || currentVersion == null)
{
checkForUpdates();
}
else
{
compareVersions();
}
}
private void btnCopy_Click(object sender, EventArgs e)
{
Clipboard.SetText(txtLoginToken.Text);
}
// Tool strip menu handlers
private void menuQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void menuRemoveAccountFromManifest_Click(object sender, EventArgs e)
{
if (manifest.Encrypted)
{
MessageBox.Show("You cannot remove accounts from the manifest file while it is encrypted.", "Remove from manifest", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
DialogResult res = MessageBox.Show("This will remove the selected account from the manifest file.\nUse this to move a maFile to another computer.\nThis will NOT delete your maFile.", "Remove from manifest", MessageBoxButtons.OKCancel);
if (res == DialogResult.OK)
{
manifest.RemoveAccount(currentAccount, false);
MessageBox.Show("Account removed from manifest.\nYou can now move its maFile to another computer and import it using the File menu.", "Remove from manifest");
loadAccountsList();
}
}
}
private void menuLoginAgain_Click(object sender, EventArgs e)
{
this.PromptRefreshLogin(currentAccount);
}
private void menuImportMaFile_Click(object sender, EventArgs e)
{
ImportAccountForm currentImport_maFile_Form = new ImportAccountForm();
currentImport_maFile_Form.ShowDialog();
loadAccountsList();
}
private void menuImportAndroid_Click(object sender, EventArgs e)
{
new PhoneExtractForm().ShowDialog();
loadAccountsList();
}
private void menuSettings_Click(object sender, EventArgs e)
{
new SettingsForm().ShowDialog();
manifest = Manifest.GetManifest(true);
loadSettings();
}
private void menuDeactivateAuthenticator_Click(object sender, EventArgs e)
{
if (currentAccount == null) return;
DialogResult res = MessageBox.Show("Would you like to remove Steam Guard completely?\nYes - Remove Steam Guard completely.\nNo - Switch back to Email authentication.", "Remove Steam Guard", MessageBoxButtons.YesNoCancel);
int scheme = 0;
if (res == DialogResult.Yes)
{
scheme = 2;
}
else if (res == DialogResult.No)
{
scheme = 1;
}
else if (res == DialogResult.Cancel)
{
scheme = 0;
}
if (scheme != 0)
{
string confCode = currentAccount.GenerateSteamGuardCode();
InputForm confirmationDialog = new InputForm(String.Format("Removing Steam Guard from {0}. Enter this confirmation code: {1}", currentAccount.AccountName, confCode));
confirmationDialog.ShowDialog();
if (confirmationDialog.Canceled)
{
return;
}
string enteredCode = confirmationDialog.txtBox.Text.ToUpper();
if (enteredCode != confCode)
{
MessageBox.Show("Confirmation codes do not match. Steam Guard not removed.");
return;
}
bool success = currentAccount.DeactivateAuthenticator(scheme);
if (success)
{
MessageBox.Show(String.Format("Steam Guard {0}. maFile will be deleted after hitting okay. If you need to make a backup, now's the time.", (scheme == 2 ? "removed completely" : "switched to emails")));
this.manifest.RemoveAccount(currentAccount);
this.loadAccountsList();
}
else
{
MessageBox.Show("Steam Guard failed to deactivate.");
}
}
else
{
MessageBox.Show("Steam Guard was not removed. No action was taken.");
}
}
private async void menuRefreshSession_Click(object sender, EventArgs e)
{
bool status = await RefreshAccountSession(currentAccount);
if (status == true)
{
MessageBox.Show("Your session has been refreshed.", "Session refresh", MessageBoxButtons.OK, MessageBoxIcon.Information);
manifest.SaveAccount(currentAccount, manifest.Encrypted, passKey);
}
else
{
MessageBox.Show("Failed to refresh your session.\nTry using the \"Login again\" option.", "Session refresh", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Tray menu handlers
private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
trayRestore_Click(sender, EventArgs.Empty);
}
private void trayRestore_Click(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
private void trayQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void trayTradeConfirmations_Click(object sender, EventArgs e)
{
btnTradeConfirmations_Click(sender, e);
}
private void trayCopySteamGuard_Click(object sender, EventArgs e)
{
if (txtLoginToken.Text != "")
{
Clipboard.SetText(txtLoginToken.Text);
}
}
private void trayAccountList_SelectedIndexChanged(object sender, EventArgs e)
{
listAccounts.SelectedIndex = trayAccountList.SelectedIndex;
}
// Misc UI handlers
private void listAccounts_SelectedValueChanged(object sender, EventArgs e)
{
for (int i = 0; i < allAccounts.Length; i++)
{
SteamGuardAccount account = allAccounts[i];
if (account.AccountName == (string)listAccounts.Items[listAccounts.SelectedIndex])
{
trayAccountList.Text = account.AccountName;
currentAccount = account;
loadAccountInfo();
break;
}
}
}
private void txtAccSearch_TextChanged(object sender, EventArgs e)
{
List<string> names = new List<string>(getAllNames());
names = names.FindAll(new Predicate<string>(IsFilter));
listAccounts.Items.Clear();
listAccounts.Items.AddRange(names.ToArray());
trayAccountList.Items.Clear();
trayAccountList.Items.AddRange(names.ToArray());
}
// Timers
private async void timerSteamGuard_Tick(object sender, EventArgs e)
{
lblStatus.Text = "Aligning time with Steam...";
steamTime = await TimeAligner.GetSteamTimeAsync();
lblStatus.Text = "";
currentSteamChunk = steamTime / 30L;
int secondsUntilChange = (int)(steamTime - (currentSteamChunk * 30L));
loadAccountInfo();
if (currentAccount != null)
{
pbTimeout.Value = 30 - secondsUntilChange;
}
}
private async void timerTradesPopup_Tick(object sender, EventArgs e)
{
if (currentAccount == null || popupFrm.Visible) return;
if (!confirmationsSemaphore.Wait(0))
{
return; //Only one thread may access this critical section at once. Mutex is a bad choice here because it'll cause a pileup of threads.
}
List<Confirmation> confs = new List<Confirmation>();
Dictionary<SteamGuardAccount, List<Confirmation>> autoAcceptConfirmations = new Dictionary<SteamGuardAccount, List<Confirmation>>();
SteamGuardAccount[] accs =
manifest.CheckAllAccounts ? allAccounts : new SteamGuardAccount[] { currentAccount };
try
{
lblStatus.Text = "Checking confirmations...";
foreach (var acc in accs)
{
try
{
Confirmation[] tmp = await currentAccount.FetchConfirmationsAsync();
foreach (var conf in tmp)
{
if ((conf.ConfType == Confirmation.ConfirmationType.MarketSellTransaction && manifest.AutoConfirmMarketTransactions) ||
(conf.ConfType == Confirmation.ConfirmationType.Trade && manifest.AutoConfirmTrades))
{
if (!autoAcceptConfirmations.ContainsKey(acc))
autoAcceptConfirmations[acc] = new List<Confirmation>();
autoAcceptConfirmations[acc].Add(conf);
}
else
confs.Add(conf);
}
}
catch (SteamGuardAccount.WGTokenInvalidException)
{
lblStatus.Text = "Refreshing session";
await currentAccount.RefreshSessionAsync(); //Don't save it to the HDD, of course. We'd need their encryption passkey again.
lblStatus.Text = "";
}
catch (SteamGuardAccount.WGTokenExpiredException)
{
//Prompt to relogin
PromptRefreshLogin(currentAccount);
break; //Don't bombard a user with login refresh requests if they have multiple accounts. Give them a few seconds to disable the autocheck option if they want.
}
catch (WebException)
{
}
}
lblStatus.Text = "";
if (confs.Count > 0)
{
popupFrm.Confirmations = confs.ToArray();
popupFrm.Popup();
}
if (autoAcceptConfirmations.Count > 0)
{
foreach(var acc in autoAcceptConfirmations.Keys)
{
var confirmations = autoAcceptConfirmations[acc].ToArray();
acc.AcceptMultipleConfirmations(confirmations);
}
}
}
catch (SteamGuardAccount.WGTokenInvalidException)
{
lblStatus.Text = "";
}
confirmationsSemaphore.Release();
}
// Other methods
/// <summary>
/// Refresh this account's session data using their OAuth Token
/// </summary>
/// <param name="account">The account to refresh</param>
/// <param name="attemptRefreshLogin">Whether or not to prompt the user to re-login if their OAuth token is expired.</param>
/// <returns></returns>
private async Task<bool> RefreshAccountSession(SteamGuardAccount account, bool attemptRefreshLogin = true)
{
if (account == null) return false;
try
{
bool refreshed = await account.RefreshSessionAsync();
return refreshed; //No exception thrown means that we either successfully refreshed the session or there was a different issue preventing us from doing so.
}
catch (SteamGuardAccount.WGTokenExpiredException)
{
if (!attemptRefreshLogin) return false;
PromptRefreshLogin(account);
return await RefreshAccountSession(account, false);
}
}
/// <summary>
/// Display a login form to the user to refresh their OAuth Token
/// </summary>
/// <param name="account">The account to refresh</param>
private void PromptRefreshLogin(SteamGuardAccount account)
{
var loginForm = new LoginForm(LoginForm.LoginType.Refresh, account);
loginForm.ShowDialog();
}
/// <summary>
/// Load UI with the current account info, this is run every second
/// </summary>
private void loadAccountInfo()
{
if (currentAccount != null && steamTime != 0)
{
popupFrm.Account = currentAccount;
txtLoginToken.Text = currentAccount.GenerateSteamGuardCodeForTime(steamTime);
groupAccount.Text = "Account: " + currentAccount.AccountName;
}
}
/// <summary>
/// Decrypts files and populates list UI with accounts
/// </summary>
private void loadAccountsList()
{
currentAccount = null;
listAccounts.Items.Clear();
listAccounts.SelectedIndex = -1;
trayAccountList.Items.Clear();
trayAccountList.SelectedIndex = -1;
allAccounts = manifest.GetAllAccounts(passKey);
if (allAccounts.Length > 0)
{
for (int i = 0; i < allAccounts.Length; i++)
{
SteamGuardAccount account = allAccounts[i];
listAccounts.Items.Add(account.AccountName);
trayAccountList.Items.Add(account.AccountName);
}
listAccounts.SelectedIndex = 0;
trayAccountList.SelectedIndex = 0;
}
menuDeactivateAuthenticator.Enabled = btnTradeConfirmations.Enabled = allAccounts.Length > 0;
}
private void listAccounts_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
int to = listAccounts.SelectedIndex - (e.KeyCode == Keys.Up ? 1 : -1);
manifest.MoveEntry(listAccounts.SelectedIndex, to);
loadAccountsList();
}
return;
}
if (!IsKeyAChar(e.KeyCode) && !IsKeyADigit(e.KeyCode))
{
return;
}
txtAccSearch.Focus();
txtAccSearch.Text = e.KeyCode.ToString();
txtAccSearch.SelectionStart = 1;
}
private static bool IsKeyAChar(Keys key)
{
return key >= Keys.A && key <= Keys.Z;
}
private static bool IsKeyADigit(Keys key)
{
return (key >= Keys.D0 && key <= Keys.D9) || (key >= Keys.NumPad0 && key <= Keys.NumPad9);
}
private bool IsFilter(string f)
{
if (txtAccSearch.Text.StartsWith("~"))
{
try
{
return Regex.IsMatch(f, txtAccSearch.Text);
}
catch (Exception)
{
return true;
}
}
else
{
return f.Contains(txtAccSearch.Text);
}
}
private string[] getAllNames()
{
string[] itemArray = new string[allAccounts.Length];
for (int i = 0; i < itemArray.Length; i++)
{
itemArray[i] = allAccounts[i].AccountName;
}
return itemArray;
}
private void loadSettings()
{
timerTradesPopup.Enabled = manifest.PeriodicChecking;
timerTradesPopup.Interval = manifest.PeriodicCheckingInterval * 1000;
}
// Logic for version checking
private Version newVersion = null;
private Version currentVersion = null;
private WebClient updateClient = null;
private string updateUrl = null;
private bool startupUpdateCheck = true;
private void checkForUpdates()
{
if (updateClient != null) return;
updateClient = new WebClient();
updateClient.DownloadStringCompleted += UpdateClient_DownloadStringCompleted;
updateClient.Headers.Add("Content-Type", "application/json");
updateClient.Headers.Add("User-Agent", "Steam Desktop Authenticator");
updateClient.DownloadStringAsync(new Uri("https://api.github.com/repos/Jessecar96/SteamDesktopAuthenticator/releases/latest"));
}
private void compareVersions()
{
if (newVersion > currentVersion)
{
labelUpdate.Text = "Download new version"; // Show the user a new version is available if they press no
DialogResult updateDialog = MessageBox.Show(String.Format("A new version is available! Would you like to download it now?\nYou will update from version {0} to {1}", Application.ProductVersion, newVersion.ToString()), "New Version", MessageBoxButtons.YesNo);
if (updateDialog == DialogResult.Yes)
{
Process.Start(updateUrl);
}
}
else
{
if (!startupUpdateCheck)
{
MessageBox.Show(String.Format("You are using the latest version: {0}", Application.ProductVersion));
}
}
newVersion = null; // Check the api again next time they check for updates
updateClient = null; // Set to null to indicate it's done checking
startupUpdateCheck = false; // Set when it's done checking on startup
}
private void UpdateClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
dynamic resultObject = JsonConvert.DeserializeObject(e.Result);
newVersion = new Version(resultObject.tag_name.Value);
currentVersion = new Version(Application.ProductVersion);
updateUrl = resultObject.assets.First.browser_download_url.Value;
compareVersions();
}
catch (Exception)
{
MessageBox.Show("Failed to check for updates.");
}
}
private void menuImportWinAuth_Click(object sender, EventArgs e)
{
new ImportWinAuthForm().ShowDialog();
}
}
}