@chat21/chat21-ionic 3.4.30-rc2 → 3.4.30

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.
Files changed (75) hide show
  1. package/CHANGELOG.md +4 -119
  2. package/angular.json +0 -1
  3. package/package.json +1 -1
  4. package/src/app/app.component.html +1 -3
  5. package/src/app/app.component.ts +16 -71
  6. package/src/app/chatlib/conversation-detail/message/image/image.component.html +0 -1
  7. package/src/app/chatlib/conversation-detail/message/image/image.component.ts +0 -19
  8. package/src/app/components/canned-response/canned-response.component.html +23 -26
  9. package/src/app/components/canned-response/canned-response.component.scss +2 -0
  10. package/src/app/components/canned-response/canned-response.component.ts +1 -3
  11. package/src/app/components/conversation-detail/message-text-area/message-text-area.component.html +1 -24
  12. package/src/app/components/conversation-detail/message-text-area/message-text-area.component.scss +0 -30
  13. package/src/app/components/conversation-detail/message-text-area/message-text-area.component.ts +9 -39
  14. package/src/app/components/conversation-info/info-content/info-content.component.ts +2 -2
  15. package/src/app/components/conversation-info/info-group/info-group.component.ts +21 -23
  16. package/src/app/components/conversations-list/header-conversations-list/header-conversations-list.component.html +1 -1
  17. package/src/app/components/conversations-list/header-conversations-list/header-conversations-list.component.ts +1 -5
  18. package/src/app/components/navbar/navbar.component.html +3 -3
  19. package/src/app/components/navbar/navbar.component.ts +38 -29
  20. package/src/app/components/project-item/project-item.component.ts +11 -11
  21. package/src/app/components/sidebar/sidebar.component.html +45 -65
  22. package/src/app/components/sidebar/sidebar.component.ts +117 -110
  23. package/src/app/components/sidebar-user-details/sidebar-user-details.component.html +2 -2
  24. package/src/app/components/sidebar-user-details/sidebar-user-details.component.ts +7 -10
  25. package/src/app/modals/create-ticket/create-ticket.page.ts +2 -4
  26. package/src/app/pages/conversation-detail/conversation-detail.page.html +3 -7
  27. package/src/app/pages/conversation-detail/conversation-detail.page.ts +7 -95
  28. package/src/app/pages/conversations-list/conversations-list.page.html +0 -2
  29. package/src/app/pages/conversations-list/conversations-list.page.ts +2 -40
  30. package/src/app/services/global-settings/global-settings.service.ts +3 -11
  31. package/src/app/services/nav-proxy.service.ts +1 -0
  32. package/src/app/services/tiledesk/tiledesk.service.ts +16 -0
  33. package/src/app/services/triggerEvents/triggerEvents.ts +0 -28
  34. package/src/app/services/websocket/websocket-js.ts +534 -59
  35. package/src/app/services/websocket/websocket.service.ts +10 -9
  36. package/src/app/shared/shared.module.ts +2 -11
  37. package/src/app/utils/globals.ts +0 -2
  38. package/src/app/utils/project-utils.ts +2 -2
  39. package/src/app/utils/utils.ts +1 -18
  40. package/src/assets/i18n/ar.json +1 -11
  41. package/src/assets/i18n/az.json +1 -11
  42. package/src/assets/i18n/de.json +1 -11
  43. package/src/assets/i18n/en.json +1 -11
  44. package/src/assets/i18n/es.json +1 -11
  45. package/src/assets/i18n/fr.json +1 -11
  46. package/src/assets/i18n/it.json +3 -13
  47. package/src/assets/i18n/kk.json +1 -11
  48. package/src/assets/i18n/pt.json +1 -11
  49. package/src/assets/i18n/ru.json +1 -11
  50. package/src/assets/i18n/sr.json +1 -11
  51. package/src/assets/i18n/sv.json +1 -11
  52. package/src/assets/i18n/tr.json +1 -11
  53. package/src/assets/i18n/uk.json +1 -11
  54. package/src/assets/i18n/uz.json +1 -12
  55. package/src/assets/js/chat21client.js +0 -36
  56. package/src/assets/test.html +2 -5
  57. package/src/chat-config-template.json +0 -1
  58. package/src/chat-config.json +0 -1
  59. package/src/chat21-core/providers/abstract/upload.service.ts +1 -5
  60. package/src/chat21-core/providers/firebase/firebase-conversation-handler.ts +1 -1
  61. package/src/chat21-core/providers/firebase/firebase-upload.service.ts +9 -136
  62. package/src/chat21-core/providers/mqtt/mqtt-conversation-handler.ts +1 -1
  63. package/src/chat21-core/providers/native/native-image-repo.ts +1 -1
  64. package/src/chat21-core/providers/native/native-upload-service.ts +45 -143
  65. package/src/chat21-core/providers/tiledesk/tiledesk-auth.service.ts +0 -3
  66. package/src/chat21-core/utils/utils.ts +2 -16
  67. package/src/app/services/project_users/project-users.service.spec.ts +0 -16
  68. package/src/app/services/project_users/project-users.service.ts +0 -63
  69. package/src/app/services/websocket/websocket-js_old.ts +0 -578
  70. package/src/app/services/websocket/websocket.worker.ts +0 -242
  71. package/src/app/utils/permissions.constants.ts +0 -138
  72. package/src/assets/img/no_data_found.png +0 -0
  73. package/src/assets/js/agentDesktop-sdk.js +0 -55
  74. package/src/assets/js/mqtt-keepalive-worker.js +0 -53
  75. package/src/chat21-core/models/projectUsers.ts +0 -19
