forked from CubeCoders/GenericConfigGen
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerator.js
More file actions
2254 lines (1953 loc) · 127 KB
/
Copy pathgenerator.js
File metadata and controls
2254 lines (1953 loc) · 127 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
function omitNonPublicMembers(key, value) {
return (key.indexOf("_") === 0) ? undefined : value;
}
function omitPrivateMembers(key, value) {
return (key.indexOf("__") === 0) ? undefined : value;
}
function newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
//The order AMP itself writes GenericModule.kvp in - the field declaration order of each section in
//GenericModuleConfig.cs. Keys not listed here are written after the ones that are, in the order the
//view model declares them.
//Fields AMP has dropped (App.MonitorChildProcess, App.MonitorChildProcessWaitMs, Console.ActivateLogRegex)
//aren't listed, and the ones it still declares but has marked obsolete (App.SteamWorkshopDownloadLocation,
//App.RCONConnectRetrySeconds, App.SteamForceLoginPrompt) are listed for ordering but never written - see
//templateimport.js for how a configuration that still has them is brought forward.
const kvpKeyOrder = [
"Meta.DisplayName",
"Meta.Description",
"Meta.OS",
"Meta.AarchSupport",
"Meta.Arch",
"Meta.Author",
"Meta.URL",
"Meta.DisplayImageSource",
"Meta.EndpointURIFormat",
"Meta.ConfigManifest",
"Meta.MetaConfigManifest",
"Meta.ConfigRoot",
"Meta.DeprecatedReason",
"Meta.ResourceUsageInfo",
"Meta.MinAMPVersion",
"Meta.SpecificDockerImage",
"Meta.DockerRequired",
"Meta.DockerBaseReadOnly",
"Meta.ContainerPolicy",
"Meta.ContainerPolicyReason",
"Meta.ExtraSetupStepsURI",
"Meta.Prerequisites",
"Meta.ExtraContainerPackages",
"Meta.ConfigReleaseState",
"Meta.NoCommercialUsage",
"Meta.ConfigVersion",
"Meta.ReleaseNotes",
"Meta.BreakingReleaseNotes",
"Meta.AppConfigId",
"Meta.OriginalSource",
"Meta.ImportableExtensions",
"Meta.AppIsMultiIPAware",
"App.DisplayName",
"App.RootDir",
"App.BaseDirectory",
"App.StoresSupported",
"App.SteamWorkshopDownloadLocation",
"App.StoreSpecificSettings",
"App.StoreDownloadLocations",
"App.ExecutableWin",
"App.ExecutableLinux",
"App.WorkingDir",
"App.LinuxCommandLineArgs",
"App.WindowsCommandLineArgs",
"App.CommandLineArgs",
"App.UseLinuxIOREDIR",
"App.AppSettings",
"App.EnvironmentVariables",
"App.CommandLineParameterFormat",
"App.CommandLineParameterDelimiter",
"App.ExitMethod",
"App.ExitMethodWindows",
"App.ExitTimeout",
"App.ExitString",
"App.ExitFile",
"App.RestartDelaySeconds",
"App.HasWriteableConsole",
"App.HasReadableConsole",
"App.UDPLogger",
"App.SupportsLiveSettingsChanges",
"App.LiveSettingChangeCommandFormat",
"App.ForceIPBinding",
"App.SupportsIPv6",
"App.ApplicationIPBinding",
"App.Ports",
"App.AdminPortRef",
"App.PrimaryApplicationPortRef",
"App.UniversalSleepApplicationUDPPortRef",
"App.UniversalSleepSteamQueryPortRef",
"App.MaxUsers",
"App.UseRandomAdminPassword",
"App.PersistRandomPassword",
"App.RemoteAdminPassword",
"App.AdminMethod",
"App.IgnoreSTDOUTAfterRCON",
"App.AdminLoginTransform",
"App.StripANSIControlCodes",
"App.LoginTransformPrefix",
"App.RCONConnectDelaySeconds",
"App.RCONConnectRetrySeconds",
"App.RCONHeartbeatMinutes",
"App.RCONHeartbeatCommand",
"App.RCONSelectIPMethod",
"App.TelnetLoginFormat",
"App.TelnetNewLineType",
"App.TailLogFilePath",
"App.UpdateSources",
"App.PreStartStages",
"App.CommandTriggers",
"App.UserActions",
"App.ForceUpdate",
"App.ForceUpdateReason",
"App.Compatibility",
"App.SteamUpdateAnonymousLogin",
"App.SteamForceLoginPrompt",
"App.RapidStartup",
"App.HasSuccessfullyUpdatedAtLeastOnce",
"App.SmartExcludeExemptions",
"App.SmartExcludeSupported",
"App.DumpFullChildProcessTree",
"App.MonitorChildProcessName",
"App.MonitorDirectChildOnly",
"App.SupportsUniversalSleep",
"App.UseSteamQueryForStatus",
"App.WakeupMode",
"App.ApplicationReadyMode",
"App.QuiesceCommand",
"App.DequiesceCommand",
"App.QuiesceSettleDelayMilliseconds",
"Console.FilterMatchRegex",
"Console.FilterMatchReplacement",
"Console.ThrowawayMessageRegex",
"Console.AppReadyRegex",
"Console.UserJoinRegex",
"Console.UserLeaveRegex",
"Console.UserChatRegex",
"Console.UpdateAvailableRegex",
"Console.PreConnectRegex",
"Console.ConnectIPRegex",
"Console.MetricsRegex",
"Console.ServerInfoRegex",
"Console.ServerAuthURLPromptRegex",
"Console.ServerAuthAckRegex",
"Console.ConsoleFormatRegex",
"Console.DownloadProgressRegex",
"Console.HideFromConsoleRegex",
"Console.SuppressLogAtStart",
"Console.UserActions",
"Limits.SleepMode",
"Limits.SleepOnStart",
"Limits.SleepDelayMinutes",
"Limits.DozeDelay",
"Limits.AutoRetryCount",
"Limits.SleepStartThresholdSeconds",
];
//Stable sort - anything AMP doesn't write (or that was added since) keeps its relative order at the end.
function sortByKvpKeyOrder(keys) {
return keys.slice().sort((a, b) => {
var indexA = kvpKeyOrder.indexOf(a);
var indexB = kvpKeyOrder.indexOf(b);
if (indexA == indexB) { return 0; }
if (indexA == -1) { return 1; }
if (indexB == -1) { return -1; }
return indexA - indexB;
});
}
//AMP looks the main game, query and admin ports up by a fixed Ref, so a configuration can only have one
//of each. Everything else is a custom port and can appear as many times as the application needs.
const portTypes = ["Custom Port", "Main Game Port", "Steam Query Port", "RCON Port"];
//Every value of GenericModuleConfig.UpdateSteps, with the fields each one actually reads taken from the
//switch in GenericApp.PerformUpdateStage. "value" is the flag AMP gives the step in the enum - it's only
//needed to read back an instance's own kvp, which stores the number rather than the name.
//A step only shows the fields it uses, because anything else is written into the manifest for AMP to
//ignore and reads as though it does something.
const updateStepSpecs = [
{ name: "SteamCMD", value: 4, description: "Downloads an application by its Steam App ID.", fields: {
UpdateSourceData: { label: "Server App ID", help: "The App ID of the dedicated server to download. Find it via SteamDB.", placeholder: "896660" },
UpdateSourceArgs: { label: "Client App ID", help: "The App ID of the game client on the Steam store. AMP takes the applications image from it - the server App ID has no store page, so leaving this blank means no image. Also used for the SteamAppId variable, which falls back to the server App ID.", placeholder: "892970" },
UpdateSourceVersion: { label: "Branch", help: "The beta branch to download. Can be a fixed value or the field name of a setting. Public branch if left blank.", placeholder: "{{ReleaseStream}}" },
UpdateSourceExtra: { label: "Workshop Mod Name", help: "Only used when downloading a Steam Workshop item rather than an application.", placeholder: "" },
UpdateSourceTarget: { label: "Install Directory", help: "Where SteamCMD installs to. Defaults to the applications base directory.", placeholder: "" },
}, flags: ["ForcePlatform"] },
{ name: "FetchURL", value: 1, description: "Downloads a file from a fixed URL.", fields: {
UpdateSourceData: { label: "URL", help: "The URL of the file to download.", placeholder: "https://example.com/server.zip" },
UpdateSourceArgs: { label: "Save As", help: "The filename to save it under. Taken from the URL if left blank.", placeholder: "server.zip" },
UpdateSourceTarget: { label: "Target Directory", help: "Where to save it, relative to the root directory.", placeholder: "serverfiles" },
}, flags: ["Unzip", "Overwrite", "DeleteAfterExtract"] },
{ name: "GithubRelease", value: 16, description: "Downloads a file attached to a GitHub release.", fields: {
UpdateSourceArgs: { label: "Repository", help: "The repository the release is published from, as owner/name.", placeholder: "tModLoader/tModLoader" },
UpdateSourceData: { label: "Asset Filename", help: "The file to take from the release.", placeholder: "tModLoader.zip" },
UpdateSourceVersion: { label: "Release Tag", help: "The release to download. The latest release is used if left blank.", placeholder: "v2024.1" },
UpdateSourceTarget: { label: "Target Directory", help: "Where to save it, relative to the root directory.", placeholder: "serverfiles" },
}, flags: ["Unzip", "Overwrite", "DeleteAfterExtract"] },
{ name: "FetchURLfromJQ", value: 256, description: "Reads a download URL out of a JSON API, then downloads it.", fields: {
UpdateSourceData: { label: "API URL", help: "The URL returning the JSON document.", placeholder: "https://example.com/api/latest" },
UpdateSourceArgs: { label: "JSONPath", help: "The path within the response holding the download URL. The last match is used.", placeholder: "$.downloads.server.url" },
UpdateSourceTarget: { label: "Target Directory", help: "Where to save the downloaded file, relative to the root directory.", placeholder: "serverfiles" },
}, flags: ["Unzip", "Overwrite", "DeleteAfterExtract"] },
{ name: "GitRepo", value: 128, description: "Clones a git repository, or pulls it if it is already there. Requires git on the host.", fields: {
UpdateSourceData: { label: "Repository URL", help: "The repository to clone.", placeholder: "https://github.com/owner/name.git" },
UpdateSourceTarget: { label: "Target Directory", help: "Where to clone it, relative to the base directory. Required.", placeholder: "serverfiles" },
}, flags: [] },
{ name: "ExtractArchive", value: 32768, description: "Extracts an archive that is already on disk.", fields: {
UpdateSourceData: { label: "Archive File", help: "The archive to extract, including the root directory.", placeholder: "./myapp/374040/dedicated_server.zip" },
UpdateSourceTarget: { label: "Extract To", help: "Where to extract it, relative to the root directory. Defaults to the base directory.", placeholder: "serverfiles" },
}, flags: ["Overwrite", "DeleteAfterExtract"] },
{ name: "CopyFilePath", value: 2, description: "Copies a file from one place to another.", fields: {
UpdateSourceArgs: { label: "Source File", help: "The file to copy, including the root directory.", placeholder: "./myapp/1829350/default.cfg" },
UpdateSourceData: { label: "Destination File", help: "Where to copy it to, including the root directory.", placeholder: "./myapp/1829350/save/config.cfg" },
UpdateSourceTarget: { label: "Extract To", help: "Only used when the copied file is unzipped - where to extract it, relative to the root directory.", placeholder: "serverfiles" },
}, flags: ["Unzip", "Overwrite", "DeleteAfterExtract"] },
{ name: "MoveFile", value: 2048, description: "Moves or renames a file.", fields: {
UpdateSourceArgs: { label: "Source File", help: "The file to move, including the root directory.", placeholder: "./myapp/serverfiles/old.cfg" },
UpdateSourceData: { label: "Destination File", help: "Where to move it to, including the root directory.", placeholder: "./myapp/serverfiles/new.cfg" },
}, flags: ["Overwrite"] },
{ name: "CreateFile", value: 512, description: "Writes a file with fixed contents.", fields: {
UpdateSourceArgs: { label: "File Path", help: "The file to write, including the root directory.", placeholder: "./myapp/serverfiles/eula.txt" },
UpdateSourceData: { label: "Contents", help: "What to write into it.", placeholder: "eula=true" },
}, flags: ["Overwrite"] },
{ name: "CreateDirectory", value: 1024, description: "Creates a directory.", fields: {
UpdateSourceArgs: { label: "Directory Path", help: "The directory to create, including the root directory.", placeholder: "./myapp/serverfiles/logs" },
}, flags: [] },
{ name: "CreateSymlink", value: 64, description: "Creates a symlink. Linux only.", platform: "Linux", fields: {
UpdateSourceArgs: { label: "Existing Path", help: "The file or directory the link points at.", placeholder: "./myapp/1829350/save" },
UpdateSourceData: { label: "Link Path", help: "Where to create the link, relative to the root directory.", placeholder: "save" },
}, flags: [] },
{ name: "SetExecutableFlag", value: 32, description: "Marks a file as executable. Linux only.", platform: "Linux", fields: {
UpdateSourceArgs: { label: "File", help: "The file to mark executable, relative to the root directory.", placeholder: "serverfiles/dedicated_server.x86_64" },
}, flags: [] },
{ name: "Executable", value: 8, description: "Runs an executable. Not a shell script or a batch file - use Bash, PowerShell or CMD for those.", fields: {
UpdateSourceData: { label: "Executable", help: "The executable to run, including the root directory.", placeholder: "./myapp/serverfiles/setup" },
UpdateSourceArgs: { label: "Arguments", help: "The arguments to pass to it.", placeholder: "-config -force" },
}, flags: ["RunInBackground", "ProcessToolOutput"] },
{ name: "Bash", value: 524288, description: "Runs a shell command through bash. Linux only.", platform: "Linux", fields: {
UpdateSourceArgs: { label: "Command", help: "The command to run, from the root directory.", placeholder: "chmod -R +x ./serverfiles" },
}, flags: [] },
{ name: "PowerShell", value: 1048576, description: "Runs a command through PowerShell. Windows only.", platform: "Windows", fields: {
UpdateSourceArgs: { label: "Command", help: "The command to run, from the root directory.", placeholder: "Expand-Archive server.zip" },
}, flags: [] },
{ name: "CMD", value: 2097152, description: "Runs a command through cmd.exe. Windows only.", platform: "Windows", fields: {
UpdateSourceArgs: { label: "Command", help: "The command to run, from the root directory.", placeholder: "mklink /D save serverfiles\\save" },
}, flags: [] },
{ name: "RunConsoleCommand", value: 262144, description: "Sends a line to the running application's console.", fields: {
UpdateSourceArgs: { label: "Command", help: "The line to send.", placeholder: "save-all" },
}, flags: [] },
{ name: "Pause", value: 131072, description: "Waits before moving on to the next stage.", fields: {
UpdateSourceArgs: { label: "Seconds", help: "How long to wait.", placeholder: "10" },
}, flags: [] },
{ name: "StartApplication", value: 4096, description: "Starts the application once. Useful when it generates its config files on first run.", fields: {}, flags: [] },
{ name: "WaitForStartupComplete", value: 8192, description: "Waits for the application to report itself ready before moving on.", fields: {}, flags: [] },
{ name: "ShutdownApplication", value: 16384, description: "Stops the application and waits for it to exit.", fields: {}, flags: [] },
{ name: "DelegateToPlugin", value: 65536, description: "Hands the update over to a plugin that provides one. Fails if no plugin has registered.", fields: {}, flags: [] },
//Not offered for new stages - these three aren't ready to be used yet. They're still recognised on
//import so a template that already uses one keeps working and comes back out unchanged.
{ name: "Wine32", value: 4194304, description: "Initialises a 32-bit Wine prefix. Linux only.", platform: "Linux", fields: {}, flags: [], hidden: true },
{ name: "Wine64", value: 8388608, description: "Initialises a 64-bit Wine prefix. Linux only.", platform: "Linux", fields: {}, flags: [], hidden: true },
{ name: "Proton", value: 16777216, description: "Downloads and initialises Proton-GE. Linux only.", platform: "Linux", fields: {}, flags: [], hidden: true },
{ name: "None", value: 0, description: "Does nothing. Useful as a placeholder.", fields: {}, flags: [] },
];
//The fields AMP can't run the step without - it either fails outright or quietly does nothing.
const updateStepRequiredFields = {
SteamCMD: ["UpdateSourceData"],
FetchURL: ["UpdateSourceData"],
GithubRelease: ["UpdateSourceArgs"],
FetchURLfromJQ: ["UpdateSourceData", "UpdateSourceArgs"],
GitRepo: ["UpdateSourceData", "UpdateSourceTarget"],
ExtractArchive: ["UpdateSourceData"],
CopyFilePath: ["UpdateSourceArgs", "UpdateSourceData"],
MoveFile: ["UpdateSourceArgs", "UpdateSourceData"],
CreateFile: ["UpdateSourceArgs"],
CreateDirectory: ["UpdateSourceArgs"],
CreateSymlink: ["UpdateSourceArgs", "UpdateSourceData"],
SetExecutableFlag: ["UpdateSourceArgs"],
Executable: ["UpdateSourceData"],
Bash: ["UpdateSourceArgs"],
PowerShell: ["UpdateSourceArgs"],
CMD: ["UpdateSourceArgs"],
RunConsoleCommand: ["UpdateSourceArgs"],
Pause: ["UpdateSourceArgs"],
};
const updateStepSpecsByName = {};
const updateStepNamesByValue = {};
for (const spec of updateStepSpecs) {
updateStepSpecsByName[spec.name] = spec;
updateStepNamesByValue[String(spec.value)] = spec.name;
}
//The generator used to store its own index for the step type rather than the name AMP uses. These are
//what those indexes meant, so a configuration exported before the change still opens.
const legacyUpdateSourceIndexes = {
"0": "CopyFilePath",
"1": "CreateSymlink",
"2": "Executable",
"3": "ExtractArchive",
"4": "FetchURL",
"5": "GithubRelease",
"6": "SetExecutableFlag",
"7": "StartApplication",
"8": "SteamCMD",
};
function normalizeUpdateSource(updateSource) {
var text = String(updateSource == null ? "" : updateSource).trim();
if (text == "") { return "None"; }
if (updateStepSpecsByName[text]) { return text; }
//Case only, for a template that spells it differently to the enum.
for (const name of Object.keys(updateStepSpecsByName)) {
if (name.toLowerCase() == text.toLowerCase()) { return name; }
}
return legacyUpdateSourceIndexes[text] || null;
}
function downloadString(data, filename) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
ko.validation.init();
class generatorViewModel {
constructor() {
var self = this;
this._compatibility = ko.observable("None");
this.Meta_DisplayName = ko.observable("").extend({ required: "Please enter an application name" });
this.Meta_Description = ko.observable("");
this.Meta_Arch = ko.observable("x86_64");
this._Meta_Author = ko.observable("");
this.Meta_Author = ko.computed(() => self._Meta_Author() + ' - Made with AMP Config Generator');
this._Meta_GithubOrigin = ko.computed(() => 'https://github.com/' + self._Meta_Author() + '/AMPTemplates.git');
this._Meta_GithubURL = ko.computed(() => 'https://github.com/' + self._Meta_Author() + '/AMPTemplates');
this.Meta_URL = ko.observable("");
//2.8.0.4 is the first build with App.StoreDownloadLocations/App.StoresSupported, which is where the
//Steam Workshop path lives now that App.SteamWorkshopDownloadLocation is obsolete.
this.Meta_MinAMPVersion = ko.observable("2.8.0.4");
//An imported template may name a more specific image than the generator would pick - AMP takes it
//literally, so it's kept rather than being rewritten to the generic wine/xvfb one.
this._Meta_SpecificDockerImageRaw = ko.observable("");
this.__Meta_SpecificDockerImageForCompatibility = ko.computed(() => self._compatibility() != "None" ? (self._compatibility().substring(self._compatibility().length - 4) == "Xvfb" ? `cubecoders/ampbase:xvfb` : `cubecoders/ampbase:wine`) : ``);
this.Meta_SpecificDockerImage = ko.computed(() => self._Meta_SpecificDockerImageRaw() != "" ? self._Meta_SpecificDockerImageRaw() : self.__Meta_SpecificDockerImageForCompatibility());
this.Meta_DockerRequired = ko.observable("False");
this.Meta_ContainerPolicy = ko.observable("Supported");
this.Meta_ContainerPolicyReason = ko.observable("");
this.Meta_Prerequisites = ko.observable("[]");
this.Meta_ExtraContainerPackages = ko.observable("[]");
this.Meta_ConfigReleaseState = ko.observable("NotSpecified");
this.Meta_NoCommercialUsage = ko.observable(false);
this.Meta_AppConfigId = ko.observable(newGuid());
//Written by AMP itself, so they're carried here too - otherwise a template that sets them loses
//them the moment it's imported and downloaded again. Values match the defaults in
//GenericModuleConfig.cs unless the generator has a reason to differ.
this.Meta_AarchSupport = ko.observable("Unknown");
this.Meta_DockerBaseReadOnly = ko.observable("False");
this.Meta_ExtraSetupStepsURI = ko.observable("");
this.Meta_ConfigVersion = ko.observable("1");
this.Meta_ReleaseNotes = ko.observable("");
this.Meta_BreakingReleaseNotes = ko.observable("");
this.Meta_ImportableExtensions = ko.observable("[]");
this.Meta_AppIsMultiIPAware = ko.observable("False");
this._SupportsWindows = ko.observable(true);
this._SupportsLinux = ko.observable(true);
this.App_AdminMethod = ko.observable("STDIO");
this.App_HasReadableConsole = ko.observable(true);
this.App_HasWriteableConsole = ko.observable(true);
this.App_DisplayName = ko.computed(() => this.Meta_DisplayName());
this.App_CommandLineArgs = ko.observable("{{$PlatformArgs}} {{$FormattedArgs}}")
this.App_WindowsCommandLineArgs = ko.observable("");
this.App_CommandLineParameterFormat = ko.observable("+{0} {1}");
this.App_CommandLineParameterDelimiter = ko.observable(" ");
this.App_RapidStartup = ko.observable("False");
this.App_ApplicationReadyMode = ko.observable("RegexMatch");
//Deliberately not AMP's default (String) - most applications the generator is used for can't be
//asked to stop over their console.
this.App_ExitMethod = ko.observable("OS_CLOSE");
this.App_ExitString = ko.observable("stop");
this.App_UseLinuxIOREDIR = ko.observable("False");
this.App_ExitTimeout = ko.observable("30");
this.App_ExitFile = ko.observable("app_exit.lck");
this.App_SupportsLiveSettingsChanges = ko.observable("False");
this.App_LiveSettingChangeCommandFormat = ko.observable("set {0} \"{1}\"");
this.App_ApplicationIPBinding = ko.observable("0.0.0.0");
//The port Refs follow the generators own naming rather than AMP's ApplicationPort1/2.
this.App_AdminPortRef = ko.observable("RemoteAdminPort");
this.App_UniversalSleepApplicationUDPPortRef = ko.observable("MainGamePort");
this.App_PrimaryApplicationPortRef = ko.observable("MainGamePort");
this.App_UniversalSleepSteamQueryPortRef = ko.observable("SteamQueryPort");
this.App_MaxUsers = ko.observable("20");
this.App_UseRandomAdminPassword = ko.observable(false);
this.App_RemoteAdminPassword = ko.observable("");
this.App_AdminLoginTransform = ko.observable("None");
this.App_RCONConnectDelaySeconds = ko.observable("5");
this.App_RCONHeartbeatCommand = ko.observable("ping");
this.App_RCONHeartbeatMinutes = ko.observable("0");
this.App_TelnetLoginFormat = ko.observable("{0}");
this.App_SteamUpdateAnonymousLogin = ko.observable("True");
this.App_SupportsUniversalSleep = ko.observable("False");
this.App_WakeupMode = ko.observable("Any");
//AMP dropped App.MonitorChildProcess/App.MonitorChildProcessWaitMs - child monitoring is now driven
//by this name being set at all, and it only applies on Linux.
this.App_MonitorChildProcessName = ko.observable("");
this.App_Compatibility = ko.observable("None");
//AMP fills this in with the live value of every setting once the instance runs - a template ships it empty.
this.App_AppSettings = ko.observable("{}");
//Whatever an imported template had, so its own variables survive being downloaded again.
this._App_EnvironmentVariablesImported = ko.observable("{}");
//Exit handling and process supervision.
this.App_ExitMethodWindows = ko.observable("None"); //None means "use App.ExitMethod on Windows too".
this.App_RestartDelaySeconds = ko.observable("0");
this.App_DumpFullChildProcessTree = ko.observable("False");
this.App_MonitorDirectChildOnly = ko.observable(false);
//Networking and logging.
this.App_UDPLogger = ko.observable("False");
this.App_ForceIPBinding = ko.observable(false);
this.App_SupportsIPv6 = ko.observable(false);
this.App_TailLogFilePath = ko.observable("server.log");
//RCON and admin login.
this.App_PersistRandomPassword = ko.observable(false);
this.App_IgnoreSTDOUTAfterRCON = ko.observable("False");
this.App_StripANSIControlCodes = ko.observable("True");
this.App_LoginTransformPrefix = ko.observable(""); //Only used when App.AdminLoginTransform is Prefix.
this.App_RCONSelectIPMethod = ko.observable("Default");
this.App_TelnetNewLineType = ko.observable("Default");
//Triggers the generator has no editor for - shipped empty so they survive a round trip.
this.App_CommandTriggers = ko.observable("{}");
this.App_UserActions = ko.observable("[]");
//Updates and backups.
this.App_ForceUpdate = ko.observable("False");
this.App_ForceUpdateReason = ko.observable("");
this.App_SmartExcludeSupported = ko.observable("True");
this.App_SmartExcludeExemptions = ko.observable(JSON.stringify(["*.cfg", "*.conf", "*.config", "*.ini", "*.json", "*.xml", "*.properties", "*.kvp", "*.yml", "*.yaml", "*.toml", "*.lua"]));
//Sleep mode and quiescing.
this.App_UseSteamQueryForStatus = ko.observable("False");
this.App_QuiesceCommand = ko.observable("");
this.App_DequiesceCommand = ko.observable("");
this.App_QuiesceSettleDelayMilliseconds = ko.observable("5000");
//App.SteamWorkshopDownloadLocation is obsolete in AMP and nothing reads it any more, so it isn't
//written. AMP takes the path out of App.StoreDownloadLocations (keyed on the store name minus its
//"Store" suffix), and a store only offers itself if App.StoresSupported has its flag.
this._App_SteamWorkshopDownloadLocation = ko.observable("");
this._App_WorkshopDownloadPath = ko.computed(() => self._App_SteamWorkshopDownloadLocation() != '' ? "{{$FullBaseDir}}" + self._App_SteamWorkshopDownloadLocation() : '');
this.App_StoresSupported = ko.computed(() => self._App_WorkshopDownloadPath() != '' ? "SteamWorkshop" : "None");
this.App_StoreSpecificSettings = ko.observable("{}");
this.App_StoreDownloadLocations = ko.computed(() => JSON.stringify(self._App_WorkshopDownloadPath() != '' ? { "SteamWorkshop": self._App_WorkshopDownloadPath() } : {}));
this.Console_FilterMatchRegex = ko.observable("");
this.Console_FilterMatchReplacement = ko.observable("");
this.Console_ThrowawayMessageRegex = ko.observable("");
//The sample console lines the generator builds the event expressions from...
this._Console_AppReadyRegex = ko.observable("");
this._Console_UserJoinRegex = ko.observable("");
this._Console_UserLeaveRegex = ko.observable("");
this._Console_UserChatRegex = ko.observable("");
//...and the expressions themselves, for anything written by hand or brought in from a template.
//WildcardToRegex escapes what it's given, so an existing expression can't go back through it - it's
//held here instead and used as-is whenever there's no sample line to build one from.
this._Console_AppReadyRegexRaw = ko.observable("");
this._Console_UserJoinRegexRaw = ko.observable("");
this._Console_UserLeaveRegexRaw = ko.observable("");
this._Console_UserChatRegexRaw = ko.observable("");
this.Console_UpdateAvailableRegex = ko.observable("");
this.Console_MetricsRegex = ko.observable("");
//No editor for these yet, but AMP writes them and templates use them - carried so an imported
//template keeps whatever it had.
this.Console_PreConnectRegex = ko.observable("");
this.Console_ConnectIPRegex = ko.observable("");
this.Console_ServerInfoRegex = ko.observable("");
this.Console_ServerAuthURLPromptRegex = ko.observable("");
this.Console_ServerAuthAckRegex = ko.observable("");
this.Console_ConsoleFormatRegex = ko.observable("");
this.Console_DownloadProgressRegex = ko.observable("");
this.Console_HideFromConsoleRegex = ko.observable("");
this.Console_SuppressLogAtStart = ko.observable("False");
this.Console_UserActions = ko.observable("{}");
this.Limits_SleepMode = ko.observable("True");
this.Limits_SleepOnStart = ko.observable("False");
this.Limits_SleepDelayMinutes = ko.observable("5");
this.Limits_DozeDelay = ko.observable("2");
this.Limits_AutoRetryCount = ko.observable("5");
this.Limits_SleepStartThresholdSeconds = ko.observable("25");
this._PortMappings = ko.observableArray(); //of portMappingViewModel
this.__NewPort = ko.observable("7777");
this.__NewName = ko.observable("");
this.__NewDescription = ko.observable("");
this.__NewPortType = ko.observable("Custom Port");
this.__NewProtocol = ko.observable("0");
//Worked out from the ports themselves rather than tracked by hand as they are added and removed,
//so changing a port's type after it has been added keeps the list right.
this.__TakenPortTypes = ko.computed(() => self._PortMappings().map(port => port._PortType()).filter(portType => portType != "Custom Port"));
this.__AvailablePortOptions = ko.computed(() => portTypes.filter(portType => portType == "Custom Port" || !self.__TakenPortTypes().contains(portType)));
//What the four port role settings can be pointed at. Whatever they already hold stays on offer even
//when no port answers to it - a template can name a port the generator has no row for, and dropping
//the value from the list would have the dropdown quietly rewrite it to something else on load.
//Parents and their children both, the way AMP flattens the list before looking a ref up.
this.__AllPortRefs = ko.computed(() => {
var refs = [];
for (const port of self._PortMappings()) {
refs.push(port.Ref());
for (const child of port._ChildPorts()) { refs.push(child.Ref()); }
}
return refs;
});
this.__PortRefOptions = ko.computed(() => {
var refs = self.__AllPortRefs().filter(ref => ref != "");
for (const ref of [self.App_PrimaryApplicationPortRef(), self.App_AdminPortRef(), self.App_UniversalSleepApplicationUDPPortRef(), self.App_UniversalSleepSteamQueryPortRef()]) {
if (ref != "") { refs.push(ref); }
}
return [""].concat(refs.filter((ref, index) => refs.indexOf(ref) == index));
});
//AMP resolves a role to a port by exact Ref and falls back to port 0 when it misses, so a ref with
//no port behind it is called out in the list rather than looking like any other choice.
this.__PortRefText = ref => ref == "" ? "None" : (self.__AllPortRefs().contains(ref) ? ref : `${ref} (no such port)`);
//AMP writes these as "True"/"False" text, so the checkboxes go through a computed rather than
//binding to the value that gets written.
var trueFalseChecked = observable => ko.computed({
read: () => observable() == "True",
write: value => observable(value ? "True" : "False"),
});
this.__SupportsUniversalSleepChecked = trueFalseChecked(self.App_SupportsUniversalSleep);
this.__UseSteamQueryForStatusChecked = trueFalseChecked(self.App_UseSteamQueryForStatus);
this._ConfigFileMappings = ko.observableArray(); //of configFileMappingViewModel
//Files an imported template shipped that the generator has no concept of. They go back into the
//download untouched - see parseTemplateFiles.
this._ExtraFiles = ko.observableArray(); //of { name, text }
this.__NewConfigFile = ko.observable("");
this.__NewAutoMap = ko.observable(true);
this.__NewConfigType = ko.observable("0");
this._UpdateSourceURL = ko.observable("");
this._UpdateSourceGitRepo = ko.observable("");
this._UpdateSourceUnzip = ko.observable(false);
this._DisplayImageSource = ko.observable("");
//Whatever an imported template already had, for the sources the generator can't work out for itself
//- an "internal:" image, or a "steam:" one on a template whose stage doesn't name a client App ID.
this._Meta_DisplayImageSourceRaw = ko.observable("");
this._SteamServerAppID = ko.observable("");
this._WinExecutableName = ko.observable("");
this._LinuxExecutableName = ko.observable("");
this._AppSettings = ko.observableArray(); //of appSettingViewModel
this.__AddEditSetting = ko.observable(null); //of appSettingViewModel
this.__IsEditingSetting = ko.observable(false);
this._UpdateStages = ko.observableArray(); //of updateStageViewModel
//AMP runs these before every start rather than only when updating, using the same stage type.
this._PreStartStages = ko.observableArray(); //of updateStageViewModel
this.__AddEditStage = ko.observable(null); //of updateStageViewModel
this.__IsEditingStage = ko.observable(false);
this.__NewStageList = ko.observable(null);
//Computed values
//A sample line wins when there is one, otherwise whatever expression was typed or imported is kept.
var consoleEventRegex = (sample, raw) => ko.computed(() => sample() != "" ? WildcardToRegex(sample()) : raw());
this.Console_AppReadyRegex = consoleEventRegex(self._Console_AppReadyRegex, self._Console_AppReadyRegexRaw);
this.Console_UserJoinRegex = consoleEventRegex(self._Console_UserJoinRegex, self._Console_UserJoinRegexRaw);
this.Console_UserLeaveRegex = consoleEventRegex(self._Console_UserLeaveRegex, self._Console_UserLeaveRegexRaw);
this.Console_UserChatRegex = consoleEventRegex(self._Console_UserChatRegex, self._Console_UserChatRegexRaw);
this.__QueryPortName = ko.computed(() => {
var queryPort = self._PortMappings().find(p => p._PortType() == "Steam Query Port");
return queryPort ? queryPort.Ref() : "";
});
//Built from the query port when there is one, but an imported template's own format wins - most
//of them name a port the generator has no concept of, and blanking it takes the connect button
//off the instance.
this._Meta_EndpointURIFormatRaw = ko.observable("");
this.Meta_EndpointURIFormat = ko.computed(() => self._Meta_EndpointURIFormatRaw() != "" ? self._Meta_EndpointURIFormatRaw() : (self.__QueryPortName() != "" ? `steam://connect/{ip}:{GenericModule.App.Ports.$${self.__QueryPortName()}}` : ""));
this.__SanitizedName = ko.computed(() => self.Meta_DisplayName().replace(/\s+/g, "-").replace(/[^a-z\d-_]/ig, "").toLowerCase());
//AMP reads either the flag value or the names, and the templates are all written with names.
this.Meta_OS = ko.computed(() => [self._SupportsWindows() ? "Windows" : null, self._SupportsLinux() ? "Linux" : null].filter(name => name != null).join(", ") || "None");
this.Meta_ConfigManifest = ko.computed(() => self.__SanitizedName() + "config.json");
this.Meta_MetaConfigManifest = ko.computed(() => self.__SanitizedName() + "metaconfig.json");
this._Meta_PortsManifest = ko.computed(() => self.__SanitizedName() + "ports.json");
this._Meta_StagesManifest = ko.computed(() => self.__SanitizedName() + "updates.json");
this._Meta_PreStartManifest = ko.computed(() => self.__SanitizedName() + "prestart.json");
this.Meta_ConfigRoot = ko.computed(() => self.__SanitizedName() + ".kvp");
this.App_RootDir = ko.computed(() => `./${self.__SanitizedName()}/`);
this._SteamAppID = ko.computed(() => {
for (const stage of self._UpdateStages()) {
if (stage._UpdateSource() == "SteamCMD" && stage.UpdateSourceData() != "") {
return stage.UpdateSourceData();
}
}
return '0';
});
//Only the client App ID names something with a store page. It falls back to the server App ID for
//the SteamAppId environment variable, where the two are usually interchangeable - the store image
//below deliberately doesn't take that fallback.
this._SteamClientAppID = ko.computed(() => {
for (const stage of self._UpdateStages()) {
if (stage._UpdateSource() == "SteamCMD") {
var clientAppID = stage.UpdateSourceArgs() != "" ? stage.UpdateSourceArgs() : stage.UpdateSourceData();
if (clientAppID != "") { return clientAppID; }
}
}
return '';
});
//AMP builds the image URL as store_item_assets/steam/apps/<id>/header.jpg, which only exists for
//the game on the store - a dedicated server App ID has no store page, so pointing this at one
//leaves every instance of the application with a broken image.
this._SteamStoreAppID = ko.computed(() => {
for (const stage of self._UpdateStages()) {
if (stage._UpdateSource() == "SteamCMD" && stage.UpdateSourceArgs() != "") { return stage.UpdateSourceArgs(); }
}
return '';
});
//AMP's own default when a template has nothing better - it resolves to an image that exists,
//where an empty "url:" leaves the instance with a blank one.
this.Meta_DisplayImageSource = ko.computed(() => {
if (self._SteamStoreAppID() != '') { return 'steam:' + self._SteamStoreAppID(); }
if (self._DisplayImageSource() != '') { return 'url:' + self._DisplayImageSource(); }
if (self._Meta_DisplayImageSourceRaw() != '') { return self._Meta_DisplayImageSourceRaw(); }
return 'internal:UnknownApp';
});
this.App_BaseDirectory = ko.computed(() => self._SteamAppID() == 0 ? self.App_RootDir() + 'serverfiles/' : self.App_RootDir() + self._SteamAppID() + '/');
this.App_WorkingDir = ko.computed(() => self._SteamAppID() == 0 ? 'serverfiles' : self._SteamAppID());
this.App_ExecutableWin = ko.computed(() => self.App_WorkingDir() == "" ? self._WinExecutableName() : `${self.App_WorkingDir()}\\${self._WinExecutableName()}`);
this.App_ExecutableLinux = ko.computed(() => self._compatibility() == "None" ? (self.App_WorkingDir() == "" ? self._LinuxExecutableName() : `${self.App_WorkingDir()}/${self._LinuxExecutableName()}`) : (self._compatibility().substring(self._compatibility().length - 4) == "Xvfb" ? '/usr/bin/xvfb-run' : (self._compatibility() == "Wine" ? '/usr/bin/wine' : '1580130/proton')));
this._WinExecutableLinuxPath = ko.computed(() => self._WinExecutableName().replace(/\\/g, "/"));
this._App_LinuxCommandLineArgsCompat = ko.computed(() => self._compatibility() == "None" ? '' : (self._compatibility() == "WineXvfb" ? '-a wine \"./' + self._WinExecutableLinuxPath() + '\"' : (self._compatibility() == "ProtonXvfb" ? '-a \"{{$FullRootDir}}1580130/proton\" run \"./' + self._WinExecutableLinuxPath() + '\"' : (self._compatibility() == "Proton" ? 'run \"./' + self._WinExecutableLinuxPath() + '\"' : '\"./' + self._WinExecutableLinuxPath() + '\"'))));
this._App_LinuxCommandLineArgsInput = ko.observable("");
this.App_LinuxCommandLineArgs = ko.computed(() => (self._App_LinuxCommandLineArgsCompat() != '' ? self._App_LinuxCommandLineArgsCompat() + ' ' + self._App_LinuxCommandLineArgsInput() : self._App_LinuxCommandLineArgsInput()).trim());
this.App_Ports = ko.computed(() => `@IncludeJson[` + self._Meta_PortsManifest() + `]`);
this.App_UpdateSources = ko.computed(() => `@IncludeJson[` + self._Meta_StagesManifest() + `]`);
//Written inline while there are none, so a template without pre-start stages doesn't ship an
//extra file that only ever holds an empty list.
this.App_PreStartStages = ko.computed(() => self._PreStartStages().length > 0 ? `@IncludeJson[` + self._Meta_PreStartManifest() + `]` : `[]`);
/*
this.__BuildPortMappings = ko.computed(() => {
var data = {};
var allPorts = self._PortMappings();
var appPortNum = 1;
self.__QueryPortName("");
for (var i = 0; i < allPorts.length; i++) {
var portEntry = allPorts[i];
if (portEntry.PortType() == "2") //RCON
{
data["RemoteAdminPort"] = portEntry.Port();
}
else {
if (appPortNum > 3) { continue; }
var portName = "ApplicationPort" + appPortNum;
data[portName] = portEntry.Port();
appPortNum++;
if (portEntry.PortType() == "1") //QueryPort
{
self.__QueryPortName(portName);
}
}
}
return data;
});
*/
this.__SampleFormattedArgs = ko.computed(function () {
return self._AppSettings().filter(s => s.IncludeInCommandLine()).map(s => s.IsFlagArgument() ? s._CheckedValue() : self.App_CommandLineParameterFormat().format(s.ParamFieldName(), s.DefaultValue())).join(self.App_CommandLineParameterDelimiter());
});
/*
this.__SampleCommandLineFlags = ko.computed(function () {
var replacements = ko.toJS(self.__BuildPortMappings());
replacements["ApplicationIPBinding"] = "0.0.0.0";
replacements["FormattedArgs"] = self.__SampleFormattedArgs();
replacements["MaxUsers"] = "10";
replacements["RemoteAdminPassword"] = "r4nd0m-pa55w0rd-g0e5_h3r3";
return self.App_CommandLineArgs().template(replacements);
});
*/
this.__GenData = ko.computed(function () {
var data = [
{
"key": "Generated Name",
"value": self.__SanitizedName()
},
{
"key": "Config Root",
"value": self.Meta_ConfigRoot()
},
{
"key": "Settings Manifest",
"value": self.Meta_ConfigManifest()
},
{
"key": "Ports Manifest",
"value": self._Meta_PortsManifest()
},
{
"key": "Config Files Manifest",
"value": self.Meta_MetaConfigManifest()
},
{
"key": "Image Source",
"value": self.Meta_DisplayImageSource(),
"longValue": true
},
{
"key": "Root Directory",
"value": self.App_RootDir()
},
{
"key": "Base Directory",
"value": self.App_BaseDirectory()
},
{
"key": "Working Directory",
"value": self.App_WorkingDir()
},
{
"key": "Docker Image",
"value": self.Meta_SpecificDockerImage(),
"longValue": true
},
{
"key": "Compatibility",
"value": self._compatibility()
}
];
if (self._SupportsWindows()) {
data.push({
"key": "Windows Executable",
"value": self.App_ExecutableWin()
});
}
if (self._SupportsLinux()) {
data.push({
"key": "Linux Executable",
"value": self.App_ExecutableLinux()
});
}
return data;
});
//Action methods (add/remove/update)
this.__RemovePort = function (toRemove) {
self._PortMappings.remove(toRemove);
};
this.__AddPort = function () {
self._PortMappings.push(new portMappingViewModel(self.__NewPort(), self.__NewName(), self.__NewDescription(), self.__NewPortType(), self.__NewProtocol(), self));
//The type that was just used is no longer on offer, so the new-port row goes back to a custom
//one rather than being left pointing at something that has gone from the list.
self.__NewPortType("Custom Port");
self.__NewName("");
self.__NewDescription("");
};
this.__RemoveConfigFile = function (toRemove) {
self._ConfigFileMappings.remove(toRemove);
};
this.__AddConfigFile = function () {
self._ConfigFileMappings.push(new configFileMappingViewModel(self.__NewConfigFile(), self.__NewAutoMap(), self.__NewConfigType(), self));
};
this.__RemoveSetting = function (toRemove) {
self._AppSettings.remove(toRemove);
};
this.__EditSetting = function (toEdit) {
self.__IsEditingSetting(true);
self.__AddEditSetting(toEdit);
$("#addEditSettingModal").modal('show');
};
this.__AddSetting = function () {
self.__IsEditingSetting(false);
self.__AddEditSetting(new appSettingViewModel(self));
$("#addEditSettingModal").modal('show');
};
this.__DoAddSetting = function () {
self._AppSettings.push(self.__AddEditSetting());
$("#addEditSettingModal").modal('hide');
};
this.__CloseSetting = function () {
$("#addEditSettingModal").modal('hide');
};
//A stage only ever lives in one of the two lists, so removing it from the other is a no-op.
this.__RemoveStage = function (toRemove) {
self._UpdateStages.remove(toRemove);
self._PreStartStages.remove(toRemove);
};
this.__EditStage = function (toEdit) {
self.__IsEditingStage(true);
self.__AddEditStage(toEdit);
$("#addEditStageModal").modal('show');
};
this.__AddStageTo = function (list) {
self.__IsEditingStage(false);
self.__NewStageList(list);
self.__AddEditStage(new updateStageViewModel(self));
$("#addEditStageModal").modal('show');
};
this.__AddStage = () => self.__AddStageTo(self._UpdateStages);
this.__AddPreStartStage = () => self.__AddStageTo(self._PreStartStages);
this.__Errors = ko.validation.group(self);
this.__isValid = ko.computed(function () {
return self.__Errors().length == 0;
});
this.__DoAddStage = function () {
(self.__NewStageList() || self._UpdateStages).push(self.__AddEditStage());
$("#addEditStageModal").modal('hide');
};
this.__CloseStage = function () {
$("#addEditStageModal").modal('hide');
};
this.__Serialize = function () {
var asJS = ko.toJS(self);
var result = JSON.stringify(asJS, omitPrivateMembers);
return result;
};
//Keys that were renamed once it turned out they didn't match the module config - configurations
//exported before the rename are migrated on import so their values aren't silently dropped.
this.__RenamedKeys = {
"App_HasWritableConsole": "App_HasWriteableConsole",
"Meta_Prerequsites": "Meta_Prerequisites",
"Console_SleepMode": "Limits_SleepMode",
"Console_SleepOnStart": "Limits_SleepOnStart",
"Console_SleepDelayMinutes": "Limits_SleepDelayMinutes",
"Console_DozeDelay": "Limits_DozeDelay",
"Console_AutoRetryCount": "Limits_AutoRetryCount",
"Console_SleepStartThresholdSeconds": "Limits_SleepStartThresholdSeconds"
};
this.__Deserialize = function (inputData) {
var asJS = JSON.parse(inputData);
for (const [oldKey, newKey] of Object.entries(self.__RenamedKeys)) {
if (typeof asJS[oldKey] !== "undefined") {
if (typeof asJS[newKey] === "undefined") { asJS[newKey] = asJS[oldKey]; }
delete asJS[oldKey];
}
}
var ports = asJS._PortMappings || [];
var configFiles = asJS._ConfigFileMappings || [];
var settings = asJS._AppSettings || [];
var stages = asJS._UpdateStages || [];
var preStartStages = asJS._PreStartStages || [];
delete asJS._PortMappings;
delete asJS._ConfigFileMappings;
delete asJS._AppSettings;
delete asJS._UpdateStages;
delete asJS._PreStartStages;
self.__ApplyImportedData({ values: asJS, ports: ports, configFiles: configFiles, settings: settings, stages: stages, preStartStages: preStartStages });
};
//Fills the whole view model in from plain data using the same field names an export uses - shared
//by importing an exported configuration and importing a finished set of template files.
this.__ApplyImportedData = function (data) {
var ports = data.ports || [];
var configFiles = data.configFiles || [];
var settings = data.settings || [];
var stages = data.stages || [];
var preStartStages = data.preStartStages || [];
ko.quickmap.map(self, data.values || {});
self._PortMappings.removeAll();
//quickmap only maps one level deep, so each port rebuilds its own child ports - see
//portMappingViewModel.__ApplyImportedData.
var mappedPorts = [];
for (const portData of ports) {
var mappedPort = new portMappingViewModel("", "", "", "Custom Port", "0", self);
mappedPort.__ApplyImportedData(portData || {});
mappedPorts.push(mappedPort);
}
self._PortMappings.push.apply(self._PortMappings, mappedPorts);
self._ConfigFileMappings.removeAll();
var mappedConfigFiles = ko.quickmap.to(configFileMappingViewModel, configFiles, false, { __vm: self });
self._ConfigFileMappings.push.apply(self._ConfigFileMappings, mappedConfigFiles);
self._AppSettings.removeAll();
//quickmap only maps one level deep, so each setting rebuilds its own nested parts - see
//appSettingViewModel.__ApplyImportedData.
var mappedSettings = [];
for (const settingData of settings) {
var mappedSetting = new appSettingViewModel(self);
mappedSetting.__ApplyImportedData(settingData || {});
mappedSettings.push(mappedSetting);
}
self._AppSettings.push.apply(self._AppSettings, mappedSettings);
//The step type used to be stored as the generators own index rather than the name AMP reads,
//so an older configuration is brought onto the names before it's mapped.
var mapStages = stageData => ko.quickmap.to(updateStageViewModel, stageData.filter(stage => stage != null).map(stage => {
var mapped = Object.assign({}, stage);
if (typeof mapped._UpdateSource !== "undefined") { mapped._UpdateSource = normalizeUpdateSource(mapped._UpdateSource) || "None"; }
if (mapped._Passthrough == null || typeof mapped._Passthrough !== "object") { mapped._Passthrough = {}; }
return mapped;
}), false, { __vm: self });
self._UpdateStages.removeAll();
self._UpdateStages.push.apply(self._UpdateStages, mapStages(stages));
self._PreStartStages.removeAll();
self._PreStartStages.push.apply(self._PreStartStages, mapStages(preStartStages));
self.__NewPortType("Custom Port");
self._ExtraFiles.removeAll();
self._ExtraFiles.push.apply(self._ExtraFiles, data.extraFiles || []);
};
this.__IsExporting = ko.observable(false);
this.__Export = function () {
self.__IsExporting(true);
$("#importexporttextarea").val(self.__Serialize());
$("#importexporttextarea").attr("readonly", true);
$("#importExportDialog").modal("show");
autoSave();
};
this.__CopyExportToClipboard = function (data, element) {
navigator.clipboard.writeText($("#importexporttextarea").val());
setTimeout(() => $(element.target).tooltip('hide'), 2000);
};
this.__CloseImportExport = function () {
$("#importExportDialog").modal("hide");
};
this.__Import = function () {
self.__IsExporting(false);
$("#importexporttextarea").val("");
$("#importexporttextarea").prop("readonly", false);
$("#importExportDialog").modal("show");
};