forked from ForgeVTT/fvtt-module-forge-vtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forgevtt-module.js
1906 lines (1813 loc) · 93.7 KB
/
forgevtt-module.js
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
/**
* Copyright (C) 2021 - The Forge VTT Inc.
* Author: Youness Alaoui <kakaroto@forge-vtt.com>
* This file is part of The Forge VTT.
*
* All Rights Reserved
*
* NOTICE: All information contained herein is, and remains
* the property of The Forge VTT. The intellectual and technical concepts
* contained herein are proprietary of its author and may be covered by
* U.S. and Foreign Patents, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from the author.
*/
const THE_FORGE_ASCII_ART = `
#
(%
%%%%% %%/
%%%%%%%%, %%%% *
.%%%%%%%%%% %%%%. %%%
#%%%%%%%%%%% %%%%%% %%%%%%,
(%%%%%%%%%%%%% %* ,%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%
#%%%%%%%%%%% %%%%%%%%%%, %%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%. %%%%%%%%%% %%%%%%% %%%%%%%%%
%%%%%%%%%%%# %%%% (%* %%#
(%%%%%%%%%
,%%# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%,
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%/
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%/
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%/
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
,%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Welcome to The Forge.
`;
class ForgeVTT {
static setupForge() {
// Verify if we're running on the forge or not, and set things up accordingly
this.usingTheForge = window.location.hostname.endsWith(".forge-vtt.com");
this.HOSTNAME = "forge-vtt.com";
this.DOMAIN = "forge-vtt.com";
this.UPLOAD_API_ENDPOINT = `https://upload.${ForgeVTT.DOMAIN}`;
this.FORGE_URL = `https://${this.HOSTNAME}`;
this.ASSETS_LIBRARY_URL_PREFIX = 'https://assets.forge-vtt.com/';
if (this.usingTheForge) {
// Welcome!
//console.log(THE_FORGE_ASCII_ART);
console.log('%c ', 'font-size:200px; background:url(https://forge-vtt.com/images/the-forge-logo-200x200.png) no-repeat;');
console.log('%cWelcome to the Forge!', 'font-size: 40px');
const parts = window.location.host.split(".");
this.gameSlug = parts[0];
this.HOSTNAME = parts.slice(1).join(".")
this.FORGE_URL = `https://${this.HOSTNAME}`;
this.GAME_URL = `https://${this.gameSlug}.${this.HOSTNAME}`;
this.LIVEKIT_SERVER_URL = `livekit.${this.HOSTNAME}`;
const local = this.HOSTNAME.match(/^(dev|local)(\.forge-vtt\.com)/);
if (!!local) {
this.ASSETS_LIBRARY_URL_PREFIX = `https://assets.${this.HOSTNAME}/`;
this.DOMAIN = this.HOSTNAME;
this.UPLOAD_API_ENDPOINT = "assets/upload";
this._usingDevServer = true;
}
// Use Cloudflare proxying for the websocket for all games
if (io?.connect) {
const ioConnect = io.connect;
io.connect = function(...args) {
if (typeof(args[0]) !== "string" && args[0]?.path === "/socket.io") {
args.unshift(ForgeVTT.FORGE_URL);
}
return ioConnect.apply(this, args);
}
}
}
}
static init() {
/* Test for Foundry bug where world doesn't load. Can be worse in 0.8.x and worse even if user has duplicate packs */
if (window.location.pathname == "/game" && isObjectEmpty(game.data)) {
console.warn("Detected empty world data. Reloading the page as a workaround for a Foundry bug");
setTimeout(() => window.location.reload(), 1000);
}
// Register Settings
game.settings.register("forge-vtt", "apiKey", {
name: "API Secret Key",
hint: "API Key to access the Forge assets library. Leave empty to use your own account while playing on The Forge. API Key is available in the My Account page.",
scope: "client",
config: true,
default: "",
type: String,
});
game.settings.register("forge-vtt", "lastBrowsedDirectory", {
name: "Last Browsed Directory",
hint: "Last Browsed Directory",
scope: "client",
default: "",
type: String,
});
// Fix critical 0.6.6 bug
if (ForgeVTT.foundryVersion === "0.6.6") {
TextureLoader.prototype._attemptCORSReload = async function (src, resolve, reject) {
try {
if (src.startsWith("https://assets.forge-vtt.com/"))
return reject(`Failed to load texture ${src}`);
if ( /https?:\/\//.test(src) ) {
const url = new URL(src);
const isCrossOrigin = url.origin !== window.location.origin;
if ( isCrossOrigin && !/\?cors-retry=/.test(url.search) ) {
url.search += `?cors-retry=${Date.now()}`;
return this.loadImageTexture(url.href).then(tex => {
this.setCache(src, tex);
resolve(tex);
}).catch(reject);
}
}
} catch (err) { }
return reject(`Failed to load texture ${src}`);
}
} else {
// Avoid the CORS retry for Forge assets library
const original = TextureLoader.prototype._attemptCORSReload;
if (original) {
TextureLoader.prototype._attemptCORSReload = async function (src, resolve, reject) {
try {
if (src.startsWith("https://assets.forge-vtt.com/"))
return reject(`Failed to load texture ${src}`);
} catch (err) {}
return original.call(this, src, resolve, reject).catch(reject);
}
}
// Foundry 0.8.x
if (isNewerVersion(ForgeVTT.foundryVersion, "0.8.0")) {
// we need to do this for BaseActor and BaseMacro as well because they override the two methods but don't call `super`
for (const klass of [foundry.abstract.Document, foundry.documents.BaseActor, foundry.documents.BaseMacro]) {
const preCreate = klass.prototype._preCreate;
klass.prototype._preCreate = async function (data, options, user) {
await ForgeVTT.findAndDestroyDataImages(this.documentName, data).catch(err => {});
return preCreate.call(this, ...arguments);
}
const preUpdate = klass.prototype._preUpdate;
klass.prototype._preUpdate = async function (changed, options, user) {
await ForgeVTT.findAndDestroyDataImages(this.documentName, changed).catch(err => {});
return preUpdate.call(this, ...arguments);
}
}
} else if (isNewerVersion(ForgeVTT.foundryVersion, "0.7.0")) {
const create = Entity.create;
Entity.create = async function (data, options) {
await ForgeVTT.findAndDestroyDataImages(this.entity, data).catch(err => {});
return create.call(this, ...arguments);
}
const update = Entity.update;
Entity.update = async function (data, options) {
await ForgeVTT.findAndDestroyDataImages(this.entity, data).catch(err => {});
return update.call(this, ...arguments);
}
}
}
if (this.usingTheForge) {
// Replacing MESSAGES allows Forge to set Forge specific strings before translations are loaded
ForgeVTT.replaceFoundryMessages();
// Translations are loaded after the init hook is called but may be used before the ready hook is called
// To ensure Forge strings are available we must also replace translations on renderNotifications
Hooks.once('renderNotifications', () => ForgeVTT.replaceFoundryTranslations());
if (window.location.pathname.startsWith("/join")) {
// Add return to setup for 0.7.x
this._addReturnToSetup();
// Add Return to Setup to 0.8.x (hook doesn't exist in 0.7.x)
Hooks.on('renderJoinGameForm', (obj, html) => this._addReturnToSetup(html));
} else if (window.location.pathname.startsWith("/setup")) {
// On v9, a request to install a package returns immediately and Foundry waits for the package installation
// to be done asynchronously via a websocket progress signal.
// Since we can do instant installations from the Bazaar and we can't intercept/inject signals into the websocket
// connection from the server side, we instead hijack the `Setup.post` on the client side so if a package is installed
// successfully and synchronsouly (a Bazaar install, not a protected content), we can fake a progress report
// of step "Package" which vends the API result.
if (isNewerVersion(ForgeVTT.foundryVersion, "9")) {
const origPost = Setup.post;
Setup.post = async function (data, ...args) {
const request = await origPost.call(this, data, ...args);
if (data.action === "installPackage") {
const response = await request.json();
// After reading the data, we need to replace the json method to return
// the json data, since it can only be called once
request.json = async () => response;
if (response.installed) {
// Send a fake 100% progress report with package data vending
this._onProgress({
action: data.action,
id: data.id || data.name,
name: data.name,
type: data.type || "module",
pct: 100,
step: "Package",
pkg: isNewerVersion(ForgeVTT.foundryVersion, "10") ? response.data : response
});
}
}
return request;
}
}
}
// Remove Configuration tab from /setup page
Hooks.on('renderSetupConfigurationForm', (setup, html) => {
html.find(`a[data-tab="configuration"],a[data-tab="update"]`).remove()
});
Hooks.on('renderSettings', (obj, html) => {
const forgevtt_button = $(`<button data-action="forgevtt"><i class="fas fa-home"></i> Back to The Forge</button>`);
forgevtt_button.click(() => window.location = `${this.FORGE_URL}/game/${this.gameSlug}`);
const join = html.find("button[data-action=logout]");
join.after(forgevtt_button);
// Change "Logout" button
if (ForgeAPI.lastStatus && ForgeAPI.lastStatus.autojoin) {
this._addJoinGameAs(join);
// Redirect the "Configure player" for autojoin games
$("#settings button[data-action=players]")
.attr("data-action", "forgevtt-players")
.off("click").on('click', ev => {
if (ForgeAPI.lastStatus.isOwner)
window.location.href = `${this.FORGE_URL}/setup#${this.gameSlug}&players`;
else
window.location.href = `${this.FORGE_URL}/game/${this.gameSlug}#players`;
});
} else {
join.html(`<i class="fas fa-door-closed"></i> Back to Join Screen`);
}
// Remove "Return to setup" for non tables
if (ForgeAPI.lastStatus && !ForgeAPI.lastStatus.table) {
html.find("button[data-action=setup]").hide();
}
});
Hooks.on('renderMainMenu', (obj, html) => {
if (!ForgeAPI.lastStatus) return;
if (ForgeAPI.lastStatus && !ForgeAPI.lastStatus.table) {
html.find("li.menu-world").removeClass("menu-world").addClass("menu-forge")
.html(`<i class="fas fa-home"></i><h4>Back to The Forge</h4>`)
.off('click').click(() => window.location = `${this.FORGE_URL}/game/${this.gameSlug}`);
}
if (ForgeAPI.lastStatus && ForgeAPI.lastStatus.autojoin) {
const join = html.find("li.menu-logout").removeClass("menu-logout").addClass("menu-join-as");
// Don't use game.user.isGM because we could be logged in as a player
if (!ForgeAPI.lastStatus.isGM) {
return join.hide();
} else {
join.html(`<i class="fas fa-random"></i><h4>Join Game As</h4>`)
.off('click').click(ev => this._joinGameAs());
}
} else {
html.find("li.menu-logout").html(`<i class="fas fa-door-closed"></i><h4>Back to Join Screen</h4>`);
}
});
// Hide Legacy users when user management is enabled
Hooks.on('renderPlayerList', (obj, html) => {
if (!ForgeAPI.lastStatus || !ForgeAPI.lastStatus.autojoin) return;
for (let player of html.find("li.player")) {
const user = game.users.get(player.dataset.userId);
if (user && !this._getUserFlag(user, "player")) {
player.remove();
}
}
});
// TODO: Probably better to just replace the entire Application and use API to get the invite link if user is owner
Hooks.on('renderInvitationLinks', (obj, html) => {
html.find("form p.notes").html(`Share the below invitation links with users who you wish to have join your game.<br/>
* The Invitation Link is for granting access to Forge users to this game (required for private games).<br/>
* The Game URL is the direct link to this game for public games or for players who already joined it.`);
html.find("label[for=local]").html(`<i class="fas fa-key"></i> Invitation Link`)
html.find("label[for=remote]").html(`<i class="fas fa-share-alt"></i> Game URL`)
if (isNewerVersion(ForgeVTT.foundryVersion, "9.0")) {
html.find(".show-hide").remove();
html.find("#remote-link").attr("type", "text").css({"flex": "3"});
}
obj.setPosition({ height: "auto" });
});
// Actor image is being updated. If token image falls back to bazaar default token, update it as well
Hooks.on("preUpdateActor", (actor, changed) => {
if (!changed?.img) return;
const defaultTokenImages = [CONST.DEFAULT_TOKEN];
defaultTokenImages.push(`${ForgeVTT.ASSETS_LIBRARY_URL_PREFIX}bazaar/core/${CONST.DEFAULT_TOKEN}`);
const systemId = game.system.id || game.system.data?.name;
switch (systemId) {
case "pf2e":
// Special default icons for pf2e
defaultTokenImages.push(`systems/pf2e/icons/default-icons/${actor.type}.svg`);
defaultTokenImages.push(`${ForgeVTT.ASSETS_LIBRARY_URL_PREFIX}bazaar/systems/pf2e/assets/icons/default-icons/${actor.type}.svg`);
break;
default:
break;
}
if (isNewerVersion(ForgeVTT.foundryVersion, "10") ) {
if (!changed.prototypeToken?.texture.src) {
if (!actor.prototypeToken.texture.src || defaultTokenImages.includes(actor.prototypeToken.texture.src)) {
setProperty(changed, "prototypeToken.texture.src", changed.img);
}
}
} else if (!changed.token?.img) {
if (!actor.data.token.img || defaultTokenImages.includes(actor.data.token.img)) {
setProperty(changed, "token.img", changed.img);
}
}
});
// Hook on any server activity to reset the user's activity detection
Hooks.on('createToken', () => this._onServerActivityEvent());
Hooks.on('updateToken', () => this._onServerActivityEvent());
Hooks.on('createActor', () => this._onServerActivityEvent());
Hooks.on('updateActor', () => this._onServerActivityEvent());
Hooks.on('createJournalEntry', () => this._onServerActivityEvent());
Hooks.on('updateJournalEntry', () => this._onServerActivityEvent());
Hooks.on('createChatMessage', () => this._onServerActivityEvent());
Hooks.on('canvasInit', () => this._onServerActivityEvent());
// Start the activity checker to track player usage and prevent people from idling forever
this._checkForActivity();
} else {
// Not running on the Forge
Hooks.on('renderSettings', (app, html, data) => {
const forgevtt_button = $(`<button class="forge-vtt" data-action="forgevtt" title="Go to ${this.FORGE_URL}"><img class="forge-vtt-icon" src="https://forge-vtt.com/images/the-forge-logo-200x200.png"> Go to The Forge</button>`);
forgevtt_button.click(() => window.location = `${this.FORGE_URL}/`);
const logoutButton = html.find("button[data-action=logout]");
logoutButton.after(forgevtt_button);
});
if (typeof(ForgeAssetSyncApp) !== "undefined") {
/* If we're not running on the Forge, then add the assets sync button */
game.settings.registerMenu("forge-vtt", "assetSyncApp", {
name: "Asset Sync (Beta)",
label: "Open Asset Sync",
icon: "fas fa-sync",
hint: "Open the Forge Asset Sync app to sync Forge Assets to this Foundry server",
restricted: true,
type: ForgeAssetSyncApp
});
}
}
}
static async setup() {
this.injectForgeModules();
if (game.modules.get('forge-vtt-optional')?.active) {
// Fix Infinite duration on some uncached audio files served by Cloudflare,
// See https://gitlab.com/foundrynet/foundryvtt/-/issues/5869#note_754029249
// Only override this on 0.8.x and v9 as this bug should presumably be fixed in v10
if (isNewerVersion(ForgeVTT.foundryVersion, "0.8.0") && !isNewerVersion(ForgeVTT.foundryVersion, "10")) {
const original = AudioContainer.prototype._createAudioElement;
AudioContainer.prototype._createAudioElement = async function(...args) {
const element = await original.call(this, ...args);
// After creating the element, if its duration was not calculated, force a time update by seeking to the end
if (element.duration != Infinity) return element;
// Workaround for Chrome bug which may not load the duration correctly
return new Promise(resolve => {
// In case of a "live source" which would never have a duration, timeout after 5 seconds
const timeoutId = setTimeout(() => resolve(element), 5000);
// Some mp3 files will signal an `ontimeupdate`
element.ontimeupdate = () => {
element.ondurationchange = undefined;
element.ontimeupdate = undefined;
clearTimeout(timeoutId);
element.currentTime = 0;
resolve(element);
}
// Some ogg files will signal `ondurationchange` since that time can never be reached
element.ondurationchange = () => {
element.ondurationchange = undefined;
element.ontimeupdate = undefined;
clearTimeout(timeoutId);
element.currentTime = 0;
resolve(element);
}
element.currentTime = 1e101;
});
}
}
// Add the Progressive Web App manifest and install button
if (this.usingTheForge) {
window.addEventListener('beforeinstallprompt', (event) => {
// Prevent the mini-infobar from appearing on mobile
event.preventDefault();
// Register the install menu the first time we get the event
if (!ForgeVTTPWA.installEvent) {
game.settings.registerMenu("forge-vtt-optional", "pwa", {
name: "Install Player Application",
label: "Install",
icon: "fas fa-download",
hint: "Installs a dedicated app to access your Forge game directly.",
restricted: false,
type: ForgeVTTPWA
});
}
ForgeVTTPWA.installEvent = event;
});
const link = document.createElement("LINK");
link.rel = "manifest"
link.href = `/pwa/manifest.json`;
link.crossOrigin = "use-credentials";
document.head.append(link);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(`/pwa/worker.js`, {scope: "/"}).catch(console.error);
}
}
}
// If user has avclient-livekit is enabled and is at least 0.4.1 (with custom server type support), then set it up to work with the Forge
if (this.usingTheForge &&
game.modules.get('avclient-livekit')?.active &&
isNewerVersion(game.modules.get('avclient-livekit').data.version, "0.5")) {
// hook on liveKitClientAvailable in 0.5.2+ as it gets called earlier and fixes issues seeing the Forge option if A/V isn't enabled yet
const hookName = isNewerVersion(game.modules.get('avclient-livekit').data.version, "0.5.1") ? "liveKitClientAvailable" : "liveKitClientInitialized";
// Foundry creates the client and connects it immediately without any hooks or anything to let us act on it
// So we need to set this up on the client class itself in the setup hook before webrtc is configured
Hooks.once(hookName, (client) => {
const liveKitClient = isNewerVersion(game.modules.get('avclient-livekit').data.version, "0.5.1") ? client : client._liveKitClient;
liveKitClient.addLiveKitServerType({
key: "forge",
label: "The Forge",
urlRequired: false,
usernameRequired: false,
passwordRequired: false,
url: this.LIVEKIT_SERVER_URL,
tokenFunction: this._getLivekitAccessToken.bind(this),
details: `<p>Connects to <a href="https://forums.forge-vtt.com/t/livekit-voice-and-video-chat/17792" target="_blank">The Forge's LiveKit</a> servers.</p><p>No setup necessary!</p><p><em>Requires a World Builder subscription</em></p>`
});
});
}
// For v10 and above, use Forge FilePicker to check the Assets Library when token image is wildcard
if (isNewerVersion(ForgeVTT.foundryVersion, "10")) {
const original = Actor._requestTokenImages;
Actor._requestTokenImages = async function (...args) {
const actor = game.actors.get(args[0]); // actorId
const target = actor?.prototypeToken?.texture?.src;
if (target) {
const wildcard = actor?.prototypeToken?.randomImg;
// Use 'data' source since the FilePicker will decide the right source to use
// based on whether the assets library prefix is there, or the path is in a module/system, etc...
const response = await ForgeVTT_FilePicker.browse("data", target, { wildcard }).catch(err => null);
if (response && response.files.length > 0) {
return response.files;
}
}
return original.apply(this, args);
}
}
}
static async ready() {
// If on The Forge, get the status/invitation url and start heartbeat to track player usage
if (this.usingTheForge) {
ForgeVTT.replaceFoundryTranslations();
game.data.addresses.local = "<Not available>";
const status = ForgeAPI.lastStatus || await ForgeAPI.status().catch(console.error) || {};
if (status.invitation)
game.data.addresses.local = `${this.FORGE_URL}/invite/${this.gameSlug}/${status.invitation}`;
game.data.addresses.remote = this.GAME_URL;
if (isNewerVersion(ForgeVTT.foundryVersion, "9.0"))
game.data.addresses.remoteIsAccessible = true;
if (status.annoucements)
this._handleAnnouncements(status.annoucements);
// Send heartbeats for in game players
if (window.location.pathname.startsWith("/game"))
this._sendHeartBeat(true);
// Remove "Return to setup" for non tables
if (!status.table) {
$("#settings button[data-action=setup]").hide();
}
if (status.autojoin) {
$("#settings button[data-action=players]")
.attr("data-action", "forgevtt-players")
.off("click").click(ev => {
if (status.isOwner)
window.location.href = `${this.FORGE_URL}/setup#${this.gameSlug}&players`;
else
window.location.href = `${this.FORGE_URL}/game/${this.gameSlug}#players`;
});
this._addJoinGameAs();
}
if (isNewerVersion(ForgeVTT.foundryVersion, "10")) {
// On v10, make The Forge module appear enabled
const moduleConfiguration = game.settings.get("core", "moduleConfiguration");
if (!moduleConfiguration["forge-vtt"]) {
moduleConfiguration["forge-vtt"] = true;
game.settings.set("core", "moduleConfiguration", moduleConfiguration);
}
}
const lastBrowsedDir = game.settings.get("forge-vtt", "lastBrowsedDirectory");
if (lastBrowsedDir && FilePicker.LAST_BROWSED_DIRECTORY === ForgeVTT.ASSETS_LIBRARY_URL_PREFIX) {
FilePicker.LAST_BROWSED_DIRECTORY = lastBrowsedDir;
}
}
}
static injectForgeModules() {
// If we're running on the forge and there is no loaded module, then add a fake module
// so the user can change the settings.
if (!game.modules.get('forge-vtt')) {
const data = {
author: "The Forge",
authors: [],
bugs: "",
changelog: "",
compatibleCoreVersion: ForgeVTT.foundryVersion,
coreTranslation: false,
dependencies: [],
description: "<p>This module allows players to browse their Forge Assets Library from their local games.</p><p>This module is automatically enabled for users on The Forge and is therefore not required when running your games on The Forge website.</p>",
download: "",
esmodules: [],
flags: {},
keywords: [],
languages: [],
license: "The Forge VTT Inc. - All Rights Reserved",
manifest: "",
minimumCoreVersion: undefined,
id: "forge-vtt",
minimumSystemVersion: undefined,
name: "forge-vtt",
packs: [],
protected: false,
readme: "",
scripts: [],
socket: false,
styles: [],
system: [],
title: "The Forge",
url: "https://forge-vtt.com",
version: "1.10",
availability: 0,
unavailable: false
};
let moduleData = data;
if (isNewerVersion(ForgeVTT.foundryVersion, "10")) {
game.modules.set('forge-vtt', new Module({
active: true,
locked: true,
unavailable: false,
compatibility: {
minimum: "10",
verified: ForgeVTT.foundryVersion
},
...data
}));
// v10 will display it in the manage modules section, so we should make it a requirement of the world.
game.world.relationships.requires.add({type: "module", id: "forge-vtt"});
} else {
if (isNewerVersion(ForgeVTT.foundryVersion, "0.8.0")) {
moduleData = new foundry.packages.ModuleData(data);
}
let module = {
active: true,
availability: 0,
esmodules: [],
id: "forge-vtt",
languages: [],
locked: true,
packs: [],
path: "/forge-vtt/Data/modules/forge-vtt",
scripts: [],
styles: [],
type: "module",
unavailable: false,
data: moduleData
}
game.modules.set('forge-vtt', module);
}
}
if (!game.modules.get('forge-vtt-optional') && isNewerVersion(ForgeVTT.foundryVersion, "0.8.0")) {
const settings = game.settings.get("core", ModuleManagement.CONFIG_SETTING) || {};
const data = {
id: "forge-vtt-optional",
name: "forge-vtt-optional",
title: "The Forge: More Awesomeness",
description: "<p>This is an optional module provided by The Forge to fix various issues and bring its own improvements to Foundry VTT. You can read more about it <a href='https://forums.forge-vtt.com/t/what-is-the-forge-optional-module/16836' target='_blank'>here</a>.</p>",
version: "1.1",
minimumCoreVersion: "0.8.0",
compatibleCoreVersion: "9",
scripts: [],
esmodules: [],
styles: [],
packs: [],
languages: [],
authors: [],
keywords: [],
socket: false,
url: "https://forge-vtt.com",
manifest: "",
download: "",
license: "",
readme: "",
bugs: "",
changelog: "",
author: "The Forge",
availability: 0,
unavailable: false
};
if (isNewerVersion(ForgeVTT.foundryVersion, "10")) {
game.modules.set('forge-vtt-optional', new Module({
active: settings["forge-vtt-optional"] || false,
availability: 0,
type: 'module',
unavailable: false,
path: "/forge-vtt/data/modules/forge-vtt",
compatibility: {
minimum: "10",
verified: ForgeVTT.foundryVersion
},
...data
}));
game.data.modules.push(data);
} else {
let module = {
active: settings["forge-vtt-optional"] || false,
availability: 0,
esmodules: [],
id: "forge-vtt-optional",
languages: [],
locked: true,
packs: [],
path: "",
scripts: [],
styles: [],
type: 'module',
unavailable: false,
data: new foundry.packages.ModuleData(data)
}
game.modules.set('forge-vtt-optional', module);
game.data.modules.push(module);
}
}
}
static async _getLivekitAccessToken(apiKey, secretKey, roomName, userName, metadata) {
const status = ForgeAPI.lastStatus || await ForgeAPI.status();
if (!status.supportsLivekit) {
ui.notifications.error("This server does not have support for Livekit");
return "";
}
if (!status.canUseLivekit) {
ui.notifications.error("Livekit support is a feature exclusive to the World Builder tier. Please upgrade your subscription and try again.");
return "";
}
const response = await ForgeAPI.call(null, {
action: "get-livekit-credentials",
room: roomName,
username: userName,
metadata
}).catch(err => null);
if (response && response.token) {
if (response.server && this.LIVEKIT_SERVER_URL !== response.server) {
this.LIVEKIT_SERVER_URL = response.server;
// Update the url configuration in livekit avclient custom server type
if (game.webrtc.client._liveKitClient?.liveKitServerTypes?.forge?.url) {
game.webrtc.client._liveKitClient.liveKitServerTypes.forge.url = this.LIVEKIT_SERVER_URL;
}
}
return response.token;
}
ui.notifications.error(`Error retreiviving Livekit credentials: ${(response && response.error) || "Unknown Error"}.`);
return "";
}
/**
* MESSAGES[i].message represents the key that will be called from Foundry translation files
* If the key is missing from translation files, the key itself will return as default translation value
*/
static replaceFoundryMessages() {
if (!MESSAGES) return;
const forgeStrings = this._getForgeStrings();
for (let i = 0; i < MESSAGES.length; i++) {
const key = MESSAGES[i].message;
if (forgeStrings[key] !== undefined) {
MESSAGES[i].message = forgeStrings[key];
}
}
}
/**
* Replace Foundry translations values with Forge specific strings
* Run after Foundry initialized abd translations are loaded, but before values are referenced
*/
static replaceFoundryTranslations() {
if (!game?.i18n?.translations) return;
if (this._translationsInitialized) return;
mergeObject(game.i18n.translations, this._getForgeStrings());
this._translationsInitialized = true;
}
static async _addReturnToSetup(html) {
// Foundry 0.8.x doesn't name the divs anymore, so we have to guess it.
const joinForm = html ? $(html.find("section .left > div")[0]) : $("#join-form");
// If we can't find it, hen html is null and we're running on 0.8.x, so let the onRenderJoinGame call us again
if (joinForm.length === 0) return;
const status = ForgeAPI.lastStatus || await ForgeAPI.status().catch(console.error) || {};
// Add return to setup
if (status.isOwner && status.table) {
const button = $(`<button type="button" name="back-to-setup"><i class="fas fa-home"></i> Return to Setup</button>`);
joinForm.append(button)
button.click(ev => {
// Use invalid slug world to cause it to ignore world selection
ForgeAPI.call('game/idle', { game: this.gameSlug, force: true, world: "/"}, { cookieKey: true})
.then(() => window.location = "/setup")
.catch(err => console.error);
})
}
// Add return to the forge
const forgevtt_button = $(`<button type="button" name="back-to-forge-vtt"><i class="fas fa-hammer"></i> Back to The Forge</button>`);
forgevtt_button.click(() => window.location = `${this.FORGE_URL}/games`);
joinForm.append(forgevtt_button)
// Remove "Return to Setup" section from login screen when the game is not of type Table.
if (!status.table || status.isOwner) {
// Foundry 0.8.x doesn't name the divs anymore, so we have to guess it.
const shutdown = html ? $(html.find("section .left > div")[2]) : $("form#shutdown");
shutdown.parent().css({"justify-content": "start"});
shutdown.hide();
}
}
static _addJoinGameAs(join) {
if (!join)
join = $("#settings button[data-action=logout]");
// Don't use game.user.isGM because we could be logged in as a player
if (!ForgeAPI.lastStatus.isGM)
return join.hide();
join.attr("data-action", "join-as").html(`<i class="fas fa-random"></i> Join Game As`);
join.off('click').click(ev => this._joinGameAs());
}
static _joinGameAs() {
const options = [];
// Could be logged in as someone else
const gameusers = (isNewerVersion(ForgeVTT.foundryVersion, "9.0") ? game.users : game.users.entities);
if (ForgeAPI.lastStatus.isGM && !this._getUserFlag(game.user, "temporary")) {
const myUser = gameusers.find(user => this._getUserFlag(user, "player") === ForgeAPI.lastStatus.user) || game.user;
options.push({name: `${myUser.name} (As Player)`, role: 1, id: "temp"});
}
for (const user of gameusers) {
if (user.isSelf) continue;
const id = this._getUserFlag(user, "player");
const temp = this._getUserFlag(user, "temporary");
if (id && !temp)
options.push({name: user.name, role: user.role, id});
}
const roleToImgUrl = (role) => {
switch(role) {
case 4:
return "/images/dice/red-d20.png";
case 3:
return "/images/dice/cyan-d12.png";
case 2:
return "/images/dice/purple-d10.png";
case 1:
return "/images/dice/green-d8.png";
default:
return null;
}
}
const roleToImg = (role) => {
const img = roleToImgUrl(role);
if (!img) return '';
return `<img src="${ForgeVTT.FORGE_URL}${img}" width="24" style="border: 0px; vertical-align:middle;"/>`;
}
const buttons = options.map(p => `<div><button data-join-as="${p.id}">${p.name} ${roleToImg(p.role)}</button></div>`).join("");
// Close the main menu if it was open
ui.menu.close();
new Dialog({
title: "Join Game As",
content: `<p>Select a player to re-join the game as : </p>${buttons}`,
buttons: {
},
render: html => {
for (const button of html.find("button[data-join-as]")) {
const as = button.dataset.joinAs;
$(button).click(ev => window.location.href = `/join?as=${as}`)
}
},
}, {height: "auto"}).render(true);
}
static async _checkForActivity() {
this.activity = {
lastX: 0,
lastY: 0,
mouseX: 0,
mouseY: 0,
keyUp: false,
lastActive: Date.now(),
focused: true,
reports: [],
events: [],
active: true
};
$(window).blur(() => {
this.activity.focused = false
}).focus(() => {
this.activity.focused = true
}).on('mousemove', (ev) => {
this.activity.mouseX = ev.clientX;
this.activity.mouseT = ev.clientY;
}).on('keyup', (ev) => {
this.activity.keyUp = true;
});
setInterval(() => this._addActivityReport(), ForgeVTT.ACTIVITY_CHECK_INTERVAL);
setInterval(() => this._updateActivity(), ForgeVTT.ACTIVITY_UPDATE_INTERVAL);
}
static _addActivityReport() {
const report = {
mouseMoved: this.activity.lastX !== this.activity.mouseX || this.activity.lastY !== this.activity.mouseY,
keyboardUsed: this.activity.keyUp,
focused: this.activity.focused
};
//console.log("New activity report : ", report);
this.activity.lastX = this.activity.mouseX;
this.activity.lastY = this.activity.mouseY;
this.activity.keyUp = false;
this.activity.reports.push(report);
}
static _updateActivity() {
const minEvents = this.activity.reports.length / 2;
const numEvents = this.activity.reports.reduce((acc, report) => {
// Ignore window unfocused for now since if the player moved the mouse/keyb, it's enough
// and they might have focus on a separate window (Beyond 20)
if (report.mouseMoved || report.keyboardUsed)
acc++;
return acc;
}, 0);
this.activity.active = numEvents >= minEvents;
// keep the last 100 activity events
this.activity.events = this.activity.events.concat([this.activity.active]).slice(-100);
this.activity.reports = [];
if (this.activity.active) {
this.activity.lastActive = Date.now();
} else {
this._verifyInactivePlayer()
}
}
static _onServerActivityEvent() {
// canvasInit gets called before ready hook
if (!this.activity) return;
this.activity.lastActive = Date.now();
}
static async _verifyInactivePlayer() {
const inactiveFor = Date.now() - this.activity.lastActive;
let inactiveThreshold = ForgeVTT.GAME_INACTIVE_THRESHOLD;
if (["/game", "/stream"].includes(window.location.pathname) && game?.users) {
if (game.users.filter(u => u.active).length <= 1)
inactiveThreshold = ForgeVTT.GAME_SOLO_INACTIVE_THRESHOLD;
} else {
inactiveThreshold = ForgeVTT.OTHER_INACTIVE_THRESHOLD;
}
if (inactiveFor > inactiveThreshold) {
await ForgeAPI.call(null, { action: "inactive", path: window.location.pathname, inactivity: inactiveFor }).catch(console.error);
window.location = `https://${this.HOSTNAME}/game/${this.gameSlug}`;
} else if (inactiveFor > inactiveThreshold - ForgeVTT.IDLE_WARN_ADVANCE) {
this._warnInactivePlayer(inactiveFor);
}
}
static _tsToH(ts) {
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
const time = ts > HOUR ? `${Math.round(ts / HOUR)} hour` : `${Math.round(ts / MINUTE)} minute`;
const plural = ts > HOUR ? Math.round(ts / HOUR) > 1 : Math.round(ts / MINUTE) > 1;
return `${time}${plural ? "s" : ""}`;
}
static _warnInactivePlayer(inactivity) {
if (this.activity.warning) return;
const redirectTS = new Date(Date.now() + ForgeVTT.IDLE_WARN_ADVANCE);
const time = new Intl.DateTimeFormat('default', {
hour12: true,
hour: 'numeric',
minute: 'numeric'
}).format(redirectTS);
this.activity.warning = new Dialog({
title: "The Forge",
content: `<div>You have been inactive for ${this._tsToH(inactivity)}.</div>
<div>In case this is wrong, please confirm that you are still active or you will be redirected to the Forge main website in ${ this._tsToH(ForgeVTT.IDLE_WARN_ADVANCE)} (${time}).</div>`,
buttons: {
active: {
label: "I'm here!",
callback: () => {
this.activity.events.push(true);
this.activity.lastActive = Date.now();
this.activity.warning = null;
}
},
inactive: {
label: "You're right, take me home",
callback: () => {
window.location = `https://${this.HOSTNAME}/game/${this.gameSlug}`;
}
}
}
}).render(true)
}
// Consider the user active if they had one activity event in the last HEARTBEAT_ACTIVE_IN_LAST_EVENTS events
static _getActivity() {
return this.activity.events.slice(-1 * ForgeVTT.HEARTBEAT_ACTIVE_IN_LAST_EVENTS).some(active => active);
}
static async _sendHeartBeat(force) {
const active = force || this._getActivity();
const response = await ForgeAPI.call(null, { action: "heartbeat", active }).catch(console.error) || {};
if (response.announcements)
this._handleAnnouncements(response.announcements);
// Redirect back in case of an expired demo license
if (response.demo !== undefined) {
if (response.demo < 0) {
setTimeout(() => window.location = `https://${this.HOSTNAME}/game/${this.gameSlug}`, 2500);
} else {
if (this._demoTimeout)
clearTimeout(this._demoTimeout);
this._demoTimeout = setTimeout(this._sendHeartBeat.bind(this), response.demo);
}
}
// Send a heartbeat every 10 minutes;
setTimeout(this._sendHeartBeat.bind(this), ForgeVTT.HEARTBEAT_TIMER);
}
static _handleAnnouncements(announcements) {
this.displayedAnnouncements = this.displayedAnnouncements || [];
const newAnnouncements = Object.keys(announcements).filter(id => !this.displayedAnnouncements.includes(id));
for (let id of newAnnouncements) {
ui.notifications.info(announcements[id], { permanent: true });
this.displayedAnnouncements.push(id);
}
}
// Need to use this because user.getFlag can error out if we get the forge API to respond before the init hook is called
// causing the error of "invalid scope"
static _getUserFlag(user, key) {
return getProperty(user.data.flags, `forge-vtt.${key}`);
}
/**
* Finds data URL for images from various entities data and replaces them a valid
* assets library URL.
* This is a counter to the issue with Dungeon Alchemist that exports scenes with the
* base64 encoded image in the json, that users import into Foundry. Causing databases
* to quickly bloat beyond what Foundry can handle.
*/
static async findAndDestroyDataImages(entityType, data) {
switch (entityType) {
case 'Actor':
data.img = await this._uploadDataImage(entityType, data.img);
if (data.prototypeToken) {
data.prototypeToken = await this.findAndDestroyDataImages('Token', data.prototypeToken);
} else if (data.token) {
data.token = await this.findAndDestroyDataImages('Token', data.token);
}
if (data.items) {
data.items = await Promise.all(data.items.map(item => this.findAndDestroyDataImages('Item', item)));
}
if (data.data?.details?.biography?.value) {
data.data.details.biography.value = await this._migrateDataImageInHTML(entityType, data.data.details.biography.value);
}
break;
case 'Token':
if (data.texture) {
data.texture.src = await this._uploadDataImage(entityType, data.texture.src);
} else {
data.img = await this._uploadDataImage(entityType, data.img);
}
break;
case 'JournalEntry':
if (data.pages) {
data.pages = await Promise.all(data.pages.map(page => this.findAndDestroyDataImages('JournalEntryPage', page)));
} else {
data.img = await this._uploadDataImage(entityType, data.img);
data.content = await this._migrateDataImageInHTML(entityType, data.content);
}
break;
case 'JournalEntryPage':
data.src = await this._uploadDataImage(entityType,data.src);
data.text.content = await this._migrateDataImageInHTML(entityType, data.text.content);
data.text.markdown = await this._migrateDataImageInMarkdown(entityType, data.text.markdown);
break;