-
Notifications
You must be signed in to change notification settings - Fork 62
/
MessageBroker.js
2378 lines (2103 loc) · 94.5 KB
/
MessageBroker.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
// this shouln't be here...
function mydebounce(func, timeout = 800){ // This had to be in both core and here to get this to work due to load orders. I might look at this more later
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
function throttle(func, timeFrame = 800) {
let lastTime = 0;
return function (...args) {
let now = new Date();
if (now - lastTime >= timeFrame) {
func(...args);
lastTime = now;
}
};
}
function clearFrame(){
$(".streamer-canvas").each(function() {
let canvas=$(this).get(0);
let ctx=canvas.getContext('2d');
ctx.clearRect(0,0,canvas.width,canvas.height);
});
}
const delayedClear = mydebounce(() => clearFrame());
function hideVideo(streamerid) {
$("#streamer-video-"+streamerid+", #streamer-canvas-"+streamerid).toggleClass("hidden", true);
}
function revealVideo(streamerid) {
$("#streamer-video-"+streamerid+", #streamer-canvas-"+streamerid).toggleClass("hidden", false);
}
function addVideo(stream,streamerid) {
$("#streamer-video-"+streamerid+" , #streamer-canvas-"+streamerid).remove();
let video = document.createElement("video");
video.setAttribute("class", "dicestream");
video.setAttribute("id","streamer-video-"+streamerid);
video.autoplay = true;
$(video).hide();
video.srcObject = stream;
document.body.appendChild(video);
video.play();
let dicecanvas=$(`<canvas width='${window.innerWidth}' height='${window.innerHeight}' class='streamer-canvas' />`);
dicecanvas.attr("id","streamer-canvas-"+streamerid);
//dicecanvas.css("opacity",0.5);
dicecanvas.css("position","fixed");
dicecanvas.css("top","50%");
dicecanvas.css("left","50%");
dicecanvas.css("transform","translate(-50%, -50%)");
dicecanvas.css("z-index",60000);
dicecanvas.css("touch-action","none");
dicecanvas.css("pointer-events","none");
dicecanvas.css("filter", "drop-shadow(-16px 18px 15px black)");
dicecanvas.css("clip-path", "inset(2px 2px 2px 2px)");
$("#site").append(dicecanvas);
window.MB.sendMessage("custom/myVTT/whatsyourdicerolldefault", {
to: streamerid,
from: window.MYSTREAMID
});
let canvas=dicecanvas.get(0);
let ctx=canvas.getContext('2d');
let tmpcanvas = document.createElement("canvas");
video.addEventListener("resize", function(){
let videoAspectRatio = video.videoWidth / video.videoHeight
if (video.videoWidth > video.videoHeight)
{
tmpcanvas.width = Math.min(video.videoWidth, window.innerWidth);
tmpcanvas.height = Math.min(video.videoHeight, window.innerWidth / videoAspectRatio);
}
else {
tmpcanvas.width = Math.min(video.videoWidth, window.innerHeight / (1 / videoAspectRatio));
tmpcanvas.height = Math.min(video.videoHeight, window.innerHeight);
}
dicecanvas.attr("width", tmpcanvas.width + "px");
dicecanvas.attr("height", tmpcanvas.height + "px");
dicecanvas.css("height",tmpcanvas.height);
dicecanvas.css("width",tmpcanvas.width );
});
let updateCanvas=function(){
//resize canvas due to Chrome bug - this may be fixed in chrome later
resizeCanvasChromeBug()
let tmpctx = tmpcanvas.getContext("2d");
window.requestAnimationFrame(updateCanvas);
tmpctx.drawImage(video, 0, 0, tmpcanvas.width, tmpcanvas.height);
if(tmpcanvas.width>0)
{
const frame = tmpctx.getImageData(0, 0, tmpcanvas.width, tmpcanvas.height);
for (let i = 0; i < frame.data.length; i += 4) {
const red = frame.data[i + 0];
const green = frame.data[i + 1];
const blue = frame.data[i + 2];
if ((red < 24) && (green < 24) && (blue < 24))
frame.data[i + 3] = 128;
if ((red < 8) && (green < 8) && (blue < 8))
frame.data[i + 3] = 0;
}
ctx.putImageData(frame,0,0);
}
};
updateCanvas();
}
function resizeCanvasChromeBug(){
let diceRollCanvas = $(".dice-rolling-panel__container");
if(parseInt(diceRollCanvas.attr("width")) % 2 != 0){
diceRollCanvas.attr("width", parseInt(diceRollCanvas.attr("width"))+1);
}
if(parseInt(diceRollCanvas.attr("height")) % 2 != 0){
diceRollCanvas.attr("height", parseInt(diceRollCanvas.attr("height"))+1);
}
}
function addFloatingCombatText(id, damageValue, heal = false){
if(get_avtt_setting_value('disableCombatText'))
return;
let token = $(`#tokens .token[data-id="${id}"]`);
let combatText = $(`<div style='--font-size: ${parseInt(token.width())}' class='floating-combat-text ${heal ? 'heal' : 'dmg'}'>${heal ? '+' : '-'}${Math.abs(damageValue)}</div>`);
token.append(combatText);
setTimeout(function(){
combatText.remove();
}, 2000)
}
class MessageBroker {
loadAboveWS(callback=null){
let self=this;
if (callback)
this.callbackAboveQueue.push(callback);
// current dev wss://b2u1l4fzc7.execute-api.eu-west-1.amazonaws.com/v1
// current prod wss://blackjackandhookers.abovevtt.net/v1
let searchParams = new URLSearchParams(window.location.search)
if(searchParams.has("dev")){
let url="wss://b2u1l4fzc7.execute-api.eu-west-1.amazonaws.com/v1?campaign="+window.CAMPAIGN_SECRET;
if(window.DM)
url=url+="&DM=1";
this.abovews = new WebSocket(url);
}
else{
let url="wss://blackjackandhookers.abovevtt.net/v1?campaign="+window.CAMPAIGN_SECRET;
if(window.DM)
url=url+="&DM=1";
this.abovews = new WebSocket(url);
}
this.abovews.onopen=function(){
}
if (this.loadingAboveWS) {
return;
}
this.loadingAboveWS=true;
this.abovews.onerror = function(errorEvent) {
self.loadingAboveWS = false;
try {
console.error("MB.onerror", errorEvent);
} catch (err) { // this is probably overkill, but just in case
console.error("MB.onerror failed to log event", err);
}
};
this.abovews.onmessage=this.onmessage;
this.abovews.onopen = function() {
self.loadingAboveWS = false;
let recovered = false;
if (self.callbackAboveQueue.length > 1) {
recovered = true;
}
let cb;
console.log('Empting callback queue list');
while (cb = self.callbackAboveQueue.shift()) {
cb();
};
if (recovered && (!window.DM)) {
console.log('asking the DM for recovery!');
self.sendMessage("custom/myVTT/syncmeup");
}
};
}
loadWS(token, callback = null) {
if (callback)
this.callbackQueue.push(callback);
console.log("LOADING WS: There Are " + this.callbackQueue.length + " elements in the queue");
if (this.loadingWS) {
console.log("ALREADY LOADING A WS");
return;
}
this.loadingWS = true;
let self = this;
let url = this.url;
let userid = this.userid;
let gameid = this.gameid;
console.log("STARTING MB WITH TOKEN");
this.ws = new WebSocket(url + "?gameId=" + gameid + "&userId=" + userid + "&stt=" + token);
this.ws.onmessage=this.onmessage;
this.ws.onerror = function() {
self.loadingWS = false;
};
this.ws.onopen = function() {
self.loadingWS = false;
let cb;
console.log('Empting callback queue list');
while (cb = self.callbackQueue.shift()) {
cb();
};
};
}
/// this will find all pending messages and reprocess them if needed. This is necessary on the characters page because DDB removes/injects the gamelog frequently. Any time they inject it, this gets called
reprocess_chat_message_history() {
for (let i = 0; i < window.MB.chat_message_history.length; i++) {
window.MB.chat_pending_messages.push(window.MB.chat_message_history[i]);
}
window.MB.handle_injected_data(window.MB.chat_pending_messages[0], false);
}
// we keep a list of the 100 most recent messages so we can re-inject them when DDB re-injects the gamelog on the characters page.
track_message_history(data) {
let existingMessage = window.MB.chat_message_history.find(message => message.id == data.id);
if (existingMessage) {
// already have this one
return;
}
window.MB.chat_message_history.unshift(data);
if (window.MB.chat_message_history > 100) {
window.MB.chat_message_history.pop();
}
}
handle_injected_data(data, trackHistory = true){
let self=this;
if(data != undefined)
self.chat_pending_messages.push(data);
let animationDuration = trackHistory ? 250 : 0; // don't animate if we're reprocessing messages
if (trackHistory) {
window.MB.track_message_history(data);
}
if(window.DM && data.data.injected_data?.rollTitle == 'Initiative'){
let total = parseFloat(data.data.injected_data?.result);
let entityid = data.data.injected_data?.entityId ? data.data.injected_data?.entityId : data.data.injected_data?.playerId;
if(data.data.injected_data?.entityId){
let monsterid = window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.monster
if(monsterid =='open5e')
{
window.StatHandler.getStat(monsterid, function(data) {
total = parseFloat(total + data.stats[1].value/100).toFixed(2);
}, window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.itemId);
}
else if(monsterid =='customStat'){
let decimalAdd = (window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.customInit != undefined || (window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.customStat != undefined && window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.customStat[1]?.mod != undefined)) ? ((window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.customStat[1]?.mod*2)+10)/100 : 0
total = parseFloat(total + decimalAdd).toFixed(2);
}
else{
window.StatHandler.getStat(monsterid, function(stat) {
total = parseFloat(total + stat.data.stats[1].value/100).toFixed(2);
}, window.TOKEN_OBJECTS[data.data.injected_data?.entityId]?.options?.itemId);
}
}
else{
let dexScore = window.pcs.filter(d=> d.characterId == entityid)[0].abilities[1].score;
if(dexScore){
total = parseFloat(total + dexScore/100).toFixed(2);
}
}
let combatSettingData = getCombatTrackersettings();
if(combatSettingData['tie_breaker'] !='1'){
total = parseInt(total);
}
$("#tokens .VTTToken").each(
function(){
let converted = $(this).attr('data-id').replace(/^.*\/([0-9]*)$/, "$1"); // profiles/ciccio/1234 -> 1234
if(converted==entityid){
ct_add_token(window.TOKEN_OBJECTS[$(this).attr('data-id')]);
window.all_token_objects[$(this).attr('data-id')].options.init = total;
window.TOKEN_OBJECTS[$(this).attr('data-id')].options.init = total;
window.TOKEN_OBJECTS[$(this).attr('data-id')].update_and_sync();
}
}
);
$("#combat_area tr").each(function() {
let converted = $(this).attr('data-target').replace(/^.*\/([0-9]*)$/, "$1"); // profiles/ciccio/1234 -> 1234
if (converted == entityid) {
$(this).find(".init").val(total);
window.all_token_objects[$(this).attr('data-target')].options.init = total;
window.TOKEN_OBJECTS[$(this).attr('data-target')].options.init = total;
window.TOKEN_OBJECTS[$(this).attr('data-target')].update_and_sync();
}
});
debounceCombatReorder(true);
}
// start the task
if(self.chat_decipher_task==null){
self.chat_decipher_task=setInterval(function(){
console.log("deciphering");
let pend_length = self.chat_pending_messages.length;
for(let i=0;i<pend_length;i++){
let current=self.chat_pending_messages.shift();
let injection_id=current.data?.rolls[0]?.rollType;
let injection_data=current.data?.injected_data;
console.log(`injection_id = ${injection_id}`);
console.log(`injection_data = ${injection_data}`);
let found=false;
$(self.diceMessageSelector).each(function(){
if($(this).text()==injection_id){
found=true;
let li = $(this).closest("li");
console.log("TROVATOOOOOOOOOOOOOOOOO");
let oldheight=li.height();
let newlihtml=self.convertChat(injection_data, current.data.player_name==window.PLAYER_NAME ).html();
if(newlihtml=="") {
li.css("display","none"); // THIS IS TO HIDE DMONLY STUFF
} else if (injection_data.dmonly && window.DM) {
}
li.animate({ opacity: 0 }, animationDuration, function() {
li.html(newlihtml);
window.JOURNAL.translateHtmlAndBlocks(li);
window.JOURNAL.add_journal_roll_buttons(li);
window.JOURNAL.add_journal_tooltip_targets(li);
add_stat_block_hover(li)
let neweight = li.height();
li.height(oldheight);
li.animate({ opacity: 1, height: neweight }, animationDuration, () => { li.height("") });
let output = $(`${current.data.injected_data.whisper == '' ? '' : `<div class='above-vtt-roll-whisper'>To: ${(current.data.injected_data.whisper == window.PLAYER_NAME && current.data.player_name == window.PLAYER_NAME) ? `Self` : current.data.injected_data.whisper}</div>`}<div class='above-vtt-container-roll-output'>${li.find('.abovevtt-roll-container').attr('title')}</div>`);
li.find('.abovevtt-roll-container [class*="Result"]').append(output);
let img = li.find(".magnify");
for(let i=0; i<img.length; i++){
if($(img[i]).is('img')){
$(img[i]).magnificPopup({type: 'image', closeOnContentClick: true });
img[i].onload = () => {
if (img[i].naturalWidth > 0) {
$(img[i]).css({
'display': 'block',
'width': '100%'
});
li.find('.chat-link').css('display', 'none');
}
$(img[i]).attr('href', img[i].src);
}
$(img[i]).off('error').on("error", function (e) {
let el = $(e.target)
let cur = el.attr("data-current-avatar-url");
if(cur != undefined){
let nextUrl;
if (cur === "largeAvatarUrl") {
nextUrl = el.attr("data-large-avatar-url");
try {
let parts = nextUrl.split("/");
parts[parts.length - 2] = "1000";
parts[parts.length - 3] = "1000";
nextUrl = parts.join("/");
el.attr("data-current-avatar-url", "hacky");
} catch (error) {
console.warn("imageHtml failed to hack the largeAvatarUrl", el, e);
nextUrl = el.attr("data-avatar-url");
el.attr("data-current-avatar-url", "avatarUrl");
}
} else if (cur === "hacky") {
nextUrl = el.attr("data-avatar-url");
el.attr("data-current-avatar-url", "avatarUrl");
} else if (cur === "avatarUrl") {
nextUrl = el.attr("data-basic-avatar-url");
el.attr("data-current-avatar-url", "basicAvatarUrl");
} else {
console.warn("imageHtml failed to load image", el, e);
return;
}
console.log("imageHtml failed to load image. Trying nextUrl", nextUrl, el, e);
el.attr("src", nextUrl);
el.attr("href", nextUrl);
}
});
}
else if($(img[i]).is('video')){
$(img[i]).magnificPopup({type: 'iframe', closeOnContentClick: true});
img[i].addEventListener('loadeddata', function() {
if(img[i].videoWidth > 0) {
$(img[i]).css({
'display': 'block',
'width': '100%'
});
li.find('.chat-link').css('display', 'none');
}
}, false);
}
}
let rollType = current.data.injected_data?.rollType?.toLowerCase();
let rollAction = current.data.injected_data?.rollTitle?.toLowerCase();
if(rollType != undefined && rollAction != 'initiative' && rollType != "tohit" && rollType != "attack" && rollType != "to hit" && rollType != "save" && rollType != "skill" && rollType != "check" && window.DM){
let damageButtonContainer = $(`<div class='damageButtonsContainer'></div>`);
let damageSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" class="ddbc-svg ddbc-combat-attack__icon-img--weapon-melee ddbc-attack-type-icon ddbc-attack-type-icon--1-1"><path class="prefix__st0" d="M237.9 515.1s-.1-.1 0 0c2-2.7 4.3-5.8 5.3-8.4 0 0-3.8 2.4-7.8 6.1.5.6 1.8 1.7 2.5 2.3zM231.4 517.8c-.2-.2-1.5-1.6-1.5-1.6l-1.6 1 2.4 2.6-3.7 4.6 1 1 3.7-4.3 1.1.9c.4-.5.8-.9 1.2-1.4l.2-.2c-1-.8-1.9-1.7-2.8-2.6zM0 0s6.1 5.8 12.2 11.5l1.4-2.2 1.8 1.3-2.9 2.5 3.7 4.6-1 1-3.7-4.3-2.8 2.5-1.3-1 2-1.6C9.4 14.2 2.2 5.6 0 0z"></path></svg>`
let healSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" class="ddbc-svg ddbc-attunement-svg ddbc-healing-icon__icon"><path d="M9.2,2.9c3.4-6.9,13.8,0,6.9,6.9c-6.9,6.9-6.9,10.4-6.9,10.4s0-3.5-6.9-10.4C-4.6,2.9,5.8-4,9.2,2.9"></path></svg>`
let damageButton = $(`<button class='applyDamageButton flat'>${damageSVG}</button>`);
let halfDamage = $(`<button class='applyDamageButton resist'>1/2 ${damageSVG}</button>`);
let doubleDamage = $(`<button class='applyDamageButton vulnerable'>2x${damageSVG}</button>`);
let healDamage = $(`<button class='applyDamageButton heal'>${healSVG}</button>`);
damageButtonContainer.off('click.damage').on('click.damage', 'button', function(e){
const clicked = $(e.currentTarget);
let damage = current.data.injected_data.result;
if(clicked.hasClass('resist')){
damage = Math.max(1, Math.floor(damage/2));
}
else if(clicked.hasClass('vulnerable')){
damage = damage*2;
}
else if(clicked.hasClass('heal')){
damage = -1*damage;
}
if(is_gamelog_popout()){
tabCommunicationChannel.postMessage({
msgType: 'gamelogDamageButtons',
damage: damage
});
return;
}
if($(`.tokenselected:not([data-id*='profile'])`).length == 0){
showTempMessage('No non-player tokens selected');
}
for(let i in window.CURRENTLY_SELECTED_TOKENS){
let id = window.CURRENTLY_SELECTED_TOKENS[i];
let token = window.TOKEN_OBJECTS[id];
if(token.isPlayer() || token.isAoe())
continue;
let newHp = Math.max(0, parseInt(token.hp) - parseInt(damage));
if(window.all_token_objects[id] != undefined){
window.all_token_objects[id].hp = newHp;
}
if(token != undefined){
token.hp = newHp;
token.place_sync_persist()
}
addFloatingCombatText(id, damage, damage<0);
}
})
if(rollType == 'damage'){
damageButtonContainer.append(damageButton, halfDamage, doubleDamage);
}
else if(rollType == 'heal'){
damageButtonContainer.append(healDamage);
}
else{
damageButtonContainer.append(damageButton, halfDamage, doubleDamage, healDamage);
}
$(this).find(`[class*='MessageContainer-Flex']`).append(damageButtonContainer);
}
if (injection_data.dmonly && window.DM) { // ADD THE "Send To Player Buttons"
let btn = $("<button>Show to Players</button>")
li.append(btn);
btn.click(() => {
li.css("display", "none");
delete injection_data.dmonly;
self.inject_chat(injection_data); // RESEND THE MESSAGE REMOVING THE "injection only"
});
}
});
}
});
if(!found && $('.ct-game-log-pane').length>0){
console.warn(`couldn't find a message matching ${JSON.stringify(current)}`);
// It's possible that we could lose messages due to this not being here, but
// if we push the message here, we can end up in an infinite loop.
// We may need to revisit this and do better with error handling if we end up missing too many messages.
// self.chat_pending_messages.push(current);
}
}
if(self.chat_pending_messages.length==0){
console.log("stop deciphering");
clearInterval(self.chat_decipher_task);
self.chat_decipher_task=null;
}
},500);
}
}
constructor() {
let self = this;
this.mysenderid=uuid();
this.stats={
reflected:0,
peers : {}
};
this.above_sequence=0;
this.chat_id=uuid();
this.chat_counter=0;
this.chat_pending_messages=[];
this.chat_message_history=[];
this.chat_decipher_task=null;
this.callbackQueue = [];
this.callbackAboveQueue = [];
this.userid = $("#message-broker-client").attr("data-userId");
this.gameid = find_game_id();
this.url = $("#message-broker-client").attr("data-connectUrl");
this.diceMessageSelector = "[class*='DiceMessage_RollType']";
if (is_encounters_page() || is_characters_page() || is_campaign_page()) {
this.diceMessageSelector = "[class*='-RollType']";
}
this.origRequestAnimFrame = null;
this.lastAlertTS = 0;
this.latestVersionSeen = window.AVTT_VERSION;
this.onmessage = async function(event,tries=0) {
if (event.data == "pong")
return;
if (event.data == "ping")
return;
let msg = {};
try {
msg = JSON.parse(event.data);
} catch (parsingError) {
console.error("MB.onmessage failed to handle", event, parsingError);
return;
}
if (window.location.search.includes("popoutgamelog=true") && msg.eventType != "dice/roll/pending" && msg.eventType != "dice/roll/fulfilled")
return;
console.log(msg.eventType);
if(msg.sender){ // THIS MESSAGE CONTAINS DATA FOR TELEMEMTRY (from AboveWS)
if(msg.sender==self.mysenderid){
self.stats.reflected++;
console.warn("WARNING. WE RECEIVED BACK OUR OWN MESSAGE - IGNORING");
return;
}
if(self.stats.peers[msg.sender]){
let shouldbethis=self.stats.peers[msg.sender].sequence+1;
if(msg.sequence==shouldbethis){
self.stats.peers[msg.sender].sequence=msg.sequence;
if(tries>0){
console.log("FIXED");
self.stats.peers[msg.sender].future_fixed++;
}
}
if(msg.sequence > shouldbethis){
if(tries==0)
self.stats.peers[msg.sender].future++;
console.log("MSG in the future. (was expecting "+shouldbethis+" but we got "+msg.sequence+ " retries :" + tries);
if(tries<20){
setTimeout(self.onmessage,300,event,tries+1);
console.log("trying to fix");
return;
}
else{
console.error("lost a message");
self.stats.peers[msg.sender].sequence=msg.sequence;
}
}
if(msg.sequence < shouldbethis){
if((msg.sequence - self.stats.peers[msg.sender].first_sequence) > 10){
self.stats.peers[msg.sender].past++;
console.error("Sequence message is in the past. We should try to recover");
}
else{
console.log("message in the past, but the che connection is new.. so.. I guess it's ok");
}
}
}
else{
self.stats.peers[msg.sender]={
future:0,
future_fixed:0,
past:0,
sequence: msg.sequence,
first_sequence: msg.sequence,
}
}
}
// WE NEED TO IGNORE CERTAIN MESSAGE IF THEY'RE NOT FROM THE CURRENT SCENE
if (msg.sceneId && window.CURRENT_SCENE_DATA && msg.sceneId !== window.CURRENT_SCENE_DATA.id && [
"custom/myVTT/delete_token",
"custom/myVTT/createtoken",
"custom/myVTT/reveal",
"custom/myVTT/fogdata",
"custom/myVTT/drawing",
"custom/myVTT/drawdata",
"custom/myVTT/highlight",
"custom/myVTT/pointer",
"custom/myVTT/place-extras-token"
].includes(msg.eventType)) {
console.log("skipping msg from a different scene");
return;
}
if (msg.eventType == "custom/myVTT/token" && (msg.sceneId == window.CURRENT_SCENE_DATA.id || msg.data.id in window.TOKEN_OBJECTS)) {
self.handleToken(msg);
}
if(msg.eventType=="custom/myVTT/delete_token"){
let tokenid=msg.data.id;
if(tokenid in window.TOKEN_OBJECTS){
window.TOKEN_OBJECTS[tokenid].options.deleteableByPlayers = true;
window.TOKEN_OBJECTS[tokenid].delete(false);
}
}
if(msg.eventType == "custom/myVTT/createtoken"){
if(window.DM){
let left = parseInt(msg.data.left);
let top = parseInt(msg.data.top);
if (!isNaN(top) && !isNaN(left)) {
place_token_at_map_point(msg.data, left, top);
} else {
place_token_in_center_of_view(msg.data);
}
}
}
if(msg.eventType == "custom/myVTT/deleteExplore"){
if(!window.DM){
deleteExploredScene(msg.data.sceneId)
}
}
if(msg.eventType == "custom/myVTT/place-extras-token"){
if(window.DM){
let left = parseInt(msg.data.centerView.x);
let top = parseInt(msg.data.centerView.y);
let monsterId = msg.data.monsterData.baseId;
fetch_and_cache_monsters([monsterId], function(){
create_and_place_token(window.cached_monster_items[monsterId], undefined, undefined, left, top, undefined, undefined, true, msg.data.extraOptions)
});
}
}
if (msg.eventType === "custom/myVTT/fetchscene") {
if(msg.data.sceneid.players){
if(msg.data.sceneid[window.PLAYER_ID] !== undefined)
msg.data.sceneid = msg.data.sceneid[window.PLAYER_ID];
else
msg.data.sceneid = msg.data.sceneid.players
}
if (window.startupSceneId === msg.data.sceneid) {
// we fetch this on startup because it's faster. Don't reload what we've already loaded
console.log("received custom/myVTT/fetchscene, but we've already loaded", msg.data.sceneid)
}
else if (msg.data?.sceneid) {
AboveApi.getScene(msg.data.sceneid).then((response) => {
self.handleScene(response);
}).catch((error) => {
console.error("Failed to download scene", error);
});
}
delete window.startupSceneId; // we only want to prevent a double load of the initial scene, so we want to delete this no matter what.
}
if (msg.eventType == "custom/myVTT/scene") {
self.handleScene(msg);
}
if (msg.eventType == "custom/myVTT/syncmeup") {
self.handleSyncMeUp(msg);
}
if (msg.eventType == "custom/myVTT/audioPlayingSyncMe") {
self.handleAudioPlayingSync(msg);
}
if(msg.eventType == ('custom/myVTT/character-update')){
update_pc_with_data(msg.data.characterId, msg.data.pcData);
}
if(msg.eventType == ('character-sheet/character-update/fulfilled')) {
console.log('update_pc character-sheet/character-update/fulfilled', msg);
update_pc_with_api_call(msg.data?.characterId);
}
if (msg.eventType == "custom/myVTT/reveal") {
window.REVEALED.push(msg.data);
redraw_fog();
check_token_visibility(); // CHECK FOG OF WAR VISIBILITY OF TOKEN
}
if(msg.eventType== "custom/myVTT/fogdata"){ // WE RESEND ALL THE FOG EVERYTIME NOW
window.REVEALED=msg.data;
redraw_fog();
check_token_visibility();
}
if (msg.eventType == "custom/myVTT/drawing") {
window.DRAWINGS.push(msg.data);
redraw_light_walls();
redraw_drawn_light();
redraw_drawings();
redraw_elev();
redraw_text();
await redraw_light();
check_token_visibility();
}
if(msg.eventType=="custom/myVTT/drawdata"){
window.DRAWINGS=msg.data;
redraw_light_walls();
setTimeout(async function(){
redraw_drawn_light();
redraw_elev();
redraw_drawings();
redraw_text();
await redraw_light();
}, 100)
check_token_visibility();
}
if (msg.eventType == "custom/myVTT/chat") { // DEPRECATED!!!!!!!!!
if(!window.NOTIFIEDOLDVERSION){
alert('One of the player is using AboveTT 0.0.51 or less. Please update everyone to 0.0.52 or higher');
window.NOTIFIEDOLDVERSION=true;
}
}
if (msg.eventType == "custom/myVTT/CT" && (!window.DM)) {
self.handleCT(msg.data);
}
if (msg.eventType == "custom/myVTT/highlight") {
if (msg.data.id in window.TOKEN_OBJECTS) {
window.TOKEN_OBJECTS[msg.data.id].highlight(true);
}
}
if (msg.eventType == "custom/myVTT/pointer") {
set_pointer(msg.data,(!msg.data.dm || (msg.data.dm && !msg.data.center_on_ping)));
}
if (msg.eventType == "custom/myVTT/lock") {
if (window.DM)
return;
if (getPlayerIDFromSheet(msg.data.player_sheet) == window.PLAYER_ID) {
//alert('locked');
let lock_display = $("<div id='lock_display'>The DM is looking at your character sheet</p></div>");
lock_display.css("font-size", "18px");
lock_display.css("text-align","center");
lock_display.css('font-weight', "bold");
lock_display.css('background', "rgba(255,255,0,0.7)");
lock_display.css('position', 'absolute');
if (is_characters_page()) {
lock_display.css({
"top": "0px",
"left": "0px",
"width": "100%",
"height": "100%"
});
$(".site-bar").append(lock_display);
adjust_site_bar();
} else {
lock_display.css('top', '27px');
lock_display.css('left', '0px');
lock_display.width($("#sheet").width());
//lock_display.height($("#sheet").height());
lock_display.height(25);
//lock_display.css('padding-top', '50px');
//$("#sheet iframe").css('opacity', '0.8');
$("#sheet").append(lock_display);
//$("#sheet iframe").attr('disabled', 'disabled');
}
}
}
if (msg.eventType == "custom/myVTT/unlock") {
if (window.DM)
{
return;
}
else if (getPlayerIDFromSheet(msg.data.player_sheet) == window.PLAYER_ID) {
//alert('unlocked');
$("#lock_display").remove();
adjust_site_bar();
$("#sheet iframe").removeAttr('disabled');
$("#sheet iframe").css('opacity', '1');
$("#sheet iframe").attr('src', function(i, val) { return val; }); // RELOAD IFRAME
}
}
if (msg.eventType == "custom/myVTT/player_sheet_closed") {
if (window.DM)
{
//$("[id='PlayerSheet"+getPlayerIDFromSheet(msg.data.player_sheet)+"']").attr('src', function(i, val) { return val; });
$("[id='PlayerSheet"+getPlayerIDFromSheet(msg.data.player_sheet)+"']").attr('data-changed', 'true');
return;
}
}
if(msg.eventType=="custom/myVTT/JournalChapters"){
if(!window.DM){
window.JOURNAL.chapters=msg.data.chapters;
window.JOURNAL.build_journal();
window.JOURNAL.persist(true);
}
}
if(msg.eventType=="custom/myVTT/note"){
if(!window.DM){
window.JOURNAL.notes[msg.data.id]=msg.data.note;
window.JOURNAL.build_journal();
if(msg.data.id in window.TOKEN_OBJECTS){
window.TOKEN_OBJECTS[msg.data.id].place();
}
if(msg.data.popup)
window.JOURNAL.display_note(msg.data.id);
window.JOURNAL.persist(true);
}
}
if(msg.eventType=="custom/myVTT/notesSync"){
if(!window.DM){
for(let i in msg.data.notes){
let noteId = msg.data.notes[i].id;
window.JOURNAL.notes[noteId] = msg.data.notes[i];
delete window.JOURNAL.notes[noteId].id;
if(msg.data.notes[i].id in window.TOKEN_OBJECTS){
window.TOKEN_OBJECTS[msg.data.id].place();
}
}
window.JOURNAL.build_journal();
window.JOURNAL.persist(true);
}
}
if(msg.eventType=="custom/myVTT/DMAvatar"){
dmAvatarUrl = msg.data.avatar;
$(`.player-card[data-player-id=''] .player-token img`).attr('src', dmAvatarUrl);
}
if(msg.eventType=="custom/myVTT/pausePlayer"){
if(!window.DM){
$("#VTT").toggleClass('paused', msg.data.paused);
}
if(msg.data.paused){
if($(".paused-indicator").length == 0){
let pausedIndicator = $(`
<div class="paused-indicator">
<div class="paused-status-indicator__subtext">Game Paused. Waiting for DM</div>
<svg class="beholder-dm-screen loading-status-indicator__svg animate" viewBox="0 0 285 176" fill="none" xmlns="http://www.w3.org/2000/svg" style="overflow:overlay;width:100%;position:relative;padding:0 10%;"><defs><path id="beholder-eye-move-path" d="M0 0 a 15 5 0 0 0 15 0 a 15 5 0 0 1 -15 0 z"></path><clipPath id="beholder-eye-socket-clip-path"><path id="eye-socket" fill-rule="evenodd" clip-rule="evenodd" d="M145.5 76c-8.562 0-15.5-7.027-15.5-15.694 0-8.663 6.938-1.575 15.5-1.575 8.562 0 15.5-7.088 15.5 1.575C161 68.973 154.062 76 145.5 76z"></path></clipPath></defs><g class="beholder-dm-screen__beholder"><path fill-rule="evenodd" clip-rule="evenodd" d="M145.313 77.36c-10.2 0-18.466-8.27-18.466-18.47 0-10.197 8.266-1.855 18.466-1.855 10.199 0 18.465-8.342 18.465 1.855 0 10.2-8.266 18.47-18.465 18.47m59.557 4.296l-.083-.057c-.704-.5-1.367-1.03-1.965-1.59a12.643 12.643 0 0 1-1.57-1.801c-.909-1.268-1.51-2.653-1.859-4.175-.355-1.521-.461-3.179-.442-4.977.007-.897.049-1.835.087-2.827.038-.995.079-2.032.053-3.194-.031-1.158-.11-2.445-.519-3.97a10.494 10.494 0 0 0-1.014-2.43 8.978 8.978 0 0 0-1.938-2.32 9.64 9.64 0 0 0-2.468-1.54l-.314-.137-.299-.114-.609-.212c-.382-.105-.787-.227-1.151-.298-1.495-.315-2.819-.383-4.065-.39-1.248-.004-2.407.087-3.534.2a56.971 56.971 0 0 0-3.18.44c-6.271.646-12.648 1.559-13.689-.837-1.079-2.487-3.35-8.058 3.115-12.19 4.076.154 8.141.347 12.179.62 1.461.098 2.914.212 4.36.34-4.614.924-9.314 1.7-14.019 2.43h-.015a2.845 2.845 0 0 0-2.388 3.066 2.84 2.84 0 0 0 3.088 2.574c5.125-.462 10.25-.973 15.416-1.696 2.592-.378 5.17-.776 7.88-1.42a29.7 29.7 0 0 0 2.108-.59c.181-.06.363-.117.56-.193.197-.072.378-.136.594-.227.208-.09.405-.17.643-.291l.345-.174.394-.235c.064-.042.124-.076.196-.125l.235-.174.235-.174.117-.099.148-.136c.098-.094.189-.189.283-.287l.137-.152a3.44 3.44 0 0 0 .166-.22c.114-.154.224-.317.318-.484l.072-.125.038-.064.042-.09a5.06 5.06 0 0 0 .367-1.154c.045-.308.06-.63.045-.944a4.322 4.322 0 0 0-.042-.458 5.19 5.19 0 0 0-.386-1.207 5.356 5.356 0 0 0-.499-.799l-.091-.117-.072-.083a5.828 5.828 0 0 0-.303-.318l-.155-.151-.083-.076-.057-.05a9.998 9.998 0 0 0-.503-.382c-.152-.102-.28-.178-.424-.265l-.205-.124-.181-.091-.36-.186a18.713 18.713 0 0 0-.643-.28l-.591-.23c-1.521-.538-2.853-.856-4.197-1.159a83.606 83.606 0 0 0-3.951-.772c-2.604-.45-5.185-.829-7.763-1.166-4.273-.564-8.531-1.029-12.785-1.46 0-.004-.004-.004-.004-.004a38.55 38.55 0 0 0-4.81-3.1v-.004c.397-.223.965-.424 1.688-.549 1.135-.208 2.551-.242 4.05-.185 3.024.11 6.366.59 10.022.662 1.832.02 3.781-.056 5.84-.56a12.415 12.415 0 0 0 3.081-1.188 10.429 10.429 0 0 0 2.702-2.135 2.841 2.841 0 0 0-3.774-4.205l-.208.152c-.825.594-1.76.87-2.956.942-1.188.068-2.566-.09-4.004-.367-2.907-.553-6.003-1.556-9.5-2.32-1.763-.371-3.644-.7-5.802-.73a16.984 16.984 0 0 0-3.455.298 13.236 13.236 0 0 0-3.774 1.333 13.065 13.065 0 0 0-3.376 2.615 14.67 14.67 0 0 0-1.646 2.154h-.004a41.49 41.49 0 0 0-8.436-.863c-1.518 0-3.017.079-4.489.238-1.79-1.563-3.444-3.198-4.833-4.913a21.527 21.527 0 0 1-1.4-1.903 15.588 15.588 0 0 1-1.094-1.893c-.606-1.241-.905-2.422-.893-3.22a3.38 3.38 0 0 1 .038-.55c.034-.155.06-.31.121-.446.106-.273.276-.534.571-.776.579-.496 1.681-.81 2.884-.689 1.207.114 2.487.629 3.615 1.476 1.135.848 2.111 2.044 2.868 3.444l.038.076a2.848 2.848 0 0 0 3.471 1.329 2.843 2.843 0 0 0 1.714-3.641c-.768-2.135-1.96-4.235-3.675-6.003-1.71-1.76-3.924-3.18-6.502-3.872a12.604 12.604 0 0 0-4.076-.416 11.248 11.248 0 0 0-4.284 1.128 10.405 10.405 0 0 0-3.702 3.054c-.499.655-.901 1.37-1.237 2.104-.318.73-.568 1.488-.731 2.237-.337 1.503-.356 2.96-.238 4.315.125 1.362.405 2.63.764 3.822.36 1.196.803 2.317 1.298 3.373a31.9 31.9 0 0 0 1.605 3.043c.458.768.935 1.506 1.427 2.233h-.004a39.13 39.13 0 0 0-4.515 2.384c-3.111-.344-6.2-.76-9.242-1.294-2.033-.364-4.043-.769-6.007-1.26-1.96-.485-3.876-1.045-5.662-1.726a24.74 24.74 0 0 1-2.528-1.102c-.772-.393-1.48-.829-1.987-1.234a4.916 4.916 0 0 1-.56-.507c-.02-.015-.03-.03-.046-.045.288-.28.761-.621 1.314-.905.719-.382 1.566-.711 2.456-.984 1.79-.556 3.762-.9 5.76-1.098l.046-.007a2.843 2.843 0 0 0 2.547-2.805 2.846 2.846 0 0 0-2.824-2.868c-2.301-.02-4.628.11-7.028.567-1.2.231-2.418.538-3.671 1.022-.628.246-1.26.526-1.911.901a10.12 10.12 0 0 0-1.96 1.446c-.648.62-1.307 1.438-1.757 2.524-.114.261-.197.56-.284.844a7.996 7.996 0 0 0-.166.909c-.061.609-.05 1.237.049 1.809.189 1.162.632 2.12 1.109 2.891a11.265 11.265 0 0 0 1.529 1.942c1.056 1.082 2.127 1.88 3.194 2.6a33.287 33.287 0 0 0 3.21 1.855c2.142 1.093 4.284 1.979 6.434 2.774a98.121 98.121 0 0 0 6.464 2.112c.511.147 1.018.291 1.529.435a36.8 36.8 0 0 0-4.458 7.089v.004c-1.908-2.014-3.876-3.997-6.022-5.931a52.386 52.386 0 0 0-3.471-2.888 31.347 31.347 0 0 0-2.028-1.408 17.575 17.575 0 0 0-2.574-1.378 11.177 11.177 0 0 0-1.888-.616c-.761-.16-1.73-.31-3.02-.107a6.543 6.543 0 0 0-1.007.254 6.508 6.508 0 0 0-2.79 1.84 6.7 6.7 0 0 0-.594.783c-.083.129-.174.269-.238.39a7.248 7.248 0 0 0-.681 1.692 9.383 9.383 0 0 0-.3 2.02c-.022.584 0 1.09.038 1.568.084.953.231 1.786.401 2.577l.39 1.764c.027.14.065.268.087.408l.057.428.121.855.065.428.033.443.072.886c.061.586.061 1.196.076 1.801.05 2.426-.11 4.92-.435 7.407a50.6 50.6 0 0 1-1.503 7.35c-.17.594-.367 1.17-.548 1.76a55.283 55.283 0 0 1-.632 1.684l-.352.791c-.061.129-.114.276-.178.39l-.193.356-.186.355c-.064.121-.129.246-.193.326-.129.185-.257.375-.378.575l-.303.485a2.813 2.813 0 0 0 4.462 3.387c.295-.322.59-.655.878-.988.155-.17.265-.333.382-.496l.349-.488.344-.492c.117-.166.2-.325.303-.492l.583-.98a53.92 53.92 0 0 0 1.018-1.964c.295-.659.61-1.321.89-1.984a58.231 58.231 0 0 0 2.69-8.114 58.405 58.405 0 0 0 1.51-8.493c.068-.73.152-1.454.167-2.203l.045-1.12.02-.56-.012-.568-.004-.205c.167.186.333.371.496.557 1.608 1.84 3.179 3.838 4.708 5.889a181.94 181.94 0 0 1 4.481 6.328c.14.2.311.428.477.617.284.33.594.62.924.874 0 .216.003.424.015.636-2.661 2.861-5.265 5.821-7.748 9.034-1.567 2.06-3.096 4.19-4.485 6.715-.685 1.267-1.347 2.645-1.854 4.363-.246.879-.454 1.851-.496 3.02l-.007.44.022.473c.012.159.02.314.038.477.023.166.05.337.076.503.113.666.333 1.385.65 2.07.16.337.356.67.557.992.212.299.44.613.681.878a8.075 8.075 0 0 0 1.54 1.328c1.05.697 2.04 1.06 2.938 1.31 1.79.466 3.292.519 4.723.507 2.842-.053 5.367-.48 7.853-.98 4.943-1.022 9.618-2.434 14.243-3.948a2.845 2.845 0 0 0 1.911-3.236 2.842 2.842 0 0 0-3.323-2.267h-.015c-4.648.878-9.322 1.635-13.864 1.965-2.252.155-4.511.208-6.46-.027a10.954 10.954 0 0 1-1.685-.322c.004-.015.012-.026.015-.037.133-.273.322-.606.534-.954.235-.36.477-.73.768-1.117 1.14-1.548 2.619-3.164 4.183-4.723a83.551 83.551 0 0 1 2.585-2.468 35.897 35.897 0 0 0 2.312 4.16c.125.2.261.405.397.602 3.747-.413 7.415-1.06 10.356-1.617l.037-.007a7.47 7.47 0 0 1 8.702 5.957 7.491 7.491 0 0 1-4.724 8.38C132.172 94.372 138.542 96 145.313 96c20.358 0 37.087-14.708 38.994-33.514.193-.05.386-.098.576-.144a23.261 23.261 0 0 1 2.354-.458c.726-.102 1.393-.14 1.847-.125.125-.004.193.015.299.012.03.003.064.007.098.007h.053c.008.004.015.004.027.004.106 0 .094-.019.09-.068-.007-.05-.022-.125.019-.117.038.007.125.083.216.26.087.19.186.443.269.761.079.33.159.69.219 1.102.129.806.216 1.745.307 2.725.091.984.178 2.02.306 3.1.262 2.138.682 4.435 1.533 6.683.837 2.245 2.154 4.406 3.812 6.15.825.871 1.725 1.655 2.66 2.336.943.677 1.919 1.26 2.911 1.782a2.848 2.848 0 0 0 3.641-.874 2.848 2.848 0 0 0-.674-3.966" fill="#0398F3"></path><g clip-path="url(#beholder-eye-socket-clip-path)"><circle cx="137.5" cy="60" r="7" fill="#1B9AF0"><animateMotion dur="2.3s" repeatCount="indefinite"><mpath xlink:href="#beholder-eye-move-path"></mpath></animateMotion></circle></g></g><g class="beholder-dm-screen__screen"><path fill="#EAEEF0" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" d="M76 76h136v97H76z"></path><path d="M218 170.926V74.282l64-35.208v96.644l-64 35.208zM70 171.026V74.318L3 38.974v96.708l67 35.344z" fill="#F3F6F9" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"></path></g></svg>
</div>
`);
$("body").append(pausedIndicator);
}
if(!window.DM){
deselect_all_tokens();
}
}
else{
$(".paused-indicator").remove();
}
}
if(msg.eventType=="custom/myVTT/playerjoin"){
if (window.DM) {
if (msg.data == null || typeof msg.data.abovevtt_version === "undefined") {
// Player with version <= 0.64 - avoiding popping too many alert messages
if (self.lastAlertTS == 0 || (Date.now() - self.lastAlertTS) >= 4 * 1000) {
console.log("A player just joined with an old version <= 0.64");
alert("Please note, a player just joined with an old version <= 0.64.\nFor best experience and compatibility, we recommend all players and DM to run the latest AboveVTT version.");
self.lastAlertTS = Date.now();
}
} else {
if (window.CONNECTED_PLAYERS[msg.data.player_id] === "undefined" ||
window.CONNECTED_PLAYERS[msg.data.player_id] != msg.data.abovevtt_version) {
window.CONNECTED_PLAYERS[msg.data.player_id] = msg.data.abovevtt_version;
if (msg.data.abovevtt_version != self.latestVersionSeen) {
self.latestVersionSeen = check_versions_match();
}
}
}
if($("[name='streamDiceRolls'].rc-switch-checked").length > 0) {
window.MB.sendMessage("custom/myVTT/enabledicestreamingfeature")
}
window.JOURNAL.sync();
window.MB.sendMessage("custom/myVTT/DMAvatar", {
avatar: dmAvatarUrl
})
}
if (msg.data && msg.data.player_id && msg.data.pc) {
// a player just joined and gave us their pc data, so let's update our window.pcs with what they gave us
update_pc_with_data(msg.data.player_id, msg.data.pc);
}
if (is_characters_page()) {
// a player just joined so send them our pc data
window.MB.sendMessage("custom/myVTT/pcsync", {
player_id: window.PLAYER_ID,
pc: read_pc_object_from_character_sheet(window.PLAYER_ID)
});
}
}
if(msg.eventType==="custom/myVTT/pcsync"){
// a player just sent us their pc data, so let's update our window.pcs with what they gave us
if (msg.data && msg.data.player_id && msg.data.pc) {
update_pc_with_data(msg.data.player_id, msg.data.pc);
}
}
if(msg.eventType == "custom/myVTT/endplayerturn" && window.DM){
let tokenId = $("#combat_area tr[data-current=1]").attr('data-target');
if(tokenId.endsWith(`characters/${msg.data.from}`) || window.all_token_objects[tokenId].options.player_owned)
$("#combat_next_button").click();
}
if(msg.eventType=="custom/myVTT/mixer"){
handle_mixer_event(msg.data);
}
if(msg.eventType=="custom/myVTT/soundpad"){
build_soundpad(msg.data.soundpad, msg.data.playing);
}
if(msg.eventType=="custom/myVTT/playchannel"){
audio_playchannel(msg.data.channel,msg.data.time,msg.data.volume);
}
if(msg.eventType=="custom/myVTT/pausechannel"){
audio_pausechannel(msg.data.channel);
}
if(msg.eventType=="custom/myVTT/changechannel"){
audio_changesettings(msg.data.channel,msg.data.volume,msg.data.loop);
}
if(msg.eventType=="custom/myVTT/changeyoutube"){
if(window.YTPLAYER?.setVolume){
window.YTPLAYER.setVolume(msg.data.volume*$("#master-volume input").val());
}
if($('video#scene_map').length > 0){
$('video#scene_map')[0].volume = msg.data.volume/100*$("#master-volume input").val();
$('video#scene_map').attr('data-volume', msg.data.volume/100)
}
}
if (msg.eventType == "dice/roll/pending"){
// check for injected_data!
if(msg.data.injected_data){
notify_gamelog();
self.handle_injected_data(msg);
}
}
if(msg.eventType== "custom/myVTT/iceforyourgintonic"){
if( !window.JOINTHEDICESTREAM)
return;
if( (!window.MYSTREAMID) || (msg.data.to!= window.MYSTREAMID) )
return;
setTimeout( () => {