@@ -1,85 +1,560 @@
1
- import { Injectable } from '@angular/core';
1
+
2
+ //import { Injectable } from '@angular/core';
3
+ import { forwardRef, Inject } from '@angular/core';
4
+
2
5
  import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service';
3
6
  import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance';
7
+ //@Injectable()
8
+ export class WebSocketJs {
4
9
 
5
- interface Subscription {
6
- topic: string;
7
- label?: string;
8
- onCreate?: (msg: any, notification: any) => void;
9
- onUpdate?: (msg: any, notification: any) => void;
10
- onData?: (msg: any, notification: any) => void;
11
- }
10
+ public url;
11
+ public onCreate;
12
+ public onUpdate;
13
+ public onOpen;
14
+ public onData;
15
+ public ws;
16
+ public topics;
17
+ public callbacks;
18
+ public readyState: number;
19
+ // public userHasClosed: boolean;
12
20
 
13
- @Injectable({
14
- providedIn: 'root'
15
- })
16
- export class WebSocketJs {
17
- private worker: Worker;
18
- private subscriptions: Map<string, Subscription> = new Map();
21
+ // HEARTBEAT https://github.com/zimv/websocket-heartbeat-js/blob/master/lib/index.js
22
+ private pingTimeoutId;
23
+ private pongTimeoutId;
24
+
25
+ public pingMsg = { action: "heartbeat", payload: { message: { text: "ping" } } }
26
+
27
+ public pongMsg = { action: "heartbeat", payload: { message: { text: "pong" } } }
28
+
29
+
30
+ public pongTimeout = 10000;
31
+ public pingTimeout = 15000;
32
+
33
+ // nktest
34
+ // startTimeMS = 0;
19
35
 
20
36
  private logger: LoggerService = LoggerInstance.getInstance();
21
37
 
22
38
  constructor() {
23
- this.worker = new Worker(new URL('./websocket.worker', import.meta.url));
24
-
25
- // ➤ AGGIUNTA: notifica al worker quando la tab va in background
26
- document.addEventListener("visibilitychange", () => {
27
- this.worker.postMessage({
28
- action: "visibility",
29
- data: { hidden: document.hidden }
30
- });
31
- });
32
-
33
- // ricezione dei messaggi dal worker
34
- this.worker.onmessage = (event) => {
35
- const msg = event.data;
36
- this.logger.log('[WEBSOCKET-JS] Message received from worker:', msg);
37
- // msg deve avere almeno .topic e .type (create/update/data)
38
- const sub = this.subscriptions.get(msg.topic);
39
- if (!sub) return;
40
-
41
- let object = { event: msg.payload, data: msg.data };
42
- switch (msg.method) {
43
- case 'CREATE': sub.onCreate?.(msg.payload, object); break;
44
- case 'UPDATE': sub.onUpdate?.(msg.payload, object); break;
45
- case 'DATA': sub.onData?.(msg.payload, object); break;
46
- }
47
- };
48
- }
49
39
 
50
- init(url: string) {
51
- this.worker.postMessage({ action: 'init', data: { url } });
52
- this.worker.postMessage({ action: 'visibility', data: { hidden: document.hidden } });
40
+ // this.logger.log("[WEBSOCKET-JS] HELLO !!!");
41
+ this.topics = [];
42
+ this.callbacks = new Map();
43
+
44
+ // this.sendingMessages = [];//new Map();
53
45
  }
54
46
 
55
- ref(topic: string, calledby?: string, onCreate?: (msg:any, notification: any)=>void, onUpdate?: (msg:any, notification: any)=>void, onData?: (msg:any, notification: any)=>void) {
47
+
48
+ /**
49
+ * readyState: A read-only attribute. It represents the state of the connection. It can have the following values:
50
+ * 0: Connection is in progress and has not yet been established.
51
+ * 1: Connection is established and messages can be sent between the client and the server.
52
+ * 2: Connection is going through the closing handshake.
53
+ * 3: Connection has been closed or could not be opened.
54
+ */
55
+
56
+ // -----------------------------------------------------------------------------------------------------
57
+ // @ ref - called by 'WsRequestsService' and 'WsMsgsService' & call 'subscribe'
58
+ // -----------------------------------------------------------------------------------------------------
59
+ // WsRequestsService:
60
+ // - in getCurrentProjectAndSubscribeTo_WsRequests()
61
+ // - in subscribeTo_wsRequestById() called when in
62
+ // WsRequestsMsgsComponent onInit() is got the request id from url params
63
+ // WsMsgsService
64
+ // - in subsToWS_MsgsByRequestId() called when in
65
+ // WsRequestsMsgsComponent onInit() is got the request id from url params
66
+
67
+ ref(topic, calledby, onCreate, onUpdate, onData) {
68
+ // this.logger.log('[WEBSOCKET-JS] ****** CALLING REF ****** ');
56
69
  this.logger.log('[WEBSOCKET-JS] - REF - calledby ', calledby);
57
70
  this.logger.log('[WEBSOCKET-JS] - REF - TOPIC ', topic);
71
+ this.logger.log('[WEBSOCKET-JS] - REF - CALLBACKS', this.callbacks);
58
72
 
59
- const sub: Subscription = { topic, onCreate, onUpdate, onData };
60
- this.subscriptions.set(topic, sub);
61
- this.logger.log('[WEBSOCKET-JS] - CALLBACK-SET - subscriptions', this.subscriptions);
62
- this.subscribe(topic);
63
- return sub;
73
+ if (!this.callbacks) {
74
+ this.logger.log('[WEBSOCKET-JS] - REF OOOOPS! NOT CALLBACKS ***', this.callbacks);
75
+ return
76
+ }
77
+
78
+ this.callbacks.set(topic, { onCreate: onCreate, onUpdate: onUpdate, onData: onData });
79
+ this.logger.log('[WEBSOCKET-JS] - CALLBACK-SET - callbacks', this.callbacks);
80
+
81
+ if (this.ws && this.ws.readyState == 1) {
82
+ this.logger.log('[WEBSOCKET-JS] - REF - READY STATE ', this.ws.readyState);
83
+ this.logger.log('[WEBSOCKET-JS] - REF - READY STATE = 1 > SUBSCRIBE TO TOPICS ');
84
+
85
+ this.subscribe(topic);
86
+
87
+ } else {
88
+ // this.ws = new WebSocket("wss://tiledesk-server-pre.herokuapp.com/?token=JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGRkMzBiZmYwMTk1ZjAwMTdmNzJjNmQiLCJlbWFpbCI6InByZWdpbm9AZjIxdGVzdC5pdCIsImZpcnN0bmFtZSI6Ikdpbm8iLCJsYXN0bmFtZSI6IlByZSIsImVtYWlsdmVyaWZpZWQiOnRydWUsImlhdCI6MTYwODgwNjY0MCwiYXVkIjoiaHR0cHM6Ly90aWxlZGVzay5jb20iLCJpc3MiOiJodHRwczovL3RpbGVkZXNrLmNvbSIsInN1YiI6InVzZXIiLCJqdGkiOiI1YmVmMDcxYy00ODBlLTQzYzQtOTRhYS05ZjQxYzMyNDcxMGQifQ.wv6uBn2P6H9wGb5WCYQkpPEScMU9PB1pBUzFouhJk20");
89
+
90
+ this.logger.log('[WEBSOCKET-JS] - REF - READY STATE ≠ 1 > OPEN WS AND THEN SUBSCRIBE TO TOPICS');
91
+ this.logger.log('% »»» WebSocketJs WF *** REF *** WS 2 ', this.ws);
92
+
93
+ var that = this;
94
+ if (this.ws) {
95
+ this.ws.addEventListener("open", function (event) {
96
+ that.logger.log('[WEBSOCKET-JS] - REF - OPEN EVENT *** ', event);
97
+ that.subscribe(topic);
98
+ });
99
+ } else {
100
+
101
+
102
+ }
103
+
104
+ if (this.topics.indexOf(topic) === -1) {
105
+ this.topics.push(topic);
106
+ }
107
+ }
64
108
  }
65
109
 
66
- subscribe(topic: string){
110
+ // -----------------------------------------------------------------------------------------------------
111
+ // @ subscribe - is called by 'ref' & call 'send'
112
+ // -----------------------------------------------------------------------------------------------------
113
+ subscribe(topic) {
114
+
115
+ if (this.topics.indexOf(topic) === -1) {
116
+ this.topics.push(topic);
117
+ }
67
118
  this.logger.log('[WEBSOCKET-JS] - SUBSCRIBE TO TOPIC ', topic);
68
- this.worker.postMessage({ action: 'subscribe', data: { topic } });
119
+
120
+ var message = {
121
+ action: 'subscribe',
122
+ payload: {
123
+ //topic: '/' + project_id + '/requests',
124
+ topic: topic,
125
+ message: undefined,
126
+ method: undefined
127
+ },
128
+ };
129
+ var str = JSON.stringify(message);
130
+ this.logger.log("[WEBSOCKET-JS] - SUBSCRIBE TO TOPIC - STRING TO SEND " + str, " FOR SUBSCRIBE TO TOPIC: ", topic);
131
+
132
+ this.send(str, `SUBSCRIBE to ${topic}`);
69
133
  }
70
134
 
71
- unsubscribe(topic: string) {
135
+ // -----------------------------------------------------------------------------------------------------
136
+ // @ unsubscribe
137
+ // - called by: 'WsRequestsService' > getCurrentProjectAndSubscribeTo_WsRequests()
138
+ // > unsubscribeTo_wsRequestById() called by WsRequestsMsgsComponent > On Init & On Destroy
139
+ // 'WsMsgsService' > unsubsToWS_MsgsByRequestId() > On Init & On Destroy
140
+ // - call 'send'
141
+ // -----------------------------------------------------------------------------------------------------
142
+ unsubscribe(topic) {
72
143
  this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - FROM TOPIC: ", topic);
73
- this.subscriptions.delete(topic);
74
- this.worker.postMessage({ action: 'unsubscribe', data: { topic } });
144
+ // this.logger.log("% »»» WebSocketJs WF *** UNSUBSCRIBE *** - this.topics ", this.topics);
145
+ // this.logger.log("% »»» WebSocketJs WF *** UNSUBSCRIBE *** - topic ", topic);
146
+ // this.logger.log("% »»» WebSocketJs WF *** UNSUBSCRIBE *** - callbacks ", this.callbacks);
147
+
148
+
149
+ var index = this.topics.indexOf(topic);
150
+
151
+ if (index > -1) {
152
+ this.topics.splice(index, 1);
153
+ }
154
+
155
+ this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - TOPICS AFTER SPLICE THE TOPIC ", this.topics);
156
+ this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - DELETE TOPIC FROM CALLBACKS - CALLBACKS SIZE ", this.callbacks.size);
157
+
158
+ // if (this.callbacks.length > 0) {
159
+ if (this.callbacks.size > 0) {
160
+ this.callbacks.delete(topic);
161
+ this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE - CALLBACKS AFTER DELETE TOPIC ", this.callbacks);
162
+ }
163
+
164
+ var message = {
165
+ action: 'unsubscribe',
166
+ payload: {
167
+ //topic: '/' + project_id + '/requests',
168
+ topic: topic,
169
+ message: undefined,
170
+ method: undefined
171
+ },
172
+ };
173
+ var str = JSON.stringify(message);
174
+ this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE str " + str);
175
+
176
+ if (this.ws && this.ws.readyState == 1) {
177
+ this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE TO TOPIC - STRING TO SEND " + str, " FOR UNSUBSCRIBE TO TOPIC: ", topic);
178
+ this.send(str, `UNSUSCRIBE from ${topic}`);
179
+
180
+ } else if (this.ws) {
181
+ this.logger.log("[WEBSOCKET-JS] - UN-SUBSCRIBE TRY 'SEND' BUT READY STASTE IS : ", this.ws.readyState);
182
+ }
75
183
  }
76
184
 
77
- send(message: any) {
78
- this.worker.postMessage({ action: 'send', data: { message } });
185
+ // -----------------------------------------------------------------------------------------------------
186
+ // @ send -
187
+ // -----------------------------------------------------------------------------------------------------
188
+ send(initialMessage, calling_method) {
189
+ // this.logger.log("[WEBSOCKET-JS] - SEND - INIZIAL-MSG ", initialMessage, " CALLED BY ", calling_method);
190
+
191
+ this.ws.send(initialMessage);
79
192
  }
80
193
 
194
+
195
+ // -----------------------------------------------------------------------------------------------------
196
+ // @ close (to find where is used search for x webSocketClose())
197
+ // -----------------------------------------------------------------------------------------------------
81
198
  close() {
82
- this.worker.postMessage({ action: 'close' });
83
- this.subscriptions.clear();
199
+ this.topics = [];
200
+ this.callbacks = [];
201
+ this.logger.log("[WEBSOCKET-JS] - CALLED CLOSE - TOPICS ", this.topics, ' - CALLLBACKS ', this.callbacks);
202
+
203
+ if (this.ws) {
204
+ this.ws.onclose = function () { }; // disable onclose handler first
205
+ this.ws.close();
206
+ }
207
+ this.heartReset();
208
+ }
209
+
210
+ // -----------------------------------------------------------------------------------------------------
211
+ // @ Resubscribe
212
+ // -----------------------------------------------------------------------------------------------------
213
+ resubscribe() {
214
+ this.logger.log("[WEBSOCKET-JS] - RESUBSCRIBE - TO TOPICS ", this.topics);
215
+ this.logger.log("[WEBSOCKET-JS] - RESUBSCRIBE - CALLBACKS ", this.callbacks);
216
+
217
+ if (this.topics.length > 0) {
218
+ this.topics.forEach(topic => {
219
+ this.logger.log("[WEBSOCKET-JS] - RESUBSCRIBE - SUBDCRIBE TO TOPICS ", topic);
220
+ this.subscribe(topic); // nn fa sudbcribe
221
+ });
222
+ }
223
+ }
224
+
225
+ // -----------------------------------------------------------------------------------------------------
226
+ // @ HeartCheck
227
+ // -----------------------------------------------------------------------------------------------------
228
+ heartCheck() {
229
+ this.heartReset();
230
+ this.heartStart();
231
+ }
232
+
233
+ // _heartStart() {
234
+ // // if(this.forbidReconnect) return;//Non ricollegare o eseguire il battito cardiaco
235
+ // this.pingTimeoutId = setTimeout(() => {
236
+ // // Qui viene inviato un battito cardiaco Dopo averlo ricevuto, viene restituito un messaggio di battito cardiaco.
237
+ // // onmessage Ottieni il battito cardiaco restituito per indicare che la connessione è normale
238
+ // try {
239
+ // this.logger.log('% »»» WebSocketJs - HEARTBEAT send MSG ', JSON.stringify(this.pingMsg));
240
+ // this.ws.send(JSON.stringify(this.pingMsg));
241
+ // // Se non viene ripristinato dopo un determinato periodo di tempo, il backend viene attivamente disconnesso
242
+ // this.pongTimeoutId = setTimeout(() => {
243
+ // // se onclose Si esibirà reconnect,Eseguiamo ws.close() Bene, se lo esegui direttamente reconnect Si innescherà onclose Causa riconnessione due volte
244
+ // this.ws.close();
245
+ // }, this.pongTimeout);
246
+
247
+ // } catch (e) {
248
+
249
+ // this.logger.log('% »»» WebSocketJs - HEARTBEAT err ', e);
250
+ // }
251
+
252
+ // }, this.pingTimeout);
253
+ // }
254
+
255
+
256
+ // getRemainingTime() {
257
+ // var milliSecondsTime = 15000;
258
+ // var timer;
259
+
260
+ // this.logger.log('% »»» WebSocketJs - heartStart timer 1', milliSecondsTime / 1000);
261
+ // timer = setInterval(function () {
262
+ // milliSecondsTime = milliSecondsTime - 1000;
263
+ // if (milliSecondsTime / 1000 == 0) {
264
+ // clearTimeout(timer);
265
+ // }
266
+ // else {
267
+ // this.logger.log('% »»» WebSocketJs - heartStart timer 2 ', milliSecondsTime / 1000);
268
+ // }
269
+ // }, 1000);
270
+ // }
271
+
272
+ // -----------------------------------------------------------------------------------------------------
273
+ // @ HeartStart
274
+ // -----------------------------------------------------------------------------------------------------
275
+ heartStart() {
276
+ // this.getRemainingTime();
277
+ this.pingTimeoutId = setTimeout(() => {
278
+
279
+ // Qui viene inviato un battito cardiaco Dopo averlo ricevuto, viene restituito un messaggio di battito cardiaco.
280
+ // onmessage Ottieni il battito cardiaco restituito per indicare che la connessione è normale
281
+ if (this.ws && this.ws.readyState == 1) {
282
+
283
+ this.logger.log("[WEBSOCKET-JS] - HEART-START - SEND PING-MSG");
284
+
285
+ this.send(JSON.stringify(this.pingMsg), 'HEART-START')
286
+
287
+ } else if (this.ws) {
288
+
289
+ this.logger.log("[WEBSOCKET-JS] - HEART-START - TRY TO SEND PING-MSG BUT READY STATE IS ", this.ws.readyState);
290
+
291
+ }
292
+
293
+ // Se non viene ripristinato dopo un determinato periodo di tempo, il backend viene attivamente disconnesso
294
+ this.pongTimeoutId = setTimeout(() => {
295
+ this.logger.log("[WEBSOCKET-JS] - HEART-START - PONG-TIMEOUT-ID - CLOSE WS ");
296
+ // se onclose Si esibirà reconnect,Eseguiamo ws.close() Bene, se lo esegui direttamente reconnect Si innescherà onclose Causa riconnessione due volte
297
+ this.ws.close();
298
+ }, this.pongTimeout);
299
+
300
+ }, this.pingTimeout);
301
+ }
302
+
303
+ // -----------------------------------------------------------------------------------------------------
304
+ // @ heartReset
305
+ // -----------------------------------------------------------------------------------------------------
306
+ heartReset() {
307
+ // this.logger.log("[WEBSOCKET-JS] - HEART-RESET");
308
+ clearTimeout(this.pingTimeoutId);
309
+ clearTimeout(this.pongTimeoutId);
84
310
  }
85
- }
311
+
312
+ // -----------------------------------------------------------------------------------------------------
313
+ // @ init
314
+ // -----------------------------------------------------------------------------------------------------
315
+ init(url, onCreate, onUpdate, onData, onOpen = undefined, onOpenCallback = undefined, _topics = [], _callbacks = new Map()) {
316
+
317
+
318
+
319
+ this.url = url;
320
+ this.onCreate = onCreate;
321
+ this.onUpdate = onUpdate;
322
+ this.onData = onData;
323
+ this.onOpen = onOpen;
324
+ this.topics = _topics//[];//new Map();
325
+ this.callbacks = _callbacks// new Map();
326
+ // this.userHasClosed = false;
327
+ // this.logger.log('% »»» WebSocketJs WF - closeWebsocket this.userHasClosed ' , this.userHasClosed);
328
+
329
+ // this.sendingMessages = [];//new Map();
330
+ // this.data = [];
331
+ // this.init(this.sendMesagesInSendingArray);
332
+ this.logger.log("[WEBSOCKET-JS] - CALLING INIT - url ", this.url);
333
+ this.logger.log("[WEBSOCKET-JS] - CALLING INIT - topics ", this.topics);
334
+ this.logger.log("[WEBSOCKET-JS] - CALLING INIT - url ", this.url);
335
+ this.logger.log("[WEBSOCKET-JS] - CALLING INIT - callbacks ", this.callbacks);
336
+
337
+
338
+ var that = this;
339
+ return new Promise(function (resolve, reject) {
340
+ // var options = {
341
+ // // headers: {
342
+ // // "Authorization" : "JWT " + token
343
+ // // }
344
+ // };
345
+ // this.logger.log('options', options);
346
+ // var ws = new WebSocket('ws://localhost:3000');
347
+ // var ws = new WebSocket('ws://localhost:3000/public/requests');
348
+ // var ws = new WebSocket('ws://localhost:3000/5bae41325f03b900401e39e8/messages');
349
+
350
+
351
+ // -----------------------------------------------------------------------------------------------------
352
+ // @ new WebSocket
353
+ // -----------------------------------------------------------------------------------------------------
354
+ that.ws = new WebSocket(that.url);
355
+
356
+
357
+ // -----------------------------------------------------------------------------------------------------
358
+ // @ onopen
359
+ // -----------------------------------------------------------------------------------------------------
360
+ that.ws.onopen = function (e) {
361
+ that.logger.log('[WEBSOCKET-JS] - websocket is connected ...', e);
362
+
363
+ // -----------------
364
+ // @ heartCheck
365
+ // -----------------
366
+ that.heartCheck();
367
+
368
+
369
+ if (onOpenCallback) {
370
+ onOpenCallback();
371
+ }
372
+
373
+ if (that.onOpen) {
374
+ that.onOpen();
375
+ }
376
+
377
+ }
378
+
379
+ // -----------------------------------------------------------------------------------------------------
380
+ // @ onclose
381
+ // -----------------------------------------------------------------------------------------------------
382
+ that.ws.onclose = function (e) {
383
+ that.logger.log('[WEBSOCKET-JS] websocket IS CLOSED ... Try to reconnect in 3 seconds ', e);
384
+
385
+ // this.logger.log('% »»» WebSocketJs - websocket onclose this.userHasClosed ', that.userHasClosed);
386
+ // https://stackoverflow.com/questions/3780511/reconnection-of-client-when-server-reboots-in-websocket
387
+ // Try to reconnect in 3 seconds
388
+
389
+ // --------------------
390
+ // @ init > resubscribe
391
+ // --------------------
392
+
393
+ setTimeout(function () {
394
+ that.init(url, onCreate, onUpdate, onData, onOpen, function () {
395
+ that.logger.log('[WEBSOCKET-JS] websocket IS CLOSED ... CALLING RESUSCRIBE ');
396
+ that.resubscribe();
397
+ }, that.topics, that.callbacks);
398
+ }, 3000);
399
+ }
400
+
401
+ // -----------------------------------------------------------------------------------------------------
402
+ // @ onerror
403
+ // -----------------------------------------------------------------------------------------------------
404
+ that.ws.onerror = function (err) {
405
+ that.logger.error('[WEBSOCKET-JS] websocket IS CLOSED - websocket error ...', err)
406
+ }
407
+
408
+ // -----------------------------------------------------------------------------------------------------
409
+ // @ onmessage
410
+ // -----------------------------------------------------------------------------------------------------
411
+ that.ws.onmessage = function (message) {
412
+ // that.logger.log('[WEBSOCKET-JS] websocket onmessage ', message);
413
+ // that.logger.log('[WEBSOCKET-JS] websocket onmessage data', message.data);
414
+
415
+ // 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"}]}}'
416
+ // 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"}]}}'
417
+
418
+ try {
419
+ var json = JSON.parse(message.data);
420
+ // var json = JSON.parse(test_due);
421
+ // this.logger.log('% »»» WebSocketJs - websocket onmessage JSON.parse(message.data) json payload', json.payload);
422
+ // this.logger.log('% »»» WebSocketJs - websocket onmessage JSON.parse(message.data) json payload topic', json.payload.topic);
423
+ // this.logger.log('% »»» WebSocketJs - websocket onmessage JSON.parse(message.data) json ', json);
424
+ } catch (e) {
425
+ that.logger.error('[WEBSOCKET-JS] - This doesn\'t look like a valid JSON: ', message.data);
426
+ return;
427
+ }
428
+
429
+
430
+ // -------------------
431
+ // @ heartCheck
432
+ // -------------------
433
+ that.heartCheck();
434
+
435
+ // --------------------------------------------------------------------------------------------------------------------
436
+ // @ check the action and the message's text - if action is 'heartbeat' and text is ping send the PONG message and return
437
+ // --------------------------------------------------------------------------------------------------------------------
438
+
439
+ if (json.action == "heartbeat") {
440
+
441
+ if (json.payload.message.text == "ping") {
442
+ // -------------------
443
+ // @ send PONG
444
+ // -------------------
445
+ // that.logger.log('[WEBSOCKET-JS] - RECEIVED PING -> SEND PONG MSG');
446
+
447
+ that.send(JSON.stringify(that.pongMsg), 'ON-MESSAGE')
448
+
449
+ } else {
450
+ // nk
451
+ // this.logger.log('[WEBSOCKET-JS] - NOT RECEIVED PING ');
452
+ }
453
+ return;
454
+ }
455
+
456
+ var object = { event: json.payload, data: json };
457
+ if (that.onData) {
458
+ that.onData(json.payload.message, object);
459
+ }
460
+
461
+ var callbackObj = that.callbacks.get(object.event.topic);
462
+ if (callbackObj && callbackObj.onData) {
463
+ callbackObj.onData(json.payload.message, object);
464
+ }
465
+
466
+ if (json && json.payload && json.payload.message && that.isArray(json.payload.message)) {
467
+
468
+ json.payload.message.forEach(element => {
469
+
470
+ //let insUp = that.insertOrUpdate(element);
471
+ let insUp = json.payload.method;
472
+
473
+ var object = { event: json.payload, data: element };
474
+
475
+ var callbackObj = that.callbacks.get(object.event.topic);
476
+
477
+
478
+ if (insUp == "CREATE") {
479
+ if (that.onCreate) {
480
+ that.onCreate(element, object);
481
+ }
482
+
483
+ if (callbackObj) {
484
+ callbackObj.onCreate(element, object);
485
+ }
486
+ }
487
+
488
+ if (insUp == "UPDATE") {
489
+ if (that.onUpdate) {
490
+ that.onUpdate(element, object);
491
+ }
492
+
493
+ if (callbackObj && callbackObj.onUpdate) {
494
+ callbackObj.onUpdate(element, object);
495
+ }
496
+ }
497
+ resolve({ element: element, object: object });
498
+ });
499
+
500
+ } else {
501
+ //let insUp = that.insertOrUpdate(json.payload.message);
502
+ let insUp = json.payload.method;
503
+
504
+ var object = { event: json.payload, data: json };
505
+ var callbackObj = that.callbacks.get(object.event.topic);
506
+
507
+
508
+ if (insUp == "CREATE") {
509
+ if (that.onCreate) {
510
+ that.onCreate(json.payload.message, object);
511
+ }
512
+
513
+ if (callbackObj && callbackObj.onCreate) {
514
+ callbackObj.onCreate(json.payload.message, object);
515
+ }
516
+ }
517
+
518
+ if (insUp == "UPDATE") {
519
+ if (that.onUpdate) {
520
+ that.onUpdate(json.payload.message, object);
521
+ }
522
+
523
+ if (callbackObj && callbackObj.onUpdate) {
524
+ callbackObj.onUpdate(json.payload.message, object);
525
+ }
526
+
527
+ }
528
+
529
+ resolve({ element: json.payload.message, object: object });
530
+ // resolve:
531
+ // $('#messages').after(json.text + '<br>');
532
+ }
533
+ }
534
+ }); // .PROMISE
535
+ }
536
+
537
+ // -------------------------------------
538
+ // !! not use this but the above close()
539
+ // -------------------------------------
540
+
541
+ // closeWebsocket() {
542
+ // this.topics = [];
543
+ // this.callbacks = [];
544
+ // this.logger.log('% »»» WebSocketJs WF - closeWebsocket this.ws ', this.ws)
545
+
546
+ // if (this.ws) {
547
+ // this.ws.close();
548
+ // this.logger.log('% »»» WebSocketJs WF - closeWebsocket ')
549
+ // }
550
+ // }
551
+
552
+
553
+
554
+
555
+ isArray(what) {
556
+ return Object.prototype.toString.call(what) === '[object Array]';
557
+ }
558
+
559
+
560
+ }