-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapp.ts
More file actions
3958 lines (3698 loc) · 122 KB
/
app.ts
File metadata and controls
3958 lines (3698 loc) · 122 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
import transparentImg from "@img/app/transparent.webp";
import customImg from "@img/presets/custom.webp";
import highImg from "@img/presets/high.webp";
import lowImg from "@img/presets/low.webp";
import mediumHighImg from "@img/presets/medium-high.webp";
import ultraImg from "@img/presets/ultra.webp";
import { BlobReader, BlobWriter, ZipWriter } from "@zip.js/zip.js";
import { ScrollSpy, Tab } from "bootstrap";
import { del, entries, get, set, setMany } from "idb-keyval";
import LazyLoad, { type ILazyLoadInstance } from "vanilla-lazyload";
import { stringify } from "vdf-parser";
import TSON from "@utils/tson";
import fastClone from "./fastClone.ts";
import { getCrosshairPacks } from "./game.ts";
// Import custom crosshair utilities
let getCustomCrosshairForDownload: ((name: string) => Promise<{ vtf: Blob; vmt: Blob } | null>) | null = null;
// Dynamically import the custom crosshair module to avoid circular dependencies
(async () => {
try {
const module = await import("../components/items/CustomCrosshairUpload");
getCustomCrosshairForDownload = module.getCustomCrosshairForDownload;
} catch (err) {
console.error("Failed to load custom crosshair module:", err);
}
})();
const idbKeyval = {
get,
set,
del,
};
// https://stackoverflow.com/a/56842762
const MAX_COLOR = 256.0 - Number.EPSILON * 128;
function floatToByte(f) {
// HACK: handling legacy values
if (f >= 0.78 && f <= 0.784) {
return 200.0;
}
return Math.floor(f * MAX_COLOR);
}
export async function app() {
const downloadStatusEl = document.getElementById("download-status");
if (downloadStatusEl) {
// HACK: skip loading app if download status is mutated
if (downloadStatusEl.innerHTML === "") {
return;
}
downloadStatusEl.innerHTML = "";
downloadStatusEl.classList.remove("download-status-fill");
}
console.log("App loading...");
const parms = new URLSearchParams(window.location.search);
const dfirebase = import("firebase/compat/app")
.then(async (firebase) => {
await import("firebase/compat/auth");
await import("firebase/compat/firestore");
return firebase.default;
})
.then((firebase) => {
const firebaseConfig = {
apiKey: "AIzaSyBKDPeOgq97k5whdxL_Z94ak9jSfdjXU4E",
authDomain: "mastercomfig-app.firebaseapp.com",
projectId: "mastercomfig-app",
storageBucket: "mastercomfig-app.appspot.com",
messagingSenderId: "1055009628964",
appId: "1:1055009628964:web:6ad7954859d843050d49b1",
measurementId: "G-S0F8JT6ZQE",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
return firebase;
});
const dkeyboard = import("simple-keyboard/build/index.modern.js").then(
(Keyboard) => Keyboard.default,
);
// convenience format method for string
function formatString(str: string, ...args) {
return str.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] !== "undefined" ? args[number] : match;
});
}
function isValid(value) {
return value !== undefined || value !== null;
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
function getEl(element) {
const el = document.getElementById(element);
if (el) {
return el;
}
return undefined;
}
const memDB = {};
async function tryDBGet(key) {
try {
return await idbKeyval.get(key);
} catch (err) {
console.error(err);
return memDB[key];
}
}
async function tryDBSet(key, value) {
try {
await idbKeyval.set(key, value);
} catch (err) {
console.error(err);
memDB[key] = value;
}
}
async function tryDBDelete(key) {
try {
await idbKeyval.del(key);
} catch (err) {
console.error(err);
delete memDB[key];
}
}
// Current state of module selections
let selectedModules = {};
async function loadModules() {
const storedModulesDB = await tryDBGet("modules");
if (storedModulesDB) {
storedModules = storedModulesDB;
}
}
async function saveModules() {
const bHasModules = Object.keys(selectedModules).length > 0;
if (bHasModules) {
await tryDBSet("hasModules", true);
}
await tryDBSet("modules", selectedModules);
}
async function resetModules() {
await tryDBDelete("modules");
selectedModules = {};
storedModules = {};
}
// convenience proper case for modules
function properCaseModuleName(name) {
const split = name.split("_");
split.forEach((str, index, array) => {
array[index] = capitalize(str);
});
return split.join(" ");
}
// convenience proper case name or display for modules
function properCaseOrDisplayModuleName(module, name?) {
const displayName =
module?.display ?? properCaseModuleName(name ? name : module.name);
return displayName;
}
// Map preset IDs to display names for download
const presets = {
custom: {
name: "Custom",
description: "<h4>Skip setting quality options unless set by you</h4>",
},
ultra: {
name: "Ultra",
description: "<h4>Absolute maximum graphical quality</h4>",
},
high: {
name: "High",
description: "<h4>High graphical quality</h4>",
},
medium: {
name: "Medium",
description: "<h4>Medium graphical quality</h4>",
},
low: {
name: "Low",
description: "<h4>Low graphical quality</h4>",
},
};
// The only addons we can override when preset switches
const recommendableAddons = [
"no-footsteps",
"no-pyroland",
"no-soundscapes",
"no-tutorial",
];
// Set what addons we recommend for each preset
const recommendedAddons = new Map();
function setRecommendedAddons(id, values) {
// don't set non-recommendable addons
const addons = values.filter(
(addon) => recommendableAddons.indexOf(addon) !== -1,
);
if (addons.length != values.length) {
console.error("Attempted to set non-recommendable addon!");
}
recommendedAddons.set(id, addons);
}
setRecommendedAddons("custom", []);
setRecommendedAddons("ultra", []);
setRecommendedAddons("high", []);
setRecommendedAddons("medium", []);
setRecommendedAddons("low", ["no-pyroland", "no-soundscapes"]);
// End preset -> recommended addon mapping
// Base release URL
const releasesUrl = "https://github.com/mastercomfig/mastercomfig/releases";
// Release homepage
const releaseUrl = {
default: releasesUrl + "/{0}",
};
const assetsUrl = releaseUrl.default;
// Where a specific release's downloads come from
const releaseDownloadUrl = releasesUrl + "/download/{0}/";
// Prefix for mastercomfig files
const mastercomfigFileUrl = "mastercomfig-";
// Addon extension format string to download
const addonFileUrl = mastercomfigFileUrl + "addon-{1}.vpk";
const addonUrl = releaseDownloadUrl + addonFileUrl;
// Preset extension format string to download
const presetFileUrl = mastercomfigFileUrl + "base.vpk";
const presetUrl = releaseDownloadUrl + presetFileUrl;
// Current mastercomfig version, comes in from API
let version = null;
let latestVersion = null;
let userVersion = "latest";
// Current presets modules def
let presetModulesDef = {};
// Available module levels
let availableModuleLevels = {};
// Defined addons (found through parsing HTML)
const addons = [];
// Currently selected preset
let selectedPreset: string | null = null;
// Currently selected addons
let selectedAddons: string[] = [];
// Current state of autoexec binds
let selectedBinds = {};
// Overlaid bind layers
let bindLayers = {
gameoverrides: {},
};
// Current state of overrides
const selectedOverrides = {};
// Config contents
const configContentsRaw = {};
const contentsDefaulter = {
get: (target, name) => target?.[name] ?? "",
};
const configContents = new Proxy(configContentsRaw, contentsDefaulter);
// Data cache
let cachedData = null;
// Overrides for default game action binds
const customActionMappings = {};
// Addons which override action mappings
const addonActionMappings = {
"null-canceling-movement": {
"Move Forward": "+mf",
"Move Back": "+mb",
"Move Left": "+ml",
"Move Right": "+mr",
},
};
const bindConfigLayers = {
gameoverrides: "game_overrides.cfg",
scout: "scout.cfg",
soldier: "soldier.cfg",
pyro: "pyro.cfg",
demoman: "demoman.cfg",
heavy: "heavyweapons.cfg",
engineer: "engineer.cfg",
medic: "medic.cfg",
sniper: "sniper.cfg",
spy: "spy.cfg",
};
let storedModules = {};
await loadModules();
// Track if multi-download is active
let downloading = false;
function disableDownload(element) {
downloading = true; // Still retain in-progress even after switching preset
// Indicate not useable/in-progress
element.style.cursor = "not-allowed";
element.classList.add("disabled", "text-light");
}
function enableDownload(element) {
downloading = false; // Unlock updating preset test with new download
// Restore downloadable style
element.style.cursor = "pointer";
element.classList.remove("disabled", "text-light");
}
const forcedDirectInstall = parms.get("directinstall") === "1";
function isDirectInstallAllowed() {
return forcedDirectInstall && !!window.showDirectoryPicker;
}
let isDirectInstallUserEnabled = false;
async function isDirectInstallEnabled() {
if (!isDirectInstallAllowed()) {
return false;
}
//const userEnabled = await tryDBGet("enable-direct-install");
const userEnabled = isDirectInstallUserEnabled;
return userEnabled;
}
async function setDirectInstallEnabled(enable) {
//await tryDBSet("enable-direct-install", enable);
isDirectInstallUserEnabled = enable;
}
// Once user clicks to multi-download, we download and swap our behavior to in-progress
async function downloadClickEvent(id, fnGatherUrls) {
// Make sure we block clicks, since onclick state is not managed in offline mode
if (downloading) {
return;
}
// Mark we have started a download
const element = getEl(id);
element.onclick = null; // Ignore clicks
disableDownload(element);
const directInstall = await isDirectInstallEnabled();
element.innerHTML = element.innerHTML
.replace("Install", directInstall ? "Installing" : "Downloading")
.replace("Download", directInstall ? "Installing" : "Downloading")
.replace(" ", "…");
// Do the download once clicked
const urls = await fnGatherUrls();
// Only download if we have a download
if (urls.length > 0) {
await downloadUrls(urls, id, fnGatherUrls);
} else {
// We've gotten to the last in the download stack, so we're done
bindDownloadClick(id, fnGatherUrls);
}
}
function handleConnectivityChange() {
const element = getEl("vpk-dl");
if (!element) {
return;
}
// HACK: we are currently using a hack, by using the "downloading" variable
// to block downloads and track blocked download state.
if (navigator.onLine) {
enableDownload(element);
element.innerHTML = element.innerHTML.replace("(you are offline)", "");
} else {
disableDownload(element);
element.innerHTML += "(you are offline)";
}
}
function requireVersion(
major: number,
minor: number,
patch: number,
latest?: boolean,
dev?: boolean,
) {
if (import.meta.env.DEV && cachedData) {
let debugVersion = "" + major;
if (minor !== undefined) {
debugVersion += "." + minor;
}
if (patch !== undefined) {
debugVersion += "." + patch;
}
let isSupported = false;
for (const version of cachedData.v) {
if (version.startsWith(debugVersion)) {
isSupported = true;
}
}
if (!isSupported) {
// Check if even the latest version doesn't support the requirement
// If so, it's an upcoming version, currently unknown, so we shouldn't throw
const backupVersion = userVersion;
userVersion = cachedData.v[0];
const backupData = cachedData;
cachedData = null;
const fatal = requireVersion(major, minor, patch);
userVersion = backupVersion;
cachedData = backupData;
if (fatal) {
throw new Error("Requiring unsupported version: " + debugVersion);
} else {
console.log("Requiring unknown version: " + debugVersion);
}
}
}
if (userVersion === "dev") {
return dev === undefined ? true : dev;
}
if (userVersion === "latest") {
return latest === undefined ? true : latest;
}
const versions = [major, minor, patch];
const versionSplit = (version ?? userVersion).split(".");
for (let i = 0; i < versions.length; i++) {
const requiredVersion = versions[i];
if (!isValid(requiredVersion)) {
continue;
}
const currentVersion = parseInt(versionSplit[i], 10);
if (currentVersion < requiredVersion) {
return false;
}
if (currentVersion > requiredVersion) {
return true;
}
}
return true;
}
// This is what we do when multi-download is ready (init or after finish)
function bindDownloadClick(id, fnGatherUrls) {
// Reregister that we can respond to a click
const element = getEl(id);
element.onclick = async () => await downloadClickEvent(id, fnGatherUrls);
enableDownload(element);
element.innerHTML = element.innerHTML
.replace("Installing", gameDirectory ? "Install" : "Download")
.replace("Downloading", gameDirectory ? "Install" : "Download")
.replace("…", " ");
}
// Helper functions to format download URLs
function getDownloadUrl(url: string) {
url = url.replace(
"https://github.com/mastercomfig/mastercomfig/releases",
"https://api.comfig.app/download",
);
return `${url}`;
}
function getAddonUrl(id: string) {
return getDownloadUrl(formatString(addonUrl, version, id));
}
function getPresetUrl() {
return getDownloadUrl(formatString(presetUrl, version));
}
// End download URL helpers
let pendingObjectURLs = [];
async function downloadUrls(urls, id, fnGatherUrls) {
updateDownloadProgress(20, "Downloading files...");
const downloadFailures: {
url: { blob: Blob; name: string };
err: Error;
}[] = [];
if (customDirectory) {
try {
await Promise.all(
urls.map((url) =>
url.blob.catch((err) => downloadFailures.push({ url, err })),
),
);
if (downloadFailures.length) {
throw new Error(
`Download failures detected: ${downloadFailures
.map(({ url, err }) => `(${url.name}, ${err.toString()})`)
.join(",")}`,
);
} else {
updateDownloadProgress(100, "Done!");
}
} catch (err) {
console.error(err);
updateDownloadProgress(
0,
(downloadFailures.length > 3
? `Failed to download ${downloadFailures.length} files`
: `Failed to download ${downloadFailures
.map(({ url }) => url.name)
.join(", ")}`) + ". Please try again later.",
);
}
} else {
try {
let zipWriter = new ZipWriter(new BlobWriter("application/zip"), {
bufferedWrite: true,
});
let wroteFile = false;
await Promise.all(
urls.map((url) =>
Promise.resolve(url.blob)
.then((blob) => {
zipWriter.add(url.path, new BlobReader(blob));
wroteFile = true;
})
.catch((err) => downloadFailures.push({ url, err })),
),
);
if (wroteFile) {
const blobURL = URL.createObjectURL(await zipWriter.close());
zipWriter = null;
const link = document.createElement("a");
link.href = blobURL;
link.download = "mastercomfig.zip";
document.body.append(link);
link.dispatchEvent(
new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
}),
);
link.remove();
pendingObjectURLs.push(blobURL);
}
if (downloadFailures.length) {
throw new Error(
`Download failures detected: ${downloadFailures
.map(({ url, err }) => `(${url.name}, ${err.toString()})`)
.join(",")}`,
);
} else {
updateDownloadProgress(100, "Done!");
}
} catch (err) {
console.error(err);
updateDownloadProgress(
0,
(downloadFailures.length > 3
? `Failed to download ${downloadFailures.length} files`
: `Failed to download ${downloadFailures
.map(({ url, err }) => url.name)
.join(", ")}`) + ". Please try again later.",
);
}
}
// We're done
bindDownloadClick(id, fnGatherUrls);
// Once it's long past our time to download, remove the object URLs
setTimeout(() => {
for (const objectURL of pendingObjectURLs) {
URL.revokeObjectURL(objectURL);
}
pendingObjectURLs = [];
}, 120000);
}
async function verifyPermission(fileHandle, readWrite) {
const options = {};
if (readWrite) {
options.mode = "readwrite";
}
// Check if permission was already granted. If so, return true.
if ((await fileHandle.queryPermission(options)) === "granted") {
return true;
}
// Request permission. If the user grants permission, return true.
if ((await fileHandle.requestPermission(options)) === "granted") {
return true;
}
// The user didn't grant permission, so return false.
return false;
}
let gameDirectory = null;
let customDirectory = null;
let overridesDirectory = null;
let appDirectory = null;
let comfigCustomDirectory = null;
let scriptsDirectory = null;
let materialsDirectory = null;
let bindDirectInstall = true;
async function updateDirectInstall() {
const directInstall = await isDirectInstallEnabled();
if (!directInstall) {
getEl("game-folder-container").classList.add("d-none");
await restoreDirectoryInstructions();
gameDirectory = null;
customDirectory = null;
overridesDirectory = null;
appDirectory = null;
comfigCustomDirectory = null;
scriptsDirectory = null;
materialsDirectory = null;
updatePresetDownloadButton();
return;
}
getEl("game-folder-container").classList.remove("d-none");
if (
!(await tryDBGet("hide-game-folder-warning")) &&
getEl("game-folder-warning")
) {
getEl("game-folder-warning").classList.remove("d-none");
}
if (bindDirectInstall) {
bindDirectInstall = false;
if (getEl("game-folder-warning-btn")) {
getEl("game-folder-warning-btn").addEventListener("click", async () => {
await tryDBSet("hide-game-folder-warning", true);
});
}
getEl("game-folder-group").addEventListener("click", async () => {
await promptDirectory();
});
getEl("game-folder-clear").addEventListener("click", async (e) => {
e.stopPropagation();
await clearDirectory();
});
}
await updateDirectory();
updatePresetDownloadButton();
}
async function clearDirectoryInstructions() {
const instructionEls = document.querySelectorAll(".instructions-text");
for (const instructionEl of instructionEls) {
instructionEl.classList.add("d-none");
}
}
async function restoreDirectoryInstructions() {
const instructionEls = document.querySelectorAll(".instructions-text");
for (const instructionEl of instructionEls) {
instructionEl.classList.remove("d-none");
}
if (
(await tryDBGet("hide-game-folder-warning")) &&
getEl("game-folder-warning")
) {
getEl("game-folder-warning").classList.add("d-none");
}
}
const bannedDirectories = new Set([
"tf",
"custom",
"cfg",
"user",
"overrides",
"app",
]);
const silentBannedDirectories = new Set([""]);
function checkDirectory(directoryHandle) {
if (!directoryHandle.name) {
alert(
`Due to browser security policy, selected folders cannot be imported. To continue using Direct Install, please reselect your "Team Fortress 2" folder.`,
);
return false;
}
const name = directoryHandle.name;
let fail = bannedDirectories.has(name);
if (fail) {
alert(
`${name} is not a valid folder. To install to your game, please select the top-level "Team Fortress 2" folder.`,
);
} else {
fail = silentBannedDirectories.has(name);
}
return !fail;
}
async function promptDirectory() {
if (!isDirectInstallAllowed()) {
return;
}
try {
const directoryHandle = await window.showDirectoryPicker({
id: "tf2",
startIn: "desktop",
});
if (!directoryHandle) {
return;
}
if (!checkDirectory(directoryHandle)) {
return;
}
await tryDBSet("directory", directoryHandle);
await updateDirectory();
} catch (err) {
if (err.toString().includes("aborted")) {
return;
}
console.error("Directory prompt failed:", err);
}
}
// TODO: use this in more places, when things error out
async function clearDirectory() {
if (!isDirectInstallAllowed()) {
return;
}
await tryDBDelete("directory");
gameDirectory = null;
customDirectory = null;
overridesDirectory = null;
appDirectory = null;
getEl("game-folder-text").innerText =
"No folder chosen, Direct Install not enabled";
restoreDirectoryInstructions();
updatePresetDownloadButton();
}
async function updateDirectory() {
if (!isDirectInstallAllowed()) {
return;
}
try {
const directoryHandle = await tryDBGet("directory");
if (!directoryHandle) {
return;
}
if (!checkDirectory(directoryHandle)) {
clearDirectory();
return;
}
clearDirectoryInstructions();
gameDirectory = directoryHandle;
updatePresetDownloadButton();
getEl("game-folder-text").innerText =
`"${gameDirectory.name}" folder chosen, click to change`;
} catch (err) {
console.error("Get directory failed:", err);
}
}
async function accessDirectory() {
if (!isDirectInstallAllowed()) {
return true;
}
if (!gameDirectory) {
return true;
}
try {
if (!(await verifyPermission(gameDirectory, true))) {
console.log("Directory permission refused");
return false;
}
const tfDirectory = await gameDirectory.getDirectoryHandle("tf", {
create: true,
});
customDirectory = await tfDirectory.getDirectoryHandle("custom", {
create: true,
});
comfigCustomDirectory = await customDirectory.getDirectoryHandle(
"comfig-custom",
{
create: true,
},
);
scriptsDirectory = await comfigCustomDirectory.getDirectoryHandle(
"scripts",
{
create: true,
},
);
const materialsRootDirectory =
await comfigCustomDirectory.getDirectoryHandle("materials", {
create: true,
});
const vguiDirectory = await materialsRootDirectory.getDirectoryHandle(
"vgui",
{
create: true,
},
);
const replayDirectory = await vguiDirectory.getDirectoryHandle("replay", {
create: true,
});
materialsDirectory = await replayDirectory.getDirectoryHandle(
"thumbnails",
{
create: true,
},
);
const cfgDirectory = await tfDirectory.getDirectoryHandle("cfg", {
create: true,
});
overridesDirectory = await cfgDirectory.getDirectoryHandle("overrides", {
create: true,
});
const cfgCustomDirectory = await comfigCustomDirectory.getDirectoryHandle(
"cfg",
{
create: true,
},
);
appDirectory = await cfgCustomDirectory.getDirectoryHandle("app", {
create: true,
});
return true;
} catch (err) {
console.error("Get directory failed:", err);
clearDirectory();
return true;
}
}
let filesInUse = false;
const unlinkErrHandler = {
"could not be found": () => {},
"state had changed since it was read from disk": () => {
filesInUse = true;
},
"modifications are not allowed": () => {
filesInUse = true;
},
};
async function safeUnlink(name, directory) {
try {
await directory.removeEntry(name);
} catch (err) {
const errString = err.toString();
for (const key in unlinkErrHandler) {
if (errString.includes(key)) {
unlinkErrHandler[key]();
return;
}
}
console.error(`Failed deleting ${name}`, err);
}
}
async function getWritable(name, directory, skipDelete?) {
if (!directory) {
return null;
}
if (!skipDelete) {
await safeUnlink(name, directory);
}
const file = await directory.getFileHandle(name, { create: true });
try {
const writable = await file.createWritable();
return writable;
} catch (err) {
console.error(`getWritable for ${name} failed`, err);
return null;
}
}
function newFile(contents, name, directory) {
if (contents.length < 1) {
return null;
}
if (directory) {
return getWritable(name, directory).then((writable) =>
writable.write(contents).then(() => writable.close()),
);
} else {
const file = new File([contents], name, {
type: "application/octet-stream",
});
return file;
}
}
function wait(delay) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
async function checkFetch(response) {
if (!response.ok) {
const text = await response.text();
throw new Error(`${response.status}: ${text}`);
}
return response;
}
function fetchRetry(url, delay, tries, fetchOptions = {}) {
function onError(err) {
const triesLeft = tries - 1;
if (!triesLeft) {
throw err;
}
return wait(delay).then(() => {
return fetchRetry(url, delay * 2, triesLeft, fetchOptions);
});
}
return fetch(url, fetchOptions).then(checkFetch).catch(onError);
}
async function writeRemoteFile(url, directory, fetchOptions = {}) {
try {
const response = fetchRetry(url, 125, 6, fetchOptions);
const name = url.split("/").pop();
if (directory) {
const writable = await getWritable(name, directory, true);
return { name, blob: response.then((r) => r.body.pipeTo(writable)) };
}
return { name, blob: response.then((r) => r.blob()) };
} catch (err) {
console.error(`Failed fetching ${url}`, err);
return false;
}
}
function updateDownloadProgress(progress, status) {
getEl("download-progress-status").innerText = status;
const progressBar = getEl("download-progress-bar");
progressBar.style.width = `${progress}%`;
progressBar.setAttribute("aria-valuenow", progress);
}
const staticModules = {
sound: new Set(["low"]),
decals: new Set(["off"]),
};
async function getVPKDownloadUrls() {
// We need permissions for the directory
if (!(await accessDirectory())) {
return [];
}
let downloads = [];
getEl("download-progress-bar").classList.remove("d-none");
updateDownloadProgress(0, "Generating files...");
const presetUrl = getPresetUrl();
if (customDirectory) {
console.log("Using Direct Install.");
filesInUse = false;
// Clear out all existing files
const presetFile = presetFileUrl;
await safeUnlink(presetFile, customDirectory);
await safeUnlink(presetFile + ".sound.cache", customDirectory);
for (const addon of addons) {
const addonFile = formatString(addonFileUrl, null, addon);
await safeUnlink(addonFile, customDirectory);
await safeUnlink(addonFile + ".sound.cache", customDirectory);
}
if (filesInUse) {
alert(
"Files are in use. Please close TF2 before updating mastercomfig.",
);
return downloads;
}
} else {
console.log("Using ZIP download.");
}
const remoteDownloadHeaders = {
headers: {
Authorization: "EsohjoaThatooloaj1GuN0Pooc4Dah9eedee6zoa",
},
};
// Write preset file
const presetResult = await writeRemoteFile(
presetUrl,
customDirectory,
remoteDownloadHeaders,
);
if (presetResult) {
presetResult.path = `tf/custom/${presetResult.name}`;
// Then push our preset download
downloads.push(presetResult);
} else {
alert("Failed to download preset file. Please try again later.");
}