-
Notifications
You must be signed in to change notification settings - Fork 62
/
CoreFunctions.js
1541 lines (1388 loc) · 58.5 KB
/
CoreFunctions.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
/** CoreFunctions.js
* A place for functions that are required for proper functionality
* This is loaded from Load.js and LoadCharacterPage.js
* so be thoughtful about which functions go in this file
* */
/** The first time we load, collect all the things that we need.
* Remember that this is injected from both Load.js and LoadCharacterPage.js
* If you need to add things for when AboveVTT is actively running, do that in Startup.js
* If you need to add things for when the CharacterPage is running, do that in CharacterPage.js
* If you need to add things for all of the above situations, do that here */
$(function() {
window.EXPERIMENTAL_SETTINGS = {};
window.EXTENSION_PATH = $("#extensionpath").attr('data-path');
window.AVTT_VERSION = $("#avttversion").attr('data-version');
$("head").append('<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"></link>');
$("head").append('<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" />');
if (is_encounters_page()) {
window.DM = true; // the DM plays from the encounters page
dmAvatarUrl = $('#site-bar').attr('user-avatar');
} else if (is_campaign_page()) {
// The owner of the campaign (the DM) is the only one with private notes on the campaign page
window.DM = $(".ddb-campaigns-detail-body-dm-notes-private").length === 1;
} else {
window.DM = false;
}
});
const async_sleep = m => new Promise(r => setTimeout(r, m));
const charactersPageRegex = /\/characters\/\d+/;
const tabCommunicationChannel = new BroadcastChannel('aboveVttTabCommunication');
function mydebounce(func, timeout = 800){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(async () => {await func.apply(this, args); }, timeout);
};
}
function find_currently_open_character_sheet() {
if (is_characters_page()) {
return window.location.pathname;
}
let sheet;
$("#sheet").find("iframe").each(function () {
const src = $(this).clone().attr("src");
if (src != "") {
sheet = src;
}
})
return sheet;
}
function monitor_console_logs() {
// slightly modified version of https://stackoverflow.com/a/67449524
if (console.concerningLogs === undefined) {
console.concerningLogs = [];
console.otherLogs = [];
function TS() {
return (new Date).toISOString();
}
function addLog(log) {
if (log.type !== 'log' && log.type !== 'debug') { // we don't currently track debug, but just in case we add them
console.concerningLogs.unshift(log);
if (console.concerningLogs.length > 100) {
console.concerningLogs.length = 100;
}
if (get_avtt_setting_value("aggressiveErrorMessages")) {
showError(new Error(`${log.type} ${log.message}`), ...log.value);
}
} else {
console.otherLogs.unshift(log);
if (console.otherLogs.length > 100) {
console.otherLogs.length = 100;
}
}
}
window.addEventListener('error', function(event) {
addLog({
type: "exception",
timeStamp: TS(),
value: [event.message, `${event.filename}:${event.lineno}:${event.colno}`, event.error?.stack]
});
return false;
});
window.addEventListener('onunhandledrejection', function(event) {
addLog({
type: "exception",
timeStamp: TS(),
value: [event.message, `${event.filename}:${event.lineno}:${event.colno}`, event.error?.stack]
});
return false;
});
window.onerror = function (error, url, line, colno) {
addLog({
type: "exception",
timeStamp: TS(),
value: [error, `${url}:${line}:${colno}`]
});
return false;
}
window.onunhandledrejection = function (event) {
addLog({
type: "promiseRejection",
timeStamp: TS(),
value: [event.message, `${event.filename}: ${event.lineno}:${event.colno}`, event.error?.stack]
});
}
function hookLogType(logType) {
const original = console[logType].bind(console);
return function() {
addLog({
type: logType,
timeStamp: TS(),
value: Array.from(arguments)
});
// Function.prototype.apply.call(console.log, console, arguments);
original.apply(console, arguments);
}
}
// we don't care about debug logs right now
['log', 'error', 'warn'].forEach(logType=> {
console[logType] = hookLogType(logType)
});
}
}
async function openDB() {
const DBOpenRequest = await indexedDB.open(`AboveVTT-${window.gameId}`, 2); // version 2
DBOpenRequest.onsuccess = (e) => {
window.gameIndexedDb = DBOpenRequest.result;
};
DBOpenRequest.onerror = (e) => {
console.warn(e);
};
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
if(!db.objectStoreNames?.contains('exploredData')){
const objectStore = db.createObjectStore("exploredData", { keyPath: "exploredId" });
}
if(!db.objectStoreNames?.contains('journalData')){
const objectStore2 = db.createObjectStore("journalData", { keyPath: "journalId" });
}
};
const DBOpenRequest2 = await indexedDB.open(`AboveVTT-Global`, 2);
DBOpenRequest2.onsuccess = (e) => {
window.globalIndexedDB = DBOpenRequest2.result;
};
DBOpenRequest2.onerror = (e) => {
console.warn(e);
};
DBOpenRequest2.onupgradeneeded = (event) => {
const db = event.target.result;
if(!db.objectStoreNames?.contains('customizationData')){
const objectStore = db.createObjectStore("customizationData", { keyPath: "customizationId" });
}
if(!db.objectStoreNames?.contains('journalData')){
const objectStore2 = db.createObjectStore("journalData", { keyPath: "journalId" });
}
};
}
function deleteDB(){
let d = confirm("DELETE ALL LOCAL EXPLORE DATA (CANNOT BE UNDONE)");
if (d === true) {
const objectStore = gameIndexedDb.transaction([`exploredData`], "readwrite").objectStore('exploredData');
const objectStoreRequest = objectStore.clear();
objectStoreRequest.onsuccess = function(event) {
exploredCanvas = document.getElementById("exploredCanvas");
if(exploredCanvas != undefined){
let exploredCanvasContext = exploredCanvas.getContext('2d');
exploredCanvasContext.fillStyle = "black";
exploredCanvasContext.fillRect(0,0,exploredCanvas.width,exploredCanvas.height);
}
redraw_light();
alert('This campaigns local explored vision data has been cleared.')
};
}
}
function deleteCurrentExploredScene(){
let d = confirm("DELETE CURRENT SCENE EXPLORE DATA (CANNOT BE UNDONE)");
if (d === true) {
deleteExploredScene(window.CURRENT_SCENE_DATA.id)
}
}
function deleteExploredScene(sceneId){
const deleteRequest = gameIndexedDb
.transaction([`exploredData`], "readwrite")
.objectStore('exploredData')
.delete(`explore${window.gameId}${sceneId}`);
deleteRequest.onsuccess = function(event) {
if(sceneId == window.CURRENT_SCENE_DATA.id){
let exploredCanvas = $('#exploredCanvas')
if(exploredCanvas.length > 0){
let exploredCanvasContext = exploredCanvas[0].getContext('2d');
exploredCanvasContext.globalCompositeOperation ='source-over';
exploredCanvasContext.fillStyle = "black";
exploredCanvasContext.fillRect(0,0,exploredCanvas[0].width,exploredCanvas[0].height);
}
redraw_light();
alert('Scene Explore Trail Data Cleared')
}
};
}
function process_monitored_logs() {
const logs = [...console.concerningLogs, ...console.otherLogs].sort((a, b) => a.timeStamp < b.timeStamp ? 1 : -1);
let processedLogs = [];
logs.forEach(log => {
let messageString = `\n${log.type.toUpperCase()} ${log.timeStamp}`;
// processedLogs.push(prefix);
log.value.forEach((value, index) => {
try {
const logItem = log.value[index];
let logString = '\n';
if (typeof logItem === "object") {
logString += ` ${JSON.stringify(logItem)}`;
} else {
logString += ` ${logItem}`;
}
messageString += logString.replaceAll(MYCOBALT_TOKEN, '[REDACTED]').replaceAll(window.CAMPAIGN_SECRET, '[REDACTED]');
} catch (err) {
console.debug("failed to process log value", err);
}
})
processedLogs.push(messageString);
});
return processedLogs.join('\n');
}
function is_release_build() {
return (!is_beta_build() && !is_local_build());
}
function is_beta_build() {
return AVTT_ENVIRONMENT.versionSuffix?.includes("beta");
}
function is_local_build() {
return AVTT_ENVIRONMENT.versionSuffix?.includes("local");
}
/** @return {boolean} true if the current page url includes "/characters/<someId>" */
function is_characters_page() {
return window.location.pathname.match(charactersPageRegex)?.[0] !== undefined;
}
/** @return {boolean} true if the current page url includes "/characters/" */
function is_characters_list_page() {
return window.location.pathname.match(/\/characters(?!\/\d)/)?.[0] !== undefined;
}
/** @return {boolean} true if the current page url includes "/campaigns/" */
function is_campaign_page() {
return window.location.pathname.includes("/campaigns/");
}
/** @return {boolean} true if the current page url includes "/encounters/" */
function is_encounters_page() {
return window.location.pathname.includes("/encounters/");
}
/** @return {boolean} true if the url has abovevtt=true, and is one of the pages that we allow the app to run on */
function is_abovevtt_page() {
// we only run the app on the enounters page (DM), and the characters page (players)
// we also only run the app if abovevtt=true is in the query params
return window.location.search.includes("abovevtt=true") && (is_encounters_page() || is_characters_page());
}
/** @return {boolean} true if the current page url includes "/campaigns/" and the query contains "popoutgamelog=true" */
function is_gamelog_popout() {
return is_campaign_page() && window.location.search.includes("popoutgamelog=true");
}
let MYCOBALT_TOKEN = false;
let MYCOBALT_TOKEN_EXPIRATION = 0;
/**
* UNIFIED TOKEN HANDLING
* Triggers callback with a valid DDB cobalt token
* @param {Function} callback
* @returns void
*/
function get_cobalt_token(callback) {
if (Date.now() < MYCOBALT_TOKEN_EXPIRATION) {
console.log("TOKEN IS CACHED");
callback(MYCOBALT_TOKEN);
return;
}
console.log("GETTING NEW TOKEN");
$.ajax({
url: "https://auth-service.dndbeyond.com/v1/cobalt-token",
type: "post",
xhrFields: {
// To allow cross domain cookies
withCredentials: true
},
success: function(data) {
console.log("GOT NEW TOKEN");
MYCOBALT_TOKEN = data.token;
MYCOBALT_TOKEN_EXPIRATION = Date.now() + (data.ttl * 1000) - 10000;
callback(data.token);
}
});
}
function removeError() {
$("#above-vtt-error-message").remove();
remove_loading_overlay(); // in case there was an error starting up, remove the loading overlay, so they're not completely stuck
delete window.logSnapshot;
}
function createCustomOnedriveChooser(text, callback = function(){}, selectionMode = 'single', selectionType = ['photo', 'video', '.webp']){
let button = $(`<button class="launchPicker"><span class='onedrive-btn-status'></span>${text}</button>`);
button.off('click.onedrive').on('click.onedrive', function(e){
e.stopPropagation();
launchPicker(e, callback, selectionMode, selectionType);
})
return button;
}
function createCustomDropboxChooser(text, options){
let button = $(`<button class="dropboxChooser"><span class="dropin-btn-status"></span>${text}</button>`)
button.off('click.dropbox').on('click.dropbox', function(e){
e.stopPropagation();
Dropbox.choose(options)
})
return button;
}
function dropBoxOptions(callback, multiselect = false, fileType=['images', 'video']){
let options = {
// Required. Called when a user selects an item in the Chooser.
success: function(files) {
for(let i = 0; i<files.length; i++){
files[i].name = files[i].name.replace(/\.[0-9a-zA-Z]*$/g, '')
}
callback(files)
//alert("Here's the file link: " + files[0].link)
},
// Optional. Called when the user closes the dialog without selecting a file
// and does not include any parameters.
cancel: function() {
},
// Optional. "preview" (default) is a preview link to the document for sharing,
// "direct" is an expiring link to download the contents of the file. For more
// information about link types, see Link types below.
linkType: "preview", // or "direct"
// Optional. A value of false (default) limits selection to a single file, while
// true enables multiple file selection.
multiselect: multiselect, // or true
// Optional. This is a list of file extensions. If specified, the user will
// only be able to select files with these extensions. You may also specify
// file types, such as "video" or "images" in the list. For more information,
// see File types below. By default, all extensions are allowed.
extensions: fileType,
// Optional. A value of false (default) limits selection to files,
// while true allows the user to select both folders and files.
// You cannot specify `linkType: "direct"` when using `folderselect: true`.
folderselect: false, // or true
}
return options
}
/** Displays an error to the user. Only use this if you don't want to look for matching github issues
* @see showError
* @param {Error} error an error object to be parsed and displayed
* @param {string|*[]} extraInfo other relevant information */
function showErrorMessage(error, ...extraInfo) {
removeError();
window.logSnapshot = process_monitored_logs(false);
console.log("showErrorMessage", ...extraInfo, error.stack);
if (!(error instanceof Error)) {
if (typeof error === "object") {
error = JSON.stringify(error);
}
error = new Error(error?.toString());
}
const stack = error.stack || new Error().stack;
if(stack.includes('Internal Server Error') && stack.includes('AboveApi.getScene')){
if(!window.DM){
extraInfo.push('<br/><b>The last scene players were on may have been deleted by the DM. Ask the DM to click the player button beside an existing scene. Even if one is already highlighted click it again to update the server info.</b>')
}
else{
extraInfo.push('<br/><b>The scene you are trying to load does not exist. You may have deleted it - try setting the DM scene to an existing map.</b>')
}
}
const extraStrings = extraInfo.map(ei => {
if (typeof ei === "object") {
if(JSON.stringify(ei).length>300)
return JSON.stringify(ei).substr(0, 300) + "...";
else
return JSON.stringify(ei)
} else {
if(ei?.toString().length>300)
return ei?.toString().substr(0, 300) + "...";
else
return ei?.toString()
}
}).join('<br />');
if(typeof error.message == 'object'){
error.message = JSON.strigify(error.message);
}
let container = $("#above-vtt-error-message");
if(error.message.length > 300)
error.message = error.message.substr(0, 300) + "...";
if (container.length === 0) {
const container = $(`
<div id="above-vtt-error-message">
<h2>An unexpected error occurred!</h2>
<h3 id="error-message">${error.message}</h3>
<div id="error-message-details">${extraStrings}</div>
<pre id="error-message-stack" style='max-height: 200px;'>${error.message}<br/>${extraStrings}</pre>
<div id="error-github-issue"></div>
<div class="error-message-buttons">
<button id="close-error-button">Close</button>
<button id="copy-error-button">Copy logs to clipboard</button>
</div>
</div>
`);
$(document.body).append(container);
} else {
$("#error-message-stack").append("<br /><br />---------- Another Error Occurred ----------<br /><br />");
}
$("#error-message-stack")
.append('<br />')
.append(stack);
$("#close-error-button").on("click", removeError);
$("#copy-error-button").on("click", function () {
copy_to_clipboard(build_external_error_message());
});
if (get_avtt_setting_value("aggressiveErrorMessages")) {
$("#error-message-stack").show();
}
}
function showDiceDisabledWarning(){
window.diceWarning = 1;
let container = $("#above-vtt-error-message");
let containerHTML = $(`
<div id="above-vtt-error-message">
<h2>DDB dice roller not detected</h2>
<div id="error-message-details">Dice must be enabled on the character sheet for AboveVTT to function properly.</div>
<div class="error-message-buttons">
<button id="close-error-button">Close</button>
</div>
</div>
`)
if (container.length === 0) {
container = containerHTML;
$(document.body).append(container);
}
else {
container.html(containerHTML);
}
$("#close-error-button").on("click", removeError);
}
function showGoogleDriveWarning(){
let container = $("#above-vtt-error-message");
let containerHTML = $(`
<div id="above-vtt-error-message">
<h2>Google Drive Issue</h2>
<h3 id="error-message">Google has made changes</h3>
<div id="error-message-details"><p>Google has made some changes to google drive links that may cause maps and other images/audio/video to no longer load. </p><p>They no longer support (it was never officially supported) google drive as a public host.</p> <p>We suggesting moving to other hosts such as dropbox, onedrive, imgur, or your prefered hosting solution.</p><p> For more information or help with other hosting options see our discord: <a href='https://discord.com/channels/815028457851191326/823177610149756958/1201995534038990909'>Google Drive Issue</a></p></div>
<div class="error-message-buttons">
<button id="close-error-button">Close</button>
</div>
</div>
`)
if (container.length === 0) {
container = containerHTML;
$(document.body).append(container);
}
else {
container.html(containerHTML);
}
$("#close-error-button").on("click", removeError);
}
/** Displays an error to the user, and looks for matching github issues
* @param {Error} error an error object to be parsed and displayed
* @param {string|*[]} extraInfo other relevant information */
function showError(error, ...extraInfo) {
if (!(error instanceof Error)) {
if (typeof error === "object") {
error = JSON.stringify(error);
}
error = new Error(error?.toString());
}
$('#loadingStyles').remove();
showErrorMessage(error, ...extraInfo);
$("#above-vtt-error-message .error-message-buttons").append(`<div style="float: right;top:-22px;position:relative;">Use this button to share logs with developers!<span class="material-symbols-outlined" style="color:red;font-size: 40px;top: 14px;position: relative;">line_end_arrow_notch</span></div>`);
look_for_github_issue(error.message, ...extraInfo)
.then((issues) => {
add_issues_to_error_message(issues, error.message);
})
.catch(githubError => {
console.log("look_for_github_issue", "Failed to look for github issues", githubError);
});
}
function build_external_error_message(limited = false) {
const codeBookend = "\n```\n";
const error = $("#error-message-stack").html().replaceAll("<br />", "\n").replaceAll("<br/>", "\n").replaceAll("<br>", "\n");
const formattedError = `**Error:**${codeBookend}${error}${codeBookend}`;
const environment = JSON.stringify({
avttVersion: `${window.AVTT_VERSION}${AVTT_ENVIRONMENT.versionSuffix}`,
browser: get_browser(),
});
const formattedEnvironment = `**Environment:**${codeBookend}${environment}${codeBookend}`;
const formattedConsoleLogs = `**Other Logs:**${codeBookend}${window.logSnapshot}`; // exclude the closing codeBookend, so we can cleanly slice the full message
const fullMessage = formattedError + formattedEnvironment + formattedConsoleLogs;
if (limited) {
return fullMessage.slice(0, 2000) + codeBookend;
}
return fullMessage + codeBookend;
}
function add_issues_to_error_message(issues, errorMessage) {
if (issues.length > 0) {
let ul = $("#error-issues-list");
if (ul.length === 0) {
ul = $(`<ul id="error-issues-list" style="list-style: inside"></ul>`);
$("#error-github-issue").append(`<p class="error-good-news">We found some issues that might be similar. Check them out to see if there's a known workaround for the error you just encountered.</p>`);
$("#error-github-issue").append(ul);
}
issues.forEach(issue => {
const li = $(`<li><a href="${issue.html_url}" target="_blank">${issue.title}</a></li>`);
ul.append(li);
if (issue.labels.find(l => l.name === "workaround")) {
li.addClass("github-issue-workaround");
}
});
}
// give them a button to create a new github issue.
// If this gets spammed, we can change the logic to only include this if issues.length === 0
if ($("#create-github-button").length === 0) {
$("#error-github-issue").append(`<div style="margin-top:20px;">Creating a Github Issue <i>(account required)</i> is very helpful. It gives the developers all the details they need to fix the bug. Alternatively, you can use the copy "Copy Error Message" button and then paste it on the AboveVTT <a style="font-weight:bold;text-decoration: underline;" target="_blank" href="https://discord.gg/cMkYKqGzRh">Discord Server</a>. Watch threads in discord channel #bugs-n-screenshots for known issues, it may also be addressed in #support.</div>`);
const githubButton = $(`<button id="create-github-button" style="float: left">Create Github Issue</button>`);
githubButton.click(function() {
const textToCopy = $("#error-message-stack").html().replaceAll("<br />", "\n").replaceAll("<br/>", "\n").replaceAll("<br>", "\n");
const environment = JSON.stringify({
avttVersion: `${window.AVTT_VERSION}${AVTT_ENVIRONMENT.versionSuffix}`,
browser: get_browser(),
});
const errorBody = build_external_error_message(true);
console.log("look_for_github_issue", `appending createIssueUrl`, errorMessage, errorBody);
open_github_issue(errorMessage, errorBody);
});
$("#above-vtt-error-message .error-message-buttons").append(githubButton);
}
}
function showTempMessage(messageString){
$('.abovevttTempMessage').remove();
let messageBox = $(`<div class='abovevttTempMessage'>${messageString}</div>`);
$('body').append(messageBox);
setTimeout(function(){
messageBox.fadeOut(1000, function() { $(this).remove(); });
}, 1000);
}
/** The string "THE DM" has been used in a lot of places.
* This prevents typos or case sensitivity in strings.
* @return {String} "THE DM" */
const dm_id = "THE DM";
// Use Acererak as the avatar, because he's on the DMG cover... but also because he's the fucking boss!
let dmAvatarUrl = "https://www.dndbeyond.com/avatars/thumbnails/30/787/140/140/636395106768471129.jpeg";
const defaultAvatarUrl = "https://www.dndbeyond.com/content/1-0-2416-0/skins/waterdeep/images/characters/default-avatar.png";
/** an object that mimics window.pcs, but specific to the DM */
function generic_pc_object(isDM) {
let pc = {
decorations: {
backdrop: { // barbarian because :shrug:
largeBackdropAvatarUrl: "https://www.dndbeyond.com/avatars/61/473/636453122224164304.jpeg",
smallBackdropAvatarUrl: "https://www.dndbeyond.com/avatars/61/472/636453122223383028.jpeg",
backdropAvatarUrl: "https://www.dndbeyond.com/avatars/61/471/636453122222914252.jpeg",
thumbnailBackdropAvatarUrl: "https://www.dndbeyond.com/avatars/61/474/636453122224476777.jpeg"
},
characterTheme: {
name: "DDB Red",
isDarkMode: false,
isDefault: true,
backgroundColor: "#FEFEFE",
themeColor: "#C53131"
},
avatar: {
avatarUrl: defaultAvatarUrl,
frameUrl: null
}
},
id: 0,
image: defaultAvatarUrl,
isAssignedToPlayer: false,
name: "Unknown Character",
sheet: "",
userId: 0,
passivePerception: 8,
passiveInvestigation: 8,
passiveInsight: 8,
armorClass: 8,
abilities: [
{name: "str", save: 0, score: 10, label: "Strength", modifier: 0},
{name: "dex", save: 0, score: 10, label: "Dexterity", modifier: 0},
{name: "con", save: 0, score: 10, label: "Constitution", modifier: 0},
{name: "int", save: 0, score: 10, label: "Intelligence", modifier: 0},
{name: "wis", save: 0, score: 10, label: "Wisdom", modifier: 0},
{name: "cha", save: 0, score: 10, label: "Charisma", modifier: 0}
],
proficiencyGroups: [
{group: 'Languages', values: ''}
]
};
if (isDM) {
pc.image = dmAvatarUrl;
pc.decorations.avatar.avatarUrl = dmAvatarUrl;
pc.name = dm_id;
}
return pc;
}
function color_for_player_id(playerId) {
const pc = find_pc_by_player_id(playerId);
return color_from_pc_object(pc);
}
function color_from_pc_object(pc) {
if (!pc) return get_token_color_by_index(-1);
if (pc.name === dm_id && pc.id === 0) {
// this is a DM pc object. The DM uses the default DDB theme
return pc.decorations.characterTheme.themeColor;
}
const isDefaultTheme = !!pc.decorations?.characterTheme?.isDefault;
if (!isDefaultTheme && pc.decorations?.characterTheme?.themeColor) { // only the DM can use the default theme color
return pc.decorations.characterTheme.themeColor;
} else {
const pcIndex = window.pcs.findIndex(p => p.id === p.id);
return get_token_color_by_index(pcIndex);
}
}
function hp_from_pc_object(pc) {
let hpValue = 0;
if (!isNaN((pc?.hitPointInfo?.current))) {
hpValue += parseInt(pc.hitPointInfo.current);
}
if (!isNaN((pc?.hitPointInfo?.temp))) {
hpValue += parseInt(pc.hitPointInfo.temp);
}
return hpValue;
}
function max_hp_from_pc_object(pc) {
if (!isNaN((pc?.hitPointInfo?.maximum))) {
return parseInt(pc.hitPointInfo.maximum);
}
return 1; // this is wrong, but we want to avoid any NaN results from division
}
function hp_aura_color_from_pc_object(pc) {
const hpValue = hp_from_pc_object(pc);
const maxHp = max_hp_from_pc_object(pc);
return token_health_aura(Math.round((hpValue / maxHp) * 100));
}
function hp_aura_box_shadow_from_pc_object(pc) {
const auraValue = hp_aura_color_from_pc_object(pc);
return `${auraValue} 0px 0px 11px 3px`;
}
function speed_from_pc_object(pc, speedName = "Walking") {
return pc?.speeds?.find(s => s.name === speedName)?.distance || 0;
}
/** @return {string} The id of the player as a string, {@link dm_id} for the dm */
function my_player_id() {
if (window.DM) {
return dm_id;
} else {
return `${window.PLAYER_ID}`;
}
}
/** @param {string} idOrSheet the playerId or pc.sheet of the pc you're looking for
* @param {boolean} useDefault whether to return a generic default object if the pc object is not found
* @return {object} The window.pcs object that matches the idOrSheet */
function find_pc_by_player_id(idOrSheet, useDefault = true) {
if (idOrSheet === dm_id) {
return generic_pc_object(true);
}
if (!window.pcs) {
if(is_abovevtt_page())
console.error("window.pcs is undefined");
return useDefault ? generic_pc_object(false) : undefined;
}
const pc = window.pcs.find(pc => pc.sheet.includes(idOrSheet));
if (pc) {
return pc;
}
if (useDefault) {
return generic_pc_object(false);
}
return undefined;
}
async function rebuild_window_pcs() {
const campaignCharacters = await DDBApi.fetchCampaignCharacterDetails(window.gameId);
window.pcs = campaignCharacters.map(characterData => {
// we are not making a shortcut for `color` because the logic is too complex. See color_from_pc_object for details
return {
...characterData,
image: characterData.decorations?.avatar?.avatarUrl || characterData.avatarUrl || defaultAvatarUrl,
sheet: `/profile/${characterData.userId}/characters/${characterData.characterId}`,
lastSynchronized: Date.now()
};
});
}
/**
* Returns known languages of player's PC
* @returns {string[]}
*/
function get_my_known_languages() {
const pc = find_pc_by_player_id(my_player_id())
const knownLanguages = pc?.proficiencyGroups.find(g => g.group === "Languages")?.values?.trim().split(/\s*,\s*/gi) ?? [];
knownLanguages?.push('Telepathy');
return knownLanguages;
}
async function rebuild_window_users() {
window.playerUsers = await DDBApi.fetchCampaignCharacters(window.gameId);
let playerUser = window.playerUsers.filter(d=> d.id == window.PLAYER_ID)[0]?.userId;
window.myUser = playerUser ? playerUser : 'THE_DM';
}
function update_pc_with_data(playerId, data) {
if (data.constructor !== Object) {
console.warn("update_pc_with_data was given invalid data", playerId, data);
return;
}
const index = window.pcs.findIndex(pc => pc.sheet.includes(playerId));
if (index < 0) {
console.warn("update_pc_with_data could not find pc with id", playerId);
return;
}
console.debug(`update_pc_with_data is updating ${playerId} with`, data);
const pc = window.pcs[index];
window.pcs[index] = {
...pc,
...data,
lastSynchronized: Date.now()
}
if (window.DM) {
if (!window.PC_TOKENS_NEEDING_UPDATES.includes(playerId)) {
window.PC_TOKENS_NEEDING_UPDATES.push(playerId);
}
debounce_pc_token_update();
}
}
const debounce_pc_token_update = mydebounce(() => {
if (window.DM) {
window.PC_TOKENS_NEEDING_UPDATES.forEach((playerId) => {
const pc = find_pc_by_player_id(playerId, false);
let token = window.TOKEN_OBJECTS[pc?.sheet];
if (token) {
let currentImage = token.options.imgsrc;
token.hp = pc.hitPointInfo.current;
token.options = {
...token.options,
...pc,
imgsrc: (token.options.alternativeImages?.length == 0) ? pc.image : currentImage,
id: pc.sheet // pc.id is DDB characterId, but we use the sheet as an id for tokens
};
token.place_sync_persist(); // not sure if this is overkill
}
token = window.all_token_objects[pc?.sheet] //for the combat tracker and cross scene syncing/tokens - we want to update this even if the token isn't on the current map
if(token){
let currentImage = token.options.imgsrc;
token.options = {
...token.options,
...pc,
imgsrc: (token.options.alternativeImages?.length == 0) ? pc.image : currentImage,
id: pc.sheet // pc.id is DDB characterId, but we use the sheet as an id for tokens
};
}
});
update_pc_token_rows();
window.PC_TOKENS_NEEDING_UPDATES = [];
}
},50);
function update_pc_with_api_call(playerId) {
if (!playerId) {
console.log('update_pc_with_api_call was called without a playerId');
return;
}
if (window.PC_TOKENS_NEEDING_UPDATES.includes(playerId)) {
console.log(`update_pc_with_api_call isn't adding ${playerId} because we're already waiting for debounce_pc_token_update to handle it`);
} else if (Object.keys(window.PC_NEEDS_API_CALL).includes(playerId)) {
console.log(`update_pc_with_api_call is already waiting planning to call the API to fetch ${playerId}. Nothing to do right now.`);
} else {
const pc = find_pc_by_player_id(playerId, false);
const twoSecondsAgo = new Date(Date.now() - 2000).getTime();
if (pc && pc.lastSynchronized && pc.lastSynchronized > twoSecondsAgo) {
console.log(`update_pc_with_api_call is not adding ${playerId} to window.PC_NEEDS_API_CALL because it has been updated within the last 2 seconds`);
} else {
console.log(`update_pc_with_api_call is adding ${playerId} to window.PC_NEEDS_API_CALL`);
window.PC_NEEDS_API_CALL[playerId] = Date.now();
}
}
debounce_fetch_character_from_api();
}
const debounce_fetch_character_from_api = mydebounce(() => {
const idsAndDates = { ...window.PC_NEEDS_API_CALL }; // make a copy so we can refer to it later
window.PC_NEEDS_API_CALL = {}; // clear it out in case we get new updates while the API call is active
const characterIds = Object.keys(idsAndDates);
console.log('debounce_fetch_character_from_api is about to call DDBApi before update_pc_with_data for ', characterIds);
DDBApi.fetchCharacterDetails(characterIds).then((characterDataCollection) => {
characterDataCollection.forEach((characterData) => {
// check if we've synchronized this player data while the API call was active because we don't want to update the PC with stale data
const lastSynchronized = find_pc_by_player_id(characterData.characterId, false)?.lastSynchronized;
if (!lastSynchronized || lastSynchronized < idsAndDates[characterData.characterId]) {
console.log('debounce_fetch_character_from_api is about to call update_pc_with_data with', characterData.characterId, characterData);
update_pc_with_data(characterData.characterId, characterData);
} else {
console.log(`debounce_fetch_character_from_api is not calling update_pc_with_data for ${characterData.characterId} because ${lastSynchronized} < ${idsAndDates[characterData.characterId]}`);
}
});
});
}, 5000); // wait 5 seconds before making API calls. We don't want to make these calls unless we absolutely have to
async function harvest_game_id() {
if (is_campaign_page()) {
const fromPath = window.location.pathname.split("/").pop();
console.log("harvest_game_id found gameId in the url:", fromPath);
return fromPath;
}
if (is_encounters_page()) {
const encounterId = window.location.pathname.split("/").pop();
const encounterData = await DDBApi.fetchEncounter(encounterId);
return encounterData.campaign.id.toString();
}
if (is_characters_page()) {
const campaignSummaryButton = $(".ddbc-campaign-summary, [class*='styles_campaignSummary']");
if (campaignSummaryButton.length > 0) {
if ($(".ct-campaign-pane__name-link").length === 0) {
campaignSummaryButton.click(); // campaign sidebar is closed. open it
}
const fromLink = $(".ct-campaign-pane__name-link").attr("href")?.split("/")?.pop();
if (typeof fromLink === "string" && fromLink.length > 1) {
return fromLink;
}
}
// we didn't find it on the page so hit the DDB API, and try to pull it from there
const characterId = window.location.pathname.split("/").pop();
window.characterData = await DDBApi.fetchCharacter(characterId);
return window.characterData.campaign.id.toString();
}
throw new Error(`harvest_game_id failed to find gameId on ${window.location.href}`);
}
function set_game_id(gameId) {
window.gameId = gameId;
}
async function harvest_campaign_secret() {
if (typeof window.gameId !== "string" || window.gameId.length <= 1) {
throw new Error("harvest_campaign_secret requires gameId to be set. Make sure you call harvest_game_id first");
}
if (is_campaign_page()) {
return $(".ddb-campaigns-invite-primary").text().split("/").pop();
}
const secretFromLocalStorage = read_campaign_info(window.gameId);
if (typeof secretFromLocalStorage === "string" && secretFromLocalStorage.length > 1) {
console.log("harvest_campaign_secret found it in localStorage");
return secretFromLocalStorage;
}
// we don't have it so load up the campaign page and try to grab it from there
const iframe = $(`<iframe id='campaign-page-iframe'></iframe>`);
iframe.css({
"width": "100%",
"height": "100%",
"top": "0px",
"left": "0px",
"position": "absolute",
"visibility": "hidden"
});
$(document.body).append(iframe);
return new Promise((resolve, reject) => {
iframe.on("load", function (event) {
if (!this.src) {
// it was just created. no need to do anything until it actually loads something
return;
}
try {
const joinLink = $(event.target).contents().find(".ddb-campaigns-invite-primary").text().split("/").pop();
console.log("harvest_campaign_secret found it by loading the campaign page in an iframe");
resolve(joinLink);
} catch(error) {
console.error("harvest_campaign_secret failed to find the campaign secret by loading the campaign page in an iframe", error);
reject("harvest_campaign_secret loaded it in localStorage")
}
$(event.target).remove();
});
iframe.attr("src", `/campaigns/${window.gameId}`);
});
}
function set_campaign_secret(campaignSecret) {
window.CAMPAIGN_SECRET = campaignSecret;
}
function projector_scroll_event(event){
event.stopImmediatePropagation();
if($('#projector_toggle.enabled > [class*="is-active"]').length>0){
let sidebarSize = ($('#hide_rightpanel.point-right').length>0 ? 340 : 0);
let center = center_of_view();
let zoom = $('#projector_zoom_lock.enabled > [class*="is-active"]').length>0 ? false : window.ZOOM
tabCommunicationChannel.postMessage({
msgType: 'projectionScroll',
x: window.pageXOffset + window.innerWidth/2 - sidebarSize/2,
y: window.pageYOffset + window.innerHeight/2,
sceneId: window.CURRENT_SCENE_DATA.id,
innerHeight: window.innerHeight,
scrollPercentageY: (window.pageYOffset + window.innerHeight/2) / Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ),
scrollPercentageX: (window.pageXOffset + window.innerWidth/2 - sidebarSize/2) / Math.max( document.body.scrollWidth, document.body.offsetWidth,
document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth ),
zoom: zoom,
mapPos: convert_point_from_view_to_map(center.x, center.y, true)
});
}
}
/** writes window.gameId and window.CAMPAIGN_SECRET to localStorage for faster retrieval in the future */
function store_campaign_info() {
const campaignId = window.gameId;
const campaignSecret = window.CAMPAIGN_SECRET;
if (typeof campaignId !== "string" || campaignId.length < 0) return;
if (typeof campaignSecret !== "string" || campaignSecret.length < 0) return;
localStorage.setItem(`AVTT-CampaignInfo-${campaignId}`, campaignSecret);
}
/** @param {string} campaignId the DDB id of the campaign
* @return {string|undefined} the join link secret if it exists */
function read_campaign_info(campaignId) {
if (typeof campaignId !== "string" || campaignId.length < 0) return undefined;
const cs = localStorage.getItem(`AVTT-CampaignInfo-${campaignId}`);
if (typeof cs === "string" && cs.length > 0) return cs;
return undefined;
}
/** @param {string} campaignId the DDB id of the campaign */
function remove_campaign_info(campaignId) {
localStorage.removeItem(`AVTT-CampaignInfo-${campaignId}`);
}