@chat21/chat21-ionic 3.4.27-rc21 → 3.4.27-rc22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,578 +1,84 @@
1
-
2
- //import { Injectable } from '@angular/core';
3
- import { forwardRef, Inject } from '@angular/core';
4
-
1
+ import { Injectable } from '@angular/core';
5
2
  import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service';
6
3
  import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance';
7
- //@Injectable()
8
- export class WebSocketJs {
9
-
10
- public url;
11
- public onCreate?: Function;
12
- public onUpdate?: Function;
13
- public onOpen?: Function;
14
- public onData?: Function;
15
- public ws;
16
- public topics;
17
- public callbacks;
18
- // public userHasClosed: boolean;
19
-
20
- // HEARTBEAT https://github.com/zimv/websocket-heartbeat-js/blob/master/lib/index.js
21
- private pingTimeoutId;
22
- private pongTimeoutId;
23
4
 
24
- public pingMsg = { action: "heartbeat", payload: { message: { text: "ping" } } }
25
- public pongMsg = { action: "heartbeat", payload: { message: { text: "pong" } } }
26
-
27
- public pongTimeout = 10000;
28
- public pingTimeout = 15000;
29
-
30
- private reconnectAttempts = 0;
31
- private readonly maxReconnectDelay = 30000;
32
- private manuallyClosed = false;
5
+ interface Subscription {
6
+ topic: string;
7
+ label?: string;
8
+ onCreate?: (msg: any) => void;
9
+ onUpdate?: (msg: any) => void;
10
+ onData?: (msg: any) => void;
11
+ }
33
12
 
34
- // nktest
35
- // startTimeMS = 0;
13
+ @Injectable({
14
+ providedIn: 'root'
15
+ })
16
+ export class WebSocketJs {
17
+ private worker: Worker;
18
+ private subscriptions: Map<string, Subscription> = new Map();
36
19
 
37
20
  private logger: LoggerService = LoggerInstance.getInstance();
38
21
 
39
22
  constructor() {
23
+ this.worker = new Worker(new URL('./websocket.worker', import.meta.url));
24
+
25
+ // ricezione dei messaggi dal worker
26
+ this.worker.onmessage = (event) => {
27
+ const msg = event.data;
28
+ this.logger.log('[WEBSOCKET-JS] Message received from worker:', msg);
29
+ // msg deve avere almeno .topic e .type (create/update/data)
30
+ const sub = this.subscriptions.get(msg.topic);
31
+ if (!sub) return;
32
+
33
+ switch (msg.method) {
34
+ case 'CREATE': sub.onCreate?.(msg.payload); break;
35
+ case 'UPDATE': sub.onUpdate?.(msg.payload); break;
36
+ case 'DATA': sub.onData?.(msg.payload); break;
37
+ }
40
38
 
41
- // this.logger.log("[WEBSOCKET-JS] HELLO !!!");
42
- this.topics = [];
43
- this.callbacks = new Map();
39
+ // AGGIUNTA: notifica al worker quando la tab va in background
40
+ document.addEventListener("visibilitychange", () => {
41
+ this.worker.postMessage({
42
+ action: "visibility",
43
+ data: { hidden: document.hidden }
44
+ });
45
+ });
44
46
 
45
- // this.sendingMessages = [];//new Map();
47
+ };
46
48
  }
47
49
 
50
+ init(url: string) {
51
+ this.worker.postMessage({ action: 'init', data: { url } });
52
+ }
48
53
 
49
- /**
50
- * readyState: A read-only attribute. It represents the state of the connection. It can have the following values:
51
- * 0: Connection is in progress and has not yet been established.
52
- * 1: Connection is established and messages can be sent between the client and the server.
53
- * 2: Connection is going through the closing handshake.
54
- * 3: Connection has been closed or could not be opened.
55
- */
56
-
57
- // -----------------------------------------------------------------------------------------------------
58
- // @ ref - called by 'WsRequestsService' and 'WsMsgsService' & call 'subscribe'
59
- // -----------------------------------------------------------------------------------------------------
60
- // WsRequestsService:
61
- // - in getCurrentProjectAndSubscribeTo_WsRequests()
62
- // - in subscribeTo_wsRequestById() called when in
63
- // WsRequestsMsgsComponent onInit() is got the request id from url params
64
- // WsMsgsService
65
- // - in subsToWS_MsgsByRequestId() called when in
66
- // WsRequestsMsgsComponent onInit() is got the request id from url params
67
-
68
- ref(topic, calledby, onCreate, onUpdate, onData) {
69
- // this.logger.log('[WEBSOCKET-JS] ****** CALLING REF ****** ');
54
+ ref(topic: string, calledby?: string, onCreate?: (msg:any)=>void, onUpdate?: (msg:any)=>void, onData?: (msg:any)=>void) {
70
55
  this.logger.log('[WEBSOCKET-JS] - REF - calledby ', calledby);
71
56
  this.logger.log('[WEBSOCKET-JS] - REF - TOPIC ', topic);
72
- this.logger.log('[WEBSOCKET-JS] - REF - CALLBACKS', this.callbacks);
73
-
74
- if (!this.callbacks) {
75
- this.logger.log('[WEBSOCKET-JS] - REF OOOOPS! NOT CALLBACKS ***', this.callbacks);
76
- return
77
- }
78
57
 
79
- this.callbacks.set(topic, { onCreate: onCreate, onUpdate: onUpdate, onData: onData });
80
- this.logger.log('[WEBSOCKET-JS] - CALLBACK-SET - callbacks', this.callbacks);
81
-
82
- if (this.ws && this.ws.readyState == WebSocket.OPEN) {
83
- this.logger.log('[WEBSOCKET-JS] - REF - READY STATE ', this.ws.readyState);
84
- this.logger.log('[WEBSOCKET-JS] - REF - READY STATE = 1 > SUBSCRIBE TO TOPICS ');
85
-
86
- this.subscribe(topic);
87
-
88
- } else {
89
- // this.ws = new WebSocket("wss://tiledesk-server-pre.herokuapp.com/?token=JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGRkMzBiZmYwMTk1ZjAwMTdmNzJjNmQiLCJlbWFpbCI6InByZWdpbm9AZjIxdGVzdC5pdCIsImZpcnN0bmFtZSI6Ikdpbm8iLCJsYXN0bmFtZSI6IlByZSIsImVtYWlsdmVyaWZpZWQiOnRydWUsImlhdCI6MTYwODgwNjY0MCwiYXVkIjoiaHR0cHM6Ly90aWxlZGVzay5jb20iLCJpc3MiOiJodHRwczovL3RpbGVkZXNrLmNvbSIsInN1YiI6InVzZXIiLCJqdGkiOiI1YmVmMDcxYy00ODBlLTQzYzQtOTRhYS05ZjQxYzMyNDcxMGQifQ.wv6uBn2P6H9wGb5WCYQkpPEScMU9PB1pBUzFouhJk20");
90
-
91
- this.logger.log('[WEBSOCKET-JS] - REF - READY STATE ≠ 1 > OPEN WS AND THEN SUBSCRIBE TO TOPICS');
92
- this.logger.log('% »»» WebSocketJs WF *** REF *** WS 2 ', this.ws);
93
-
94
- var that = this;
95
- if (this.ws) {
96
- this.ws.addEventListener("open", function (event) {
97
- that.logger.log('[WEBSOCKET-JS] - REF - OPEN EVENT *** ', event);
98
- that.subscribe(topic);
99
- });
100
- } else {
101
-
102
-
103
- }
104
-
105
- if (this.topics.indexOf(topic) === -1) {
106
- this.topics.push(topic);
107
- }
108
- }
58
+ const sub: Subscription = { topic, onCreate, onUpdate, onData };
59
+ this.subscriptions.set(topic, sub);
60
+ this.logger.log('[WEBSOCKET-JS] - CALLBACK-SET - subscriptions', this.subscriptions);
61
+ this.subscribe(topic);
62
+ return sub;
109
63
  }
110
64
 
111
- // -----------------------------------------------------------------------------------------------------
112
- // @ subscribe - is called by 'ref' & call 'send'
113
- // -----------------------------------------------------------------------------------------------------
114
- subscribe(topic) {
115
-
116
- if (this.topics.indexOf(topic) === -1) {
117
- this.topics.push(topic);
118
- }
65
+ subscribe(topic: string){
119
66
  this.logger.log('[WEBSOCKET-JS] - SUBSCRIBE TO TOPIC ', topic);
120
-
121
- var message = {
122
- action: 'subscribe',
123
- payload: {
124
- //topic: '/' + project_id + '/requests',
125
- topic: topic,
126
- message: undefined,
127
- method: undefined
128
- },
129
- };
130
- this.logger.log("[WEBSOCKET-JS] - SUBSCRIBE TO TOPIC - DATA TO SEND ", message, " FOR SUBSCRIBE TO TOPIC: ", topic);
131
- this.send(message, `SUBSCRIBE to ${topic}`);
67
+ this.worker.postMessage({ action: 'subscribe', data: { topic } });
132
68
  }
133
69
 
134
- // -----------------------------------------------------------------------------------------------------
135
- // @ unsubscribe
136
- // - called by: 'WsRequestsService' > getCurrentProjectAndSubscribeTo_WsRequests()
137
- // > unsubscribeTo_wsRequestById() called by WsRequestsMsgsComponent > On Init & On Destroy
138
- // 'WsMsgsService' > unsubsToWS_MsgsByRequestId() > On Init & On Destroy
139
- // - call 'send'
140
- // -----------------------------------------------------------------------------------------------------
141
- unsubscribe(topic) {
70
+ unsubscribe(topic: string) {
142
71
  this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - FROM TOPIC: ", topic);
143
- // this.logger.log("% »»» WebSocketJs WF *** UNSUBSCRIBE *** - this.topics ", this.topics);
144
- // this.logger.log("% »»» WebSocketJs WF *** UNSUBSCRIBE *** - topic ", topic);
145
- // this.logger.log("% »»» WebSocketJs WF *** UNSUBSCRIBE *** - callbacks ", this.callbacks);
146
-
147
-
148
- var index = this.topics.indexOf(topic);
149
-
150
- if (index > -1) {
151
- this.topics.splice(index, 1);
152
- }
153
-
154
- this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - TOPICS AFTER SPLICE THE TOPIC ", this.topics);
155
- this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - DELETE TOPIC FROM CALLBACKS - CALLBACKS SIZE ", this.callbacks.size);
156
-
157
- // if (this.callbacks.length > 0) {
158
- if (this.callbacks.size > 0) {
159
- this.callbacks.delete(topic);
160
- this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - CALLBACKS AFTER DELETE TOPIC ", this.callbacks);
161
- }
162
-
163
- var message = {
164
- action: 'unsubscribe',
165
- payload: {
166
- //topic: '/' + project_id + '/requests',
167
- topic: topic,
168
- message: undefined,
169
- method: undefined
170
- },
171
- };
172
- this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE " + message);
173
-
174
- if (this.ws && this.ws.readyState == WebSocket.OPEN) {
175
- this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE TO TOPIC - DATA TO SEND ", message, " FOR UNSUBSCRIBE TO TOPIC: ", topic);
176
- this.send(message, `UNSUSCRIBE from ${topic}`);
177
-
178
- } else if (this.ws) {
179
- this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE TRY 'SEND' BUT READY STASTE IS : ", this.ws.readyState);
180
- }
72
+ this.subscriptions.delete(topic);
73
+ this.worker.postMessage({ action: 'unsubscribe', data: { topic } });
181
74
  }
182
75
 
183
- // -----------------------------------------------------------------------------------------------------
184
- // @ send -
185
- // -----------------------------------------------------------------------------------------------------
186
- send(data, calling_method) {
187
- // this.logger.log("[WEBSOCKET-JS] - SEND - INIZIAL-MSG ", initialMessage, " CALLED BY ", calling_method);
188
-
189
- this.ws.send(JSON.stringify(data));
76
+ send(message: any) {
77
+ this.worker.postMessage({ action: 'send', data: { message } });
190
78
  }
191
79
 
192
-
193
- // -----------------------------------------------------------------------------------------------------
194
- // @ close (to find where is used search for x webSocketClose())
195
- // -----------------------------------------------------------------------------------------------------
196
80
  close() {
197
- this.topics = [];
198
- this.callbacks = [];
199
- this.logger.log("[WEBSOCKET-JS] - CALLED CLOSE - TOPICS ", this.topics, ' - CALLLBACKS ', this.callbacks);
200
-
201
- if (this.ws) {
202
- this.ws.onclose = function () { }; // disable onclose handler first
203
- this.ws.close();
204
- }
205
- this.heartReset();
206
- this.manuallyClosed = true;
207
- }
208
-
209
- reconnect(url, onCreate, onUpdate, onData, onOpen = undefined, onOpenCallback = undefined, _topics = [], _callbacks = new Map()) {
210
- this.reconnectAttempts++;
211
- const delay = Math.min(this.reconnectAttempts * 1000, this.maxReconnectDelay);
212
-
213
- console.log(`WebSocket reconnect in ${delay}ms`);
214
- const that = this;
215
- setTimeout(() => {
216
- if (!that.manuallyClosed) {
217
- that.init(url, onCreate, onUpdate, onData, onOpen, function () {
218
- that.logger.log('[WEBSOCKET-JS] websocket IS CLOSED ... CALLING RESUSCRIBE ');
219
- that.resubscribe();
220
- }, that.topics, that.callbacks);
221
- }
222
- }, delay);
223
- }
224
-
225
- // -----------------------------------------------------------------------------------------------------
226
- // @ Resubscribe
227
- // -----------------------------------------------------------------------------------------------------
228
- resubscribe() {
229
- this.logger.log("[WEBSOCKET-JS] - RESUBSCRIBE - TO TOPICS ", this.topics);
230
- this.logger.log("[WEBSOCKET-JS] - RESUBSCRIBE - CALLBACKS ", this.callbacks);
231
-
232
- if (this.topics.length > 0) {
233
- this.topics.forEach(topic => {
234
- this.logger.log("[WEBSOCKET-JS] - RESUBSCRIBE - SUBDCRIBE TO TOPICS ", topic);
235
- this.subscribe(topic); // nn fa sudbcribe
236
- });
237
- }
238
- }
239
-
240
- // -----------------------------------------------------------------------------------------------------
241
- // @ HeartCheck
242
- // -----------------------------------------------------------------------------------------------------
243
- heartCheck() {
244
- this.heartReset();
245
- this.heartStart();
246
- }
247
-
248
- // _heartStart() {
249
- // // if(this.forbidReconnect) return;//Non ricollegare o eseguire il battito cardiaco
250
- // this.pingTimeoutId = setTimeout(() => {
251
- // // Qui viene inviato un battito cardiaco Dopo averlo ricevuto, viene restituito un messaggio di battito cardiaco.
252
- // // onmessage Ottieni il battito cardiaco restituito per indicare che la connessione è normale
253
- // try {
254
- // this.logger.log('% »»» WebSocketJs - HEARTBEAT send MSG ', JSON.stringify(this.pingMsg));
255
- // this.ws.send(JSON.stringify(this.pingMsg));
256
- // // Se non viene ripristinato dopo un determinato periodo di tempo, il backend viene attivamente disconnesso
257
- // this.pongTimeoutId = setTimeout(() => {
258
- // // se onclose Si esibirà reconnect,Eseguiamo ws.close() Bene, se lo esegui direttamente reconnect Si innescherà onclose Causa riconnessione due volte
259
- // this.ws.close();
260
- // }, this.pongTimeout);
261
-
262
- // } catch (e) {
263
-
264
- // this.logger.log('% »»» WebSocketJs - HEARTBEAT err ', e);
265
- // }
266
-
267
- // }, this.pingTimeout);
268
- // }
269
-
270
-
271
- // getRemainingTime() {
272
- // var milliSecondsTime = 15000;
273
- // var timer;
274
-
275
- // this.logger.log('% »»» WebSocketJs - heartStart timer 1', milliSecondsTime / 1000);
276
- // timer = setInterval(function () {
277
- // milliSecondsTime = milliSecondsTime - 1000;
278
- // if (milliSecondsTime / 1000 == 0) {
279
- // clearTimeout(timer);
280
- // }
281
- // else {
282
- // this.logger.log('% »»» WebSocketJs - heartStart timer 2 ', milliSecondsTime / 1000);
283
- // }
284
- // }, 1000);
285
- // }
286
-
287
- // -----------------------------------------------------------------------------------------------------
288
- // @ HeartStart
289
- // -----------------------------------------------------------------------------------------------------
290
- private heartStart() {
291
- // this.getRemainingTime();
292
-
293
- // usa intervallo adattivo se tab è in background (Chrome throtla i timer)
294
- const adaptivePing = document.hidden ? this.pingTimeout * 3 : this.pingTimeout;
295
-
296
- // pianifica invio ping
297
- this.pingTimeoutId = setTimeout(() => {
298
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
299
-
300
- // Qui viene inviato un battito cardiaco. Dopo averlo ricevuto, viene restituito un messaggio di battito cardiaco.
301
- // onmessage Ottieni il battito cardiaco restituito per indicare che la connessione è normale
302
- this.send(this.pingMsg, 'HEART-START')
303
-
304
- // Se non viene ripristinato dopo un determinato periodo di tempo, il backend viene attivamente disconnesso
305
- this.pongTimeoutId = setTimeout(() => {
306
- this.logger.log("[WEBSOCKET-JS] - HEART-START - PONG-TIMEOUT-ID - CLOSE WS ");
307
- // se onclose Si esibirà reconnect,Eseguiamo ws.close() Bene, se lo esegui direttamente reconnect Si innescherà onclose Causa riconnessione due volte
308
- this.ws.close();
309
- }, this.pongTimeout) as unknown as number;
310
-
311
-
312
- }, adaptivePing);
313
-
81
+ this.worker.postMessage({ action: 'close' });
82
+ this.subscriptions.clear();
314
83
  }
315
-
316
- // -----------------------------------------------------------------------------------------------------
317
- // @ heartReset
318
- // -----------------------------------------------------------------------------------------------------
319
- private heartReset() {
320
- if (this.pongTimeoutId !== undefined) {
321
- clearTimeout(this.pongTimeoutId);
322
- this.pongTimeoutId = undefined;
323
- }
324
-
325
- if (this.pingTimeoutId !== undefined) {
326
- clearTimeout(this.pingTimeoutId);
327
- this.pingTimeoutId = undefined;
328
- }
329
- }
330
-
331
- // -----------------------------------------------------------------------------------------------------
332
- // @ init
333
- // -----------------------------------------------------------------------------------------------------
334
- init(url, onCreate, onUpdate, onData, onOpen = undefined, onOpenCallback = undefined, _topics = [], _callbacks = new Map()) {
335
-
336
-
337
- this.manuallyClosed = false;
338
- this.url = url;
339
- this.onCreate = onCreate;
340
- this.onUpdate = onUpdate;
341
- this.onData = onData;
342
- this.onOpen = onOpen;
343
- this.topics = _topics//[];//new Map();
344
- this.callbacks = _callbacks// new Map();
345
- // this.userHasClosed = false;
346
- // this.logger.log('% »»» WebSocketJs WF - closeWebsocket this.userHasClosed ' , this.userHasClosed);
347
-
348
- // this.sendingMessages = [];//new Map();
349
- // this.data = [];
350
- // this.init(this.sendMesagesInSendingArray);
351
- this.logger.log("[WEBSOCKET-JS] - CALLING INIT - url ", this.url);
352
- this.logger.log("[WEBSOCKET-JS] - CALLING INIT - topics ", this.topics);
353
- this.logger.log("[WEBSOCKET-JS] - CALLING INIT - url ", this.url);
354
- this.logger.log("[WEBSOCKET-JS] - CALLING INIT - callbacks ", this.callbacks);
355
-
356
-
357
- var that = this;
358
- return new Promise(function (resolve, reject) {
359
- // var options = {
360
- // // headers: {
361
- // // "Authorization" : "JWT " + token
362
- // // }
363
- // };
364
- // this.logger.log('options', options);
365
- // var ws = new WebSocket('ws://localhost:3000');
366
- // var ws = new WebSocket('ws://localhost:3000/public/requests');
367
- // var ws = new WebSocket('ws://localhost:3000/5bae41325f03b900401e39e8/messages');
368
-
369
-
370
- // -----------------------------------------------------------------------------------------------------
371
- // @ new WebSocket
372
- // -----------------------------------------------------------------------------------------------------
373
- that.ws = new WebSocket(that.url);
374
-
375
-
376
- // -----------------------------------------------------------------------------------------------------
377
- // @ onopen
378
- // -----------------------------------------------------------------------------------------------------
379
- that.ws.onopen = function (e) {
380
- that.logger.log('[WEBSOCKET-JS] - websocket is connected ...', e);
381
-
382
- // Inizializza heartbeat
383
- that.heartCheck();
384
- that.reconnectAttempts = 0;
385
-
386
- if (onOpenCallback) { onOpenCallback(); }
387
- if (that.onOpen) { that.onOpen(); }
388
-
389
- }
390
-
391
- // -----------------------------------------------------------------------------------------------------
392
- // @ onclose
393
- // -----------------------------------------------------------------------------------------------------
394
- that.ws.onclose = function (e) {
395
- that.logger.log('[WEBSOCKET-JS] websocket IS CLOSED ... Try to reconnect in 3 seconds ', e);
396
-
397
- // this.logger.log('% »»» WebSocketJs - websocket onclose this.userHasClosed ', that.userHasClosed);
398
- // https://stackoverflow.com/questions/3780511/reconnection-of-client-when-server-reboots-in-websocket
399
- // Try to reconnect in 3 seconds
400
-
401
- // --------------------
402
- // @ init > resubscribe
403
- // --------------------
404
- that.heartReset();
405
-
406
- if (!that.manuallyClosed) {
407
- that.reconnect(url, onCreate, onUpdate, onData, onOpen, function () {
408
- that.logger.log('[WEBSOCKET-JS] websocket IS CLOSED ... CALLING RESUSCRIBE ');
409
- that.resubscribe();
410
- }, that.topics, that.callbacks);
411
- }
412
-
413
- // setTimeout(function () {
414
- // that.init(url, onCreate, onUpdate, onData, onOpen, function () {
415
- // that.logger.log('[WEBSOCKET-JS] websocket IS CLOSED ... CALLING RESUSCRIBE ');
416
- // that.resubscribe();
417
- // }, that.topics, that.callbacks);
418
- // }, 3000);
419
- }
420
-
421
- // -----------------------------------------------------------------------------------------------------
422
- // @ onerror
423
- // -----------------------------------------------------------------------------------------------------
424
- that.ws.onerror = function (err) {
425
- that.logger.error('[WEBSOCKET-JS] websocket IS CLOSED - websocket error ...', err)
426
- }
427
-
428
- // -----------------------------------------------------------------------------------------------------
429
- // @ onmessage
430
- // -----------------------------------------------------------------------------------------------------
431
- that.ws.onmessage = function (message) {
432
- // that.logger.log('[WEBSOCKET-JS] websocket onmessage ', message);
433
- // that.logger.log('[WEBSOCKET-JS] websocket onmessage data', message.data);
434
-
435
- // let test = '{ "action": "publish","payload": {"topic": "/5df26badde7e1c001743b63c/requests", "method": "CREATE", "message": [ { "_id": "5f29372d690e6f0034edf100", "status": 200, "preflight": false, "hasBot": true, "participants": ["bot_5df272e8de7e1c001743b645"], "participantsAgents": [], "participantsBots": ["5df272e8de7e1c001743b645"], "request_id": "support-group-MDszsSJlwqQn1_WCh6u", "requester": "5f29371b690e6f0034edf0f5", "lead": "5f29372d690e6f0034edf0ff", "first_text": "ocourse the email is valid ","department": "5df26badde7e1c001743b63e", "agents": [{"user_available": true,"online_status": "online", "number_assigned_requests": 35, "_id": "5e0f2119705a35001725714d","id_project": "5df26badde7e1c001743b63c", "id_user": "5aaa99024c3b110014b478f0", "role": "admin", "createdBy": "5df26ba1de7e1c001743b637","createdAt": "2020-01-03T11:10:17.123Z", "updatedAt": "2020-01-03T11:10:17.123Z", "__v": 0 }, { "user_available": false, "online_status": "offline", "number_assigned_requests": 0, "_id": "5e1a13824437eb0017f712b4", "id_project": "5df26badde7e1c001743b63c","id_user": "5ac7521787f6b50014e0b592", "role": "admin", "createdBy": "5df26ba1de7e1c001743b637", "createdAt": "2020-01-11T18:27:14.657Z","updatedAt": "2020-01-11T18:27:14.657Z", "__v": 0}, { "user_available": false,"online_status": "offline", "number_assigned_requests": 0, "_id": "5df26bdfde7e1c001743b640", "id_project": "5df26badde7e1c001743b63c", "id_user": "5de9200d6722370017731969","role": "admin","createdBy": "5df26ba1de7e1c001743b637", "createdAt": "2019-12-12T16:33:35.244Z", "updatedAt": "2019-12-12T16:33:35.244Z","__v": 0 }, {"user_available": true, "online_status": "online","number_assigned_requests": -11, "_id": "5eb1a3647ac005003480f54d", "id_project": "5df26badde7e1c001743b63c","id_user": "5e09d16d4d36110017506d7f","role": "owner", "createdBy": "5aaa99024c3b110014b478f0","createdAt": "2020-05-05T17:33:24.328Z", "updatedAt": "2020-05-05T17:33:24.328Z","__v": 0}], "sourcePage": "https://www.tiledesk.com/pricing-self-managed/", "language": "en","userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36","attributes": { "departmentId": "5df26badde7e1c001743b63e","departmentName": "Default Department","ipAddress": "115.96.30.154","client": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36","sourcePage": "https://www.tiledesk.com/pricing-self-managed/", "projectId": "5df26badde7e1c001743b63c", "requester_id": "ce31d3fd-a358-49c7-9b9f-5aead8330063", "subtype": "info","decoded_jwt": {"_id": "ce31d3fd-a358-49c7-9b9f-5aead8330063","firstname": "Guest", "id": "ce31d3fd-a358-49c7-9b9f-5aead8330063", "fullName": "Guest ","iat": 1596536604,"aud": "https://tiledesk.com","iss": "https://tiledesk.com","sub": "guest","jti": "702a4a7e-e56a-43cf-aadd-376f7c12f633"}},"id_project": "5df26badde7e1c001743b63c","createdBy": "ce31d3fd-a358-49c7-9b9f-5aead8330063","tags": [], "notes": [],"channel": {"name": "chat21"},"createdAt": "2020-08-04T10:23:41.641Z","updatedAt": "2021-03-25T18:01:13.371Z","__v": 3,"assigned_at": "2020-08-04T10:25:26.059Z","channelOutbound": {"name": "chat21"},"snapshot": {"agents": [{"id_user": "5aaa99024c3b110014b478f0"}, {"id_user": "5ac7521787f6b50014e0b592"}, {"id_user": "5de9200d6722370017731969"}, { "id_user": "5e09d16d4d36110017506d7f"}]},"id": "5f29372d690e6f0034edf100","requester_id": "5f29372d690e6f0034edf0ff"}]}}'
436
- // let test_due = '{ "action": "publish","payload": {"topic": "/5df26badde7e1c001743b63c/requests", "method": "CREATE", "message": [ { "_id": "5f29372d690e6f0034edf100", "status": 200, "preflight": false, "hasBot": true, "participants": ["bot_5df272e8de7e1c001743b645"], "participantsAgents": [], "participantsBots": ["5df272e8de7e1c001743b645"], "request_id": "support-group-MDszsSJlwqQn1_WCh6u", "requester": "5f29371b690e6f0034edf0f5", "lead": "5f29372d690e6f0034edf0ff", "first_text": "ocourse the email is valid ","department": "5df26badde7e1c001743b63e", "agents": [{"user_available": true,"online_status": "online", "number_assigned_requests": 35, "_id": "5e0f2119705a35001725714d","id_project": "5df26badde7e1c001743b63c", "id_user": "5aaa99024c3b110014b478f0", "role": "admin", "createdBy": "5df26ba1de7e1c001743b637","createdAt": "2020-01-03T11:10:17.123Z", "updatedAt": "2020-01-03T11:10:17.123Z", "__v": 0 }, { "user_available": false, "online_status": "offline", "number_assigned_requests": 0, "_id": "5e1a13824437eb0017f712b4", "id_project": "5df26badde7e1c001743b63c","id_user": "5ac7521787f6b50014e0b592", "role": "admin", "createdBy": "5df26ba1de7e1c001743b637", "createdAt": "2020-01-11T18:27:14.657Z","updatedAt": "2020-01-11T18:27:14.657Z", "__v": 0}, { "user_available": false,"online_status": "offline", "number_assigned_requests": 0, "_id": "5df26bdfde7e1c001743b640", "id_project": "5df26badde7e1c001743b63c", "id_user": "5de9200d6722370017731969","role": "admin","createdBy": "5df26ba1de7e1c001743b637", "createdAt": "2019-12-12T16:33:35.244Z", "updatedAt": "2019-12-12T16:33:35.244Z","__v": 0 }, {"user_available": true, "online_status": "online","number_assigned_requests": -11, "_id": "5eb1a3647ac005003480f54d", "id_project": "5df26badde7e1c001743b63c","id_user": "5e09d16d4d36110017506d7f","role": "owner", "createdBy": "5aaa99024c3b110014b478f0","createdAt": "2020-05-05T17:33:24.328Z", "updatedAt": "2020-05-05T17:33:24.328Z","__v": 0}], "sourcePage": "https://www.tiledesk.com/pricing-self-managed/", "language": "en","userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36","attributes": { "departmentId": "5df26badde7e1c001743b63e","departmentName": "Default Department","ipAddress": "115.96.30.154","client": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36","sourcePage": "https://www.tiledesk.com/pricing-self-managed/", "projectId": "5df26badde7e1c001743b63c", "requester_id": "ce31d3fd-a358-49c7-9b9f-5aead8330063", "subtype": "info","decoded_jwt": {"_id": "ce31d3fd-a358-49c7-9b9f-5aead8330063","firstname": "Guest", "id": "ce31d3fd-a358-49c7-9b9f-5aead8330063", "fullName": "Guest ","iat": 1596536604,"aud": "https://tiledesk.com","iss": "https://tiledesk.com","sub": "guest","jti": "702a4a7e-e56a-43cf-aadd-376f7c12f633"}},"id_project": "5df26badde7e1c001743b63c","createdBy": "ce31d3fd-a358-49c7-9b9f-5aead8330063","tags": [], "notes": [],"channel": {"name": "chat21"},"createdAt": "2020-08-04T10:23:41.641Z","updatedAt": "2021-03-25T18:01:13.371Z","__v": 3,"assigned_at": "2020-08-04T10:25:26.059Z","channelOutbound": {"name": "chat21"},"_snapshot": {"agents": [{"id_user": "5aaa99024c3b110014b478f0"}, {"id_user": "5ac7521787f6b50014e0b592"}, {"id_user": "5de9200d6722370017731969"}, { "id_user": "5e09d16d4d36110017506d7f"}]},"id": "5f29372d690e6f0034edf100","requester_id": "5f29372d690e6f0034edf0ff"}]}}'
437
-
438
- let json;
439
- try {
440
- json = JSON.parse(message.data);
441
- // var json = JSON.parse(test_due);
442
- // this.logger.log('% »»» WebSocketJs - websocket onmessage JSON.parse(message.data) json payload', json.payload);
443
- // this.logger.log('% »»» WebSocketJs - websocket onmessage JSON.parse(message.data) json payload topic', json.payload.topic);
444
- // this.logger.log('% »»» WebSocketJs - websocket onmessage JSON.parse(message.data) json ', json);
445
- } catch (e) {
446
- that.logger.error('[WEBSOCKET-JS] - This doesn\'t look like a valid JSON: ', message.data);
447
- return;
448
- }
449
-
450
-
451
- // -----------------------
452
- // HEARTBEAT HANDLING
453
- // @ check the action and the message's text -
454
- // if action is 'heartbeat' and text is ping send the PONG message and return
455
- // -----------------------
456
- if (json.action === "heartbeat") {
457
- const text = json?.payload?.message?.text;
458
-
459
- // Server -> Client ping
460
- if (text === "ping") {
461
- that.send(that.pongMsg, 'ON-MESSAGE');
462
- return;
463
- }
464
-
465
- // Server -> Client pong (risposta al nostro ping)
466
- if (text === "pong") {
467
- that.heartCheck();
468
- return;
469
- }
470
-
471
- return;
472
- }
473
-
474
- var object = { event: json.payload, data: json };
475
- if (that.onData) {
476
- that.onData(json.payload.message, object);
477
- }
478
-
479
- var callbackObj = that.callbacks.get(object.event.topic);
480
- if (callbackObj && callbackObj.onData) {
481
- callbackObj.onData(json.payload.message, object);
482
- }
483
-
484
- if (json && json.payload && json.payload.message && that.isArray(json.payload.message)) {
485
-
486
- json.payload.message.forEach(element => {
487
-
488
- //let insUp = that.insertOrUpdate(element);
489
- let insUp = json.payload.method;
490
-
491
- var object = { event: json.payload, data: element };
492
-
493
- var callbackObj = that.callbacks.get(object.event.topic);
494
-
495
-
496
- if (insUp == "CREATE") {
497
- if (that.onCreate) {
498
- that.onCreate(element, object);
499
- }
500
-
501
- if (callbackObj) {
502
- callbackObj.onCreate(element, object);
503
- }
504
- }
505
-
506
- if (insUp == "UPDATE") {
507
- if (that.onUpdate) {
508
- that.onUpdate(element, object);
509
- }
510
-
511
- if (callbackObj && callbackObj.onUpdate) {
512
- callbackObj.onUpdate(element, object);
513
- }
514
- }
515
- resolve({ element: element, object: object });
516
- });
517
-
518
- } else {
519
- //let insUp = that.insertOrUpdate(json.payload.message);
520
- let insUp = json.payload.method;
521
-
522
- var object = { event: json.payload, data: json };
523
- var callbackObj = that.callbacks.get(object.event.topic);
524
-
525
-
526
- if (insUp == "CREATE") {
527
- if (that.onCreate) {
528
- that.onCreate(json.payload.message, object);
529
- }
530
-
531
- if (callbackObj && callbackObj.onCreate) {
532
- callbackObj.onCreate(json.payload.message, object);
533
- }
534
- }
535
-
536
- if (insUp == "UPDATE") {
537
- if (that.onUpdate) {
538
- that.onUpdate(json.payload.message, object);
539
- }
540
-
541
- if (callbackObj && callbackObj.onUpdate) {
542
- callbackObj.onUpdate(json.payload.message, object);
543
- }
544
-
545
- }
546
-
547
- resolve({ element: json.payload.message, object: object });
548
- // resolve:
549
- // $('#messages').after(json.text + '<br>');
550
- }
551
- }
552
- }); // .PROMISE
553
- }
554
-
555
- // -------------------------------------
556
- // !! not use this but the above close()
557
- // -------------------------------------
558
-
559
- // closeWebsocket() {
560
- // this.topics = [];
561
- // this.callbacks = [];
562
- // this.logger.log('% »»» WebSocketJs WF - closeWebsocket this.ws ', this.ws)
563
-
564
- // if (this.ws) {
565
- // this.ws.close();
566
- // this.logger.log('% »»» WebSocketJs WF - closeWebsocket ')
567
- // }
568
- // }
569
-
570
-
571
-
572
-
573
- isArray(what) {
574
- return Object.prototype.toString.call(what) === '[object Array]';
575
- }
576
-
577
-
578
- }
84
+ }