forked from cyruzzo/AboveVTT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageBroker.js
425 lines (352 loc) · 12.4 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
class MessageBroker {
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;
var self = this;
var url = this.url;
var userid = this.userid;
var gameid = this.gameid;
console.log("STARTING MB WITH TOKEN=" + token);
this.ws = new WebSocket(url + "?gameId=" + gameid + "&userId=" + userid + "&stt=" + token);
this.ws.onerror = function() {
self.loadingWS = false;
};
this.ws.onopen = function() {
self.loadingWS = false;
var recovered = false;
if (self.callbackQueue.length > 1) {
recovered = true;
}
var cb;
console.log('Empting callback queue list');
while (cb = self.callbackQueue.shift()) {
cb();
};
if (recovered && (!window.DM)) {
console.log('asking the DM for recovery!');
self.sendMessage("custom/myVTT/syncmeup");
}
};
this.ws.onmessage = function(event) { // SCHIFO.. DOVREI FAR REGISTRARE GLI HANDLER ALLA CREAZIONE DELLA MB
if (event.data == "pong")
return;
var msg = $.parseJSON(event.data);
if (msg.eventType == "custom/myVTT/token") {
self.handleToken(msg);
}
if (msg.eventType == "custom/myVTT/scene") {
self.handleScene(msg);
}
if (msg.eventType == "custom/myVTT/syncmeup") {
self.handleSyncMeUp(msg);
}
if (msg.eventType == "custom/myVTT/reveal") {
window.REVEALED.push(msg.data);
redraw_canvas();
check_token_visibility(); // CHECK FOG OF WAR VISIBILITY OF TOKEN
}
if (msg.eventType == "custom/myVTT/drawing") {
window.DRAWINGS.push(msg.data);
redraw_drawings();
}
if (msg.eventType == "custom/myVTT/chat") {
self.handleChat(msg.data);
}
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);
}
if (msg.eventType == "custom/myVTT/lock") {
if (window.DM)
return;
if (msg.data.player_sheet == window.PLAYER_SHEET) {
//alert('locked');
var lock_display = $("<div id='lock_display'><h1>LOCKED BY DM</h1><p>The DM is working on your character sheet</p></div>");
lock_display.css("font-size", "80px");
lock_display.css('color', "red");
lock_display.css('position', 'absolute');
lock_display.css('top', '0px');
lock_display.css('left', '0px');
lock_display.width($("#sheet").width());
lock_display.height($("#sheet").height());
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;
if (msg.data.player_sheet == window.PLAYER_SHEET) {
//alert('unlocked');
$("#lock_display").remove();
$("#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/soundpad"){
build_soundpad(msg.data.soundpad);
}
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_changevolume(msg.data.channel,msg.data.volume);
}
if(msg.eventType=="custom/myVTT/changeyoutube"){
if(window.YTPLAYER){
$("#youtube_volume").val(msg.data.volume);
if(window.YTPLAYER)
window.YTPLAYER.setVolume(msg.data.volume);
}
}
if (msg.eventType == "custom/myVTT/playerdata") {
self.handlePlayerData(msg.data);
}
if (msg.eventType == "dice/roll/fulfilled") {
notify_gamelog();
if (!window.DM)
return;
// CHECK FOR INIT ROLLS
if (msg.data.action == "Initiative") {
console.log(msg.data);
var total = msg.data.rolls[0].result.total;
let entityid = msg.data.context.entityId;
console.log("cerco " + entityid);
$("#tokens .VTTToken").each(
function(){
var 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')]);
}
}
);
$("#combat_area tr").each(function() {
var converted = $(this).attr('data-target').replace(/^.*\/([0-9]*)$/, "$1"); // profiles/ciccio/1234 -> 1234
console.log(converted);
if (converted == entityid) {
$(this).find(".init").val(total);
ct_reorder();
}
});
ct_persist();
}
}
};
}
constructor() {
var self = this;
this.callbackQueue = [];
this.userid = $("#message-broker-client").attr("data-userId");
this.gameid = $("#message-broker-client").attr("data-gameId");
this.url = $("#message-broker-client").attr("data-connectUrl");
get_cobalt_token(function(token) {
self.loadWS(token);
});
setInterval(function() {
self.sendPing();
}, 30000);
}
handleCT(data){
$("#combat_area").empty();
ct_load(data);
}
handlePlayerData(data) {
if (!window.DM)
return;
window.PLAYER_STATS[data.id] = data;
if (data.id in window.TOKEN_OBJECTS) {
var cur = window.TOKEN_OBJECTS[data.id];
console.log("old " + cur.options.hp + " new " + data.hp);
console.log(data.conditions);
if (typeof cur.options.hp != "undefined" && cur.options.hp > data.hp && cur.options.custom_conditions.includes("Concentration(Reminder)")) {
var msgdata = {
player: cur.options.name,
img: cur.options.imgsrc,
text: "<b>Check for concentration!!</b>",
};
window.MB.sendMessage('custom/myVTT/chat', msgdata);
window.MB.handleChat(msgdata);
}
cur.options.hp = data.hp;
cur.options.max_hp = data.max_hp;
cur.options.ac = data.ac;
cur.options.conditions = data.conditions;
cur.place();
window.MB.sendMessage('custom/myVTT/token', cur.options);
}
// update combat tracker:
update_pclist();
}
handleChat(data,local=false) {
if(data.dmonly && !(window.DM) && !local) // /dmroll only for DM of or the user who initiated it
return;
notify_gamelog();
var newentry = $(`<li ${data.id ? `id="${data.id}"` : ""}></li>`);
newentry.attr('class', 'GameLogEntry_GameLogEntry__2EMUj GameLogEntry_Other__1rv5g Flex_Flex__3cwBI Flex_Flex__alignItems-flex-end__bJZS_ Flex_Flex__justifyContent-flex-start__378sw');
newentry.append($("<p role='img' class='Avatar_Avatar__131Mw Flex_Flex__3cwBI'><img class='Avatar_AvatarPortrait__3cq6B' src='" + data.img + "'></p>"));
var container = $("<div class='GameLogEntry_MessageContainer__RhcYB Flex_Flex__3cwBI Flex_Flex__alignItems-flex-start__HK9_w Flex_Flex__flexDirection-column__sAcwk'></div>");
container.append($("<div class='GameLogEntry_Line__3fzjk Flex_Flex__3cwBI Flex_Flex__justifyContent-space-between__1FcfJ'><span>" + data.player + "</span></div>"));
var entry = $("<div class='GameLogEntry_Message__1J8lC GameLogEntry_Collapsed__1_krc GameLogEntry_Other__1rv5g Flex_Flex__3cwBI'>" + data.text + "</div>");
container.append(entry);
var d = new Date();
var datetime = d.toISOString();
container.append($("<time datetime='" + datetime + "' class='GameLogEntry_TimeAgo__zZTLH TimeAgo_TimeAgo__2M8fr'></time"));
newentry.append(container);
$(".GameLog_GameLogEntries__3oNPD").prepend(newentry);
}
handleToken(msg) {
var data = msg.data;
//let t=new Token($.parseJSON(msg.data));
if (data.id in window.TOKEN_OBJECTS) {
for (var property in data) {
window.TOKEN_OBJECTS[data.id].options[property] = data[property];
}
if (!data.hidden)
delete window.TOKEN_OBJECTS[data.id].options.hidden;
window.TOKEN_OBJECTS[data.id].place();
check_token_visibility(); // CHECK FOG OF WAR VISIBILITY OF TOKEN
}
else {
// SOLO PLAYER. PUNTO UNICO DI CREAZIONE DEI TOKEN
if (window.DM) {
console.log("ATTENZIONEEEEEEEEEEEEEEEEEEE ATTENZIONEEEEEEEEEEEEEEEEEEE");
}
let t = new Token(data);
window.TOKEN_OBJECTS[data.id] = t;
t.sync = function(e) { // VA IN FUNZIONE SOLO SE IL TOKEN NON ESISTE GIA
window.MB.sendMessage('custom/myVTT/token', t.options);
};
t.place();
check_token_visibility(); // CHECK FOG OF WAR VISIBILITY OF TOKEN
}
if (window.DM) {
console.log("**** persistoooooooooo token");
window.ScenesHandler.persist();
}
}
handleScene(msg) {
if (window.DM) {
alert('WARNING!!!!!!!!!!!!! ANOTHER USER JOINED AS DM!!!! ONLY ONE USER SHOULD JOIN AS DM. EXITING NOW!!!');
location.reload();
}
if ((!window.DM) && (typeof window.PLAYERDATA !== "undefined")) { // PLAYERS RESEND STATS AFTER SCENE CHANGE.. JUST TO BE SURE
window.MB.sendMessage('custom/myVTT/playerdata', window.PLAYERDATA);
}
window.TOKEN_OBJECTS = {};
var data = msg.data;
window.CURRENT_SCENE_DATA = msg.data;
console.log("SETTO BACKGROUND A " + msg.data);
$("#tokens").children().remove();
var old_src = $("#scene_map").attr('src');
$("#scene_map").attr('src', data.map);
$("#scene_map").width(data.width);
$("#scene_map").height(data.height);
load_scenemap(data.map, data.width, data.height, function() {
$("#VTTWRAPPER").width($("#scene_map").width() * window.ZOOM + 1400);
$("#VTTWRAPPER").height($("#scene_map").height() * window.ZOOM + 1400);
$("#black_layer").width($("#scene_map").width() * window.ZOOM + 1400);
$("#black_layer").height($("#scene_map").height() * window.ZOOM + 1400)
/*if(old_src!=$("#scene_map").attr('src')){
window.ZOOM=(60.0/window.CURRENT_SCENE_DATA.hpps);
$("#VTT").css("transform", "scale("+window.ZOOM+")");
$("#VTTWRAPPER").width($("#scene_map").width()*window.ZOOM+400);
$("#VTTWRAPPER").height($("#scene_map").height()*window.ZOOM+400);
$("#black_layer").width($("#scene_map").width()*window.ZOOM+400);
$("#black_layer").height($("#scene_map").height()*window.ZOOM+400)
}*/
});
if (data.fog_of_war == 1) {
window.FOG_OF_WAR = true;
window.REVEALED = data.reveals;
reset_canvas();
redraw_canvas();
//$("#fog_overlay").show();
}
else {
window.FOG_OF_WAR = false;
window.REVEALED = [];
reset_canvas();
//$("#fog_overlay").hide();
}
if (typeof data.drawings !== "undefined") {
window.DRAWINGS = data.drawings;
}
else {
window.DRAWINGS = [];
}
redraw_drawings();
for (var i = 0; i < data.tokens.length; i++) { // QUICK HACK
this.handleToken({
data: data.tokens[i]
});
}
}
handleSyncMeUp(msg) {
if (DM) {
window.ScenesHandler.sync();
ct_persist(); // force refresh of combat tracker for late users
data={
soundpad: window.SOUNDPADS[soundpad_id]
}
window.MB.sendMessage("custom/myVTT/soundpad",data); // refresh soundpad
}
}
sendMessage(eventType, data) {
var self = this;
var message = {
id: uuid(),
//datetime: Date.now(),
source: "web",
gameId: this.gameid,
userId: this.userid,
persist: false, // INTERESSANTE PER RILEGGERLI, per ora non facciamogli casini
messageScope: "gameId",
messageTarget: this.gameid,
eventType: eventType,
data: data,
// entityId :"43263440", proviamo a non metterla
// entityType:"character", // MOLTO INTERESSANTE. PENSO VENGA USATO PER CAPIRE CHE IMMAGINE METTERCI.
};
if (this.ws.readyState == this.ws.OPEN) {
this.ws.send(JSON.stringify(message));
}
else { // TRY TO RECOVER
get_cobalt_token(function(token) {
self.loadWS(token, function() {
// TODO, CONSIDER ADDING A SYNCMEUP / SCENE PAIR HERE
self.ws.send(JSON.stringify(message));
});
});
}
}
sendPing() {
self = this;
if (this.ws.readyState == this.ws.OPEN) {
this.ws.send("{\"data\": \"ping\"}");
}
else {
get_cobalt_token(function(token) {
self.loadWS(token, null);
});
}
}
}