-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathD2Loader.ps1
More file actions
4632 lines (4615 loc) · 251 KB
/
D2Loader.ps1
File metadata and controls
4632 lines (4615 loc) · 251 KB
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.16.0 (next version edits):
Make sure only numbers can be entered as batch in accounts.csv
Fixed other apps from having maximise button disabled by accident.
Improved validation for emails/tokens.
Partially added China capability (except for TZ).
Made it so if token is selected as the auth method, passwords aren't required in accounts.csv.
Added the abilty to announce upcoming Terrorzone alarms for your preferred TZ's.
Add ability for another alternative layout. Name the file AltLayout2.csv
Fixed DClone features with ROTW changes.
Added in menu option to force close all open instances. Enable via config.xml. Use with care!
Fixed how Invoke-Webrequest works in accordance with CVE-2025-54100
1.17.0+ to do list:
Consider having dclone check 5 seconds before refresh instead of afterwards
Add config option to disable cow.
if upcoming/active tz is cow, say moo
Improve Closure options (Batch, by account).
Look to implement CTRL + Shift + number as a shortcut to switch between D2r windows. Some basic investigations show that this is possible with PowerShell. Look to build a background powershell agent that runs while the loader runs to detect key combos.
Remove diablo2.io dclone API as it's problematic and uses D2Emu data now anyway. Possibly replace with d2tz.info
Investigate building a TZ overlay now that there's capability built to auto check TZs.
Potentially look at being able to launch a Single Steam instance.
Fix whatever I broke or poorly implemented in the last update :)
The "I can't be bothered" to do list:
Investigate RAMDisk for faster loading https://sourceforge.net/projects/imdisk-toolkit/files/latest/download
Couldn't write :) in release notes without it adding a new line, some minor issue with formatfunction regex. Complex to resolve.
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 :)
#>
param($AccountUsername,$PW,$Region,$All,$Batch,$ManualSettingSwitcher,$Close) #used to capture parameters sent to the script, if anyone even wants to do that.
$CurrentVersion = "1.17.1"
###########################################################################################################################################
# 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
}
if ($Null -ne $Close){
$ScriptArguments += " -close $Close"
}
#check if parameters were used
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=52 #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
try {
$Script:SettingsProfilePath = ((Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -name "{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}" -ErrorAction Stop)."{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}" + "\Diablo II Resurrected\") #Get Saved Games folder from registry rather than assume it's in C:\Users\Username\Saved Games
}
Catch {
$Script:SettingsProfilePath = ("C:\Users\" + $Env:UserName + "\Saved Games\Diablo II Resurrected\")
}
Function RemoveMaximiseButton { # I'm removing the maximise button on the script as sometimes I misclick maximise instead of minimise and it annoys me. Get's process ID of the script to ensure we don't remove maximise button from another app by accident.
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", 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 PowerShell window
$hWnd = (Get-Process -Id $PID).MainWindowHandle
# 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 IdleTimeChecker { #Get Windows Idle time. Used for optional feature to stop adding to game timers when there is no system input. Added this feature in for me in case I'm parking DClone or have leave the house to zip down to the shops to run errands for the wife lol.
if (-not ("IdleTime" -as [type])){
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class IdleTime {
[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO {
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public static uint GetIdleTime() {
LASTINPUTINFO lii = new LASTINPUTINFO(); //Get the Last Input Info (LII)
lii.cbSize = (uint)Marshal.SizeOf(lii);
GetLastInputInfo(ref lii);
return ((uint)Environment.TickCount - lii.dwTime) / 1000; // This returns idle time in seconds. We'll calculate to minutes elswhere.
}
}
"@
}
return [IdleTime]::GetIdleTime() #when function is called, return the seconds since last keyboard/mouse activity was detected so we can see if user is active/idle in case user wants to pause time tracking stats.
}
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 + @($EnterKey,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,[bool]$AllowYesNoOnly){
$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).
if ($AllowYesNoOnly){
$AllowedKeyList = @($EnterKey,78,89)
}
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 ($inputString -eq "" -and $key_.VirtualKeyCode -notin $Script:MenuOptions + 27) -or $inputString.length -gt 0){
$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 $inputString.length -eq 1 -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. Can handle ANSI text. 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
#$Script:X = [char]0x1b
#$X[38;2;165;146;99;48;2;1;1;1;4m $X[0m# .replace([char]0x1b,"F")
#$ANSITEXT -replace '\x1b\[[0-9;]*m',''
# 38 2 165 146 99 48 2 1 1 1 2 4m
#$ANSIPatterns = "\x1b\[38;\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3}m","\x1b\[0m","\x1b\[4m"
#$ANSIPatterns = "(?:\x1b|\$X)\[[0-9;]*m","\x1b\[0m","\x1b\[4m"
# Need to adjust this function so one of 2 ways, whatevers easiest/fastest
# the easiest way would be to identify the previous opening ANSI statement, close off the ANSI at the end of the first line $X[0m then add spaces for indent and then readd the opening ANSI statement at the beginning of next line
$ANSIPatterns = "\x1b\[38;\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3}m","\x1b\[38;\d{1,3};\d{1,3};\d{1,3};\d{1,3};\d{1,3};\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){
if ($line -ne " $ContinueANSI"){
$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 {
if ($Chunk -match "(?:\x1b|\$X)\[[0-9;]*m" -and $Chunk -notmatch '\x1b\[0m'){#Open ANSI without a closing tag
$ANSIStillActive = $True
$ContinueANSI = [regex]::Matches($Chunk, "\x1b\[(?!0m)[0-9;]+m") | select-object -last 1
}
elseif ($Chunk -match "(?:\x1b|\$X)\[[0-9;]*m" -and $Chunk -match '\x1b\[0m'){#open and closing ANSI tags. Lets assess if there's an equal amount of both to determine if ANSI is open or not.
$openCount = 0
$closeCount = 0
$Pattern = '(?:\x1b|\$X)\[[0-9;]+m' #pattern to identify all opening or closing statements.
$AllANSI = [regex]::Matches($Chunk, $Pattern)
foreach ($Rakanishu in $AllANSI) {
if ($Rakanishu.Value -match '\[0m$'){
$CloseCount++
}
else {
$OpenCount++
}
}
if ($OpenCount -gt $CloseCount){ #if there's more opening statements than closed statements, we should capture the current formatting so we can use this on the following text.
$ANSIStillActive = $True
$ContinueANSI = [regex]::Matches($Chunk, "\x1b\[(?!0m)[0-9;]+m") | select-object -last 1
}
Else {
$ANSIStillActive = $False
}
}
elseif ($Chunk -notmatch "(?:\x1b|\$X)\[[0-9;]*m" -and $Chunk -match '\x1b\[0m'){ #closing ansi with no open tag
$ANSIStillActive = $False
}
$Script:ANSIUsed = $False
if ($ANSIStillActive -eq $True){#output with a closing statement and then insert the ANSI formatting into the next line to process
Write-Output ($Chunk + "$X[0m") | 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 + $ContinueANSI + $Line.Substring($chunk.Length).trimstart() #$Line is equal to $Line but without the text that's already been outputted.
}
Else {
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.length -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
write-host " Getting D2Emu Connection details..."
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
write-host " Getting D2Emu AES key..."
$AES = & "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -Command {(invoke-webrequest https://d2emu.com/api/v1/shupertoken/aes -TimeoutSec 5 -UseBasicParsing).content | convertfrom-json}
write-host " Getting D2Emu token..."
$EncryptedToken = & "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -Command {((invoke-webrequest https://d2emu.com/api/v1/shupertoken/token -TimeoutSec 5 -UseBasicParsing).content | convertfrom-json).token}
}
Else {
write-host " Getting D2Emu AES key..."
$AES = invoke-restmethod https://d2emu.com/api/v1/shupertoken/aes -TimeoutSec 5
write-host " Getting D2Emu AES token..."
$EncryptedToken = (invoke-restmethod https://d2emu.com/api/v1/shupertoken/token -TimeoutSec 5).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
write-host " D2Emu Connection successful."
}
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 Create-Shortcut {# Create Shortcut Function
param (
[string]$shortcutPath,
[string]$targetPath,
[string]$arguments
)
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = $targetPath
$shortcut.Arguments = $arguments
$shortcut.Save()
}
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 {
Write-Host " Importing Stats.csv..."
$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 12 hours. Reduces API requests.
if ($Script:CurrentStats.LastUpdateCheck -lt (Get-Date).addHours(-12).ToString('yyyy.MM.dd HH:mm:ss')){# Compare current date and time to LastUpdateCheck date & time.
try {
# Check for Updates
Write-Host " Checking 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.
Clear-Host
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 -UseBasicParsing -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 -UseBasicParsing -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 -UseBasicParsing -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 -UseBasicParsing -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
param(
[Switch]$NoOutput
)
try {
if (!$NoOutput){
Write-Host " Importing Config.xml..."
}
$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 {
write-host " Validating Config..."
#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.
Function UpdateXML {
param (
[String]$Pattern,
[String]$Replacement,
[object[]]$XML,
[Switch]$Pause
)
($XML -replace [regex]::Escape($Pattern), $Replacement) | Set-Content -Path "$Script:WorkingDirectory\Config.xml"
if ($Pause){
Start-Sleep -milliseconds 1500
PressTheAnyKey
}
}
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 the config.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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
if ($Null -eq $Script:Config.ShowCloseOptionInMenu){
Write-Host "`n Config option 'ShowCloseOptionInMenu' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
formatfunction -IsWarning -Indents 0 -text "This will enable/disable a menu option to force shut all d2r instances."
Write-Host " Added this missing option into the config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</ManualSettingSwitcherEnabled>"
$Replacement = "</ManualSettingSwitcherEnabled>`n`n`t<!--If enabled this will show a menu option to be able to force close all D2r instances. Enter True if you want to enable this. Blank (disabled) by default.-->"
$Replacement += "`n`t<ShowCloseOptionInMenu>False</ShowCloseOptionInMenu>" #add option to config file if it doesn't exist.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
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 the config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</ShowCloseOptionInMenu>"
$Replacement = "</ShowCloseOptionInMenu>`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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
if ($Null -eq $Script:Config.IdleLimitForAccountUseTime){
Write-Host "`n Config option 'IdleLimitForAccountUseTime' 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 the config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</TrackAccountUseTime>"
$Replacement = "</TrackAccountUseTime>`n`n`t<!--If set, this automatically pauses time tracking if you are idle for a certain amount of minutes. Set to a number (eg 5 for 5 minutes). Blank (disabled) by default.-->"
$Replacement += "`n`t<IdleLimitForAccountUseTime></IdleLimitForAccountUseTime>" #add option to config file if it doesn't exist.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
if ($Null -eq $Script:Config.DisableIconStacking){
Write-Host "`n Config option 'DisableIconStacking' missing from config.xml" -foregroundcolor Yellow
Write-Host " This is due to the config.xml recently being updated." -foregroundcolor Yellow
formatfunction -IsWarning -Indents 0 -text "This is an optional config option to disable D2r icons stacking in the taskbar."
Write-Host " Added this missing option into the config.xml file :)`n" -foregroundcolor green
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</ShortcutCustomIconPath>"
$Replacement = "</ShortcutCustomIconPath>`n`n`t<!--If enabled, this option prevents D2r icons from stacking in the taskbar. "
$Replacement += "Set to True if you want to enable this feature.-->`n`t<DisableIconStacking>False</DisableIconStacking>" #add option to config file if it doesn't exist.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
if ($Null -ne $Script:Config.ConvertPlainTextPasswords){
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.-->"
$XML = $XML -replace [regex]::Escape($Pattern), $Replacement
$Pattern = "ConvertPlainTextPasswords"
$Replacement = "ConvertPlainTextSecrets"
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
ImportXML -NoOutput
}
if ($Null -eq $Script:Config.ConvertPlainTextSecrets){
Write-Host "`n Config option 'ConvertPlainTextSecrets' missing from config.xml" -foregroundcolor Yellow
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "</DisableIconStacking>"
$Replacement = "</DisableIconStacking>`n`n`t<!--Whether script should convert plain text passwords in accounts.csv to a secure string, recommend leaving this set to True.-->`n`t"
$Replacement += "<ConvertPlainTextSecrets>True</ConvertPlainTextSecrets>" #add option to config file if it doesn't exist.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
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 the config.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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
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 the config.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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
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 the config.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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
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 the config.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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
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 the config.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.
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML -Pause
}
if ($Null -ne $Script:Config.DCloneAlarmList -and $Script:Config.DCloneAlarmList -ne ""){#validate data to prevent errors from typos
if ($Script:Config.UseChinaRegion -ne $True){
$pattern = "^(HC|SC)(L?)-(NA|EU|KR)(-ROTW)?$" #set pattern: must start with HC or SC, optionally has L after it, must end in -NA -EU or -KR
}
Else {
$pattern = "^(HC|SC)(L?)-(CN)(-ROTW)?$" #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 -ne $Script:Config.DCloneAlarmVoice){
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "DCloneAlarmVoice"
$Replacement = "AlarmVoice"
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML
ImportXML -NoOutput
}
if ($Null -ne $Script:Config.DCloneAlarmVolume){
$XML = Get-Content "$Script:WorkingDirectory\Config.xml"
$Pattern = "DCloneAlarmVolume"
$Replacement = "AlarmVolume"
UpdateXML -Pattern $Pattern -Replacement $Replacement -XML $XML
ImportXML -NoOutput