-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathD2Loader.ps1
3756 lines (3744 loc) · 201 KB
/
D2Loader.ps1
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
<#
Author: Shupershuff
Usage:
Happy for you to make any modifications to this script for your own needs providing:
- Any variants of this script are never sold.
- Any variants of this script published online should always be open source.
- Any variants of this script are never modifed to enable or assist in any game altering or malicious behaviour including (but not limited to): Bannable Mods, Cheats, Exploits, Phishing
Purpose:
Script will allow opening multiple Diablo 2 resurrected instances and will automatically close the 'DiabloII Check For Other Instances' handle."
Script will import account details from CSV. Alternatively you can run script parameters (see Github readme): -AccountUsername, -PW, -Region, -All, -Batch, -ManualSettingSwitcher
Instructions: See GitHub readme https://github.com/shupershuff/Diablo2RLoader
Notes:
- Multiple failed attempts (eg wrong Password) to sign onto a particular Realm via this method may temporarily lock you out. You should still be able to get in via the battlenet client if this occurs.
Servers:
NA - us.actual.battle.net
EU - eu.actual.battle.net
Asia - kr.actual.battle.net
Changes since 1.13.2 (next version edits):
Added ability to have alternative window layout csv to load settings from (AltLayout.csv). Has to be manually configured as I'm not keen to make menu more complicated.
Added better error handling for getd2emutoken if unable to connect. Script can still run albeit with TZ and DClone features disabled.
Mitigated issues with script window height for very small resolutions or users with high levels of display scaling/zoom.
Removed maximise button from PowerShell because it annoys me.
Hopefully improved window redraw to prevent flickering.
ID Checker will now not confuse with D2r offline instances launched with the Single Player Launcher (github.com/shupershuff/D2rSPLoader)
Fixed unavailable options being selectable in options menu for window resizer.
Fixed connection issue with D2Emu API for users with PowerShell 7.x
Fixed XML file having blank lines being added in each time options menu is used.
1.14.0+ to do list
Investigate accounts.backup.csv and/or stats.backup.csv possibly not restoring properly.
Couldn't write :) in release notes without it adding a new line, some minor issue with formatfunction regex
If I can be bothered, investigate the possibility of realtime DClone Alarms (using websocket connection to d2emu instead).
In line with the above, perhaps investigate putting TZ details on main menu and using the TZ screen for recent TZ's only.
To reduce lines, Tidy up all the import/export csv bits for stat updates into a function rather than copy paste the same commands throughout the script. Can't really be bothered though :)
Unlikely - ISboxer has CTRL + Alt + number as a shortcut to switch between windows. Investigate how this could be done. Would need an agent to detect key combos, Possibly via AutoIT or Autohotkey. Likely not possible within powershell and requires a separate project.
Fix whatever I broke or poorly implemented in the last update :)
#>
param($AccountUsername,$PW,$Region,$All,$Batch,$ManualSettingSwitcher) #used to capture parameters sent to the script, if anyone even wants to do that.
$CurrentVersion = "1.14.0"
###########################################################################################################################################
# Script itself
###########################################################################################################################################
$host.ui.RawUI.WindowTitle = "Diablo 2 Resurrected Loader"
if (($Null -ne $PW -or $Null -ne $AccountUsername) -and ($Null -ne $Batch -or $Null -ne $All)){#If someone sends through incompatible parameters, prioritise $All and $Batch (in that order).
$PW = $Null
$AccountUsername = $Null
if ($Null -ne $Batch -and $Null -ne $All){
$Batch = $Null
}
}
if ($Null -ne $AccountUsername){
$ScriptArguments = "-accountusername $AccountUsername" #This passes the value back through to the script when it's relaunched as admin mode.
}
if ($Null -ne $PW){
$ScriptArguments += " -PW $PW"
}
if ($Null -ne $Region){
$ScriptArguments += " -region $Region"
}
if ($Null -ne $All){
$ScriptArguments += " -all $All"
$Script:OpenAllAccounts = $true
}
if ($Null -ne $Batch){
$ScriptArguments += " -batch $Batch"
$Script:OpenBatches = $True
}
if ($Null -ne $ManualSettingSwitcher){
$ScriptArguments += " -ManualSettingSwitcher $ManualSettingSwitcher"
$Script:AskForSettings = $True
}
#check if username was passed through via parameter
if ($Null -ne $ScriptArguments){
$Script:ParamsUsed = $true
}
Else {
$Script:ParamsUsed = $false
}
#run script as admin
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){ Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" $ScriptArguments" -Verb RunAs;exit }
#DebugMode
#$DebugMode = $True # Uncomment to enable
if ($DebugMode -eq $True){
$DebugPreference = "Continue"
$VerbosePreference = "Continue"
}
#set window size
[console]::WindowWidth=77; #script has been designed around this width. Adjust at your own peril.
$WindowHeight=50 #Can be adjusted to preference, but not less than 42
do {
Try{
[console]::WindowHeight = $WindowHeight;
$HeightSuccessfullySet = $True
}
Catch {
$WindowHeight --
}
} Until ($HeightSuccessfullySet -eq $True)
[console]::BufferWidth=[console]::WindowWidth
#set misc vars
$Script:X = [char]0x1b #escape character for ANSI text colors
$ProgressPreference = "SilentlyContinue"
$Script:WorkingDirectory = ((Get-ChildItem -Path $PSScriptRoot)[0].fullname).substring(0,((Get-ChildItem -Path $PSScriptRoot)[0].fullname).lastindexof('\')) #Set Current Directory path.
$Script:StartTime = Get-Date #Used for elapsed time. Is reset when script refreshes.
$Script:MOO = "%%%"
$Script:JobIDs = @()
$MenuRefreshRate = 30 #How often the script refreshes in seconds. This should be set to 30, don't change this please.
$Script:ScriptFileName = Split-Path $MyInvocation.MyCommand.Path -Leaf #find the filename of the script in case a user renames it.
$Script:SessionTimer = 0 #set initial session timer to avoid errors in info menu.
$Script:NotificationHasBeenChecked = $False
#Baseline of acceptable characters for ReadKey functions. Used to prevents receiving inputs from folk who are alt tabbing etc.
$Script:AllowedKeyList = @(48,49,50,51,52,53,54,55,56,57) #0 to 9
$Script:AllowedKeyList += @(96,97,98,99,100,101,102,103,104,105) #0 to 9 on numpad
$Script:AllowedKeyList += @(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) # A to Z
$Script:MenuOptions = @(65,66,67,68,71,73,74,79,82,83,84,88) #a, b, c, d, g, i, j, o, r, s, t and x. Used to detect singular valid entries where script can have two characters entered.
$EnterKey = 13
Function RemoveMaximiseButton { # I'm removing the maximise button on the script as sometimes I misclick maximise instead of minimise and it annoys me. Copied this straight out of ChatGPT lol.
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowAPI {
public const int GWL_STYLE = -16;
public const int WS_MAXIMIZEBOX = 0x10000;
public const int WS_THICKFRAME = 0x40000; // Window has a sizing border
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
}
"@
# Get the handle for the current window (PowerShell window)
$hWnd = [WindowAPI]::GetForegroundWindow()
# Get the current window style
$style = [WindowAPI]::GetWindowLong($hWnd, [WindowAPI]::GWL_STYLE)
# Disable the maximize button by removing the WS_MAXIMIZEBOX style. Also disable resizing the width.
$newStyle = $style -band -bnot ([WindowAPI]::WS_MAXIMIZEBOX -bor [WindowAPI]::WS_THICKFRAME)
[WindowAPI]::SetWindowLong($hWnd, [WindowAPI]::GWL_STYLE, $newStyle) | out-null
}
Function ReadKey([string]$message=$Null,[bool]$NoOutput,[bool]$AllowAllKeys){#used to receive user input
$key = $Null
$Host.UI.RawUI.FlushInputBuffer()
if (![string]::IsNullOrEmpty($message)){
Write-Host -NoNewLine $message
}
$AllowedKeyList = $Script:AllowedKeyList + @(13,27) #Add Enter & Escape to the allowedkeylist as acceptable inputs.
while ($Null -eq $key){
if ($Host.UI.RawUI.KeyAvailable){
$key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
if ($True -ne $AllowAllKeys){
if ($key_.KeyDown -and $key_.VirtualKeyCode -in $AllowedKeyList){
$key = $key_
}
}
else {
if ($key_.KeyDown){
$key = $key_
}
}
}
else {
Start-Sleep -m 200 # Milliseconds
}
}
if ($key_.VirtualKeyCode -ne $EnterKey -and -not ($Null -eq $key) -and [bool]$NoOutput -ne $true){
Write-Host ("$X[38;2;255;165;000;22m" + "$($key.Character)" + "$X[0m") -NoNewLine
}
if (![string]::IsNullOrEmpty($message)){
Write-Host "" # newline
}
return $(
if ($Null -eq $key -or $key.VirtualKeyCode -eq $EnterKey){
""
}
ElseIf ($key.VirtualKeyCode -eq 27){ #if key pressed was escape
"Esc"
}
else {
$key.Character
}
)
}
Function ReadKeyTimeout([string]$message=$Null, [int]$timeOutSeconds=0, [string]$Default=$Null, [object[]]$AdditionalAllowedKeys = $null, [bool]$TwoDigitAcctSelection = $False){
$key = $Null
$inputString = ""
$Host.UI.RawUI.FlushInputBuffer()
if (![string]::IsNullOrEmpty($message)){
Write-Host -NoNewLine $message
}
$Counter = $timeOutSeconds * 1000 / 250
$AllowedKeyList = $Script:AllowedKeyList + $AdditionalAllowedKeys #Add any other specified allowed key inputs (eg Enter).
while ($Null -eq $key -and ($timeOutSeconds -eq 0 -or $Counter-- -gt 0)){
if ($TwoDigitAcctSelection -eq $True -and $inputString.length -ge 1){
$AllowedKeyList = $AllowedKeyList + 13 + 8 # Allow enter and backspace to be used if 1 character has been typed.
}
if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable){
$key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
if ($key_.KeyDown -and $key_.VirtualKeyCode -in $AllowedKeyList){
if ($key_.VirtualKeyCode -eq [System.ConsoleKey]::Backspace){
$Counter = $timeOutSeconds * 1000 / 250 #reset counter
if ($inputString.Length -gt 0){
$inputString = $inputString.Substring(0, $inputString.Length - 1) #remove last added character/number from variable
# Clear the last character from the console
$Host.UI.RawUI.CursorPosition = @{
X = [Math]::Max($Host.UI.RawUI.CursorPosition.X - 1, 0)
Y = $Host.UI.RawUI.CursorPosition.Y
}
Write-Host -NoNewLine " " #-ForegroundColor Black
$Host.UI.RawUI.CursorPosition = @{
X = [Math]::Max($Host.UI.RawUI.CursorPosition.X - 1, 0)
Y = $Host.UI.RawUI.CursorPosition.Y
}
}
}
ElseIf ($TwoDigitAcctSelection -eq $True -and $key_.VirtualKeyCode -notin $Script:MenuOptions + 27){
$Counter = $timeOutSeconds * 1000 / 250 #reset counter
if ($key_.VirtualKeyCode -eq $EnterKey -or $key_.VirtualKeyCode -eq 27){
break
}
$inputString += $key_.Character
Write-Host ("$X[38;2;255;165;000;22m" + $key_.Character + "$X[0m") -nonewline
if ($inputString.length -eq 2){#if 2 characters have been entered
break
}
}
Else {
$key = $key_
$inputString = $key_.Character
}
}
}
else {
Start-Sleep -m 250 # Milliseconds
}
}
if ($Counter -le 0){
if ($InputString.Length -gt 0){# if it timed out, revert to no input if one character was entered.
$InputString = "" #remove last added character/number from variable
}
}
if ($TwoDigitAcctSelection -eq $False -or ($TwoDigitAcctSelection -eq $True -and $key_.VirtualKeyCode -in $Script:MenuOptions)){
Write-Host ("$X[38;2;255;165;000;22m" + "$inputString" + "$X[0m")
}
if (![string]::IsNullOrEmpty($message) -or $TwoDigitAcctSelection -eq $True){
Write-Host "" # newline
}
Write-Host #prevent follow up text from ending up on the same line.
return $(
If ($key.VirtualKeyCode -eq $EnterKey -and $EnterKey -in $AllowedKeyList){
""
}
ElseIf ($key.VirtualKeyCode -eq 27){ #if key pressed was escape
"Esc"
}
ElseIf ($inputString.Length -eq 0){
$Default
}
else {
$inputString
}
)
}
Function PressTheAnyKey {#Used instead of Pause so folk can hit any key to continue
Write-Host " Press any key to continue..." -nonewline
readkey -NoOutput $True -AllowAllKeys $True | out-null
Write-Host
}
Function PressTheAnyKeyToExit {#Used instead of Pause so folk can hit any key to exit
Write-Host " Press Any key to exit..." -nonewline
readkey -NoOutput $True -AllowAllKeys $True | out-null
remove-job * -force
Exit
}
Function Red {
process { Write-Host $_ -ForegroundColor Red }
}
Function Yellow {
process { Write-Host $_ -ForegroundColor Yellow }
}
Function Green {
process { Write-Host $_ -ForegroundColor Green }
}
Function NormalText {
process { Write-Host $_ }
}
Function FormatFunction { # Used to get long lines formatted nicely within the CLI. Possibly the most difficult thing I've created in this script. Hooray for Regex!
param (
[string] $Text,
[int] $Indents,
[int] $SubsequentLineIndents,
[switch] $IsError,
[switch] $IsWarning,
[switch] $IsSuccess
)
if ($IsError -eq $True){
$Colour = "Red"
}
ElseIf ($IsWarning -eq $True){
$Colour = "Yellow"
}
ElseIf ($IsSuccess -eq $True){
$Colour = "Green"
}
Else {
$Colour = "NormalText"
}
$MaxLineLength = 76
If ($Indents -ge 1){
while ($Indents -gt 0){
$Indent += " "
$Indents --
}
}
If ($SubsequentLineIndents -ge 1){
while ($SubsequentLineIndents -gt 0){
$SubsequentLineIndent += " "
$SubsequentLineIndents --
}
}
$Text -split "`n" | ForEach-Object {
$Line = " " + $Indent + $_
$SecondLineDeltaIndent = ""
if ($Line -match '^[\s]*-'){ #For any line starting with any preceding spaces and a dash.
$SecondLineDeltaIndent = " "
}
if ($Line -match '^[\s]*\d+\.\s'){ #For any line starting with any preceding spaces, a number, a '.' and a space. Eg "1. blah".
$SecondLineDeltaIndent = " "
}
Function Formatter ([string]$line){
$pattern = "[\e]?[\[]?[`"-,`.!']?\b[\w\-,'`"]+(\S*)" # Regular expression pattern to find the last word including any trailing non-space characters. Also looks to include any preceding special characters or ANSI escape character.
$WordMatches = [regex]::Matches($Line, $pattern) # Find all matches of the pattern in the string
# Initialize variables to track the match with the highest index
$highestIndex = -1
$SelectedMatch = $Null
$PatternLengthCount = 0
$ANSIPatterns = "\x1b\[38;\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3}m","\x1b\[0m","\x1b\[4m"
ForEach ($WordMatch in $WordMatches){# Iterate through each match (match being a block of characters, ie each word).
ForEach ($ANSIPattern in $ANSIPatterns){ #iterate through each possible ANSI pattern to find any text that might have ANSI formatting.
$ANSIMatches = $WordMatch.value | Select-String -Pattern $ANSIPattern -AllMatches
ForEach ($ANSIMatch in $ANSIMatches){
$Script:ANSIUsed = $True
$PatternLengthCount = $PatternLengthCount + (($ANSIMatch.matches | ForEach-Object {$_.Value}) -join "").length #Calculate how many characters in the text are ANSI formatting characters and thus won't be displayed on screen, to prevent skewing word count.
}
}
$matchIndex = $WordMatch.Index
$matchLength = $WordMatch.Length
$matchEndIndex = $matchIndex + $matchLength - 1
if ($matchEndIndex -lt ($MaxLineLength + $PatternLengthCount)){# Check if the match ends within the first $MaxLineLength characters
if ($matchIndex -gt $highestIndex){# Check if this match has a higher index than the current highest
$highestIndex = $matchIndex # This word has a higher index and is the winner thus far.
$SelectedMatch = $WordMatch
$lastspaceindex = $SelectedMatch.Index + $SelectedMatch.Length - 1 #Find the index (the place in the string) where the last word can be used without overflowing the screen.
}
}
}
try {
$script:chunk = $Line.Substring(0, $lastSpaceIndex + 1) #Chunk of text to print to screen. Uses all words from the start of $line up until $lastspaceindex so that only text that fits on a single line is printed. Prevents words being cut in half and prevents loss of indenting.
}
catch {
$script:chunk = $Line.Substring(0, [Math]::Min(($MaxLineLength), ($Line.Length))) #If the above fails for whatever reason. Can't exactly remember why I put this in here but leaving it in to be safe LOL.
}
}
Formatter $Line
if ($Script:ANSIUsed -eq $True){ #if fancy pants coloured text (ANSI) is used, write out the first line. Check if ANSI was used in any overflow lines.
do {
$Script:ANSIUsed = $False
Write-Output $Chunk | out-host #have to use out-host due to pipeline shenanigans and at this point was too lazy to do things properly :)
$Line = " " + $SubsequentLineIndent + $Indent + $Line.Substring($chunk.Length).trimstart() #$Line is equal to $Line but without the text that's already been outputted.
Formatter $Line
} until ($Script:ANSIUsed -eq $False)
if ($Chunk -ne " " -and $Chunk.lenth -ne 0){#print any remaining text.
Write-Output $Chunk | out-host
}
}
Else { #if line has no ANSI formatting.
Write-Output $Chunk | &$Colour
}
$Line = $Line.Substring($chunk.Length).trimstart() #remove the string that's been printed on screen from variable.
if ($Line.length -gt 0){ # I see you're reading my comment. How thorough of you! This whole function was an absolute mindf#$! to come up with and took probably 30 hours of trial, error and rage (in ascending order of frequency). Odd how the most boring of functions can take up the most time :)
Write-Output ($Line -replace "(.{1,$($MaxLineLength - $($Indent.length) - $($SubsequentLineIndent.length) -1 - $($SecondLineDeltaIndent.length))})(\s+|$)", " $SubsequentLineIndent$SecondLineDeltaIndent$Indent`$1`n").trimend() | &$Colour
}
}
}
Function CommaSeparatedList {
param (
[object] $Values,
[switch] $NoOr,
[switch] $AndText
)
ForEach ($Value in $Values){ #write out each account option, comma separated but show each option in orange writing. Essentially output overly complicated fancy display options :)
if ($Value -ne $Values[-1]){
Write-Host "$X[38;2;255;165;000;22m$Value$X[0m" -nonewline
if ($Value -ne $Values[-2]){Write-Host ", " -nonewline}
}
else {
if ($Values.count -gt 1){
$AndOr = "or"
if ($AndText -eq $True){
$AndOr = "and"
}
if ($NoOr -eq $False){
Write-Host " $AndOr " -nonewline
}
Else {
Write-Host ", " -nonewline
}
}
Write-Host "$X[38;2;255;165;000;22m$Value$X[0m" -nonewline
}
}
}
Function GetEmuToken { #For connecting to D2Emu for tz and/or dclone data
Try {
if ($PSVersionTable.psversion.major -ge 7){# Run a PowerShell 5.1 script from within PowerShell 7.x, for whatever reason no content is returned on PS 7.x. Identified in https://github.com/shupershuff/Diablo2RLoader/issues/51
$AES = & "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -Command {(invoke-webrequest https://d2emu.com/api/v1/shupertoken/aes).content | convertfrom-json}
$EncryptedToken = & "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -Command {((invoke-webrequest https://d2emu.com/api/v1/shupertoken/token).content | convertfrom-json).token}
}
Else {
$AES = (invoke-webrequest https://d2emu.com/api/v1/shupertoken/aes).content | convertfrom-json
$EncryptedToken = ((invoke-webrequest https://d2emu.com/api/v1/shupertoken/token).content | convertfrom-json).token
}
$Key = $AES.key
$IV = $AES.iv
$bytes = [System.Convert]::FromBase64String($EncryptedToken);
$aes = [System.Security.Cryptography.Aes]::Create();
$utf8 = [System.Text.Encoding]::Utf8;
$aes.Key = $utf8.GetBytes($key);
$aes.IV = $utf8.GetBytes($iv);
$decryptor = $aes.CreateDecryptor();
$unencryptedData = $decryptor.TransformFinalBlock($bytes, 0, $bytes.Length);
$aes.Dispose();
$Script:EmuToken = [System.Text.Encoding]::UTF8.GetString($unencryptedData); #Decrypted token
}
Catch {
$Script:EmuOfflineMode = $True
$Script:EmuToken = ""
FormatFunction -IsError -indents 1 "`n`nCouldn't get D2Emu.com connection token, D2Emu API is possibly down."
if ($Script:Config.DCloneTrackerSource -eq "d2emu.com"){
$D2EmuErrorText = "Terror Zones and DClone"
}
Else {
$D2EmuErrorText = "Terror Zones"
}
FormatFunction -IsError -indents 1 "Features for $D2EmuErrorText have been disabled.`n"
PressTheAnyKey
}
}
Function DisplayPreviousAccountOpened {
Write-Host "Account previously opened was:" -foregroundcolor yellow -backgroundcolor darkgreen
$Lastopened = @(
[pscustomobject]@{Account=$Script:AccountFriendlyName;region=$Script:LastRegion}
)
Write-Host " " -NoNewLine
Write-Host ("Account: " + $Lastopened.Account) -foregroundcolor yellow -backgroundcolor darkgreen
Write-Host " " -NoNewLine
Write-Host "Region: " $Lastopened.Region -foregroundcolor yellow -backgroundcolor darkgreen
}
Function InitialiseCurrentStats {
if ((Test-Path -Path "$Script:WorkingDirectory\Stats.csv") -ne $true){#Create Stats CSV if it doesn't exist
$Null = {} | Select-Object "TotalGameTime","TimesLaunched","LastUpdateCheck","HighRunesFound","UniquesFound","SetItemsFound","RaresFound","MagicItemsFound","NormalItemsFound","Gems","CowKingKilled","PerfectGems" | Export-Csv "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation
Write-Host " Stats.csv created!"
}
do {
Try {
$Script:CurrentStats = import-csv "$Script:WorkingDirectory\Stats.csv" #Get current stats csv details
}
Catch {
Write-Host " Unable to import stats.csv. File corrupt or missing." -foregroundcolor red
}
if ($null -ne $CurrentStats){
#Todo: In the Future add CSV validation checks
$StatsCSVImportSuccess = $True
}
else {#Error out and exit if there's a problem with the csv.
if ($StatsCSVRecoveryAttempt -lt 1){
try {
Write-Host " Attempting Autorecovery of stats.csv from backup..." -foregroundcolor red
Copy-Item -Path $Script:WorkingDirectory\Stats.backup.csv -Destination $Script:WorkingDirectory\Stats.csv -ErrorAction stop
Write-Host " Autorecovery successful!" -foregroundcolor Green
$StatsCSVRecoveryAttempt ++
PressTheAnyKey
}
Catch {
$StatsCSVImportSuccess = $False
}
}
Else {
$StatsCSVRecoveryAttempt = 2
}
if ($StatsCSVImportSuccess -eq $False -or $StatsCSVRecoveryAttempt -eq 2){
Write-Host "`n Stats.csv is corrupted or empty." -foregroundcolor red
Write-Host " Replace with data from stats.backup.csv or delete stats.csv`n" -foregroundcolor red
PressTheAnyKeyToExit
}
}
} until ($StatsCSVImportSuccess -eq $True)
if (-not ($CurrentStats | Get-Member -Name "LastUpdateCheck" -MemberType NoteProperty -ErrorAction SilentlyContinue)){#For update 1.8.1+. If LastUpdateCheck column doesn't exist, add it to the CSV data
$Script:CurrentStats | ForEach-Object {
$_ | Add-Member -NotePropertyName "LastUpdateCheck" -NotePropertyValue "2000.06.28 12:00:00" #previously "28/06/2000 12:00:00 pm"
}
}
ElseIf ($CurrentStats.LastUpdateCheck -eq "" -or $CurrentStats.LastUpdateCheck -like "*/*"){# If script has just been freshly downloaded or has the old Date format.
$Script:CurrentStats.LastUpdateCheck = "2000.06.28 12:00:00" #previously "28/06/2000 12:00:00 pm"
$CurrentStats | Export-Csv "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation
}
}
Function CheckForUpdates {
#Only Check for updates if updates haven't been checked in last 8 hours. Reduces API requests.
if ($Script:CurrentStats.LastUpdateCheck -lt (Get-Date).addHours(-8).ToString('yyyy.MM.dd HH:mm:ss')){# Compare current date and time to LastUpdateCheck date & time.
try {
# Check for Updates
$Releases = Invoke-RestMethod -Uri "https://api.github.com/repos/shupershuff/Diablo2RLoader/releases"
$ReleaseInfo = ($Releases | Sort-Object id -desc)[0] #find release with the highest ID.
$Script:LatestVersion = [version[]]$ReleaseInfo.Name.Trim('v')
if ($Script:LatestVersion -gt $Script:CurrentVersion){ #If a newer version exists, prompt user about update details and ask if they want to update.
Write-Host "`n Update available! See Github for latest version and info" -foregroundcolor Yellow -nonewline
if ([version]$CurrentVersion -in (($Releases.name.Trim('v') | ForEach-Object { [version]$_ } | Sort-Object -desc)[2..$releases.count])){
Write-Host ".`n There have been several releases since your version." -foregroundcolor Yellow
Write-Host " Checkout Github releases for fixes/features added. " -foregroundcolor Yellow
Write-Host " $X[38;2;69;155;245;4mhttps://github.com/shupershuff/Diablo2RLoader/releases/$X[0m`n"
}
Else {
Write-Host ":`n $X[38;2;69;155;245;4mhttps://github.com/shupershuff/Diablo2RLoader/releases/latest$X[0m`n"
}
FormatFunction -Text $ReleaseInfo.body #Output the latest release notes in an easy to read format.
Write-Host; Write-Host
Do {
Write-Host " Your Current Version is v$CurrentVersion."
Write-Host (" Would you like to update to v" + $Script:LatestVersion + "? $X[38;2;255;165;000;22mY$X[0m/$X[38;2;255;165;000;22mN$X[0m: ") -nonewline
$ShouldUpdate = ReadKey
if ($ShouldUpdate -eq "y" -or $ShouldUpdate -eq "yes" -or $ShouldUpdate -eq "n" -or $ShouldUpdate -eq "no"){
$UpdateResponseValid = $True
}
Else {
Write-Host "`n Invalid response. Choose $X[38;2;255;165;000;22mY$X[0m $X[38;2;231;072;086;22mor$X[0m $X[38;2;255;165;000;22mN$X[0m.`n" -ForegroundColor red
}
} Until ($UpdateResponseValid -eq $True)
if ($ShouldUpdate -eq "y" -or $ShouldUpdate -eq "yes"){#if user wants to update script, download .zip of latest release, extract to temporary folder and replace old D2Loader.ps1 with new D2Loader.ps1
Write-Host "`n Updating... :)" -foregroundcolor green
try {
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") -ErrorAction stop | Out-Null #create temporary folder to download zip to and extract
}
Catch {#if folder already exists for whatever reason.
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") | Out-Null #create temporary folder to download zip to and extract
}
$ZipURL = $ReleaseInfo.zipball_url #get zip download URL
$ZipPath = ($WorkingDirectory + "\UpdateTemp\D2Loader_" + $ReleaseInfo.tag_name + "_temp.zip")
Invoke-WebRequest -Uri $ZipURL -OutFile $ZipPath
if ($Null -ne $releaseinfo.assets.browser_download_url){#Check If I didn't forget to make a version.zip file and if so download it. This is purely so I can get an idea of how many people are using the script or how many people have updated. I have to do it this way as downloading the source zip file doesn't count as a download in github and won't be tracked.
Invoke-WebRequest -Uri $releaseinfo.assets.browser_download_url -OutFile $null | out-null #identify the latest file only.
}
$ExtractPath = ($Script:WorkingDirectory + "\UpdateTemp\")
Expand-Archive -Path $ZipPath -DestinationPath $ExtractPath -Force
$FolderPath = Get-ChildItem -Path $ExtractPath -Directory -Filter "shupershuff*" | Select-Object -ExpandProperty FullName
Copy-Item -Path ($FolderPath + "\D2Loader.ps1") -Destination ($Script:WorkingDirectory + "\" + $Script:ScriptFileName) #using $Script:ScriptFileName allows the user to rename the file if they want
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force #delete update temporary folder
Write-Host " Updated :)" -foregroundcolor green
Start-Sleep -milliseconds 850
& ($Script:WorkingDirectory + "\" + $Script:ScriptFileName)
exit
}
}
$Script:CurrentStats.LastUpdateCheck = (get-date).tostring('yyyy.MM.dd HH:mm:ss')
$Script:LatestVersionCheck = $CurrentStats.LastUpdateCheck
$CurrentStats | Export-Csv -Path "$Script:WorkingDirectory\Stats.csv" -NoTypeInformation #update stats.csv with the new time played.
}
Catch {
Write-Host "`n Couldn't check for updates. GitHub API limit may have been reached..." -foregroundcolor Yellow
Start-Sleep -milliseconds 3500
}
}
#Update (or replace missing) SetTextV2.bas file. This is an newer version of SetText (built by me and ChatGPT) that allows windows to be closed by process ID.
if ((Test-Path -Path ($workingdirectory + '\SetText\SetTextv2.bas')) -ne $True){#if SetTextv2.bas doesn't exist, download it.
try {
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") -ErrorAction stop | Out-Null #create temporary folder to download zip to and extract
}
Catch {#if folder already exists for whatever reason.
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force
New-Item -ItemType Directory -Path ($Script:WorkingDirectory + "\UpdateTemp\") | Out-Null #create temporary folder to download zip to and extract
}
$Releases = Invoke-RestMethod -Uri "https://api.github.com/repos/shupershuff/Diablo2RLoader/releases"
$ReleaseInfo = ($Releases | Sort-Object id -desc)[0] #find release with the highest ID.
$ZipURL = $ReleaseInfo.zipball_url #get zip download URL
$ZipPath = ($WorkingDirectory + "\UpdateTemp\D2Loader_" + $ReleaseInfo.tag_name + "_temp.zip")
Invoke-WebRequest -Uri $ZipURL -OutFile $ZipPath
if ($Null -ne $releaseinfo.assets.browser_download_url){#Check If I didn't forget to make a version.zip file and if so download it. This is purely so I can get an idea of how many people are using the script or how many people have updated. I have to do it this way as downloading the source zip file doesn't count as a download in github and won't be tracked.
Invoke-WebRequest -Uri $releaseinfo.assets.browser_download_url -OutFile $null | out-null #identify the latest file only.
}
$ExtractPath = ($Script:WorkingDirectory + "\UpdateTemp\")
Expand-Archive -Path $ZipPath -DestinationPath $ExtractPath -Force
$FolderPath = Get-ChildItem -Path $ExtractPath -Directory -Filter "shupershuff*" | Select-Object -ExpandProperty FullName
Copy-Item -Path ($FolderPath + "\SetText\SetTextv2.bas") -Destination ($Script:WorkingDirectory + "\SetText\SetTextv2.bas")
Write-Host " SetTextV2.bas was missing and was downloaded."
Remove-Item -Path ($Script:WorkingDirectory + "\UpdateTemp\") -Recurse -Force #delete update temporary folder
}
}
Function ImportXML { #Import Config XML
try {
$Script:Config = ([xml](Get-Content "$Script:WorkingDirectory\Config.xml" -ErrorAction Stop)).D2loaderconfig
Write-Verbose "Config imported successfully."
}
Catch {
Write-Host "`n Config.xml Was not able to be imported. This could be due to a typo or a special character such as `'&`' being incorrectly used." -foregroundcolor red
Write-Host " The error message below will show which line in the config.xml is invalid:" -foregroundcolor red
Write-Host (" " + $PSitem.exception.message + "`n") -foregroundcolor red
PressTheAnyKeyToExit
}
}
Function SetDCloneAlarmLevels {
if ($Script:Config.DCloneAlarmLevel -eq "All"){
$Script:DCloneAlarmLevel = "1,2,3,4,5,6"
}
ElseIf ($Script:Config.DCloneAlarmLevel -eq "Close"){
$Script:DCloneAlarmLevel = "1,4,5,6"
}
ElseIf ($Script:Config.DCloneAlarmLevel -eq "Imminent"){
$Script:DCloneAlarmLevel = "1,5,6"
}
else {#if user has typo'd the config file or left it blank.
$DCloneErrorMessage = (" Error: DClone Alarm Levels have been misconfigured in config.xml. ### Check that the value for DCloneAlarmLevel is entered correctly.").Replace("###", "`n")
Write-Host ("`n" + $DCloneErrorMessage + "`n") -Foregroundcolor red
PressTheAnyKeyToExit
}
}
Function ValidationAndSetup {
#Perform some validation on config.xml. Helps avoid errors for people who may be on older versions of the script and are updating. Will look to remove all of this in a future update.
if (Select-String -path $Script:WorkingDirectory\Config.xml -pattern "multiple game installs"){#Sort out an incorrect description text that will have been in folks config.xml for some time. This description was never valid and was from when the setting switcher feature was being developed and tested.
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = ";;`t`tNote, if using multiple game installs \(to keep client specific config persistent for each account\), ensure these are referenced in the CustomGamePath field in accounts.csv."
$Pattern += ";;`t`tOtherwise you can use a single install instead by linking the path below.-->;;"
$NewXML = [string]::join(";;",($XML.Split("`r`n")))
$NewXML = $NewXML -replace $Pattern, "-->;;"
$NewXML = $NewXML -replace ";;","`r`n"
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Write-Host "`n Corrected the description for GamePath in config.xml." -foregroundcolor Green
Start-Sleep -milliseconds 1500
}
if ($Null -ne $Script:Config.CommandLineArguments){#remove this config option as arguments are now stored in accounts.csv so that different arguments can be set for each account
Write-Host "`n Config option 'CommandLineArguments' is being moved to accounts.csv" -foregroundcolor Yellow
Write-Host " This is to enable different CMD arguments per account." -foregroundcolor Yellow
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = ";;\t<!--Optionally add any command line arguments that you'd like the game to start with-->;;\t<CommandLineArguments>.*?</CommandLineArguments>;;"
$NewXML = [string]::join(";;",($XML.Split("`r`n")))
$NewXML = $NewXML -replace $Pattern, ""
$NewXML = $NewXML -replace ";;","`r`n"
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
$Script:OriginalCommandLineArguments = $Script:Config.CommandLineArguments
Write-Host " CommandLineArguments has been removed from config.xml" -foregroundcolor green
Start-Sleep -milliseconds 1500
}
if ($Null -eq $Script:Config.ManualSettingSwitcherEnabled){#not to be confused with the AutoSettingSwitcher.
Write-Host "`n Config option 'ManualSettingSwitcherEnabled' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This is an optional config option to allow you to manually select which " -foregroundcolor Yellow
Write-Host " config file you want to use for each account when launching." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</SettingSwitcherEnabled>"
$Replacement = "</SettingSwitcherEnabled>`n`n`t<!--Can be used standalone or in conjunction with the standard setting switcher above.`n`t"
$Replacement += "This enables the menu option to enter 's' and manually pick between settings config files. Use this if you want to select Awesome or Poo graphics settings for an account.`n`t"
$Replacement += "Any setting file with a number after it will not be an available option (eg settings1.json will not be an option).`n`t"
$Replacement += "To make settings option, you can load from, call the file settings.<name>.json eg(settings.Awesome Graphics.json) which will appear as `"Awesome Graphics`" in the menu.-->`n`t"
$Replacement += "<ManualSettingSwitcherEnabled>False</ManualSettingSwitcherEnabled>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -eq $Script:Config.TrackAccountUseTime){
Write-Host "`n Config option 'TrackAccountUseTime' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This is an optional config option to track time played per account." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</ManualSettingSwitcherEnabled>"
$Replacement = "</ManualSettingSwitcherEnabled>`n`n`t<!--This allows you to roughly track how long you've used each account while using this script. "
$Replacement += "Choose False if you want to disable this.-->`n`t<TrackAccountUseTime>True</TrackAccountUseTime>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
ImportXML
PressTheAnyKey
}
if ($Null -eq $Script:Config.ConvertPlainTextSecrets){
Write-Host "`n Renaming ConvertPlainTextPasswords to ConvertPlainTextSecrets in config.xml" -foregroundcolor Yellow
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "<!--Whether script should convert plain text passwords in accounts.csv to a secure string, recommend leaving this set to True.-->"
$Replacement = "<!--Whether script should convert plain text tokens and passwords in accounts.csv to a secure string. Recommend leaving this set to True.-->"
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$Pattern = "ConvertPlainTextPasswords"
$Replacement = "ConvertPlainTextSecrets"
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Write-Host " Config.xml file updated :)`n" -foregroundcolor green
Start-Sleep -milliseconds 1500
ImportXML
PressTheAnyKey
}
if ($Null -ne $Script:Config.EnableBatchFeature){ # remove from config.xml. Not needed anymore as script checks accounts.csv to see if batches are used.
Write-Host "`n Config option 'EnableBatchFeature' is no longer needed." -foregroundcolor Yellow
Write-Host " Removed this option from config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = ";;\t<!--Enable the ability to open a group of accounts.*?</EnableBatchFeature>;;"
$NewXML = [string]::join(";;",($XML.Split("`r`n")))
$NewXML = $NewXML -replace $Pattern, ""
$NewXML = $NewXML -replace ";;","`r`n"
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -ne $Script:Config.CheckForNextTZ){
Write-Host "`n Config option 'CheckForNextTZ' is no longer needed." -foregroundcolor Yellow
Write-Host " Removed this option from config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = ";;\t<!--Choose whether or not TZ checker.*?</CheckForNextTZ>;;"
$NewXML = [string]::join(";;",($XML.Split("`r`n")))
$NewXML = $NewXML -replace $Pattern, ""
$NewXML = $NewXML -replace ";;","`r`n"
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -ne $Script:Config.AskForRegionOnceOnly){
Write-Host "`n Config option 'AskForRegionOnceOnly' is no longer needed." -foregroundcolor Yellow
Write-Host " Removed this option from config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = ";;\t<!--Whether script should only prompt you once for region.*?</AskForRegionOnceOnly>;;"
$NewXML = [string]::join(";;",($XML.Split("`r`n")))
$NewXML = $NewXML -replace $Pattern, ""
$NewXML = $NewXML -replace ";;","`r`n"
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -eq $Script:Config.DisableOpenAllAccountsOption){
Write-Host "`n Config option 'DisableOpenAllAccountsOption' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This is an optional config option to disable the functionality for opening all accounts." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DefaultRegion>"
$Replacement = "</DefaultRegion>`n`n`t<!--Disable the functionality of being able to open all accounts at once. This is for any crazy people who have a lot of accounts and want to prevent accidentally opening all at once.-->`n`t"
$Replacement += "<DisableOpenAllAccountsOption>False</DisableOpenAllAccountsOption>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -eq $Script:Config.RememberWindowLocations){
Write-Host "`n Config option 'RememberWindowLocations' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This is an optional config option to remember game window locations/sizes." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</ConvertPlainTextSecrets>"
$Replacement = "</ConvertPlainTextSecrets>`n`n`t<!--Make game launch each instance in the same screen location so you don't have to move your game windows around when starting the game.-->`n`t"
$Replacement += "<RememberWindowLocations>False</RememberWindowLocations>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -eq $Script:Config.DCloneTrackerSource){
Write-Host "`n Config option 'DCloneTrackerSource' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This is a required config option to determine which source should be used" -foregroundcolor Yellow
Write-Host " for obtaining current DClone status." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</TrackAccountUseTime>"
$Replacement = "</TrackAccountUseTime>`n`n`t<!--Options are d2emu.com, D2runewizard.com and diablo2.io.`n`t"
$Replacement += "Default and recommended option is d2emu.com as this pulls live data from the game as opposed to crowdsourced data.-->`n`t"
$Replacement += "<DCloneTrackerSource>d2emu.com</DCloneTrackerSource>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
ImportXML
PressTheAnyKey
}
if ($Null -eq $Script:Config.DCloneAlarmLevel){
Write-Host "`n Config option 'DCloneAlarmLevel' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This field determines if alarms should activate for all DClone status " -foregroundcolor Yellow
Write-Host " changes or just when DClone is about to walk." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DCloneTrackerSource>"
$Replacement = "</DCloneTrackerSource>`n`n`t<!--Specify what Statuses you want to be alarmed on.`n`t"
$Replacement += "Enter `"All`" to be alarmed of all status changes`n`t"
$Replacement += "Enter `"Close`" to be only alarmed when status is 4/6, 5/6 or has just walked.`n`t"
$Replacement += "Enter `"Imminent`" to be only alarmed when status is 5/6 or has just walked.`n`t"
$Replacement += "Recommend setting to `"All`"-->`n`t"
$Replacement += "<DCloneAlarmLevel>All</DCloneAlarmLevel>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
ImportXML
PressTheAnyKey
}
if ($Null -eq $Script:Config.DCloneAlarmList){
Write-Host "`n Config option 'DCloneAlarmList' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This is an optional config option to enable both audible and text based" -foregroundcolor Yellow
Write-Host " alarms for DClone Status changes." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DCloneTrackerSource>"
$Replacement = "</DCloneTrackerSource>`n`n`t<!--Allow you to have the script audibly warn you of upcoming dclone walks.`n`t"
$Replacement += "Specify as many of the following options as you like: SCL-NA, SCL-EU, SCL-KR, SC-NA, SC-EU, SC-KR, HCL-NA, HCL-EU, HCL-KR, HC-NA, HC-EU, HC-KR`n`t"
$Replacement += "EG if you want to be notified for all Softcore ladder walks on all regions, enter <DCloneAlarmList>SCL-NA, SCL-EU, SCL-KR</DCloneAlarmList>`n`t"
$Replacement += "If left blank, this feature is disabled. Default is blank as this may be annoying for some people.-->`n`t"
$Replacement += "<DCloneAlarmList></DCloneAlarmList>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
ImportXML
PressTheAnyKey
}
if ($Null -ne $Script:Config.DCloneAlarmList -and $Script:Config.DCloneAlarmList -ne ""){#validate data to prevent errors from typos
$pattern = "^(HC|SC)(L?)-(NA|EU|KR)$" #set pattern: must start with HC or SC, optionally has L after it, must end in -NA -EU or -KR
ForEach ($Alarm in $Script:Config.DCloneAlarmList.split(",").trim()){
if ($Alarm -notmatch $pattern){
Write-Host "`n $Alarm is not a valid Alarm entry." -foregroundcolor Red
Write-Host " See valid options in Config.xml`n" -foregroundcolor Red
PressTheAnyKeyToExit
}
}
}
if ($Null -eq $Script:Config.DCloneAlarmVoice){
Write-Host "`n Config option 'DCloneAlarmVoice' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This config allows you to choose between a Woman or Man's robot voice." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DCloneAlarmLevel>"
$Replacement = "</DCloneAlarmLevel>`n`n`t<!--Specify what voice you want. Choose 'Paladin' for David (Man) or 'Amazon' for Zira (Woman).-->`n`t"
$Replacement += "<DCloneAlarmVoice>Paladin</DCloneAlarmVoice>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -eq $Script:Config.DCloneAlarmVolume){
Write-Host "`n Config option 'DCloneAlarmVolume' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DCloneAlarmVoice>"
$Replacement = "</DCloneAlarmVoice>`n`t<!--Specify how loud notifications can be. Range from 1 to 100.-->`n`t"
$Replacement += "<DCloneAlarmVolume>69</DCloneAlarmVolume>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Null -eq $Script:Config.ForceAuthTokenForRegion){
Write-Host "`n Config option 'ForceAuthTokenForRegion' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
Write-Host " This config allows you to force AuthToken based authentication for any." -foregroundcolor Yellow
Write-Host " regions specified in config. Useful for when Blizzard have bricked." -foregroundcolor Yellow
Write-Host " their authentication servers on a particular region." -foregroundcolor Yellow
Write-Host " Added this missing option into .xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DCloneAlarmVoice>"
$Replacement = "</DCloneAlarmVoice>`n`n`t<!--Select regions which should be forced to use Tokens over parameters (overrides config in accounts.csv).`n`t"
$Replacement += "Only use this if connecting via Parameters is down for a particular region and you don't want to have to manually toggle.`n`t"
$Replacement += "Valid options are NA, EU and KR. Default is blank.-->`n`t"
$Replacement += "<ForceAuthTokenForRegion></ForceAuthTokenForRegion>" #add option to config file if it doesn't exist.
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
$XML = Get-Content "$Script:WorkingDirectory\Config.xml" -raw
$Pattern = "d2rapi.fly.dev"
if ($Null -ne (Select-Xml -Content $xml -XPath "//*[contains(.,'$pattern')]")){
Write-Host "`n Replaced 'd2rapi.fly.dev' in config with 'd2emu.com'." -foregroundcolor Yellow
$Replacement = "d2emu.com"
$NewXML = $XML -replace [regex]::Escape($Pattern), $Replacement
$NewXML | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
if ($Script:Config.DCloneAlarmList -ne ""){
$ValidVoiceOptions =
"Amazon",
"Paladin",
"Woman",
"Man",
"Wench",
"Bloke"
if ($Script:Config.DCloneAlarmVoice -notin $ValidVoiceOptions){
Write-Host "`n Error: DCloneAlarmVoice in config has an invalid option set." -Foregroundcolor red
Write-Host " Open config.xml and set this to either Paladin or Amazon.`n" -Foregroundcolor red
PressTheAnyKeyToExit
}
SetDCloneAlarmLevels
}
$Script:Config = ([xml](Get-Content "$Script:WorkingDirectory\Config.xml" -ErrorAction Stop)).D2loaderconfig #import config.xml again for any updates made by the above.
#check if there's any missing config.xml options, if so user has out of date config file.
$AvailableConfigs = #add to this if adding features.
"GamePath",
"DefaultRegion",
"ShortcutCustomIconPath"
$BooleanConfigs =
"ConvertPlainTextSecrets",
"ManualSettingSwitcherEnabled",
"RememberWindowLocations",
"DisableOpenAllAccountsOption",
"CreateDesktopShortcut",
"ForceWindowedMode",
"SettingSwitcherEnabled",
"TrackAccountUseTime"
$AvailableConfigs = $AvailableConfigs + $BooleanConfigs
$ConfigXMLlist = ($Config | Get-Member | Where-Object {$_.membertype -eq "Property" -and $_.name -notlike "#comment"}).name
Write-Host
ForEach ($Option in $AvailableConfigs){#Config validation
if ($Option -notin $ConfigXMLlist){
Write-Host " Config.xml file is missing a config option for $Option." -foregroundcolor yellow
Start-Sleep 1
PressTheAnyKey
}
}
if ($Option -notin $ConfigXMLlist){
Write-Host "`n Make sure to grab the latest version of config.xml from GitHub" -foregroundcolor yellow
Write-Host " $X[38;2;69;155;245;4mhttps://github.com/shupershuff/Diablo2RLoader/releases/latest$X[0m`n"
PressTheAnyKey
}
if ($Config.GamePath -match "`""){#Remove any quotes from path in case someone ballses this up.
$Script:GamePath = $Config.GamePath.replace("`"","")
}
else {
$Script:GamePath = $Config.GamePath
}
ForEach ($ConfigCheck in $BooleanConfigs){#validate all configs that require "True" or "False" as the setting.
if ($Null -ne $Config.$ConfigCheck -and ($Config.$ConfigCheck -ne $true -and $Config.$ConfigCheck -ne $false)){#if config is invalid
Write-Host " Config option '$ConfigCheck' is invalid." -foregroundcolor Red
Write-Host " Ensure this is set to either True or False.`n" -foregroundcolor Red
PressTheAnyKeyToExit
}
}
if ($Config.ShortcutCustomIconPath -match "`""){#Remove any quotes from path in case someone ballses this up.
$ShortcutCustomIconPath = $Config.ShortcutCustomIconPath.replace("`"","")
}
else {
$ShortcutCustomIconPath = $Config.ShortcutCustomIconPath
}
#Check Windows Game Path for D2r.exe is accurate.
if ((Test-Path -Path "$GamePath\d2r.exe") -ne $True){
Write-Host " Gamepath is incorrect. Looks like you have a custom D2r install location!" -foregroundcolor red
Write-Host " Edit the GamePath variable in the config file.`n" -foregroundcolor red
PressTheAnyKeyToExit
}
# Create Shortcut
if ($Config.CreateDesktopShortcut -eq $True){
$DesktopPath = [Environment]::GetFolderPath("Desktop")
$Targetfile = "-ExecutionPolicy Bypass -File `"$WorkingDirectory\$ScriptFileName`""
$ShortcutFile = "$DesktopPath\D2R Loader.lnk"
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.Arguments = $TargetFile
if ($ShortcutCustomIconPath.length -eq 0){
$Shortcut.IconLocation = "$Script:GamePath\D2R.exe"
}
Else {
$Shortcut.IconLocation = $ShortcutCustomIconPath
}
$Shortcut.Save()
}
#Check if SetTextv2.exe exists, if not, compile from SetTextv2.bas. SetTextv2.exe is what's used to rename the windows.
if ((Test-Path -Path ($workingdirectory + '\SetText\SetTextv2.exe')) -ne $True){ #-PathType Leaf check windows renamer is configured.
Write-Host "`n First Time run!`n" -foregroundcolor Yellow
Write-Host " SetTextv2.exe not in .\SetText\ folder and needs to be built."
if ((Test-Path -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe") -ne $True){#check that .net4.0 is actually installed or compile will fail.
Write-Host " .Net v4.0 not installed. This is required to compile the Window Renamer for Diablo." -foregroundcolor red
Write-Host " Download and install it from Microsoft here:" -foregroundcolor red
Write-Host " https://dotnet.microsoft.com/en-us/download/dotnet-framework/net40" #actual download link https://dotnet.microsoft.com/en-us/download/dotnet-framework/thank-you/net40-web-installer
PressTheAnyKeyToExit
}
Write-Host " Compiling SetTextv2.exe from SetTextv2.bas..."
& "C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" -target:winexe -out:"`"$WorkingDirectory\SetText\SetTextv2.exe`"" "`"$WorkingDirectory\SetText\SetTextv2.bas`"" | out-null #/verbose #actually compile the bastard
if ((Test-Path -Path ($workingdirectory + '\SetText\SetTextv2.exe')) -ne $True){#if it fails for some reason and settextv2.exe still doesn't exist.
Write-Host " SetTextv2 Could not be built for some reason :/"
PressTheAnyKeyToExit
}
Write-Host " Successfully built SetTextv2.exe for Diablo 2 Launcher script :)" -foregroundcolor green
Start-Sleep -milliseconds 4000 #a small delay so the first time run outputs can briefly be seen
}
#Check Handle64.exe downloaded and placed into correct folder
$Script:WorkingDirectory = ((Get-ChildItem -Path $PSScriptRoot)[0].fullname).substring(0,((Get-ChildItem -Path $PSScriptRoot)[0].fullname).lastindexof('\'))
if ((Test-Path -Path ($workingdirectory + '\Handle\Handle64.exe')) -ne $True){ #-PathType Leaf check windows renamer is configured.
try {
Write-Host "`n Handle64.exe not in .\Handle\ folder. Downloading now..." -foregroundcolor Yellow