@twilio/conversations 2.0.0-rc.1 → 2.0.1-canary.1

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 (90) hide show
  1. package/README.md +25 -28
  2. package/dist/browser.js +3125 -3460
  3. package/dist/browser.js.map +1 -1
  4. package/dist/docs/assets/js/search.js +1 -1
  5. package/dist/docs/classes/AggregatedDeliveryReceipt.html +22 -6
  6. package/dist/docs/classes/Client.html +78 -33
  7. package/dist/docs/classes/Conversation.html +33 -17
  8. package/dist/docs/classes/DetailedDeliveryReceipt.html +22 -6
  9. package/dist/docs/classes/Media.html +23 -7
  10. package/dist/docs/classes/Message.html +23 -7
  11. package/dist/docs/classes/MessageBuilder.html +3280 -0
  12. package/dist/docs/classes/Participant.html +23 -7
  13. package/dist/docs/classes/PushNotification.html +24 -8
  14. package/dist/docs/classes/RestPaginator.html +28 -9
  15. package/dist/docs/classes/UnsentMessage.html +3144 -0
  16. package/dist/docs/classes/User.html +25 -9
  17. package/dist/docs/index.html +89 -47
  18. package/dist/docs/interfaces/ClientOptions.html +22 -6
  19. package/dist/docs/interfaces/ConversationState.html +22 -6
  20. package/dist/docs/interfaces/CreateConversationOptions.html +22 -6
  21. package/dist/docs/interfaces/LastMessage.html +22 -6
  22. package/dist/docs/interfaces/Paginator.html +3243 -0
  23. package/dist/docs/interfaces/PushNotificationData.html +3168 -0
  24. package/dist/docs/interfaces/SendEmailOptions.html +22 -6
  25. package/dist/docs/interfaces/SendMediaOptions.html +24 -7
  26. package/dist/docs/modules.html +88 -46
  27. package/dist/lib/aggregated-delivery-receipt.js +227 -0
  28. package/dist/lib/aggregated-delivery-receipt.js.map +1 -0
  29. package/dist/lib/client.js +872 -0
  30. package/dist/lib/client.js.map +1 -0
  31. package/dist/lib/command-executor.js +203 -0
  32. package/dist/lib/command-executor.js.map +1 -0
  33. package/dist/lib/configuration.js +196 -0
  34. package/dist/lib/configuration.js.map +1 -0
  35. package/dist/lib/conversation.js +973 -0
  36. package/dist/lib/conversation.js.map +1 -0
  37. package/dist/lib/data/conversations.js +443 -0
  38. package/dist/lib/data/conversations.js.map +1 -0
  39. package/dist/lib/data/messages.js +341 -0
  40. package/dist/lib/data/messages.js.map +1 -0
  41. package/dist/lib/data/participants.js +313 -0
  42. package/dist/lib/data/participants.js.map +1 -0
  43. package/dist/lib/data/users.js +228 -0
  44. package/dist/lib/data/users.js.map +1 -0
  45. package/dist/lib/detailed-delivery-receipt.js +154 -0
  46. package/dist/lib/detailed-delivery-receipt.js.map +1 -0
  47. package/dist/lib/index.js +167 -0
  48. package/dist/lib/index.js.map +1 -0
  49. package/dist/lib/interfaces/notification-types.js +143 -0
  50. package/dist/lib/interfaces/notification-types.js.map +1 -0
  51. package/dist/lib/logger.js +190 -0
  52. package/dist/lib/logger.js.map +1 -0
  53. package/dist/lib/media.js +213 -0
  54. package/dist/lib/media.js.map +1 -0
  55. package/dist/lib/message-builder.js +209 -0
  56. package/dist/lib/message-builder.js.map +1 -0
  57. package/dist/lib/message.js +450 -0
  58. package/dist/lib/message.js.map +1 -0
  59. package/dist/lib/node_modules/tslib/tslib.es6.js +161 -0
  60. package/dist/lib/node_modules/tslib/tslib.es6.js.map +1 -0
  61. package/dist/lib/packages/conversations/package.json.js +136 -0
  62. package/dist/lib/packages/conversations/package.json.js.map +1 -0
  63. package/dist/lib/participant.js +346 -0
  64. package/dist/lib/participant.js.map +1 -0
  65. package/dist/lib/push-notification.js +152 -0
  66. package/dist/lib/push-notification.js.map +1 -0
  67. package/dist/lib/rest-paginator.js +175 -0
  68. package/dist/lib/rest-paginator.js.map +1 -0
  69. package/dist/lib/services/network.js +205 -0
  70. package/dist/lib/services/network.js.map +1 -0
  71. package/dist/lib/services/typing-indicator.js +235 -0
  72. package/dist/lib/services/typing-indicator.js.map +1 -0
  73. package/dist/lib/unsent-message.js +159 -0
  74. package/dist/lib/unsent-message.js.map +1 -0
  75. package/dist/lib/user.js +392 -0
  76. package/dist/lib/user.js.map +1 -0
  77. package/dist/lib/util/deferred.js +154 -0
  78. package/dist/lib/util/deferred.js.map +1 -0
  79. package/dist/lib/util/index.js +206 -0
  80. package/dist/lib/util/index.js.map +1 -0
  81. package/dist/lib.d.ts +250 -59
  82. package/dist/lib.js +3055 -2919
  83. package/dist/lib.js.map +1 -1
  84. package/dist/twilio-conversations.js +25175 -23918
  85. package/dist/twilio-conversations.min.js +14 -2
  86. package/package.json +16 -14
  87. package/CHANGELOG.md +0 -168
  88. package/dist/post-install.js +0 -29
  89. package/dist/react-native.js +0 -4412
  90. package/dist/react-native.js.map +0 -1
@@ -1,4412 +0,0 @@
1
- /*
2
- @license
3
- The following license applies to all parts of this software except as
4
- documented below.
5
-
6
- Copyright (c) 2019, Twilio, inc.
7
- All rights reserved.
8
-
9
- Redistribution and use in source and binary forms, with or without
10
- modification, are permitted provided that the following conditions are
11
- met:
12
-
13
- 1. Redistributions of source code must retain the above copyright
14
- notice, this list of conditions and the following disclaimer.
15
-
16
- 2. Redistributions in binary form must reproduce the above copyright
17
- notice, this list of conditions and the following disclaimer in
18
- the documentation and/or other materials provided with the
19
- distribution.
20
-
21
- 3. Neither the name of Twilio nor the names of its contributors may
22
- be used to endorse or promote products derived from this software
23
- without specific prior written permission.
24
-
25
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
-
37
- This software includes javascript-state-machine under the following license.
38
-
39
- Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
40
-
41
- Permission is hereby granted, free of charge, to any person obtaining a copy
42
- of this software and associated documentation files (the "Software"), to deal
43
- in the Software without restriction, including without limitation the rights
44
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
45
- copies of the Software, and to permit persons to whom the Software is
46
- furnished to do so, subject to the following conditions:
47
-
48
- The above copyright notice and this permission notice shall be included in all
49
- copies or substantial portions of the Software.
50
-
51
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
54
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
56
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
57
-
58
- This software includes loglevel under the following license.
59
-
60
- Copyright (c) 2013 Tim Perry
61
-
62
- Permission is hereby granted, free of charge, to any person
63
- obtaining a copy of this software and associated documentation
64
- files (the "Software"), to deal in the Software without
65
- restriction, including without limitation the rights to use,
66
- copy, modify, merge, publish, distribute, sublicense, and/or sell
67
- copies of the Software, and to permit persons to whom the
68
- Software is furnished to do so, subject to the following
69
- conditions:
70
-
71
- The above copyright notice and this permission notice shall be
72
- included in all copies or substantial portions of the Software.
73
-
74
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
75
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
76
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
77
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
78
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
79
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
80
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
81
- OTHER DEALINGS IN THE SOFTWARE.
82
-
83
- This software includes q under the following license.
84
-
85
- Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved.
86
- Permission is hereby granted, free of charge, to any person obtaining a copy
87
- of this software and associated documentation files (the "Software"), to
88
- deal in the Software without restriction, including without limitation the
89
- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
90
- sell copies of the Software, and to permit persons to whom the Software is
91
- furnished to do so, subject to the following conditions:
92
-
93
- The above copyright notice and this permission notice shall be included in
94
- all copies or substantial portions of the Software.
95
-
96
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
97
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
98
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
99
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
100
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
101
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
102
- IN THE SOFTWARE.
103
-
104
- This software includes platform.js under the following license.
105
-
106
- Copyright 2014 Benjamin Tan <https://d10.github.io/>
107
- Copyright 2011-2015 John-David Dalton <http://allyoucanleet.com/>
108
-
109
- Permission is hereby granted, free of charge, to any person obtaining
110
- a copy of this software and associated documentation files (the
111
- "Software"), to deal in the Software without restriction, including
112
- without limitation the rights to use, copy, modify, merge, publish,
113
- distribute, sublicense, and/or sell copies of the Software, and to
114
- permit persons to whom the Software is furnished to do so, subject to
115
- the following conditions:
116
-
117
- The above copyright notice and this permission notice shall be
118
- included in all copies or substantial portions of the Software.
119
-
120
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
121
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
122
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
123
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
124
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
125
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
126
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
127
-
128
- */
129
- 'use strict';
130
-
131
- Object.defineProperty(exports, '__esModule', { value: true });
132
-
133
- var loglevelLog = require('loglevel');
134
- var iso8601Duration = require('iso8601-duration');
135
- var operationRetrier = require('@twilio/operation-retrier');
136
- var twilsock = require('twilsock');
137
- var notifications = require('@twilio/notifications');
138
- var twilioSync = require('twilio-sync');
139
- var mcsClient = require('@twilio/mcs-client');
140
- var JsonDiff = require('rfc6902');
141
- var declarativeTypeValidator = require('@twilio/declarative-type-validator');
142
- var uuid = require('uuid');
143
-
144
- function _interopNamespace(e) {
145
- if (e && e.__esModule) return e;
146
- var n = Object.create(null);
147
- if (e) {
148
- Object.keys(e).forEach(function (k) {
149
- if (k !== 'default') {
150
- var d = Object.getOwnPropertyDescriptor(e, k);
151
- Object.defineProperty(n, k, d.get ? d : {
152
- enumerable: true,
153
- get: function () {
154
- return e[k];
155
- }
156
- });
157
- }
158
- });
159
- }
160
- n['default'] = e;
161
- return Object.freeze(n);
162
- }
163
-
164
- var loglevelLog__namespace = /*#__PURE__*/_interopNamespace(loglevelLog);
165
- var JsonDiff__namespace = /*#__PURE__*/_interopNamespace(JsonDiff);
166
-
167
- /*! *****************************************************************************
168
- Copyright (c) Microsoft Corporation.
169
-
170
- Permission to use, copy, modify, and/or distribute this software for any
171
- purpose with or without fee is hereby granted.
172
-
173
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
174
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
175
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
176
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
177
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
178
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
179
- PERFORMANCE OF THIS SOFTWARE.
180
- ***************************************************************************** */
181
-
182
- function __decorate(decorators, target, key, desc) {
183
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
184
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
185
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
186
- return c > 3 && r && Object.defineProperty(target, key, r), r;
187
- }
188
-
189
- function __metadata(metadataKey, metadataValue) {
190
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
191
- }
192
-
193
- var domain;
194
-
195
- // This constructor is used to store event handlers. Instantiating this is
196
- // faster than explicitly calling `Object.create(null)` to get a "clean" empty
197
- // object (tested with v8 v4.9).
198
- function EventHandlers() {}
199
- EventHandlers.prototype = Object.create(null);
200
-
201
- function EventEmitter() {
202
- EventEmitter.init.call(this);
203
- }
204
-
205
- // nodejs oddity
206
- // require('events') === require('events').EventEmitter
207
- EventEmitter.EventEmitter = EventEmitter;
208
-
209
- EventEmitter.usingDomains = false;
210
-
211
- EventEmitter.prototype.domain = undefined;
212
- EventEmitter.prototype._events = undefined;
213
- EventEmitter.prototype._maxListeners = undefined;
214
-
215
- // By default EventEmitters will print a warning if more than 10 listeners are
216
- // added to it. This is a useful default which helps finding memory leaks.
217
- EventEmitter.defaultMaxListeners = 10;
218
-
219
- EventEmitter.init = function() {
220
- this.domain = null;
221
- if (EventEmitter.usingDomains) {
222
- // if there is an active domain, then attach to it.
223
- if (domain.active ) ;
224
- }
225
-
226
- if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
227
- this._events = new EventHandlers();
228
- this._eventsCount = 0;
229
- }
230
-
231
- this._maxListeners = this._maxListeners || undefined;
232
- };
233
-
234
- // Obviously not all Emitters should be limited to 10. This function allows
235
- // that to be increased. Set to zero for unlimited.
236
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
237
- if (typeof n !== 'number' || n < 0 || isNaN(n))
238
- throw new TypeError('"n" argument must be a positive number');
239
- this._maxListeners = n;
240
- return this;
241
- };
242
-
243
- function $getMaxListeners(that) {
244
- if (that._maxListeners === undefined)
245
- return EventEmitter.defaultMaxListeners;
246
- return that._maxListeners;
247
- }
248
-
249
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
250
- return $getMaxListeners(this);
251
- };
252
-
253
- // These standalone emit* functions are used to optimize calling of event
254
- // handlers for fast cases because emit() itself often has a variable number of
255
- // arguments and can be deoptimized because of that. These functions always have
256
- // the same number of arguments and thus do not get deoptimized, so the code
257
- // inside them can execute faster.
258
- function emitNone(handler, isFn, self) {
259
- if (isFn)
260
- handler.call(self);
261
- else {
262
- var len = handler.length;
263
- var listeners = arrayClone(handler, len);
264
- for (var i = 0; i < len; ++i)
265
- listeners[i].call(self);
266
- }
267
- }
268
- function emitOne(handler, isFn, self, arg1) {
269
- if (isFn)
270
- handler.call(self, arg1);
271
- else {
272
- var len = handler.length;
273
- var listeners = arrayClone(handler, len);
274
- for (var i = 0; i < len; ++i)
275
- listeners[i].call(self, arg1);
276
- }
277
- }
278
- function emitTwo(handler, isFn, self, arg1, arg2) {
279
- if (isFn)
280
- handler.call(self, arg1, arg2);
281
- else {
282
- var len = handler.length;
283
- var listeners = arrayClone(handler, len);
284
- for (var i = 0; i < len; ++i)
285
- listeners[i].call(self, arg1, arg2);
286
- }
287
- }
288
- function emitThree(handler, isFn, self, arg1, arg2, arg3) {
289
- if (isFn)
290
- handler.call(self, arg1, arg2, arg3);
291
- else {
292
- var len = handler.length;
293
- var listeners = arrayClone(handler, len);
294
- for (var i = 0; i < len; ++i)
295
- listeners[i].call(self, arg1, arg2, arg3);
296
- }
297
- }
298
-
299
- function emitMany(handler, isFn, self, args) {
300
- if (isFn)
301
- handler.apply(self, args);
302
- else {
303
- var len = handler.length;
304
- var listeners = arrayClone(handler, len);
305
- for (var i = 0; i < len; ++i)
306
- listeners[i].apply(self, args);
307
- }
308
- }
309
-
310
- EventEmitter.prototype.emit = function emit(type) {
311
- var er, handler, len, args, i, events, domain;
312
- var doError = (type === 'error');
313
-
314
- events = this._events;
315
- if (events)
316
- doError = (doError && events.error == null);
317
- else if (!doError)
318
- return false;
319
-
320
- domain = this.domain;
321
-
322
- // If there is no 'error' event listener then throw.
323
- if (doError) {
324
- er = arguments[1];
325
- if (domain) {
326
- if (!er)
327
- er = new Error('Uncaught, unspecified "error" event');
328
- er.domainEmitter = this;
329
- er.domain = domain;
330
- er.domainThrown = false;
331
- domain.emit('error', er);
332
- } else if (er instanceof Error) {
333
- throw er; // Unhandled 'error' event
334
- } else {
335
- // At least give some kind of context to the user
336
- var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
337
- err.context = er;
338
- throw err;
339
- }
340
- return false;
341
- }
342
-
343
- handler = events[type];
344
-
345
- if (!handler)
346
- return false;
347
-
348
- var isFn = typeof handler === 'function';
349
- len = arguments.length;
350
- switch (len) {
351
- // fast cases
352
- case 1:
353
- emitNone(handler, isFn, this);
354
- break;
355
- case 2:
356
- emitOne(handler, isFn, this, arguments[1]);
357
- break;
358
- case 3:
359
- emitTwo(handler, isFn, this, arguments[1], arguments[2]);
360
- break;
361
- case 4:
362
- emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
363
- break;
364
- // slower
365
- default:
366
- args = new Array(len - 1);
367
- for (i = 1; i < len; i++)
368
- args[i - 1] = arguments[i];
369
- emitMany(handler, isFn, this, args);
370
- }
371
-
372
- return true;
373
- };
374
-
375
- function _addListener(target, type, listener, prepend) {
376
- var m;
377
- var events;
378
- var existing;
379
-
380
- if (typeof listener !== 'function')
381
- throw new TypeError('"listener" argument must be a function');
382
-
383
- events = target._events;
384
- if (!events) {
385
- events = target._events = new EventHandlers();
386
- target._eventsCount = 0;
387
- } else {
388
- // To avoid recursion in the case that type === "newListener"! Before
389
- // adding it to the listeners, first emit "newListener".
390
- if (events.newListener) {
391
- target.emit('newListener', type,
392
- listener.listener ? listener.listener : listener);
393
-
394
- // Re-assign `events` because a newListener handler could have caused the
395
- // this._events to be assigned to a new object
396
- events = target._events;
397
- }
398
- existing = events[type];
399
- }
400
-
401
- if (!existing) {
402
- // Optimize the case of one listener. Don't need the extra array object.
403
- existing = events[type] = listener;
404
- ++target._eventsCount;
405
- } else {
406
- if (typeof existing === 'function') {
407
- // Adding the second element, need to change to array.
408
- existing = events[type] = prepend ? [listener, existing] :
409
- [existing, listener];
410
- } else {
411
- // If we've already got an array, just append.
412
- if (prepend) {
413
- existing.unshift(listener);
414
- } else {
415
- existing.push(listener);
416
- }
417
- }
418
-
419
- // Check for listener leak
420
- if (!existing.warned) {
421
- m = $getMaxListeners(target);
422
- if (m && m > 0 && existing.length > m) {
423
- existing.warned = true;
424
- var w = new Error('Possible EventEmitter memory leak detected. ' +
425
- existing.length + ' ' + type + ' listeners added. ' +
426
- 'Use emitter.setMaxListeners() to increase limit');
427
- w.name = 'MaxListenersExceededWarning';
428
- w.emitter = target;
429
- w.type = type;
430
- w.count = existing.length;
431
- emitWarning(w);
432
- }
433
- }
434
- }
435
-
436
- return target;
437
- }
438
- function emitWarning(e) {
439
- typeof console.warn === 'function' ? console.warn(e) : console.log(e);
440
- }
441
- EventEmitter.prototype.addListener = function addListener(type, listener) {
442
- return _addListener(this, type, listener, false);
443
- };
444
-
445
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
446
-
447
- EventEmitter.prototype.prependListener =
448
- function prependListener(type, listener) {
449
- return _addListener(this, type, listener, true);
450
- };
451
-
452
- function _onceWrap(target, type, listener) {
453
- var fired = false;
454
- function g() {
455
- target.removeListener(type, g);
456
- if (!fired) {
457
- fired = true;
458
- listener.apply(target, arguments);
459
- }
460
- }
461
- g.listener = listener;
462
- return g;
463
- }
464
-
465
- EventEmitter.prototype.once = function once(type, listener) {
466
- if (typeof listener !== 'function')
467
- throw new TypeError('"listener" argument must be a function');
468
- this.on(type, _onceWrap(this, type, listener));
469
- return this;
470
- };
471
-
472
- EventEmitter.prototype.prependOnceListener =
473
- function prependOnceListener(type, listener) {
474
- if (typeof listener !== 'function')
475
- throw new TypeError('"listener" argument must be a function');
476
- this.prependListener(type, _onceWrap(this, type, listener));
477
- return this;
478
- };
479
-
480
- // emits a 'removeListener' event iff the listener was removed
481
- EventEmitter.prototype.removeListener =
482
- function removeListener(type, listener) {
483
- var list, events, position, i, originalListener;
484
-
485
- if (typeof listener !== 'function')
486
- throw new TypeError('"listener" argument must be a function');
487
-
488
- events = this._events;
489
- if (!events)
490
- return this;
491
-
492
- list = events[type];
493
- if (!list)
494
- return this;
495
-
496
- if (list === listener || (list.listener && list.listener === listener)) {
497
- if (--this._eventsCount === 0)
498
- this._events = new EventHandlers();
499
- else {
500
- delete events[type];
501
- if (events.removeListener)
502
- this.emit('removeListener', type, list.listener || listener);
503
- }
504
- } else if (typeof list !== 'function') {
505
- position = -1;
506
-
507
- for (i = list.length; i-- > 0;) {
508
- if (list[i] === listener ||
509
- (list[i].listener && list[i].listener === listener)) {
510
- originalListener = list[i].listener;
511
- position = i;
512
- break;
513
- }
514
- }
515
-
516
- if (position < 0)
517
- return this;
518
-
519
- if (list.length === 1) {
520
- list[0] = undefined;
521
- if (--this._eventsCount === 0) {
522
- this._events = new EventHandlers();
523
- return this;
524
- } else {
525
- delete events[type];
526
- }
527
- } else {
528
- spliceOne(list, position);
529
- }
530
-
531
- if (events.removeListener)
532
- this.emit('removeListener', type, originalListener || listener);
533
- }
534
-
535
- return this;
536
- };
537
-
538
- // Alias for removeListener added in NodeJS 10.0
539
- // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener
540
- EventEmitter.prototype.off = function(type, listener){
541
- return this.removeListener(type, listener);
542
- };
543
-
544
- EventEmitter.prototype.removeAllListeners =
545
- function removeAllListeners(type) {
546
- var listeners, events;
547
-
548
- events = this._events;
549
- if (!events)
550
- return this;
551
-
552
- // not listening for removeListener, no need to emit
553
- if (!events.removeListener) {
554
- if (arguments.length === 0) {
555
- this._events = new EventHandlers();
556
- this._eventsCount = 0;
557
- } else if (events[type]) {
558
- if (--this._eventsCount === 0)
559
- this._events = new EventHandlers();
560
- else
561
- delete events[type];
562
- }
563
- return this;
564
- }
565
-
566
- // emit removeListener for all listeners on all events
567
- if (arguments.length === 0) {
568
- var keys = Object.keys(events);
569
- for (var i = 0, key; i < keys.length; ++i) {
570
- key = keys[i];
571
- if (key === 'removeListener') continue;
572
- this.removeAllListeners(key);
573
- }
574
- this.removeAllListeners('removeListener');
575
- this._events = new EventHandlers();
576
- this._eventsCount = 0;
577
- return this;
578
- }
579
-
580
- listeners = events[type];
581
-
582
- if (typeof listeners === 'function') {
583
- this.removeListener(type, listeners);
584
- } else if (listeners) {
585
- // LIFO order
586
- do {
587
- this.removeListener(type, listeners[listeners.length - 1]);
588
- } while (listeners[0]);
589
- }
590
-
591
- return this;
592
- };
593
-
594
- EventEmitter.prototype.listeners = function listeners(type) {
595
- var evlistener;
596
- var ret;
597
- var events = this._events;
598
-
599
- if (!events)
600
- ret = [];
601
- else {
602
- evlistener = events[type];
603
- if (!evlistener)
604
- ret = [];
605
- else if (typeof evlistener === 'function')
606
- ret = [evlistener.listener || evlistener];
607
- else
608
- ret = unwrapListeners(evlistener);
609
- }
610
-
611
- return ret;
612
- };
613
-
614
- EventEmitter.listenerCount = function(emitter, type) {
615
- if (typeof emitter.listenerCount === 'function') {
616
- return emitter.listenerCount(type);
617
- } else {
618
- return listenerCount.call(emitter, type);
619
- }
620
- };
621
-
622
- EventEmitter.prototype.listenerCount = listenerCount;
623
- function listenerCount(type) {
624
- var events = this._events;
625
-
626
- if (events) {
627
- var evlistener = events[type];
628
-
629
- if (typeof evlistener === 'function') {
630
- return 1;
631
- } else if (evlistener) {
632
- return evlistener.length;
633
- }
634
- }
635
-
636
- return 0;
637
- }
638
-
639
- EventEmitter.prototype.eventNames = function eventNames() {
640
- return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
641
- };
642
-
643
- // About 1.5x faster than the two-arg version of Array#splice().
644
- function spliceOne(list, index) {
645
- for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
646
- list[i] = list[k];
647
- list.pop();
648
- }
649
-
650
- function arrayClone(arr, i) {
651
- var copy = new Array(i);
652
- while (i--)
653
- copy[i] = arr[i];
654
- return copy;
655
- }
656
-
657
- function unwrapListeners(arr) {
658
- var ret = new Array(arr.length);
659
- for (var i = 0; i < ret.length; ++i) {
660
- ret[i] = arr[i].listener || arr[i];
661
- }
662
- return ret;
663
- }
664
-
665
- function prepareLine(prefix, args) {
666
- return [`${new Date().toISOString()} Conversations ${prefix}:`].concat(Array.from(args));
667
- }
668
- const log$9 = loglevelLog__namespace.getLogger('twilio-conversations'); // twilio-conversations is used by Flex SDK. Please DO NOT change
669
- class Logger {
670
- constructor(prefix) {
671
- this.prefix = '';
672
- this.prefix = prefix !== null && prefix !== undefined && prefix.length > 0
673
- ? prefix + ' '
674
- : '';
675
- }
676
- static scope(prefix) {
677
- return new Logger(prefix);
678
- }
679
- setLevel(level) {
680
- log$9.setLevel(level);
681
- }
682
- static setLevel(level) {
683
- log$9.setLevel(level);
684
- }
685
- trace(...args) { log$9.trace.apply(null, prepareLine(this.prefix + 'T', args)); }
686
- debug(...args) { log$9.debug.apply(null, prepareLine(this.prefix + 'D', args)); }
687
- info(...args) { log$9.info.apply(null, prepareLine(this.prefix + 'I', args)); }
688
- warn(...args) { log$9.warn.apply(null, prepareLine(this.prefix + 'W', args)); }
689
- error(...args) { log$9.error.apply(null, prepareLine(this.prefix + 'E', args)); }
690
- static trace(...args) { log$9.trace.apply(null, prepareLine('T', args)); }
691
- static debug(...args) { log$9.debug.apply(null, prepareLine('D', args)); }
692
- static info(...args) { log$9.info.apply(null, prepareLine('I', args)); }
693
- static warn(...args) { log$9.warn.apply(null, prepareLine('W', args)); }
694
- static error(...args) { log$9.error.apply(null, prepareLine('E', args)); }
695
- }
696
-
697
- const TYPING_TIMEOUT = 5;
698
- const HTTP_CACHE_LIFETIME = 'PT5S';
699
- const CONSUMPTION_HORIZON_SENDING_INTERVAL = 'PT5S';
700
- const USER_INFOS_TO_SUBSCRIBE = 100;
701
- const MINIMUM_RETRY_DELAY = 1000;
702
- const MAXIMUM_RETRY_DELAY = 4000;
703
- const MAXIMUM_ATTEMPTS_COUNT = 3;
704
- const RETRY_WHEN_THROTTLED = true;
705
- class Configuration {
706
- constructor(options = {}, configurationResponse, logger) {
707
- var _a, _b, _c, _d, _e, _f;
708
- this.typingIndicatorTimeoutDefault = TYPING_TIMEOUT * 1000;
709
- const constructorOptions = options.Chat || options.IPMessaging || options || {};
710
- this.productId = constructorOptions.productId;
711
- this.links = {
712
- myConversations: configurationResponse.links.my_conversations,
713
- conversations: configurationResponse.links.conversations,
714
- users: configurationResponse.links.users,
715
- currentUser: configurationResponse.links.current_user,
716
- typing: configurationResponse.links.typing,
717
- mediaService: configurationResponse.links.media_service,
718
- mediaSetService: configurationResponse.links.media_set_service,
719
- messagesReceipts: configurationResponse.links.messages_receipts
720
- };
721
- this.limits = {
722
- mediaAttachmentsCountLimit: configurationResponse.options.media_attachments_count_limit,
723
- mediaAttachmentSizeLimitInMb: configurationResponse.options.media_attachment_size_limit_in_mb,
724
- mediaAttachmentsTotalSizeLimitInMb: configurationResponse.options.media_attachments_total_size_limit_in_mb,
725
- emailHistoriesAllowedMimeTypes: configurationResponse.options.email_histories_allowed_mime_types,
726
- emailBodiesAllowedMimeTypes: configurationResponse.options.email_bodies_allowed_mime_types
727
- };
728
- this.typingIndicatorTimeoutOverride = constructorOptions.typingIndicatorTimeoutOverride;
729
- this.backoffConfiguration = Object.assign({ min: MINIMUM_RETRY_DELAY, max: MAXIMUM_RETRY_DELAY, maxAttemptsCount: MAXIMUM_ATTEMPTS_COUNT }, constructorOptions.backoffConfigOverride);
730
- this.retryWhenThrottled = constructorOptions.retryWhenThrottledOverride !== undefined
731
- ? constructorOptions.retryWhenThrottledOverride
732
- : RETRY_WHEN_THROTTLED;
733
- this.userInfosToSubscribe = (_b = (_a = constructorOptions.userInfosToSubscribeOverride) !== null && _a !== void 0 ? _a : configurationResponse.options.user_infos_to_subscribe) !== null && _b !== void 0 ? _b : USER_INFOS_TO_SUBSCRIBE;
734
- this.reachabilityEnabled = configurationResponse.options.reachability_enabled;
735
- this.userIdentity = configurationResponse.identity;
736
- this.userInfo = configurationResponse.sync_objects.my_user_info;
737
- this.myConversations = configurationResponse.sync_objects.my_conversations;
738
- const httpCacheInterval = (_d = (_c = constructorOptions.httpCacheIntervalOverride) !== null && _c !== void 0 ? _c : configurationResponse.options.http_cache_interval) !== null && _d !== void 0 ? _d : HTTP_CACHE_LIFETIME;
739
- try {
740
- this.httpCacheInterval = iso8601Duration.toSeconds(iso8601Duration.parse(httpCacheInterval));
741
- }
742
- catch (_g) {
743
- logger.error(`Failed to parse http cache interval ${httpCacheInterval}, using default value ${HTTP_CACHE_LIFETIME}`);
744
- this.httpCacheInterval = iso8601Duration.toSeconds(iso8601Duration.parse(HTTP_CACHE_LIFETIME));
745
- }
746
- const consumptionReportInterval = (_f = (_e = constructorOptions.consumptionReportIntervalOverride) !== null && _e !== void 0 ? _e : configurationResponse.options.consumption_report_interval) !== null && _f !== void 0 ? _f : CONSUMPTION_HORIZON_SENDING_INTERVAL;
747
- try {
748
- this.consumptionReportInterval = iso8601Duration.toSeconds(iso8601Duration.parse(consumptionReportInterval));
749
- }
750
- catch (_h) {
751
- logger.error(`Failed to parse consumption report interval ${consumptionReportInterval}, using default value ${CONSUMPTION_HORIZON_SENDING_INTERVAL}`);
752
- this.consumptionReportInterval = iso8601Duration.toSeconds(iso8601Duration.parse(CONSUMPTION_HORIZON_SENDING_INTERVAL));
753
- }
754
- }
755
- }
756
-
757
- class Network {
758
- constructor(configuration, services) {
759
- this.configuration = configuration;
760
- this.services = services;
761
- this.cache = new Map();
762
- this.cacheLifetime = this.configuration.httpCacheInterval * 100;
763
- this.cleanupCache();
764
- }
765
- isExpired(timestamp) {
766
- return !this.cacheLifetime || (Date.now() - timestamp) > this.cacheLifetime;
767
- }
768
- cleanupCache() {
769
- for (let [k, v] of this.cache) {
770
- if (this.isExpired(v.timestamp)) {
771
- this.cache.delete(k);
772
- }
773
- }
774
- if (this.cache.size === 0) {
775
- clearInterval(this.timer);
776
- }
777
- }
778
- pokeTimer() {
779
- this.timer = this.timer || setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);
780
- }
781
- executeWithRetry(request, retryWhenThrottled = false) {
782
- return new Promise((resolve, reject) => {
783
- let codesToRetryOn = [502, 503, 504];
784
- if (retryWhenThrottled) {
785
- codesToRetryOn.push(429);
786
- }
787
- let retrier = new operationRetrier.Retrier(this.configuration.backoffConfiguration);
788
- retrier.on('attempt', () => {
789
- request()
790
- .then(result => retrier.succeeded(result))
791
- .catch(err => {
792
- if (codesToRetryOn.indexOf(err.status) > -1) {
793
- retrier.failed(err);
794
- }
795
- else if (err.message === 'Twilsock disconnected') {
796
- // Ugly hack. We must make a proper exceptions for twilsock
797
- retrier.failed(err);
798
- }
799
- else {
800
- // Fatal error
801
- retrier.removeAllListeners();
802
- retrier.cancel();
803
- reject(err);
804
- }
805
- });
806
- });
807
- retrier.on('succeeded', result => { resolve(result); });
808
- retrier.on('cancelled', err => reject(err));
809
- retrier.on('failed', err => reject(err));
810
- retrier.start();
811
- });
812
- }
813
- async get(url) {
814
- let cacheEntry = this.cache.get(url);
815
- if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {
816
- return cacheEntry.response;
817
- }
818
- const headers = {};
819
- let response = await this.executeWithRetry(() => this.services.transport.get(url, headers, this.configuration.productId), this.configuration.retryWhenThrottled);
820
- this.cache.set(url, { response, timestamp: Date.now() });
821
- this.pokeTimer();
822
- return response;
823
- }
824
- }
825
-
826
- class NotificationTypes {
827
- }
828
- NotificationTypes.TYPING_INDICATOR = 'twilio.ipmsg.typing_indicator';
829
- NotificationTypes.NEW_MESSAGE = 'twilio.conversations.new_message';
830
- NotificationTypes.ADDED_TO_CONVERSATION = 'twilio.conversations.added_to_conversation';
831
- // static readonly INVITED_TO_CHANNEL = 'twilio.channel.invited_to_channel';
832
- NotificationTypes.REMOVED_FROM_CONVERSATION = 'twilio.conversations.removed_from_conversation';
833
- NotificationTypes.CONSUMPTION_UPDATE = 'twilio.channel.consumption_update';
834
-
835
- /**
836
- * Checks if objects are equal
837
- */
838
- function isDeepEqual(o1, o2) {
839
- return JsonDiff__namespace.createPatch(o1, o2).length === 0;
840
- }
841
- /**
842
- * Deep-clone an object. Note that this does not work on object containing
843
- * functions.
844
- * @param {object} obj - the object to deep-clone
845
- * @returns {object}
846
- */
847
- function deepClone(obj) {
848
- return JSON.parse(JSON.stringify(obj));
849
- }
850
- function parseToNumber(value) {
851
- if (typeof value !== 'undefined' && !isNaN(Number(value))) {
852
- return Number(value);
853
- }
854
- return null;
855
- }
856
- // timeString cannot be typed `string` because in member.ts
857
- // call to parseTime(data.lastReadTimestamp) uses number not a string for timestamp.
858
- function parseTime$1(timeString) {
859
- try {
860
- return new Date(timeString);
861
- }
862
- catch (e) {
863
- return null;
864
- }
865
- }
866
- function parseAttributes(rawAttributes, warningMessage, log) {
867
- let attributes = {};
868
- if (rawAttributes) {
869
- try {
870
- attributes = JSON.parse(rawAttributes);
871
- }
872
- catch (e) {
873
- log.warn(warningMessage, e);
874
- }
875
- }
876
- return attributes;
877
- }
878
- /**
879
- * Construct URI with query parameters
880
- */
881
- class UriBuilder {
882
- constructor(base) {
883
- this.base = base.replace(/\/$/, '');
884
- this.args = [];
885
- this.paths = [];
886
- }
887
- arg(name, value) {
888
- if (typeof value !== 'undefined') {
889
- this.args.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
890
- }
891
- return this;
892
- }
893
- path(name) {
894
- this.paths.push(encodeURIComponent(name));
895
- return this;
896
- }
897
- build() {
898
- let result = this.base;
899
- if (this.paths.length) {
900
- result += '/' + this.paths.join('/');
901
- }
902
- if (this.args.length) {
903
- result += '?' + this.args.join('&');
904
- }
905
- return result;
906
- }
907
- }
908
-
909
- const log$8 = Logger.scope('Participant');
910
- /**
911
- * A participant represents a remote client in a conversation.
912
- */
913
- class Participant extends EventEmitter {
914
- /**
915
- * @internal
916
- */
917
- constructor(data, sid, conversation, links, services) {
918
- super();
919
- this.conversation = conversation;
920
- this.links = links;
921
- this.services = services;
922
- this.state = {
923
- attributes: parseAttributes(data.attributes, 'Retrieved malformed attributes from the server for participant: ' + sid, log$8),
924
- dateCreated: data.dateCreated ? parseTime$1(data.dateCreated) : null,
925
- dateUpdated: data.dateCreated ? parseTime$1(data.dateUpdated) : null,
926
- sid: sid,
927
- typingTimeout: null,
928
- isTyping: false,
929
- identity: data.identity || null,
930
- roleSid: data.roleSid || null,
931
- lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex) ? data.lastConsumedMessageIndex : null,
932
- lastReadTimestamp: data.lastConsumptionTimestamp ? parseTime$1(data.lastConsumptionTimestamp) : null,
933
- type: data.type || 'chat',
934
- userInfo: data.userInfo
935
- };
936
- if (!data.identity && !data.type) {
937
- throw new Error('Received invalid Participant object from server: Missing identity or type of Participant.');
938
- }
939
- }
940
- /**
941
- * The server-assigned unique identifier for the participant.
942
- */
943
- get sid() { return this.state.sid; }
944
- /**
945
- * Custom attributes of the participant.
946
- */
947
- get attributes() { return this.state.attributes; }
948
- /**
949
- * Date this participant was created on.
950
- */
951
- get dateCreated() { return this.state.dateCreated; }
952
- /**
953
- * Date this participant was last updated on.
954
- */
955
- get dateUpdated() { return this.state.dateUpdated; }
956
- /**
957
- * Identity of the participant.
958
- */
959
- get identity() { return this.state.identity; }
960
- /**
961
- * Indicates whether the participant is currently typing.
962
- */
963
- get isTyping() { return this.state.isTyping; }
964
- /**
965
- * The index of the last read message by the participant.
966
- * Note that retrieving messages on a client endpoint does not mean that messages are read,
967
- * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon)
968
- * to find out about the proper way to mark messages as read.
969
- */
970
- get lastReadMessageIndex() { return this.state.lastReadMessageIndex; }
971
- /**
972
- * Date of the most recent read horizon update.
973
- */
974
- get lastReadTimestamp() { return this.state.lastReadTimestamp; }
975
- get roleSid() { return this.state.roleSid; }
976
- /**
977
- * Message type of the participant.
978
- */
979
- get type() { return this.state.type; }
980
- /**
981
- * Internal method used to start or reset the typing indicator timeout (with event emitting).
982
- * @internal
983
- */
984
- _startTyping(timeout) {
985
- clearTimeout(this.state.typingTimeout);
986
- this.state.isTyping = true;
987
- this.emit('typingStarted', this);
988
- this.conversation.emit('typingStarted', this);
989
- this.state.typingTimeout = setTimeout(() => this._endTyping(), timeout);
990
- return this;
991
- }
992
- /**
993
- * Internal method function used to stop the typing indicator timeout (with event emitting).
994
- * @internal
995
- */
996
- _endTyping() {
997
- if (!this.state.typingTimeout) {
998
- return;
999
- }
1000
- this.state.isTyping = false;
1001
- this.emit('typingEnded', this);
1002
- this.conversation.emit('typingEnded', this);
1003
- clearInterval(this.state.typingTimeout);
1004
- this.state.typingTimeout = null;
1005
- }
1006
- /**
1007
- * Internal method function used update local object's property roleSid with a new value.
1008
- * @internal
1009
- */
1010
- _update(data) {
1011
- let updateReasons = [];
1012
- let updateAttributes = parseAttributes(data.attributes, 'Retrieved malformed attributes from the server for participant: ' + this.state.sid, log$8);
1013
- if (data.attributes && !isDeepEqual(this.state.attributes, updateAttributes)) {
1014
- this.state.attributes = updateAttributes;
1015
- updateReasons.push('attributes');
1016
- }
1017
- let updatedDateUpdated = parseTime$1(data.dateUpdated);
1018
- if (data.dateUpdated &&
1019
- updatedDateUpdated.getTime() !== (this.state.dateUpdated && this.state.dateUpdated.getTime())) {
1020
- this.state.dateUpdated = updatedDateUpdated;
1021
- updateReasons.push('dateUpdated');
1022
- }
1023
- let updatedDateCreated = parseTime$1(data.dateCreated);
1024
- if (data.dateCreated &&
1025
- updatedDateCreated.getTime() !== (this.state.dateCreated && this.state.dateCreated.getTime())) {
1026
- this.state.dateCreated = updatedDateCreated;
1027
- updateReasons.push('dateCreated');
1028
- }
1029
- if (data.roleSid && this.state.roleSid !== data.roleSid) {
1030
- this.state.roleSid = data.roleSid;
1031
- updateReasons.push('roleSid');
1032
- }
1033
- if ((Number.isInteger(data.lastConsumedMessageIndex) || data.lastConsumedMessageIndex === null)
1034
- && this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex) {
1035
- this.state.lastReadMessageIndex = data.lastConsumedMessageIndex;
1036
- updateReasons.push('lastReadMessageIndex');
1037
- }
1038
- if (data.lastConsumptionTimestamp) {
1039
- let lastReadTimestamp = new Date(data.lastConsumptionTimestamp);
1040
- if (!this.state.lastReadTimestamp ||
1041
- this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()) {
1042
- this.state.lastReadTimestamp = lastReadTimestamp;
1043
- updateReasons.push('lastReadTimestamp');
1044
- }
1045
- }
1046
- if (updateReasons.length > 0) {
1047
- this.emit('updated', { participant: this, updateReasons: updateReasons });
1048
- }
1049
- return this;
1050
- }
1051
- /**
1052
- * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`.
1053
- */
1054
- async getUser() {
1055
- if (this.type != 'chat') {
1056
- throw new Error('Getting User is not supported for this Participant type: ' + this.type);
1057
- }
1058
- return this.services.users.getUser(this.state.identity, this.state.userInfo);
1059
- }
1060
- /**
1061
- * Remove the participant from the conversation.
1062
- */
1063
- async remove() {
1064
- return this.conversation.removeParticipant(this);
1065
- }
1066
- /**
1067
- * Update the attributes of the participant.
1068
- * @param attributes New attributes.
1069
- */
1070
- async updateAttributes(attributes) {
1071
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
1072
- attributes: JSON.stringify(attributes)
1073
- });
1074
- return this;
1075
- }
1076
- }
1077
- /**
1078
- * Fired when the participant has started typing.
1079
- *
1080
- * Parameters:
1081
- * 1. {@link Participant} `participant` - the participant in question
1082
- * @event
1083
- */
1084
- Participant.typingStarted = 'typingStarted';
1085
- /**
1086
- * Fired when the participant has stopped typing.
1087
- *
1088
- * Parameters:
1089
- * 1. {@link Participant} `participant` - the participant in question
1090
- * @event
1091
- */
1092
- Participant.typingEnded = 'typingEnded';
1093
- /**
1094
- * Fired when the fields of the participant have been updated.
1095
- *
1096
- * Parameters:
1097
- * 1. object `data` - info object provided with the event. It has the following properties:
1098
- * * {@link Participant} participant - the participant in question
1099
- * * {@link ParticipantUpdateReason}[] updateReasons - array of reasons for the update
1100
- * @event
1101
- */
1102
- Participant.updated = 'updated';
1103
- __decorate([
1104
- declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
1105
- __metadata("design:type", Function),
1106
- __metadata("design:paramtypes", [Object]),
1107
- __metadata("design:returntype", Promise)
1108
- ], Participant.prototype, "updateAttributes", null);
1109
-
1110
- const log$7 = Logger.scope('Participants');
1111
- /**
1112
- * @classdesc Represents the collection of participants for the conversation
1113
- * @fires Participants#participantJoined
1114
- * @fires Participants#participantLeft
1115
- * @fires Participants#participantUpdated
1116
- */
1117
- class Participants extends EventEmitter {
1118
- constructor(conversation, participants, links, configuration, services) {
1119
- super();
1120
- this.conversation = conversation;
1121
- this.participants = participants;
1122
- this.links = links;
1123
- this.configuration = configuration;
1124
- this.services = services;
1125
- }
1126
- async unsubscribe() {
1127
- if (this.rosterEntityPromise) {
1128
- let entity = await this.rosterEntityPromise;
1129
- entity.close();
1130
- this.rosterEntityPromise = null;
1131
- }
1132
- }
1133
- subscribe(rosterObjectName) {
1134
- return this.rosterEntityPromise = this.rosterEntityPromise
1135
- || this.services.syncClient.map({ id: rosterObjectName, mode: 'open_existing' })
1136
- .then(rosterMap => {
1137
- rosterMap.on('itemAdded', args => {
1138
- log$7.debug(this.conversation.sid + ' itemAdded: ' + args.item.key);
1139
- this.upsertParticipant(args.item.key, args.item.data)
1140
- .then(participant => {
1141
- this.emit('participantJoined', participant);
1142
- });
1143
- });
1144
- rosterMap.on('itemRemoved', args => {
1145
- log$7.debug(this.conversation.sid + ' itemRemoved: ' + args.key);
1146
- let participantSid = args.key;
1147
- if (!this.participants.has(participantSid)) {
1148
- return;
1149
- }
1150
- let leftParticipant = this.participants.get(participantSid);
1151
- this.participants.delete(participantSid);
1152
- this.emit('participantLeft', leftParticipant);
1153
- });
1154
- rosterMap.on('itemUpdated', args => {
1155
- log$7.debug(this.conversation.sid + ' itemUpdated: ' + args.item.key);
1156
- this.upsertParticipant(args.item.key, args.item.data);
1157
- });
1158
- let participantsPromises = [];
1159
- let that = this;
1160
- const rosterMapHandler = function (paginator) {
1161
- paginator.items.forEach(item => { participantsPromises.push(that.upsertParticipant(item.key, item.data)); });
1162
- return paginator.hasNextPage ? paginator.nextPage().then(rosterMapHandler) : null;
1163
- };
1164
- return rosterMap
1165
- .getItems()
1166
- .then(rosterMapHandler)
1167
- .then(() => Promise.all(participantsPromises))
1168
- .then(() => rosterMap);
1169
- })
1170
- .catch(err => {
1171
- this.rosterEntityPromise = null;
1172
- if (this.services.syncClient.connectionState != 'disconnected') {
1173
- log$7.error('Failed to get roster object for conversation', this.conversation.sid, err);
1174
- }
1175
- log$7.debug('ERROR: Failed to get roster object for conversation', this.conversation.sid, err);
1176
- throw err;
1177
- });
1178
- }
1179
- async upsertParticipant(participantSid, data) {
1180
- let participant = this.participants.get(participantSid);
1181
- if (participant) {
1182
- return participant._update(data);
1183
- }
1184
- const links = {
1185
- self: `${this.links.participants}/${participantSid}`
1186
- };
1187
- participant = new Participant(data, participantSid, this.conversation, links, this.services);
1188
- this.participants.set(participantSid, participant);
1189
- participant.on('updated', (args) => this.emit('participantUpdated', args));
1190
- return participant;
1191
- }
1192
- /**
1193
- * @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}
1194
- */
1195
- getParticipants() {
1196
- return this.rosterEntityPromise.then(() => {
1197
- let participants = [];
1198
- this.participants.forEach(participant => participants.push(participant));
1199
- return participants;
1200
- });
1201
- }
1202
- /**
1203
- * Get participant by SID from conversation
1204
- * @returns {Promise<Participant>}
1205
- */
1206
- async getParticipantBySid(participantSid) {
1207
- return this.rosterEntityPromise.then(() => {
1208
- let participant = this.participants.get(participantSid);
1209
- if (!participant) {
1210
- throw new Error('Participant with SID ' + participantSid + ' was not found');
1211
- }
1212
- return participant;
1213
- });
1214
- }
1215
- /**
1216
- * Get participant by identity from conversation
1217
- * @returns {Promise<Participant>}
1218
- */
1219
- async getParticipantByIdentity(identity) {
1220
- let foundParticipant = null;
1221
- return this.rosterEntityPromise.then(() => {
1222
- this.participants.forEach(participant => {
1223
- if (participant.identity === identity) {
1224
- foundParticipant = participant;
1225
- }
1226
- });
1227
- if (!foundParticipant) {
1228
- throw new Error('Participant with identity ' + identity + ' was not found');
1229
- }
1230
- return foundParticipant;
1231
- });
1232
- }
1233
- /**
1234
- * Add a chat participant to the conversation
1235
- * @returns {Promise<any>}
1236
- */
1237
- async add(identity, attributes) {
1238
- return await this.services.commandExecutor.mutateResource('post', this.links.participants, {
1239
- identity,
1240
- attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined
1241
- });
1242
- }
1243
- /**
1244
- * Add a non-chat participant to the conversation.
1245
- *
1246
- * @param proxyAddress
1247
- * @param address
1248
- * @param attributes
1249
- * @returns {Promise<any>}
1250
- */
1251
- addNonChatParticipant(proxyAddress, address, attributes = {}) {
1252
- return this.services.commandExecutor.mutateResource('post', this.links.participants, {
1253
- attributes: JSON.stringify(attributes),
1254
- messaging_binding: {
1255
- address,
1256
- proxy_address: proxyAddress
1257
- }
1258
- });
1259
- }
1260
- /**
1261
- * Remove the participant with a given identity from a conversation.
1262
- */
1263
- remove(identity) {
1264
- return this.services.commandExecutor.mutateResource('delete', `${this.links.participants}/${identity}`);
1265
- }
1266
- }
1267
- /**
1268
- * Fired when participant joined conversation
1269
- * @event Participants#participantJoined
1270
- * @type {Participant}
1271
- */
1272
- /**
1273
- * Fired when participant left conversation
1274
- * @event Participants#participantLeft
1275
- * @type {Participant}
1276
- */
1277
- /**
1278
- * Fired when participant updated
1279
- * @event Participants#participantUpdated
1280
- * @type {Object}
1281
- * @property {Participant} participant - Updated Participant
1282
- * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons
1283
- */
1284
-
1285
- /**
1286
- * Represents a media information for a message in a conversation.
1287
- */
1288
- class Media {
1289
- /**
1290
- * @internal
1291
- */
1292
- constructor(data, services) {
1293
- this.mcsMedia = null;
1294
- this.services = services;
1295
- if (data instanceof mcsClient.McsMedia) {
1296
- this.mcsMedia = data;
1297
- }
1298
- this.state = {
1299
- sid: data.sid,
1300
- category: data.category,
1301
- filename: data.filename,
1302
- contentType: data.contentType,
1303
- size: data.size
1304
- };
1305
- }
1306
- /**
1307
- * Server-assigned unique identifier for the media.
1308
- */
1309
- get sid() { return this.state.sid; }
1310
- /**
1311
- * File name. Null if absent.
1312
- */
1313
- get filename() { return this.state.filename; }
1314
- /**
1315
- * Content type of the media.
1316
- */
1317
- get contentType() { return this.state.contentType; }
1318
- /**
1319
- * Size of the media in bytes.
1320
- */
1321
- get size() { return this.state.size; }
1322
- /**
1323
- * Media category, can be one of the {MediaCategory} values.
1324
- */
1325
- get category() { return this.state.category; }
1326
- /**
1327
- * Returns the direct content URL for the media.
1328
- *
1329
- * This URL is impermanent, it will expire in several minutes and cannot be cached.
1330
- * If the URL becomes expired, you need to request a new one.
1331
- * Each call to this function produces a new temporary URL.
1332
- */
1333
- async getContentTemporaryUrl() {
1334
- await this._fetchMcsMedia();
1335
- return this.mcsMedia.getContentUrl();
1336
- }
1337
- /**
1338
- * Returns cached direct content URL for the media.
1339
- *
1340
- * This URL will expire in several minutes. This function does not refresh the URL and can be used to query it several times
1341
- * without causing network traffic.
1342
- * If the URL becomes expired, you need to request a new one using getContentTemporaryUrl().
1343
- *
1344
- * @returns {Promise<String>}
1345
- */
1346
- async getCachedTemporaryUrl() {
1347
- await this._fetchMcsMedia();
1348
- return this.mcsMedia.getCachedContentUrl();
1349
- }
1350
- async _fetchMcsMedia() {
1351
- if (!this.mcsMedia) {
1352
- if (this.services.mcsClient) {
1353
- this.mcsMedia = await this.services.mcsClient.get(this.state.sid);
1354
- }
1355
- else {
1356
- throw new Error('Media Content Service is unavailable');
1357
- }
1358
- }
1359
- }
1360
- }
1361
-
1362
- /**
1363
- * Contains aggregated information about delivery statuses of a message across all participants
1364
- * of a conversation.
1365
- *
1366
- * At any moment during the message delivery to a participant, the message can have zero or more of following
1367
- * delivery statuses:
1368
- * * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.
1369
- * * Message is considered as **delivered** to a participant if Twilio has received confirmation of message
1370
- * delivery from the upstream carrier, and, where available, the destination handset.
1371
- * * Message considered as **undelivered** to a participant if Twilio has received a delivery receipt
1372
- * indicating that the message was not delivered. This can happen for many reasons including carrier content
1373
- * filtering and the availability of the destination handset.
1374
- * * Message considered as **read** by a participant if the message has been delivered and opened by the
1375
- * recipient in a conversation. The recipient must have enabled the read receipts.
1376
- * * Message considered as **failed** to be delivered to a participant if the message could not be sent.
1377
- * This can happen for various reasons including queue overflows, account suspensions and media
1378
- * errors (in the case of MMS for instance).
1379
- *
1380
- * {@link AggregatedDeliveryReceipt} class contains an aggregated value {@link DeliveryAmount} for each delivery status.
1381
- */
1382
- class AggregatedDeliveryReceipt {
1383
- /**
1384
- * @internal
1385
- */
1386
- constructor(data) {
1387
- this.state = data;
1388
- }
1389
- /**
1390
- * Maximum number of delivery events expected for the message.
1391
- */
1392
- get total() {
1393
- return this.state.total;
1394
- }
1395
- /**
1396
- * Message is considered as **sent** to a participant if the nearest upstream carrier accepted the message.
1397
- *
1398
- * @return Amount of participants that have the **sent** delivery status for the message.
1399
- */
1400
- get sent() {
1401
- return this.state.sent;
1402
- }
1403
- /**
1404
- * Message is considered as **delivered** to a participant if Twilio has received confirmation of message
1405
- * delivery from the upstream carrier, and, where available, the destination handset.
1406
- *
1407
- * @return Amount of participants that have the **delivered** delivery status for the message.
1408
- */
1409
- get delivered() {
1410
- return this.state.delivered;
1411
- }
1412
- /**
1413
- * Message is considered as **read** by a participant, if the message has been delivered and opened by the
1414
- * recipient in a conversation. The recipient must have enabled the read receipts.
1415
- *
1416
- * @return Amount of participants that have the **read** delivery status for the message.
1417
- */
1418
- get read() {
1419
- return this.state.read;
1420
- }
1421
- /**
1422
- * Message is considered as **undelivered** to a participant if Twilio has received a delivery receipt
1423
- * indicating that the message was not delivered. This can happen for many reasons including carrier content
1424
- * filtering and the availability of the destination handset.
1425
- *
1426
- * @return Ammount of participants that have the **undelivered** delivery status for the message.
1427
- */
1428
- get undelivered() {
1429
- return this.state.undelivered;
1430
- }
1431
- /**
1432
- * Message is considered as **failed** to be delivered to a participant if the message could not be sent.
1433
- * This can happen for various reasons including queue overflows, account suspensions and media
1434
- * errors (in the case of MMS for instance). Twilio does not charge you for failed messages.
1435
- *
1436
- * @return Amount of participants that have the **failed** delivery status for the message.
1437
- */
1438
- get failed() {
1439
- return this.state.failed;
1440
- }
1441
- _update(data) {
1442
- this.state = data;
1443
- }
1444
- _isEquals(data) {
1445
- const isTotalSame = this.total === data.total;
1446
- const isSentSame = this.sent === data.sent;
1447
- const isDeliveredSame = this.delivered === data.delivered;
1448
- const isReadSame = this.read === data.read;
1449
- const isUndeliveredSame = this.undelivered === data.undelivered;
1450
- const isFailedSame = this.failed === data.failed;
1451
- return isTotalSame && isSentSame && isDeliveredSame && isReadSame && isUndeliveredSame && isFailedSame;
1452
- }
1453
- }
1454
-
1455
- /**
1456
- * Pagination helper class.
1457
- */
1458
- class RestPaginator {
1459
- /**
1460
- * @internal
1461
- */
1462
- constructor(items, source, prevToken, nextToken) {
1463
- this.state = {
1464
- prevToken,
1465
- nextToken,
1466
- source,
1467
- items
1468
- };
1469
- }
1470
- /**
1471
- * Indicates the existence of the next page.
1472
- */
1473
- get hasNextPage() { return !!this.state.nextToken; }
1474
- /**
1475
- * Indicates the existence of the previous page
1476
- */
1477
- get hasPrevPage() { return !!this.state.prevToken; }
1478
- /**
1479
- * Array of elements on the current page.
1480
- */
1481
- get items() { return this.state.items; }
1482
- /**
1483
- * Request the next page. Does not modify the existing object.
1484
- */
1485
- nextPage() {
1486
- return this.hasNextPage ? this.state.source(this.state.nextToken) : Promise.reject(new Error('No next page'));
1487
- }
1488
- /**
1489
- * Request the previous page. Does not modify the existing object.
1490
- */
1491
- prevPage() {
1492
- return this.hasPrevPage ? this.state.source(this.state.prevToken) : Promise.reject(new Error('No previous page'));
1493
- }
1494
- }
1495
-
1496
- /**
1497
- * Represents a delivery receipt of a message.
1498
- */
1499
- class DetailedDeliveryReceipt {
1500
- /**
1501
- * @internal
1502
- */
1503
- constructor(descriptor) {
1504
- this.sid = descriptor.sid;
1505
- this.messageSid = descriptor.message_sid;
1506
- this.conversationSid = descriptor.conversation_sid;
1507
- this.channelMessageSid = descriptor.channel_message_sid;
1508
- this.participantSid = descriptor.participant_sid;
1509
- this.status = descriptor.status || 'queued';
1510
- this.errorCode = descriptor.error_code || 0;
1511
- this.dateCreated = descriptor.date_created;
1512
- this.dateUpdated = descriptor.date_updated;
1513
- }
1514
- }
1515
-
1516
- const log$6 = Logger.scope('Message');
1517
- /**
1518
- * A message in a conversation.
1519
- */
1520
- class Message extends EventEmitter {
1521
- /**
1522
- * @internal
1523
- */
1524
- constructor(index, data, conversation, links, configuration, services) {
1525
- var _a, _b, _c, _d, _e;
1526
- super();
1527
- this.conversation = conversation;
1528
- this.links = links;
1529
- this.configuration = configuration;
1530
- this.services = services;
1531
- this.state = {
1532
- sid: data.sid,
1533
- index: index,
1534
- author: (_a = data.author) !== null && _a !== void 0 ? _a : null,
1535
- subject: (_b = data.subject) !== null && _b !== void 0 ? _b : null,
1536
- body: data.text,
1537
- timestamp: data.timestamp ? new Date(data.timestamp) : null,
1538
- dateUpdated: data.dateUpdated ? new Date(data.dateUpdated) : null,
1539
- lastUpdatedBy: (_c = data.lastUpdatedBy) !== null && _c !== void 0 ? _c : null,
1540
- attributes: parseAttributes(data.attributes, `Got malformed attributes for the message ${data.sid}`, log$6),
1541
- type: (_d = data.type) !== null && _d !== void 0 ? _d : 'text',
1542
- media: (data.type && data.type === 'media' && data.media)
1543
- ? new Media(data.media, this.services) : null,
1544
- medias: (data.type && data.type === 'media' && data.medias)
1545
- ? data.medias.map((m) => new Media(m, this.services)) : null,
1546
- participantSid: (_e = data.memberSid) !== null && _e !== void 0 ? _e : null,
1547
- aggregatedDeliveryReceipt: data.delivery ? new AggregatedDeliveryReceipt(data.delivery) : null
1548
- };
1549
- }
1550
- /**
1551
- * The server-assigned unique identifier for the message.
1552
- */
1553
- get sid() { return this.state.sid; }
1554
- /**
1555
- * Name of the user that sent the message.
1556
- */
1557
- get author() { return this.state.author; }
1558
- /**
1559
- * Message subject. Used only in email conversations.
1560
- */
1561
- get subject() { return this.state.subject; }
1562
- /**
1563
- * Body of the message.
1564
- */
1565
- get body() { return this.state.body; }
1566
- /**
1567
- * Date this message was last updated on.
1568
- */
1569
- get dateUpdated() { return this.state.dateUpdated; }
1570
- /**
1571
- * Index of the message in the conversation's messages list.
1572
- * By design of the Conversations system, the message indices may have arbitrary gaps between them,
1573
- * that does not necessarily mean they were deleted or otherwise modified - just that
1574
- * messages may have some non-contiguous indices even if they are being sent immediately one after another.
1575
- *
1576
- * Trying to use indices for some calculations is going to be unreliable.
1577
- *
1578
- * To calculate the number of unread messages it is better to use the read horizon API.
1579
- * See {@link Conversation.getUnreadMessagesCount} for details.
1580
- */
1581
- get index() { return this.state.index; }
1582
- /**
1583
- * Identity of the last user that updated the message.
1584
- */
1585
- get lastUpdatedBy() { return this.state.lastUpdatedBy; }
1586
- /**
1587
- * Date this message was created on.
1588
- */
1589
- get dateCreated() { return this.state.timestamp; }
1590
- /**
1591
- * Custom attributes of the message.
1592
- */
1593
- get attributes() { return this.state.attributes; }
1594
- /**
1595
- * Push notification type of the message.
1596
- */
1597
- get type() { return this.state.type; }
1598
- /**
1599
- * One of the attached media.
1600
- * @deprecated Use attachedMedia instead. Note that the latter is now an array.
1601
- */
1602
- get media() { return this.state.media; }
1603
- /**
1604
- * Return all media attachments, except email body/history attachments, without temporary urls.
1605
- */
1606
- get attachedMedia() { return this.getMediaByCategory(['media']); }
1607
- /**
1608
- * The server-assigned unique identifier of the authoring participant.
1609
- */
1610
- get participantSid() { return this.state.participantSid; }
1611
- /**
1612
- * Aggregated information about the message delivery statuses across all participants of a conversation..
1613
- */
1614
- get aggregatedDeliveryReceipt() {
1615
- return this.state.aggregatedDeliveryReceipt;
1616
- }
1617
- /**
1618
- * Return a (possibly empty) array of media matching a specific set of categories.
1619
- * Allowed category is so far only 'media'.
1620
- * @param categories Array of categories to match.
1621
- * @returns Array of media descriptors matching given categories.
1622
- */
1623
- getMediaByCategory(categories) {
1624
- var _a;
1625
- return (_a = this.state.medias) === null || _a === void 0 ? void 0 : _a.filter((m) => categories.includes(m.category));
1626
- }
1627
- _update(data) {
1628
- let updateReasons = [];
1629
- if ((data.text || ((typeof data.text) === 'string')) && data.text !== this.state.body) {
1630
- this.state.body = data.text;
1631
- updateReasons.push('body');
1632
- }
1633
- if (data.subject && data.subject !== this.state.subject) {
1634
- this.state.subject = data.subject;
1635
- updateReasons.push('subject');
1636
- }
1637
- if (data.lastUpdatedBy && data.lastUpdatedBy !== this.state.lastUpdatedBy) {
1638
- this.state.lastUpdatedBy = data.lastUpdatedBy;
1639
- updateReasons.push('lastUpdatedBy');
1640
- }
1641
- if (data.author && data.author !== this.state.author) {
1642
- this.state.author = data.author;
1643
- updateReasons.push('author');
1644
- }
1645
- if (data.dateUpdated &&
1646
- new Date(data.dateUpdated).getTime() !== (this.state.dateUpdated && this.state.dateUpdated.getTime())) {
1647
- this.state.dateUpdated = new Date(data.dateUpdated);
1648
- updateReasons.push('dateUpdated');
1649
- }
1650
- if (data.timestamp &&
1651
- new Date(data.timestamp).getTime() !== (this.state.timestamp && this.state.timestamp.getTime())) {
1652
- this.state.timestamp = new Date(data.timestamp);
1653
- updateReasons.push('dateCreated');
1654
- }
1655
- let updatedAttributes = parseAttributes(data.attributes, `Got malformed attributes for the message ${this.sid}`, log$6);
1656
- if (!isDeepEqual(this.state.attributes, updatedAttributes)) {
1657
- this.state.attributes = updatedAttributes;
1658
- updateReasons.push('attributes');
1659
- }
1660
- let updatedAggregatedDelivery = data.delivery;
1661
- let currentAggregatedDelivery = this.state.aggregatedDeliveryReceipt;
1662
- let isUpdatedAggregateDeliveryValid = !!updatedAggregatedDelivery && !!updatedAggregatedDelivery.total &&
1663
- !!updatedAggregatedDelivery.delivered && !!updatedAggregatedDelivery.failed && !!updatedAggregatedDelivery.read &&
1664
- !!updatedAggregatedDelivery.sent && !!updatedAggregatedDelivery.undelivered;
1665
- if (isUpdatedAggregateDeliveryValid) {
1666
- if (!currentAggregatedDelivery) {
1667
- this.state.aggregatedDeliveryReceipt = new AggregatedDeliveryReceipt(updatedAggregatedDelivery);
1668
- updateReasons.push('deliveryReceipt');
1669
- }
1670
- else if (!currentAggregatedDelivery._isEquals(updatedAggregatedDelivery)) {
1671
- currentAggregatedDelivery._update(updatedAggregatedDelivery);
1672
- updateReasons.push('deliveryReceipt');
1673
- }
1674
- }
1675
- if (updateReasons.length > 0) {
1676
- this.emit('updated', { message: this, updateReasons: updateReasons });
1677
- }
1678
- }
1679
- /**
1680
- * Get the participant who is the author of the message.
1681
- */
1682
- async getParticipant() {
1683
- let participant = null;
1684
- if (this.state.participantSid) {
1685
- participant = await this.conversation.getParticipantBySid(this.participantSid)
1686
- .catch(() => {
1687
- log$6.debug(`Participant with sid "${this.participantSid}" not found for message ${this.sid}`);
1688
- return null;
1689
- });
1690
- }
1691
- if (!participant && this.state.author) {
1692
- participant = await this.conversation.getParticipantByIdentity(this.state.author)
1693
- .catch(() => {
1694
- log$6.debug(`Participant with identity "${this.author}" not found for message ${this.sid}`);
1695
- return null;
1696
- });
1697
- }
1698
- if (participant) {
1699
- return participant;
1700
- }
1701
- let errorMesage = 'Participant with ';
1702
- if (this.state.participantSid) {
1703
- errorMesage += 'SID \'' + this.state.participantSid + '\' ';
1704
- }
1705
- if (this.state.author) {
1706
- if (this.state.participantSid) {
1707
- errorMesage += 'or ';
1708
- }
1709
- errorMesage += 'identity \'' + this.state.author + '\' ';
1710
- }
1711
- if (errorMesage === 'Participant with ') {
1712
- errorMesage = 'Participant ';
1713
- }
1714
- errorMesage += 'was not found';
1715
- throw new Error(errorMesage);
1716
- }
1717
- /**
1718
- * Get the delivery receipts of the message.
1719
- */
1720
- async getDetailedDeliveryReceipts() {
1721
- let paginator = await this._getDetailedDeliveryReceiptsPaginator();
1722
- let detailedDeliveryReceipts = [];
1723
- while (true) {
1724
- detailedDeliveryReceipts = [...detailedDeliveryReceipts, ...paginator.items];
1725
- if (!paginator.hasNextPage) {
1726
- break;
1727
- }
1728
- paginator = await paginator.nextPage();
1729
- }
1730
- return detailedDeliveryReceipts;
1731
- }
1732
- /**
1733
- * Remove the message.
1734
- */
1735
- async remove() {
1736
- await this.services.commandExecutor.mutateResource('delete', this.links.self);
1737
- return this;
1738
- }
1739
- /**
1740
- * Edit the message body.
1741
- * @param body New body of the message.
1742
- */
1743
- async updateBody(body) {
1744
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
1745
- body
1746
- });
1747
- return this;
1748
- }
1749
- /**
1750
- * Edit the message attributes.
1751
- * @param attributes New attributes.
1752
- */
1753
- async updateAttributes(attributes) {
1754
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
1755
- attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined
1756
- });
1757
- return this;
1758
- }
1759
- /**
1760
- * Get content URLs for all media attachments in the given set using single operation.
1761
- * @param contentSet Set of media attachments to query for content URL.
1762
- */
1763
- async attachTemporaryUrlsFor(contentSet) {
1764
- // We ignore existing mcsMedia members of each of the media entries.
1765
- // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.
1766
- const sids = contentSet.map((m) => m.sid);
1767
- if (this.services.mcsClient) {
1768
- return (await this.services.mcsClient.mediaSetGet(sids)).map((item) => { return new Media(item, this.services); });
1769
- }
1770
- else {
1771
- throw new Error('Media Content Service is unavailable');
1772
- }
1773
- }
1774
- async _getDetailedDeliveryReceiptsPaginator(options) {
1775
- const messagesReceiptsUrl = this.configuration.links.messagesReceipts
1776
- .replace('%s', this.conversation.sid)
1777
- .replace('%s', this.sid);
1778
- const url = new UriBuilder(messagesReceiptsUrl)
1779
- .arg('PageToken', options === null || options === void 0 ? void 0 : options.pageToken)
1780
- .arg('PageSize', options === null || options === void 0 ? void 0 : options.pageSize)
1781
- .build();
1782
- const response = await this.services.network.get(url);
1783
- return new RestPaginator(response.body.delivery_receipts.map((x) => new DetailedDeliveryReceipt(x)), (pageToken, pageSize) => this._getDetailedDeliveryReceiptsPaginator({ pageToken, pageSize }), response.body.meta.previous_token, response.body.meta.next_token);
1784
- }
1785
- }
1786
- /**
1787
- * Fired when the properties or the body of the message has been updated.
1788
- *
1789
- * Parameters:
1790
- * 1. object `data` - info object provided with the event. It has the following properties:
1791
- * * {@link Message} message - the message in question
1792
- * * {@link MessageUpdateReason}[] updateReasons - array of reasons for the update
1793
- */
1794
- Message.updated = 'updated';
1795
- __decorate([
1796
- declarativeTypeValidator.validateTypesAsync('string'),
1797
- __metadata("design:type", Function),
1798
- __metadata("design:paramtypes", [String]),
1799
- __metadata("design:returntype", Promise)
1800
- ], Message.prototype, "updateBody", null);
1801
- __decorate([
1802
- declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
1803
- __metadata("design:type", Function),
1804
- __metadata("design:paramtypes", [Object]),
1805
- __metadata("design:returntype", Promise)
1806
- ], Message.prototype, "updateAttributes", null);
1807
- __decorate([
1808
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.custom(value => [
1809
- value instanceof Array && value.length > 0 && value.reduce((a, c) => a && c instanceof Media),
1810
- 'a non-empty array of Media'
1811
- ])),
1812
- __metadata("design:type", Function),
1813
- __metadata("design:paramtypes", [Array]),
1814
- __metadata("design:returntype", Promise)
1815
- ], Message.prototype, "attachTemporaryUrlsFor", null);
1816
-
1817
- const log$5 = Logger.scope('Messages');
1818
- /**
1819
- * Represents the collection of messages in a conversation
1820
- */
1821
- class Messages extends EventEmitter {
1822
- constructor(conversation, configuration, services) {
1823
- super();
1824
- this.conversation = conversation;
1825
- this.configuration = configuration;
1826
- this.services = services;
1827
- this.messagesByIndex = new Map();
1828
- this.messagesListPromise = null;
1829
- }
1830
- /**
1831
- * Subscribe to the Messages Event Stream
1832
- * @param name - The name of Sync object for the Messages resource.
1833
- */
1834
- async subscribe(name) {
1835
- if (this.messagesListPromise) {
1836
- return this.messagesListPromise;
1837
- }
1838
- this.messagesListPromise = this.services.syncClient.list({
1839
- id: name,
1840
- mode: 'open_existing',
1841
- });
1842
- try {
1843
- const list = await this.messagesListPromise;
1844
- list.on('itemAdded', (args) => {
1845
- log$5.debug(`${this.conversation.sid} itemAdded: ${args.item.index}`);
1846
- const links = {
1847
- self: `${this.conversation.links.messages}/${args.item.data.sid}`,
1848
- conversation: this.conversation.links.self,
1849
- messages_receipts: `${this.conversation.links.messages}/${args.item.data.sid}/Receipts`,
1850
- };
1851
- const message = new Message(args.item.index, args.item.data, this.conversation, links, this.configuration, this.services);
1852
- if (this.messagesByIndex.has(message.index)) {
1853
- log$5.debug('Message arrived, but is already known and ignored', this.conversation.sid, message.index);
1854
- return;
1855
- }
1856
- this.messagesByIndex.set(message.index, message);
1857
- message.on('updated', (args) => this.emit('messageUpdated', args));
1858
- this.emit('messageAdded', message);
1859
- });
1860
- list.on('itemRemoved', (args) => {
1861
- log$5.debug(`#{this.conversation.sid} itemRemoved: ${args.index}`);
1862
- const index = args.index;
1863
- if (this.messagesByIndex.has(index)) {
1864
- let message = this.messagesByIndex.get(index);
1865
- this.messagesByIndex.delete(message.index);
1866
- message.removeAllListeners('updated');
1867
- this.emit('messageRemoved', message);
1868
- }
1869
- });
1870
- list.on('itemUpdated', (args) => {
1871
- log$5.debug(`${this.conversation.sid} itemUpdated: ${args.item.index}`);
1872
- const message = this.messagesByIndex.get(args.item.index);
1873
- if (message) {
1874
- message._update(args.item.data);
1875
- }
1876
- });
1877
- return list;
1878
- }
1879
- catch (err) {
1880
- this.messagesListPromise = null;
1881
- if (this.services.syncClient.connectionState !== 'disconnected') {
1882
- log$5.error('Failed to get messages object for conversation', this.conversation.sid, err);
1883
- }
1884
- log$5.debug('ERROR: Failed to get messages object for conversation', this.conversation.sid, err);
1885
- throw err;
1886
- }
1887
- }
1888
- async unsubscribe() {
1889
- if (!this.messagesListPromise) {
1890
- return;
1891
- }
1892
- const entity = await this.messagesListPromise;
1893
- entity.close();
1894
- this.messagesListPromise = null;
1895
- }
1896
- /**
1897
- * Send Message to the conversation, message could include both text and multiple media attachments.
1898
- * @param message Message to post
1899
- * @returns Returns promise which can fail
1900
- */
1901
- async sendV2(message) {
1902
- var _a;
1903
- log$5.debug('Sending message V2', message.mediaContent, message.attributes, message.emailOptions);
1904
- const media = [];
1905
- for (const [category, mediaContent] of message.mediaContent) {
1906
- log$5.debug(`Adding media to a message as ${mediaContent instanceof FormData ? 'FormData' : 'SendMediaOptions'}`, mediaContent);
1907
- media.push(mediaContent instanceof FormData
1908
- ? await this.services.mcsClient.postFormData(mediaContent, category)
1909
- : await this.services.mcsClient.post(mediaContent.contentType, mediaContent.media, category, mediaContent.filename));
1910
- }
1911
- return await this.services.commandExecutor.mutateResource('post', this.conversation.links.messages, {
1912
- body: message.text,
1913
- subject: (_a = message.emailOptions) === null || _a === void 0 ? void 0 : _a.subject,
1914
- media_sids: media.map((m) => m.sid),
1915
- attributes: typeof message.attributes !== 'undefined'
1916
- ? JSON.stringify(message.attributes)
1917
- : undefined,
1918
- });
1919
- }
1920
- /**
1921
- * Send Message to the conversation
1922
- * @param message Message to post
1923
- * @param attributes Message attributes
1924
- * @param emailOptions Options that modify E-mail integration behaviors.
1925
- * @returns Returns promise which can fail
1926
- */
1927
- async send(message, attributes = {}, emailOptions) {
1928
- log$5.debug('Sending text message', message, attributes, emailOptions);
1929
- return await this.services.commandExecutor.mutateResource('post', this.conversation.links.messages, {
1930
- body: message !== null && message !== void 0 ? message : '',
1931
- attributes: typeof attributes !== 'undefined'
1932
- ? JSON.stringify(attributes)
1933
- : undefined,
1934
- subject: emailOptions === null || emailOptions === void 0 ? void 0 : emailOptions.subject,
1935
- });
1936
- }
1937
- /**
1938
- * Send Media Message to the conversation
1939
- * @param mediaContent Media content to post
1940
- * @param attributes Message attributes
1941
- * @param emailOptions Email options
1942
- * @returns Returns promise which can fail
1943
- */
1944
- async sendMedia(mediaContent, attributes = {}, emailOptions) {
1945
- log$5.debug('Sending media message', mediaContent, attributes, emailOptions);
1946
- log$5.debug(`Sending media message as ${mediaContent instanceof FormData ? 'FormData' : 'SendMediaOptions'}`, mediaContent, attributes);
1947
- const media = mediaContent instanceof FormData
1948
- ? await this.services.mcsClient.postFormData(mediaContent)
1949
- : await this.services.mcsClient.post(mediaContent.contentType, mediaContent.media, 'media', mediaContent.filename);
1950
- // emailOptions are currently ignored for media messages.
1951
- return await this.services.commandExecutor.mutateResource('post', this.conversation.links.messages, {
1952
- media_sids: [media.sid],
1953
- attributes: typeof attributes !== 'undefined'
1954
- ? JSON.stringify(attributes)
1955
- : undefined,
1956
- });
1957
- }
1958
- /**
1959
- * Returns messages from conversation using paginator interface
1960
- * @param pageSize Number of messages to return in single chunk. By default it's 30.
1961
- * @param anchor Most early message id which is already known, or 'end' by default
1962
- * @param direction Pagination order 'backwards' or 'forward', 'forward' by default
1963
- * @returns Last page of messages by default
1964
- */
1965
- async getMessages(pageSize, anchor, direction = 'backwards') {
1966
- return this._getMessages(pageSize, anchor, direction);
1967
- }
1968
- _wrapPaginator(order, page, op) {
1969
- // Due to an inconsistency between Sync and Chat conventions, next and
1970
- // previous pages should be swapped.
1971
- const shouldReverse = order === 'desc';
1972
- const nextPage = () => page.nextPage().then((page) => this._wrapPaginator(order, page, op));
1973
- const previousPage = () => page.prevPage().then((page) => this._wrapPaginator(order, page, op));
1974
- return op(page.items).then((items) => ({
1975
- items: items.sort((x, y) => {
1976
- return x.index - y.index;
1977
- }),
1978
- hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage,
1979
- hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage,
1980
- prevPage: shouldReverse ? nextPage : previousPage,
1981
- nextPage: shouldReverse ? previousPage : nextPage,
1982
- }));
1983
- }
1984
- _upsertMessage(index, value) {
1985
- const cachedMessage = this.messagesByIndex.get(index);
1986
- if (cachedMessage) {
1987
- return cachedMessage;
1988
- }
1989
- const links = {
1990
- self: `${this.conversation.links.messages}/${value.sid}`,
1991
- conversation: this.conversation.links.self,
1992
- messages_receipts: `${this.conversation.links.messages}/${value.sid}/Receipts`,
1993
- };
1994
- const message = new Message(index, value, this.conversation, links, this.configuration, this.services);
1995
- this.messagesByIndex.set(message.index, message);
1996
- message.on('updated', (args) => this.emit('messageUpdated', args));
1997
- return message;
1998
- }
1999
- /**
2000
- * Returns last messages from conversation
2001
- * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30.
2002
- * @param {String} [anchor] Most early message id which is already known, or 'end' by default
2003
- * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default
2004
- * @returns {Promise<SyncPaginator<Message>>} last page of messages by default
2005
- * @private
2006
- */
2007
- async _getMessages(pageSize = 30, anchor = 'end', direction = 'forward') {
2008
- const order = direction === 'backwards' ? 'desc' : 'asc';
2009
- const list = await this.messagesListPromise;
2010
- const page = await list.getItems({
2011
- from: anchor !== 'end' ? anchor : void 0,
2012
- pageSize,
2013
- order,
2014
- limit: pageSize, // @todo Limit equals pageSize by default in Sync. This is probably not ideal.
2015
- });
2016
- return await this._wrapPaginator(order, page, (items) => Promise.all(items.map((item) => this._upsertMessage(item.index, item.data))));
2017
- }
2018
- }
2019
-
2020
- class UnsentMessage {
2021
- constructor(messagesEntity) {
2022
- this.messagesEntity = messagesEntity;
2023
- this.attributes = {};
2024
- this.mediaContent = [];
2025
- this.emailOptions = {};
2026
- }
2027
- /**
2028
- * Send the prepared message to the conversation.
2029
- * @returns {Promise<number>} new Message's index in the Conversation's messages list
2030
- */
2031
- async send() {
2032
- const response = await this.messagesEntity.sendV2(this);
2033
- return parseToNumber(response.messageId);
2034
- }
2035
- }
2036
-
2037
- class MessageBuilder {
2038
- constructor(limits, messagesEntity) {
2039
- this.limits = limits;
2040
- this.message = new UnsentMessage(messagesEntity);
2041
- }
2042
- setBody(text) {
2043
- this.message.text = text;
2044
- return this;
2045
- }
2046
- setSubject(subject) {
2047
- this.message.emailOptions.subject = subject;
2048
- return this;
2049
- }
2050
- setAttributes(attributes) {
2051
- this.message.attributes = attributes;
2052
- return this;
2053
- }
2054
- addMedia(payload) {
2055
- this.message.mediaContent.push(['media', payload]);
2056
- return this;
2057
- }
2058
- build() {
2059
- if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {
2060
- throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);
2061
- }
2062
- // @todo we don't know the sizes of the attachments in FormData
2063
- return this.message;
2064
- }
2065
- getPayloadContentType(payload) {
2066
- if (typeof FormData !== 'undefined' && (payload instanceof FormData)) {
2067
- return payload.get('Content-Type');
2068
- }
2069
- return payload.contentType;
2070
- }
2071
- }
2072
-
2073
- const log$4 = Logger.scope('Conversation');
2074
- const fieldMappings = {
2075
- lastMessage: 'lastMessage',
2076
- attributes: 'attributes',
2077
- createdBy: 'createdBy',
2078
- dateCreated: 'dateCreated',
2079
- dateUpdated: 'dateUpdated',
2080
- friendlyName: 'friendlyName',
2081
- lastConsumedMessageIndex: 'lastConsumedMessageIndex',
2082
- notificationLevel: 'notificationLevel',
2083
- sid: 'sid',
2084
- status: 'status',
2085
- uniqueName: 'uniqueName',
2086
- state: 'state'
2087
- };
2088
- function parseTime(timeString) {
2089
- try {
2090
- return new Date(timeString);
2091
- }
2092
- catch (e) {
2093
- return null;
2094
- }
2095
- }
2096
- /**
2097
- * A conversation represents communication between multiple Conversations clients
2098
- */
2099
- class Conversation extends EventEmitter {
2100
- /**
2101
- * @internal
2102
- */
2103
- constructor(descriptor, sid, links, configuration, services) {
2104
- super();
2105
- this.sid = sid;
2106
- this.links = links;
2107
- this.configuration = configuration;
2108
- this.services = services;
2109
- let attributes = descriptor.attributes || {};
2110
- let createdBy = descriptor.createdBy;
2111
- let dateCreated = parseTime(descriptor.dateCreated);
2112
- let dateUpdated = parseTime(descriptor.dateUpdated);
2113
- let friendlyName = descriptor.friendlyName || null;
2114
- let lastReadMessageIndex = Number.isInteger(descriptor.lastConsumedMessageIndex) ? descriptor.lastConsumedMessageIndex : null;
2115
- let uniqueName = descriptor.uniqueName || null;
2116
- try {
2117
- JSON.stringify(attributes);
2118
- }
2119
- catch (e) {
2120
- throw new Error('Attributes must be a valid JSON object.');
2121
- }
2122
- this.entityName = descriptor.channel;
2123
- this.channelState = {
2124
- uniqueName,
2125
- status: 'notParticipating',
2126
- attributes,
2127
- createdBy,
2128
- dateCreated,
2129
- dateUpdated,
2130
- friendlyName,
2131
- lastReadMessageIndex: lastReadMessageIndex
2132
- };
2133
- if (descriptor.notificationLevel) {
2134
- this.channelState.notificationLevel = descriptor.notificationLevel;
2135
- }
2136
- const participantsLinks = {
2137
- participants: this.links.participants
2138
- };
2139
- this.participants = new Map();
2140
- this.participantsEntity = new Participants(this, this.participants, participantsLinks, this.configuration, this.services);
2141
- this.participantsEntity.on('participantJoined', this.emit.bind(this, 'participantJoined'));
2142
- this.participantsEntity.on('participantLeft', this.emit.bind(this, 'participantLeft'));
2143
- this.participantsEntity.on('participantUpdated', (args) => this.emit('participantUpdated', args));
2144
- this.messagesEntity = new Messages(this, configuration, services);
2145
- this.messagesEntity.on('messageAdded', message => this._onMessageAdded(message));
2146
- this.messagesEntity.on('messageUpdated', (args) => this.emit('messageUpdated', args));
2147
- this.messagesEntity.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
2148
- }
2149
- /**
2150
- * Unique name of the conversation.
2151
- */
2152
- get uniqueName() { return this.channelState.uniqueName; }
2153
- /**
2154
- * Status of the conversation.
2155
- */
2156
- get status() { return this.channelState.status; }
2157
- /**
2158
- * Name of the conversation.
2159
- */
2160
- get friendlyName() { return this.channelState.friendlyName; }
2161
- /**
2162
- * Date this conversation was last updated on.
2163
- */
2164
- get dateUpdated() { return this.channelState.dateUpdated; }
2165
- /**
2166
- * Date this conversation was created on.
2167
- */
2168
- get dateCreated() { return this.channelState.dateCreated; }
2169
- /**
2170
- * Identity of the user that created this conversation.
2171
- */
2172
- get createdBy() { return this.channelState.createdBy; }
2173
- /**
2174
- * Custom attributes of the conversation.
2175
- */
2176
- get attributes() { return this.channelState.attributes; }
2177
- /**
2178
- * Index of the last message the user has read in this conversation.
2179
- */
2180
- get lastReadMessageIndex() { return this.channelState.lastReadMessageIndex; }
2181
- /**
2182
- * Last message sent to this conversation.
2183
- */
2184
- get lastMessage() { return this.channelState.lastMessage; }
2185
- /**
2186
- * User notification level for this conversation.
2187
- */
2188
- get notificationLevel() { return this.channelState.notificationLevel; }
2189
- get limits() { return this.configuration.limits; }
2190
- /**
2191
- * State of the conversation.
2192
- */
2193
- get state() { return this.channelState.state; }
2194
- /**
2195
- * Load and subscribe to this conversation and do not subscribe to its participants and messages.
2196
- * This or _subscribeStreams will need to be called before any events on conversation will fire.
2197
- * @internal
2198
- */
2199
- _subscribe() {
2200
- var _a;
2201
- return this.entityPromise = (_a = this.entityPromise) !== null && _a !== void 0 ? _a : this.services.syncClient.document({ id: this.entityName, mode: 'open_existing' })
2202
- .then(entity => {
2203
- this.entity = entity;
2204
- this.entity.on('updated', args => { this._update(args.data); });
2205
- this.entity.on('removed', () => this.emit('removed', this));
2206
- this._update(this.entity.data);
2207
- return entity;
2208
- })
2209
- .catch(err => {
2210
- this.entity = null;
2211
- this.entityPromise = null;
2212
- if (this.services.syncClient.connectionState != 'disconnected') {
2213
- log$4.error('Failed to get conversation object', err);
2214
- }
2215
- log$4.debug('ERROR: Failed to get conversation object', err);
2216
- throw err;
2217
- });
2218
- }
2219
- /**
2220
- * Load the attributes of this conversation and instantiate its participants and messages.
2221
- * This or _subscribe will need to be called before any events on the conversation will fire.
2222
- * This will need to be called before any events on participants or messages will fire
2223
- * @internal
2224
- */
2225
- async _subscribeStreams() {
2226
- try {
2227
- await this._subscribe();
2228
- log$4.trace('_subscribeStreams, this.entity.data=', this.entity.data);
2229
- const messagesObjectName = this.entity.data.messages;
2230
- const rosterObjectName = this.entity.data.roster;
2231
- await Promise.all([
2232
- this.messagesEntity.subscribe(messagesObjectName),
2233
- this.participantsEntity.subscribe(rosterObjectName)
2234
- ]);
2235
- }
2236
- catch (err) {
2237
- if (this.services.syncClient.connectionState !== 'disconnected') {
2238
- log$4.error('Failed to subscribe on conversation objects', this.sid, err);
2239
- }
2240
- log$4.debug('ERROR: Failed to subscribe on conversation objects', this.sid, err);
2241
- throw err;
2242
- }
2243
- }
2244
- /**
2245
- * Stop listening for and firing events on this conversation.
2246
- * @internal
2247
- */
2248
- async _unsubscribe() {
2249
- if (this.entity) {
2250
- await this.entity.close();
2251
- this.entity = null;
2252
- this.entityPromise = null;
2253
- }
2254
- return Promise.all([
2255
- this.participantsEntity.unsubscribe(),
2256
- this.messagesEntity.unsubscribe()
2257
- ]);
2258
- }
2259
- /**
2260
- * Set conversation status.
2261
- * @internal
2262
- */
2263
- _setStatus(status, source) {
2264
- this.statusSource = source;
2265
- if (this.channelState.status === status) {
2266
- return;
2267
- }
2268
- this.channelState.status = status;
2269
- if (status === 'joined') {
2270
- this._subscribeStreams()
2271
- .catch(err => {
2272
- log$4.debug('ERROR while setting conversation status ' + status, err);
2273
- if (this.services.syncClient.connectionState !== 'disconnected') {
2274
- throw err;
2275
- }
2276
- });
2277
- }
2278
- else if (this.entityPromise) {
2279
- this._unsubscribe().catch(err => {
2280
- log$4.debug('ERROR while setting conversation status ' + status, err);
2281
- if (this.services.syncClient.connectionState !== 'disconnected') {
2282
- throw err;
2283
- }
2284
- });
2285
- }
2286
- }
2287
- /**
2288
- * Get the source of the conversation update.
2289
- * @internal
2290
- */
2291
- _statusSource() {
2292
- return this.statusSource;
2293
- }
2294
- static preprocessUpdate(update, conversationSid) {
2295
- try {
2296
- if (typeof update.attributes === 'string') {
2297
- update.attributes = JSON.parse(update.attributes);
2298
- }
2299
- else if (update.attributes) {
2300
- JSON.stringify(update.attributes);
2301
- }
2302
- }
2303
- catch (e) {
2304
- log$4.warn('Retrieved malformed attributes from the server for conversation: ' + conversationSid);
2305
- update.attributes = {};
2306
- }
2307
- try {
2308
- if (update.dateCreated) {
2309
- update.dateCreated = new Date(update.dateCreated);
2310
- }
2311
- }
2312
- catch (e) {
2313
- log$4.warn('Retrieved malformed dateCreated from the server for conversation: ' + conversationSid);
2314
- delete update.dateCreated;
2315
- }
2316
- try {
2317
- if (update.dateUpdated) {
2318
- update.dateUpdated = new Date(update.dateUpdated);
2319
- }
2320
- }
2321
- catch (e) {
2322
- log$4.warn('Retrieved malformed dateUpdated from the server for conversation: ' + conversationSid);
2323
- delete update.dateUpdated;
2324
- }
2325
- try {
2326
- if (update.lastMessage && update.lastMessage.timestamp) {
2327
- update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);
2328
- }
2329
- }
2330
- catch (e) {
2331
- log$4.warn('Retrieved malformed lastMessage.timestamp from the server for conversation: ' + conversationSid);
2332
- delete update.lastMessage.timestamp;
2333
- }
2334
- }
2335
- /**
2336
- * Update the local conversation object with new values.
2337
- * @internal
2338
- */
2339
- _update(update) {
2340
- var _a, _b, _c, _d, _e;
2341
- log$4.trace('_update', update);
2342
- Conversation.preprocessUpdate(update, this.sid);
2343
- const updateReasons = new Set();
2344
- for (const key of Object.keys(update)) {
2345
- const localKey = fieldMappings[key];
2346
- if (!localKey) {
2347
- continue;
2348
- }
2349
- switch (localKey) {
2350
- case fieldMappings.status:
2351
- if (!update.status || update.status === 'unknown'
2352
- || this.channelState.status === update.status) {
2353
- break;
2354
- }
2355
- this.channelState.status = update.status;
2356
- updateReasons.add(localKey);
2357
- break;
2358
- case fieldMappings.attributes:
2359
- if (isDeepEqual(this.channelState.attributes, update.attributes)) {
2360
- break;
2361
- }
2362
- this.channelState.attributes = update.attributes;
2363
- updateReasons.add(localKey);
2364
- break;
2365
- case fieldMappings.lastConsumedMessageIndex:
2366
- if (update.lastConsumedMessageIndex === undefined
2367
- || update.lastConsumedMessageIndex === this.channelState.lastReadMessageIndex) {
2368
- break;
2369
- }
2370
- this.channelState.lastReadMessageIndex = update.lastConsumedMessageIndex;
2371
- updateReasons.add('lastReadMessageIndex');
2372
- break;
2373
- case fieldMappings.lastMessage:
2374
- if (this.channelState.lastMessage && !update.lastMessage) {
2375
- delete this.channelState.lastMessage;
2376
- updateReasons.add(localKey);
2377
- break;
2378
- }
2379
- this.channelState.lastMessage = this.channelState.lastMessage || {};
2380
- if (((_a = update.lastMessage) === null || _a === void 0 ? void 0 : _a.index) !== undefined
2381
- && update.lastMessage.index !== this.channelState.lastMessage.index) {
2382
- this.channelState.lastMessage.index = update.lastMessage.index;
2383
- updateReasons.add(localKey);
2384
- }
2385
- if (((_b = update.lastMessage) === null || _b === void 0 ? void 0 : _b.timestamp) !== undefined
2386
- && ((_d = (_c = this.channelState.lastMessage) === null || _c === void 0 ? void 0 : _c.dateCreated) === null || _d === void 0 ? void 0 : _d.getTime()) !== update.lastMessage.timestamp.getTime()) {
2387
- this.channelState.lastMessage.dateCreated = update.lastMessage.timestamp;
2388
- updateReasons.add(localKey);
2389
- }
2390
- if (isDeepEqual(this.channelState.lastMessage, {})) {
2391
- delete this.channelState.lastMessage;
2392
- }
2393
- break;
2394
- case fieldMappings.state:
2395
- const state = update.state || undefined;
2396
- if (state !== undefined) {
2397
- state.dateUpdated = new Date(state.dateUpdated);
2398
- }
2399
- if (isDeepEqual(this.channelState.state, state)) {
2400
- break;
2401
- }
2402
- this.channelState.state = state;
2403
- updateReasons.add(localKey);
2404
- break;
2405
- default:
2406
- const isDate = update[key] instanceof Date;
2407
- const keysMatchAsDates = isDate && ((_e = this.channelState[localKey]) === null || _e === void 0 ? void 0 : _e.getTime()) === update[key].getTime();
2408
- const keysMatchAsNonDates = !isDate && this[localKey] === update[key];
2409
- if (keysMatchAsDates || keysMatchAsNonDates) {
2410
- break;
2411
- }
2412
- this.channelState[localKey] = update[key];
2413
- updateReasons.add(localKey);
2414
- }
2415
- }
2416
- if (updateReasons.size > 0) {
2417
- this.emit('updated', { conversation: this, updateReasons: [...updateReasons] });
2418
- }
2419
- }
2420
- /**
2421
- * @internal
2422
- */
2423
- _onMessageAdded(message) {
2424
- for (let participant of this.participants.values()) {
2425
- if (participant.identity === message.author) {
2426
- participant._endTyping();
2427
- break;
2428
- }
2429
- }
2430
- this.emit('messageAdded', message);
2431
- }
2432
- async _setLastReadMessageIndex(index) {
2433
- const result = await this.services.commandExecutor.mutateResource('post', `${this.configuration.links.myConversations}/${this.sid}`, {
2434
- last_read_message_index: index
2435
- });
2436
- return result.unread_messages_count;
2437
- }
2438
- /**
2439
- * Add a participant to the conversation by its identity.
2440
- * @param identity Identity of the Client to add.
2441
- * @param attributes Attributes to be attached to the participant.
2442
- */
2443
- async add(identity, attributes) {
2444
- return this.participantsEntity.add(identity, attributes);
2445
- }
2446
- /**
2447
- * Add a non-chat participant to the conversation.
2448
- * @param proxyAddress Proxy (Twilio) address of the participant.
2449
- * @param address User address of the participant.
2450
- * @param attributes Attributes to be attached to the participant.
2451
- */
2452
- async addNonChatParticipant(proxyAddress, address, attributes = {}) {
2453
- return this.participantsEntity.addNonChatParticipant(proxyAddress, address, attributes !== null && attributes !== void 0 ? attributes : {});
2454
- }
2455
- /**
2456
- * Advance the conversation's last read message index to the current read horizon.
2457
- * Rejects if the user is not a participant of the conversation.
2458
- * Last read message index is updated only if the new index value is higher than the previous.
2459
- * @param index Message index to advance to.
2460
- * @return Resulting unread messages count in the conversation.
2461
- */
2462
- async advanceLastReadMessageIndex(index) {
2463
- await this._subscribeStreams();
2464
- if (index < this.lastReadMessageIndex) {
2465
- return await this._setLastReadMessageIndex(this.lastReadMessageIndex);
2466
- }
2467
- return await this._setLastReadMessageIndex(index);
2468
- }
2469
- /**
2470
- * Delete the conversation and unsubscribe from its events.
2471
- */
2472
- async delete() {
2473
- await this.services.commandExecutor.mutateResource('delete', this.links.self);
2474
- return this;
2475
- }
2476
- /**
2477
- * Get the custom attributes of this Conversation.
2478
- */
2479
- async getAttributes() {
2480
- await this._subscribe();
2481
- return this.attributes;
2482
- }
2483
- /**
2484
- * Returns messages from the conversation using the paginator interface.
2485
- * @param pageSize Number of messages to return in a single chunk. Default is 30.
2486
- * @param anchor Index of the newest message to fetch. Default is from the end.
2487
- * @param direction Query direction. By default it queries backwards
2488
- * from newer to older. The `"forward"` value will query in the opposite direction.
2489
- * @return A page of messages.
2490
- */
2491
- async getMessages(pageSize, anchor, direction) {
2492
- await this._subscribeStreams();
2493
- return this.messagesEntity.getMessages(pageSize, anchor, direction);
2494
- }
2495
- /**
2496
- * Get a list of all the participants who are joined to this conversation.
2497
- */
2498
- async getParticipants() {
2499
- await this._subscribeStreams();
2500
- return this.participantsEntity.getParticipants();
2501
- }
2502
- /**
2503
- * Get conversation participants count.
2504
- *
2505
- * This method is semi-realtime. This means that this data will be eventually correct,
2506
- * but will also be possibly incorrect for a few seconds. The Conversations system does not
2507
- * provide real time events for counter values changes.
2508
- *
2509
- * This is useful for any UI badges, but it is not recommended to build any core application
2510
- * logic based on these counters being accurate in real time.
2511
- */
2512
- async getParticipantsCount() {
2513
- const url = new UriBuilder(this.configuration.links.conversations)
2514
- .path(this.sid)
2515
- .build();
2516
- const response = await this.services.network.get(url);
2517
- return response.body.participants_count;
2518
- }
2519
- /**
2520
- * Get a participant by its SID.
2521
- * @param participantSid Participant SID.
2522
- */
2523
- async getParticipantBySid(participantSid) {
2524
- return this.participantsEntity.getParticipantBySid(participantSid);
2525
- }
2526
- /**
2527
- * Get a participant by its identity.
2528
- * @param identity Participant identity.
2529
- */
2530
- async getParticipantByIdentity(identity) {
2531
- return this.participantsEntity.getParticipantByIdentity(identity);
2532
- }
2533
- /**
2534
- * Get the total message count in the conversation.
2535
- *
2536
- * This method is semi-realtime. This means that this data will be eventually correct,
2537
- * but will also be possibly incorrect for a few seconds. The Conversations system does not
2538
- * provide real time events for counter values changes.
2539
- *
2540
- * This is useful for any UI badges, but it is not recommended to build any core application
2541
- * logic based on these counters being accurate in real time.
2542
- */
2543
- async getMessagesCount() {
2544
- const url = new UriBuilder(this.configuration.links.conversations)
2545
- .path(this.sid)
2546
- .build();
2547
- const response = await this.services.network.get(url);
2548
- return response.body.messages_count;
2549
- }
2550
- /**
2551
- * Get unread messages count for the user if they are a participant of this conversation.
2552
- * Rejects if the user is not a participant of the conversation.
2553
- *
2554
- * Use this method to obtain the number of unread messages together with
2555
- * {@link Conversation.updateLastReadMessageIndex} instead of relying on the
2556
- * message indices which may have gaps. See {@link Message.index} for details.
2557
- *
2558
- * This method is semi-realtime. This means that this data will be eventually correct,
2559
- * but will also be possibly incorrect for a few seconds. The Conversations system does not
2560
- * provide real time events for counter values changes.
2561
- *
2562
- * This is useful for any UI badges, but it is not recommended to build any core application
2563
- * logic based on these counters being accurate in real time.
2564
- */
2565
- async getUnreadMessagesCount() {
2566
- const url = new UriBuilder(this.configuration.links.myConversations)
2567
- .path(this.sid)
2568
- .build();
2569
- const response = await this.services.network.get(url);
2570
- if (response.body.conversation_sid !== this.sid) {
2571
- throw new Error('Conversation was not found in the user conversations list');
2572
- }
2573
- const unreadMessageCount = response.body.unread_messages_count;
2574
- if (typeof unreadMessageCount === 'number') {
2575
- return unreadMessageCount;
2576
- }
2577
- return null;
2578
- }
2579
- /**
2580
- * Join the conversation and subscribe to its events.
2581
- */
2582
- async join() {
2583
- await this.services.commandExecutor.mutateResource('post', this.links.participants, {
2584
- identity: this.configuration.userIdentity
2585
- });
2586
- return this;
2587
- }
2588
- /**
2589
- * Leave the conversation.
2590
- */
2591
- async leave() {
2592
- if (this.channelState.status === 'joined') {
2593
- await this.services.commandExecutor.mutateResource('delete', `${this.links.participants}/${this.configuration.userIdentity}`);
2594
- }
2595
- return this;
2596
- }
2597
- /**
2598
- * Remove a participant from the conversation. When a string is passed as the argument, it will assume that the string is an identity.
2599
- * @param participant Identity or the participant object to remove.
2600
- */
2601
- async removeParticipant(participant) {
2602
- await this.participantsEntity.remove(typeof participant === 'string'
2603
- ? participant
2604
- : participant.sid);
2605
- }
2606
- /**
2607
- * Send a message to the conversation.
2608
- * @param message Message body for the text message,
2609
- * `FormData` or {@link Conversation.MediaOptions) for media content. Sending FormData is supported only with the browser engine.
2610
- * @param messageAttributes Attributes for the message.
2611
- * @param emailOptions Email options for the message.
2612
- * @return Index of the new message.
2613
- */
2614
- async sendMessage(message, messageAttributes, emailOptions) {
2615
- if (typeof message === 'string' || message === null) {
2616
- let response = await this.messagesEntity.send(message, messageAttributes, emailOptions);
2617
- return parseToNumber(response.index);
2618
- }
2619
- let response = await this.messagesEntity.sendMedia(message, messageAttributes, emailOptions);
2620
- return parseToNumber(response.index);
2621
- }
2622
- /**
2623
- * New interface to prepare for sending a message.
2624
- * Use instead of `sendMessage`.
2625
- * @return {MessageBuilder} [description]
2626
- */
2627
- prepareMessage() {
2628
- return new MessageBuilder(this.limits, this.messagesEntity);
2629
- }
2630
- /**
2631
- * Set last read message index of the conversation to the index of the last known message.
2632
- * @return Resulting unread messages count in the conversation.
2633
- */
2634
- async setAllMessagesRead() {
2635
- await this._subscribeStreams();
2636
- let messagesPage = await this.getMessages(1);
2637
- if (messagesPage.items.length > 0) {
2638
- return this.advanceLastReadMessageIndex(messagesPage.items[0].index);
2639
- }
2640
- return Promise.resolve(0);
2641
- }
2642
- /**
2643
- * Set all messages in the conversation unread.
2644
- * @return Resulting unread messages count in the conversation.
2645
- */
2646
- async setAllMessagesUnread() {
2647
- await this._subscribeStreams();
2648
- return await this._setLastReadMessageIndex(null);
2649
- }
2650
- /**
2651
- * Set user notification level for this conversation.
2652
- * @param notificationLevel New user notification level.
2653
- */
2654
- async setUserNotificationLevel(notificationLevel) {
2655
- await this.services.commandExecutor.mutateResource('post', `${this.configuration.links.myConversations}/${this.sid}`, {
2656
- notification_level: notificationLevel
2657
- });
2658
- }
2659
- /**
2660
- * Send a notification to the server indicating that this client is currently typing in this conversation.
2661
- * Typing ended notification is sent after a while automatically, but by calling this method again you ensure that typing ended is not received.
2662
- */
2663
- typing() {
2664
- return this.services.typingIndicator.send(this.sid);
2665
- }
2666
- /**
2667
- * Update the attributes of the conversation.
2668
- * @param attributes New attributes.
2669
- */
2670
- async updateAttributes(attributes) {
2671
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
2672
- attributes: attributes !== undefined ? JSON.stringify(attributes) : undefined
2673
- });
2674
- return this;
2675
- }
2676
- /**
2677
- * Update the friendly name of the conversation.
2678
- * @param friendlyName New friendly name.
2679
- */
2680
- async updateFriendlyName(friendlyName) {
2681
- if (this.channelState.friendlyName !== friendlyName) {
2682
- await this.services.commandExecutor.mutateResource('post', this.links.self, { friendly_name: friendlyName });
2683
- }
2684
- return this;
2685
- }
2686
- /**
2687
- * Set the last read message index to the current read horizon.
2688
- * @param index Message index to set as last read.
2689
- * If null is provided, then the behavior is identical to {@link Conversation.setAllMessagesUnread}.
2690
- * @returns Resulting unread messages count in the conversation.
2691
- */
2692
- async updateLastReadMessageIndex(index) {
2693
- await this._subscribeStreams();
2694
- return this._setLastReadMessageIndex(index);
2695
- }
2696
- /**
2697
- * Update the unique name of the conversation.
2698
- * @param uniqueName New unique name for the conversation. Setting unique name to null removes it.
2699
- */
2700
- async updateUniqueName(uniqueName) {
2701
- if (this.channelState.uniqueName !== uniqueName) {
2702
- if (!uniqueName) {
2703
- uniqueName = '';
2704
- }
2705
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
2706
- unique_name: uniqueName
2707
- });
2708
- }
2709
- return this;
2710
- }
2711
- }
2712
- /**
2713
- * Fired when a participant has joined the conversation.
2714
- *
2715
- * Parameters:
2716
- * 1. {@link Participant} `participant` - participant that joined the conversation
2717
- * @event
2718
- */
2719
- Conversation.participantJoined = 'participantJoined';
2720
- /**
2721
- * Fired when a participant has left the conversation.
2722
- *
2723
- * Parameters:
2724
- * 1. {@link Participant} `participant` - participant that left the conversation
2725
- * @event
2726
- */
2727
- Conversation.participantLeft = 'participantLeft';
2728
- /**
2729
- * Fired when data of a participant has been updated.
2730
- *
2731
- * Parameters:
2732
- * 1. object `data` - info object provided with the event. It has the following properties:
2733
- * * {@link Participant} `participant` - participant that has received the update
2734
- * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for update
2735
- * @event
2736
- */
2737
- Conversation.participantUpdated = 'participantUpdated';
2738
- /**
2739
- * Fired when a new message has been added to the conversation.
2740
- *
2741
- * Parameters:
2742
- * 1. {@link Message} `message` - message that has been added
2743
- * @event
2744
- */
2745
- Conversation.messageAdded = 'messageAdded';
2746
- /**
2747
- * Fired when message is removed from the conversation's message list.
2748
- *
2749
- * Parameters:
2750
- * 1. {@link Message} `message` - message that has been removed
2751
- * @event
2752
- */
2753
- Conversation.messageRemoved = 'messageRemoved';
2754
- /**
2755
- * Fired when data of a message has been updated.
2756
- *
2757
- * Parameters:
2758
- * 1. object `data` - info object provided with the event. It has the following properties:
2759
- * * {@link Message} `message` - message that has received the update
2760
- * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for update
2761
- * @event
2762
- */
2763
- Conversation.messageUpdated = 'messageUpdated';
2764
- /**
2765
- * Fired when a participant has stopped typing.
2766
- *
2767
- * Parameters:
2768
- * 1. {@link Participant} `participant` - the participant that has stopped typing
2769
- * @event
2770
- */
2771
- Conversation.typingEnded = 'typingEnded';
2772
- /**
2773
- * Fired when a participant has started typing.
2774
- *
2775
- * Parameters:
2776
- * 1. {@link Participant} `participant` - the participant that has started typing
2777
- * @event
2778
- */
2779
- Conversation.typingStarted = 'typingStarted';
2780
- /**
2781
- * Fired when the data of the conversation has been updated.
2782
- *
2783
- * Parameters:
2784
- * 1. object `data` - info object provided with the event. It has the following properties:
2785
- * * {@link Conversation} `conversation` - conversation that has received the update
2786
- * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for update
2787
- * @event
2788
- */
2789
- Conversation.updated = 'updated';
2790
- /**
2791
- * Fired when the conversation was destroyed or the currently-logged-in user has left private conversation.
2792
- *
2793
- * Parameters:
2794
- * 1. {@link Conversation} `conversation` - conversation that has been removed
2795
- * @event
2796
- */
2797
- Conversation.removed = 'removed';
2798
- __decorate([
2799
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString, ['undefined', 'string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
2800
- __metadata("design:type", Function),
2801
- __metadata("design:paramtypes", [String, Object]),
2802
- __metadata("design:returntype", Promise)
2803
- ], Conversation.prototype, "add", null);
2804
- __decorate([
2805
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString, declarativeTypeValidator.nonEmptyString, [declarativeTypeValidator.pureObject, 'undefined']),
2806
- __metadata("design:type", Function),
2807
- __metadata("design:paramtypes", [String, String, Object]),
2808
- __metadata("design:returntype", Promise)
2809
- ], Conversation.prototype, "addNonChatParticipant", null);
2810
- __decorate([
2811
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonNegativeInteger),
2812
- __metadata("design:type", Function),
2813
- __metadata("design:paramtypes", [Number]),
2814
- __metadata("design:returntype", Promise)
2815
- ], Conversation.prototype, "advanceLastReadMessageIndex", null);
2816
- __decorate([
2817
- declarativeTypeValidator.validateTypesAsync(['undefined', declarativeTypeValidator.nonNegativeInteger], ['undefined', declarativeTypeValidator.nonNegativeInteger], ['undefined', declarativeTypeValidator.literal('backwards', 'forward')]),
2818
- __metadata("design:type", Function),
2819
- __metadata("design:paramtypes", [Number, Number, String]),
2820
- __metadata("design:returntype", Promise)
2821
- ], Conversation.prototype, "getMessages", null);
2822
- __decorate([
2823
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
2824
- __metadata("design:type", Function),
2825
- __metadata("design:paramtypes", [String]),
2826
- __metadata("design:returntype", Promise)
2827
- ], Conversation.prototype, "getParticipantBySid", null);
2828
- __decorate([
2829
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
2830
- __metadata("design:type", Function),
2831
- __metadata("design:paramtypes", [String]),
2832
- __metadata("design:returntype", Promise)
2833
- ], Conversation.prototype, "getParticipantByIdentity", null);
2834
- __decorate([
2835
- declarativeTypeValidator.validateTypesAsync([declarativeTypeValidator.nonEmptyString, Participant]),
2836
- __metadata("design:type", Function),
2837
- __metadata("design:paramtypes", [Object]),
2838
- __metadata("design:returntype", Promise)
2839
- ], Conversation.prototype, "removeParticipant", null);
2840
- __decorate([
2841
- declarativeTypeValidator.validateTypesAsync([
2842
- 'string',
2843
- declarativeTypeValidator.literal(null),
2844
- // Wrapping it into a custom rule is necessary because the FormData class is not available on initialization.
2845
- declarativeTypeValidator.custom((value) => [value instanceof FormData, 'an instance of FormData']),
2846
- declarativeTypeValidator.objectSchema('media options', {
2847
- contentType: declarativeTypeValidator.nonEmptyString,
2848
- media: declarativeTypeValidator.custom((value) => {
2849
- let isValid = (typeof value === 'string' && value.length > 0) || value instanceof Uint8Array || value instanceof ArrayBuffer;
2850
- if (typeof Blob === 'function') {
2851
- isValid = isValid || value instanceof Blob;
2852
- }
2853
- return [
2854
- isValid,
2855
- 'a non-empty string, an instance of Buffer or an instance of Blob'
2856
- ];
2857
- })
2858
- })
2859
- ], ['undefined', 'string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)], ['undefined', declarativeTypeValidator.literal(null), declarativeTypeValidator.objectSchema('email attributes', {
2860
- subject: [declarativeTypeValidator.nonEmptyString, 'undefined']
2861
- })]),
2862
- __metadata("design:type", Function),
2863
- __metadata("design:paramtypes", [Object, Object, Object]),
2864
- __metadata("design:returntype", Promise)
2865
- ], Conversation.prototype, "sendMessage", null);
2866
- __decorate([
2867
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('default', 'muted')),
2868
- __metadata("design:type", Function),
2869
- __metadata("design:paramtypes", [String]),
2870
- __metadata("design:returntype", Promise)
2871
- ], Conversation.prototype, "setUserNotificationLevel", null);
2872
- __decorate([
2873
- declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
2874
- __metadata("design:type", Function),
2875
- __metadata("design:paramtypes", [Object]),
2876
- __metadata("design:returntype", Promise)
2877
- ], Conversation.prototype, "updateAttributes", null);
2878
- __decorate([
2879
- declarativeTypeValidator.validateTypesAsync(['string', declarativeTypeValidator.literal(null)]),
2880
- __metadata("design:type", Function),
2881
- __metadata("design:paramtypes", [String]),
2882
- __metadata("design:returntype", Promise)
2883
- ], Conversation.prototype, "updateFriendlyName", null);
2884
- __decorate([
2885
- declarativeTypeValidator.validateTypesAsync([declarativeTypeValidator.literal(null), declarativeTypeValidator.nonNegativeInteger]),
2886
- __metadata("design:type", Function),
2887
- __metadata("design:paramtypes", [Number]),
2888
- __metadata("design:returntype", Promise)
2889
- ], Conversation.prototype, "updateLastReadMessageIndex", null);
2890
- __decorate([
2891
- declarativeTypeValidator.validateTypesAsync(['string', declarativeTypeValidator.literal(null)]),
2892
- __metadata("design:type", Function),
2893
- __metadata("design:paramtypes", [String]),
2894
- __metadata("design:returntype", Promise)
2895
- ], Conversation.prototype, "updateUniqueName", null);
2896
-
2897
- class Deferred {
2898
- constructor() {
2899
- this._promise = new Promise((resolve, reject) => {
2900
- this._resolve = resolve;
2901
- this._reject = reject;
2902
- });
2903
- }
2904
- get promise() { return this._promise; }
2905
- update(value) {
2906
- this._resolve(value);
2907
- }
2908
- set(value) {
2909
- this.current = value;
2910
- this._resolve(value);
2911
- }
2912
- fail(e) {
2913
- this._reject(e);
2914
- }
2915
- }
2916
-
2917
- const log$3 = Logger.scope('Conversations');
2918
- /**
2919
- * Represents conversations collection
2920
- * {@see Conversation}
2921
- */
2922
- class Conversations extends EventEmitter {
2923
- constructor(configuration, services) {
2924
- super();
2925
- this.conversations = new Map();
2926
- this.myConversationsRead = new Deferred();
2927
- this.tombstones = new Set();
2928
- this.myConversationsFetched = false;
2929
- this.configuration = configuration;
2930
- this.services = services;
2931
- }
2932
- async addConversation(options) {
2933
- var _a, _b, _c;
2934
- const attributes = typeof (options === null || options === void 0 ? void 0 : options.attributes) !== 'undefined'
2935
- ? options.attributes
2936
- : {};
2937
- const response = await this.services.commandExecutor.mutateResource('post', this.configuration.links.conversations, {
2938
- friendly_name: options.friendlyName,
2939
- unique_name: options.uniqueName,
2940
- attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined
2941
- });
2942
- const conversationSid = (_a = response.sid) !== null && _a !== void 0 ? _a : null;
2943
- const conversationDocument = (_c = (_b = response.sync_objects) === null || _b === void 0 ? void 0 : _b.conversation) !== null && _c !== void 0 ? _c : null;
2944
- const links = Object.assign({ self: response.url }, response.links);
2945
- const existingConversation = this.conversations.get(conversationSid);
2946
- if (existingConversation) {
2947
- await existingConversation._subscribe();
2948
- return existingConversation;
2949
- }
2950
- const conversation = new Conversation({
2951
- channel: conversationDocument,
2952
- entityName: null,
2953
- uniqueName: null,
2954
- attributes: null,
2955
- createdBy: null,
2956
- friendlyName: null,
2957
- lastConsumedMessageIndex: null,
2958
- dateCreated: null,
2959
- dateUpdated: null
2960
- }, conversationSid, links, this.configuration, this.services);
2961
- this.conversations.set(conversation.sid, conversation);
2962
- this._registerForEvents(conversation);
2963
- await conversation._subscribe();
2964
- this.emit('conversationAdded', conversation);
2965
- return conversation;
2966
- }
2967
- /**
2968
- * Fetch conversations list and instantiate all necessary objects
2969
- */
2970
- async fetchConversations() {
2971
- try {
2972
- const map = await this._getMap();
2973
- map.on('itemAdded', args => {
2974
- log$3.debug(`itemAdded: ${args.item.key}`);
2975
- this._upsertConversation('sync', args.item.key, args.item.data);
2976
- });
2977
- map.on('itemRemoved', args => {
2978
- log$3.debug(`itemRemoved: ${args.key}`);
2979
- const sid = args.key;
2980
- if (!this.myConversationsFetched) {
2981
- this.tombstones.add(sid);
2982
- }
2983
- const conversation = this.conversations.get(sid);
2984
- if (!conversation) {
2985
- return;
2986
- }
2987
- if (conversation.status === 'joined') {
2988
- conversation._setStatus('notParticipating', 'sync');
2989
- this.emit('conversationLeft', conversation);
2990
- }
2991
- this.conversations.delete(sid);
2992
- this.emit('conversationRemoved', conversation);
2993
- conversation.emit('removed', conversation);
2994
- });
2995
- map.on('itemUpdated', args => {
2996
- log$3.debug(`itemUpdated: ${args.item.key}`);
2997
- this._upsertConversation('sync', args.item.key, args.item.data);
2998
- });
2999
- const myConversations = await this._fetchMyConversations();
3000
- const upserts = [];
3001
- for (const conversation of myConversations) {
3002
- upserts.push(this._upsertConversation('rest', conversation.channel_sid, conversation));
3003
- }
3004
- this.myConversationsRead.set(true);
3005
- await Promise.all(upserts);
3006
- this.myConversationsFetched = true;
3007
- this.tombstones.clear();
3008
- log$3.debug('The conversations list has been successfully fetched');
3009
- return this;
3010
- }
3011
- catch (error) {
3012
- const errorMessage = 'Failed to fetch the conversations list';
3013
- if (this.services.syncClient.connectionState !== 'disconnected') {
3014
- log$3.error(errorMessage, error);
3015
- }
3016
- log$3.debug(`ERROR: ${errorMessage}`, error);
3017
- throw error;
3018
- }
3019
- }
3020
- async getConversations(args) {
3021
- const conversationsMap = await this._getMap();
3022
- const page = await conversationsMap.getItems();
3023
- return this._wrapPaginator(page, items => Promise.all(items.map((item) => this._upsertConversation('sync', item.key, item.data))));
3024
- }
3025
- async getConversation(sid) {
3026
- const conversationsMap = await this._getMap();
3027
- const page = await conversationsMap.getItems({ from: sid });
3028
- const items = page.items.map((item) => this._upsertConversation('sync', item.key, item.data));
3029
- return items.length > 0 ? items[0] : null;
3030
- }
3031
- async getConversationByUniqueName(uniqueName) {
3032
- const url = new UriBuilder(this.configuration.links.myConversations)
3033
- .path(uniqueName)
3034
- .build();
3035
- const response = await this.services.network.get(url);
3036
- const body = response.body;
3037
- const sid = body.conversation_sid;
3038
- const data = {
3039
- entityName: null,
3040
- lastConsumedMessageIndex: body.last_read_message_index,
3041
- status: (body === null || body === void 0 ? void 0 : body.status) || 'unknown',
3042
- friendlyName: body.friendly_name,
3043
- dateUpdated: body.date_updated,
3044
- dateCreated: body.date_created,
3045
- uniqueName: body.unique_name,
3046
- createdBy: body.created_by,
3047
- attributes: body.attributes,
3048
- channel: body.sync_objects.conversation,
3049
- notificationLevel: body === null || body === void 0 ? void 0 : body.notification_level,
3050
- sid
3051
- };
3052
- return this._upsertConversation('sync', sid, data);
3053
- }
3054
- async peekConversation(sid) {
3055
- const url = new UriBuilder(this.configuration.links.conversations)
3056
- .path(sid)
3057
- .build();
3058
- const response = await this.services.network.get(url);
3059
- const body = response.body;
3060
- if (body.type !== 'private') {
3061
- return null;
3062
- }
3063
- const data = {
3064
- entityName: null,
3065
- // lastConsumedMessageIndex: body.last_read_message_index,
3066
- status: (body === null || body === void 0 ? void 0 : body.status) || 'unknown',
3067
- friendlyName: body.friendly_name,
3068
- dateUpdated: body.date_updated,
3069
- dateCreated: body.date_created,
3070
- uniqueName: body.unique_name,
3071
- createdBy: body.created_by,
3072
- attributes: body.attributes,
3073
- channel: `${sid}.channel`,
3074
- // notificationLevel: body?.notification_level,
3075
- sid
3076
- };
3077
- return this._upsertConversation('sync', sid, data);
3078
- }
3079
- async _getMap() {
3080
- return await this.services.syncClient.map({
3081
- id: this.configuration.myConversations,
3082
- mode: 'open_existing'
3083
- });
3084
- }
3085
- async _wrapPaginator(page, op) {
3086
- const items = await op(page.items);
3087
- return {
3088
- items,
3089
- hasNextPage: page.hasNextPage,
3090
- hasPrevPage: page.hasPrevPage,
3091
- nextPage: () => page.nextPage().then(x => this._wrapPaginator(x, op)),
3092
- prevPage: () => page.prevPage().then(x => this._wrapPaginator(x, op))
3093
- };
3094
- }
3095
- async _updateConversation(source, conversation, data) {
3096
- const areSourcesDifferent = conversation._statusSource() !== undefined && source !== conversation._statusSource();
3097
- const isChannelSourceSync = source !== 'rest' || conversation._statusSource() === 'sync';
3098
- if (areSourcesDifferent && isChannelSourceSync && source !== 'sync') {
3099
- log$3.trace('upsertConversation: conversation is known from sync and came from chat, ignoring', {
3100
- sid: conversation.sid,
3101
- data: data.status,
3102
- conversation: conversation.status
3103
- });
3104
- return;
3105
- }
3106
- if (data.status === 'joined' && conversation.status !== 'joined') {
3107
- conversation._setStatus('joined', source);
3108
- let updateData = {};
3109
- if (typeof data.notificationLevel !== 'undefined') {
3110
- updateData.notificationLevel = data.notificationLevel;
3111
- }
3112
- if (typeof data.lastConsumedMessageIndex !== 'undefined') {
3113
- updateData.lastConsumedMessageIndex = data.lastConsumedMessageIndex;
3114
- }
3115
- if (!isDeepEqual(updateData, {})) {
3116
- conversation._update(updateData);
3117
- }
3118
- conversation._subscribe().then(() => {
3119
- this.emit('conversationJoined', conversation);
3120
- });
3121
- return;
3122
- }
3123
- if (data.status === 'notParticipating' && conversation.status === 'joined') {
3124
- conversation._setStatus('notParticipating', source);
3125
- conversation._update(data);
3126
- await conversation._subscribe();
3127
- this.emit('conversationLeft', conversation);
3128
- return;
3129
- }
3130
- if (data.status === 'notParticipating') {
3131
- await conversation._subscribe();
3132
- return;
3133
- }
3134
- conversation._update(data);
3135
- }
3136
- async _upsertConversation(source, sid, data) {
3137
- log$3.trace(`upsertConversation called for ${sid}`, data);
3138
- const conversation = this.conversations.get(sid);
3139
- // If the channel is known, update it
3140
- if (conversation) {
3141
- log$3.trace(`upsertConversation: the conversation ${conversation.sid} is known;` +
3142
- `its status is known from the source ${conversation._statusSource()} ` +
3143
- `and the update came from the source ${source}`, conversation);
3144
- await this._updateConversation(source, conversation, data);
3145
- await conversation._subscribe();
3146
- return conversation;
3147
- }
3148
- // If the conversations is deleted, ignore it
3149
- if (['chat', 'rest'].includes(source) && this.tombstones.has(sid)) {
3150
- log$3.trace('upsertChannel: the channel is deleted but reappeared again from chat, ignoring', sid);
3151
- return;
3152
- }
3153
- // If the conversation is unknown, fetch it
3154
- log$3.trace('upsertConversation: creating a local conversation object with sid ' + sid, data);
3155
- const baseLink = `${this.configuration.links.conversations}/${sid}`;
3156
- const links = {
3157
- self: baseLink,
3158
- messages: `${baseLink}/Messages`,
3159
- participants: `${baseLink}/Participants`
3160
- };
3161
- const newConversation = new Conversation(data, sid, links, this.configuration, this.services);
3162
- this.conversations.set(sid, newConversation);
3163
- await newConversation._subscribe();
3164
- this._registerForEvents(newConversation);
3165
- this.emit('conversationAdded', newConversation);
3166
- if (data.status === 'joined') {
3167
- newConversation._setStatus('joined', source);
3168
- this.emit('conversationJoined', newConversation);
3169
- }
3170
- return newConversation;
3171
- }
3172
- async _fetchMyConversations() {
3173
- let conversations = [];
3174
- let pageToken = null;
3175
- do {
3176
- const url = new UriBuilder(this.configuration.links.myConversations);
3177
- if (pageToken) {
3178
- url.arg('PageToken', pageToken);
3179
- }
3180
- const response = await this.services.network.get(url.build());
3181
- const receivedConversations = response.body.conversations.map((conversationDescriptor) => ({
3182
- descriptor: conversationDescriptor,
3183
- channel_sid: conversationDescriptor.conversation_sid,
3184
- status: conversationDescriptor.status,
3185
- channel: conversationDescriptor.sync_objects.conversation,
3186
- messages: conversationDescriptor.sync_objects.messages,
3187
- roster: `${conversationDescriptor.conversation_sid}.roster`,
3188
- lastConsumedMessageIndex: conversationDescriptor.last_consumed_message_index,
3189
- notificationLevel: conversationDescriptor.notification_level
3190
- }));
3191
- pageToken = response.body.meta.next_token;
3192
- conversations = [...conversations, ...receivedConversations];
3193
- } while (pageToken);
3194
- return conversations;
3195
- }
3196
- _onConversationRemoved(sid) {
3197
- const conversation = this.conversations.get(sid);
3198
- if (conversation) {
3199
- this.conversations.delete(sid);
3200
- this.emit('conversationRemoved', conversation);
3201
- }
3202
- }
3203
- _registerForEvents(conversation) {
3204
- conversation.on('removed', () => this._onConversationRemoved(conversation.sid));
3205
- conversation.on('updated', (args) => this.emit('conversationUpdated', args));
3206
- conversation.on('participantJoined', this.emit.bind(this, 'participantJoined'));
3207
- conversation.on('participantLeft', this.emit.bind(this, 'participantLeft'));
3208
- conversation.on('participantUpdated', (args) => this.emit('participantUpdated', args));
3209
- conversation.on('messageAdded', this.emit.bind(this, 'messageAdded'));
3210
- conversation.on('messageUpdated', (args) => this.emit('messageUpdated', args));
3211
- conversation.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
3212
- conversation.on('typingStarted', this.emit.bind(this, 'typingStarted'));
3213
- conversation.on('typingEnded', this.emit.bind(this, 'typingEnded'));
3214
- }
3215
- }
3216
-
3217
- const log$2 = Logger.scope('User');
3218
- /**
3219
- * Extended user information.
3220
- * Note that `isOnline` and `isNotifiable` properties are eligible
3221
- * for use only if the reachability function is enabled.
3222
- * You may check if it is enabled by reading the value of {@link Client.reachabilityEnabled}.
3223
- */
3224
- class User extends EventEmitter {
3225
- /**
3226
- * @internal
3227
- */
3228
- constructor(identity, entityName, links, configuration, services) {
3229
- super();
3230
- /**
3231
- * Fired when the properties or the reachability status of the message has been updated.
3232
- *
3233
- * Parameters:
3234
- * 1. object `data` - info object provided with the event. It has the following properties:
3235
- * * {@link User} user - the user in question
3236
- * * {@link UserUpdateReason}[] updateReasons - array of reasons for the update
3237
- * @event
3238
- */
3239
- this.updated = 'updated';
3240
- /**
3241
- * Fired when the client has subscribed to the user.
3242
- *
3243
- * Parameters:
3244
- * 1. {@link User} `user` - the user in question
3245
- * @event
3246
- */
3247
- this.userSubscribed = 'userSubscribed';
3248
- /**
3249
- * Fired when the client has unsubscribed from the user.
3250
- *
3251
- * Parameters:
3252
- * 1. {@link User} `user` - the user in question
3253
- * @event
3254
- */
3255
- this.userUnsubscribed = 'userUnsubscribed';
3256
- this.links = links;
3257
- this.configuration = configuration;
3258
- this.services = services;
3259
- this.subscribed = 'initializing';
3260
- this.setMaxListeners(0);
3261
- this.state = {
3262
- identity,
3263
- entityName,
3264
- friendlyName: null,
3265
- attributes: {},
3266
- online: null,
3267
- notifiable: null
3268
- };
3269
- }
3270
- /**
3271
- * User identity.
3272
- */
3273
- get identity() { return this.state.identity; }
3274
- set identity(identity) { this.state.identity = identity; }
3275
- set entityName(name) { this.state.entityName = name; }
3276
- /**
3277
- * Custom attributes of the user.
3278
- */
3279
- get attributes() { return this.state.attributes; }
3280
- /**
3281
- * Friendly name of the user, null if not set.
3282
- */
3283
- get friendlyName() { return this.state.friendlyName; }
3284
- /**
3285
- * Status of the real-time conversation connection of the user.
3286
- */
3287
- get isOnline() { return this.state.online; }
3288
- /**
3289
- * User push notification registration status.
3290
- */
3291
- get isNotifiable() { return this.state.notifiable; }
3292
- /**
3293
- * True if this user is receiving real-time status updates.
3294
- */
3295
- get isSubscribed() { return this.subscribed == 'subscribed'; }
3296
- // Handles service updates
3297
- _update(key, value) {
3298
- let updateReasons = [];
3299
- log$2.debug('User for', this.state.identity, 'updated:', key, value);
3300
- switch (key) {
3301
- case 'friendlyName':
3302
- if (this.state.friendlyName !== value.value) {
3303
- updateReasons.push('friendlyName');
3304
- this.state.friendlyName = value.value;
3305
- }
3306
- break;
3307
- case 'attributes':
3308
- const updateAttributes = parseAttributes(value.value, `Retrieved malformed attributes from the server for user: ${this.state.identity}`, log$2);
3309
- if (!isDeepEqual(this.state.attributes, updateAttributes)) {
3310
- this.state.attributes = updateAttributes;
3311
- updateReasons.push('attributes');
3312
- }
3313
- break;
3314
- case 'reachability':
3315
- if (this.state.online !== value.online) {
3316
- this.state.online = value.online;
3317
- updateReasons.push('reachabilityOnline');
3318
- }
3319
- if (this.state.notifiable !== value.notifiable) {
3320
- this.state.notifiable = value.notifiable;
3321
- updateReasons.push('reachabilityNotifiable');
3322
- }
3323
- break;
3324
- default:
3325
- return;
3326
- }
3327
- if (updateReasons.length > 0) {
3328
- this.emit('updated', { user: this, updateReasons: updateReasons });
3329
- }
3330
- }
3331
- // Fetch reachability info
3332
- async _updateReachabilityInfo(map, update) {
3333
- if (!this.configuration.reachabilityEnabled) {
3334
- return Promise.resolve();
3335
- }
3336
- return map.get('reachability')
3337
- .then(update)
3338
- .catch(err => { log$2.warn('Failed to get reachability info for ', this.state.identity, err); });
3339
- }
3340
- // Fetch user
3341
- async _fetch() {
3342
- if (!this.state.entityName) {
3343
- return this;
3344
- }
3345
- this.promiseToFetch = this.services.syncClient.map({ id: this.state.entityName, mode: 'open_existing', includeItems: true })
3346
- .then(map => {
3347
- this.entity = map;
3348
- map.on('itemUpdated', args => {
3349
- log$2.debug(this.state.entityName + ' (' + this.state.identity + ') itemUpdated: ' + args.item.key);
3350
- return this._update(args.item.key, args.item.data);
3351
- });
3352
- return Promise.all([
3353
- map.get('friendlyName')
3354
- .then(item => this._update(item.key, item.data)),
3355
- map.get('attributes')
3356
- .then(item => this._update(item.key, item.data)),
3357
- this._updateReachabilityInfo(map, item => this._update(item.key, item.data))
3358
- ]);
3359
- })
3360
- .then(() => {
3361
- log$2.debug('Fetched for', this.identity);
3362
- this.subscribed = 'subscribed';
3363
- this.emit('userSubscribed', this);
3364
- return this;
3365
- })
3366
- .catch(err => {
3367
- this.promiseToFetch = null;
3368
- throw err;
3369
- });
3370
- return this.promiseToFetch;
3371
- }
3372
- _ensureFetched() {
3373
- return this.promiseToFetch || this._fetch();
3374
- }
3375
- /**
3376
- * Edit user attributes.
3377
- * @param attributes New attributes.
3378
- */
3379
- async updateAttributes(attributes) {
3380
- if (this.subscribed == 'unsubscribed') {
3381
- throw new Error('Can\'t modify unsubscribed object');
3382
- }
3383
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
3384
- attributes: JSON.stringify(attributes)
3385
- });
3386
- return this;
3387
- }
3388
- /**
3389
- * Update the friendly name of the user.
3390
- * @param friendlyName New friendly name.
3391
- */
3392
- async updateFriendlyName(friendlyName) {
3393
- if (this.subscribed == 'unsubscribed') {
3394
- throw new Error('Can\'t modify unsubscribed object');
3395
- }
3396
- await this.services.commandExecutor.mutateResource('post', this.links.self, {
3397
- friendly_name: friendlyName
3398
- });
3399
- return this;
3400
- }
3401
- /**
3402
- * Remove the user from the subscription list.
3403
- * @return A promise of completion.
3404
- */
3405
- async unsubscribe() {
3406
- if (this.promiseToFetch) {
3407
- await this.promiseToFetch;
3408
- this.entity.close();
3409
- this.promiseToFetch = null;
3410
- this.subscribed = 'unsubscribed';
3411
- this.emit('userUnsubscribed', this);
3412
- }
3413
- }
3414
- }
3415
- __decorate([
3416
- declarativeTypeValidator.validateTypesAsync(['string', 'number', 'boolean', 'object', declarativeTypeValidator.literal(null)]),
3417
- __metadata("design:type", Function),
3418
- __metadata("design:paramtypes", [Object]),
3419
- __metadata("design:returntype", Promise)
3420
- ], User.prototype, "updateAttributes", null);
3421
- __decorate([
3422
- declarativeTypeValidator.validateTypesAsync(['string']),
3423
- __metadata("design:type", Function),
3424
- __metadata("design:paramtypes", [String]),
3425
- __metadata("design:returntype", Promise)
3426
- ], User.prototype, "updateFriendlyName", null);
3427
-
3428
- /**
3429
- * @classdesc Container for known users
3430
- * @fires Users#userUpdated
3431
- */
3432
- class Users extends EventEmitter {
3433
- constructor(configuration, services) {
3434
- super();
3435
- const links = {
3436
- self: `${configuration.links.users}/${configuration.userIdentity}`
3437
- };
3438
- this.configuration = configuration;
3439
- this.services = services;
3440
- this.fifoStack = [];
3441
- this.myself = new User(this.configuration.userIdentity, this.configuration.userInfo, links, this.configuration, this.services);
3442
- this.myself.on('updated', (args) => this.emit('userUpdated', args));
3443
- this.myself.on('userSubscribed', () => this.emit('userSubscribed', this.myself));
3444
- this.myself.on('userUnsubscribed', () => {
3445
- this.emit('userUnsubscribed', this.myself);
3446
- this.myself._ensureFetched();
3447
- });
3448
- this.subscribedUsers = new Map();
3449
- }
3450
- handleUnsubscribeUser(user) {
3451
- if (this.subscribedUsers.has(user.identity)) {
3452
- this.subscribedUsers.delete(user.identity);
3453
- }
3454
- let foundItemIndex = -1;
3455
- let foundItem = this.fifoStack.find((item, index) => {
3456
- if (item == user.identity) {
3457
- foundItemIndex = index;
3458
- return true;
3459
- }
3460
- return false;
3461
- });
3462
- if (foundItem) {
3463
- this.fifoStack.splice(foundItemIndex, 1);
3464
- }
3465
- this.emit('userUnsubscribed', user);
3466
- }
3467
- handleSubscribeUser(user) {
3468
- if (this.subscribedUsers.has(user.identity)) {
3469
- return;
3470
- }
3471
- if (this.fifoStack.length >= this.configuration.userInfosToSubscribe) {
3472
- this.subscribedUsers.get(this.fifoStack.shift()).unsubscribe();
3473
- }
3474
- this.fifoStack.push(user.identity);
3475
- this.subscribedUsers.set(user.identity, user);
3476
- this.emit('userSubscribed', user);
3477
- }
3478
- /**
3479
- * Gets user, if it's in subscribed list - then return the user object from it,
3480
- * if not - then subscribes and adds user to the FIFO stack
3481
- * @returns {Promise<User>} Fully initialized user
3482
- */
3483
- async getUser(identity, entityName = null) {
3484
- await this.myself._ensureFetched();
3485
- if (identity == this.myself.identity) {
3486
- return this.myself;
3487
- }
3488
- let user = this.subscribedUsers.get(identity);
3489
- if (!user) {
3490
- if (!entityName) {
3491
- entityName = await this.getSyncUniqueName(identity);
3492
- }
3493
- const links = {
3494
- self: `${this.configuration.links.users}/${identity}`
3495
- };
3496
- user = new User(identity, entityName, links, this.configuration, this.services);
3497
- user.on('updated', (args) => this.emit('userUpdated', args));
3498
- user.on('userSubscribed', () => this.handleSubscribeUser(user));
3499
- user.on('userUnsubscribed', () => this.handleUnsubscribeUser(user));
3500
- await user._ensureFetched();
3501
- }
3502
- return user;
3503
- }
3504
- /**
3505
- * @returns {Promise<Array<User>>} returns list of subscribed User objects {@see User}
3506
- */
3507
- async getSubscribedUsers() {
3508
- await this.myself._ensureFetched();
3509
- const users = [this.myself];
3510
- this.subscribedUsers.forEach((user) => users.push(user));
3511
- return users;
3512
- }
3513
- /**
3514
- * @returns {Promise<string>} User's sync unique name
3515
- */
3516
- async getSyncUniqueName(identity) {
3517
- const url = new UriBuilder(this.configuration.links.users)
3518
- .path(identity)
3519
- .build();
3520
- const response = await this.services.network.get(url);
3521
- return response.body.sync_objects.user_info_map;
3522
- }
3523
- }
3524
-
3525
- const log$1 = Logger.scope('TypingIndicator');
3526
- /**
3527
- * An important note in regards to typing timeout timers. There are two places that the SDK can get the "typing_timeout" attribute from. The first
3528
- * place that the attribute appears in is the response received from POST -> /v1/typing REST call. In the body of that response, the value of the
3529
- * "typing_timeout" attribute will be exactly the same as defined in the console. The second place that the attribute appears in is from a
3530
- * notification of type "twilio.ipmsg.typing_indicator". In this case, the "typing_timeout" value will be +1 of that in the console. This
3531
- * intentional. The timeout returned from the POST -> /v1/typing call should be used to disable further calls for that period of time. On contrary,
3532
- * the timeout returned from the notification should be used as the timeout for the "typingEnded" event, +1 is to account for latency.
3533
- *
3534
- * @private
3535
- */
3536
- /**
3537
- * @class TypingIndicator
3538
- *
3539
- * @constructor
3540
- * @private
3541
- */
3542
- class TypingIndicator {
3543
- constructor(getConversation, config, services) {
3544
- this.configuration = config;
3545
- this.services = services;
3546
- this.getConversation = getConversation;
3547
- this.serviceTypingTimeout = null;
3548
- this.sentUpdates = new Map();
3549
- }
3550
- get typingTimeout() {
3551
- return this.configuration.typingIndicatorTimeoutOverride
3552
- || this.serviceTypingTimeout
3553
- || this.configuration.typingIndicatorTimeoutDefault;
3554
- }
3555
- /**
3556
- * Initialize TypingIndicator controller
3557
- * Registers for needed message types and sets listeners
3558
- * @private
3559
- */
3560
- initialize() {
3561
- // this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock');
3562
- this.services.notificationClient.on('message', async (type, message) => {
3563
- if (type === NotificationTypes.TYPING_INDICATOR) {
3564
- await this._handleRemoteTyping(message);
3565
- }
3566
- });
3567
- }
3568
- /**
3569
- * Remote participants typing events handler
3570
- */
3571
- async _handleRemoteTyping(message) {
3572
- log$1.trace('Got new typing indicator ', message);
3573
- this.getConversation(message.channel_sid)
3574
- .then(conversation => {
3575
- if (!conversation) {
3576
- return;
3577
- }
3578
- conversation.participants.forEach(participant => {
3579
- if (participant.identity !== message.identity) {
3580
- return;
3581
- }
3582
- const timeout = this.configuration.typingIndicatorTimeoutOverride + 1000 || message.typing_timeout * 1000;
3583
- participant._startTyping(timeout);
3584
- });
3585
- })
3586
- .catch(err => {
3587
- log$1.error(err);
3588
- throw err;
3589
- });
3590
- }
3591
- /**
3592
- * Send typing event for the given conversation sid
3593
- * @param {String} conversationSid
3594
- */
3595
- send(conversationSid) {
3596
- const lastUpdate = this.sentUpdates.get(conversationSid);
3597
- if (lastUpdate && lastUpdate > (Date.now() - this.typingTimeout)) {
3598
- return Promise.resolve();
3599
- }
3600
- this.sentUpdates.set(conversationSid, Date.now());
3601
- return this._send(conversationSid);
3602
- }
3603
- _send(conversationSid) {
3604
- log$1.trace('Sending typing indicator');
3605
- const url = this.configuration.links.typing;
3606
- const headers = {
3607
- 'Content-Type': 'application/x-www-form-urlencoded'
3608
- };
3609
- const body = `ChannelSid=${conversationSid}`;
3610
- return (this.services.twilsockClient.post(url, headers, body, this.configuration.productId)
3611
- .then((response) => {
3612
- if (response.body.hasOwnProperty('typing_timeout')) {
3613
- this.serviceTypingTimeout = response.body.typing_timeout * 1000;
3614
- }
3615
- })
3616
- .catch((err) => {
3617
- log$1.error('Failed to send typing indicator:', err);
3618
- throw err;
3619
- }));
3620
- }
3621
- }
3622
-
3623
- /**
3624
- * Push notification for a Conversations client.
3625
- */
3626
- class PushNotification {
3627
- /**
3628
- * @internal
3629
- */
3630
- constructor(data) {
3631
- this.title = data.title || null;
3632
- this.body = data.body || null;
3633
- this.sound = data.sound || null;
3634
- this.badge = data.badge || null;
3635
- this.action = data.action || null;
3636
- this.type = data.type || null;
3637
- this.data = data.data || {};
3638
- }
3639
- }
3640
-
3641
- var version = "2.0.0-rc.1";
3642
-
3643
- const trimSlashes = (url) => url.replace(/(^\/+|\/+$)/g, '');
3644
- const isMutationConflictResponse = (response) => response.status.code === 202;
3645
- class CommandExecutor {
3646
- constructor(_serviceUrl, _services, _productId) {
3647
- this._serviceUrl = _serviceUrl;
3648
- this._services = _services;
3649
- this._productId = _productId;
3650
- }
3651
- _preProcessUrl(url) {
3652
- const trimmedUrl = trimSlashes(url);
3653
- if (/^https?:\/\//.test(url)) {
3654
- return trimmedUrl;
3655
- }
3656
- return `${trimSlashes(this._serviceUrl)}/${trimmedUrl}`;
3657
- }
3658
- async _makeRequest(method, url, requestBody, headers) {
3659
- const preProcessedUrl = this._preProcessUrl(url);
3660
- const finalHeaders = Object.assign({ 'Content-Type': 'application/json; charset=utf-8' }, (headers || {}));
3661
- let response;
3662
- switch (method) {
3663
- case 'get':
3664
- let getUrl = preProcessedUrl;
3665
- if (requestBody) {
3666
- getUrl +=
3667
- '?' +
3668
- Object.entries(requestBody)
3669
- .map((entry) => entry.map(encodeURIComponent).join('='))
3670
- .join('&');
3671
- }
3672
- response = await this._services.transport.get(getUrl, finalHeaders, this._productId);
3673
- break;
3674
- case 'post':
3675
- response = await this._services.transport.post(preProcessedUrl, finalHeaders, JSON.stringify(requestBody), this._productId);
3676
- break;
3677
- case 'delete':
3678
- response = await this._services.transport.delete(preProcessedUrl, finalHeaders, null, this._productId);
3679
- break;
3680
- }
3681
- if (response.status.code < 200 || response.status.code >= 300) {
3682
- throw new Error(`Request responded with a non-success code ${response.status.code}`);
3683
- }
3684
- return response;
3685
- }
3686
- async fetchResource(url, requestBody) {
3687
- const maxAttemptsCount = 6;
3688
- let result;
3689
- try {
3690
- result = await new operationRetrier.AsyncRetrier({ min: 50, max: 1600, maxAttemptsCount })
3691
- .run(() => this._makeRequest('get', url, requestBody));
3692
- }
3693
- catch (_a) {
3694
- throw new Error(`Fetch resource from "${url}" failed.`);
3695
- }
3696
- return result.body;
3697
- }
3698
- async mutateResource(method, url, requestBody) {
3699
- const result = await this._makeRequest(method, url, requestBody, {
3700
- 'X-Twilio-Mutation-Id': uuid.v4()
3701
- });
3702
- if (isMutationConflictResponse(result)) {
3703
- return await this.fetchResource(result.body.resource_url);
3704
- }
3705
- return result.body;
3706
- }
3707
- }
3708
-
3709
- var Client_1;
3710
- const log = Logger.scope('Client');
3711
- const SDK_VERSION = version;
3712
- class ClientServices {
3713
- }
3714
- /**
3715
- * A client is the starting point to the Twilio Conversations functionality.
3716
- */
3717
- exports.Client = Client_1 = class Client extends EventEmitter {
3718
- /**
3719
- * Returned Conversations instance is not yet fully initialized. Calling any operations will block until it is.
3720
- * Use connection events to monitor when client becomes fully available (connectionStateChanged with state
3721
- * 'connected') or not available (connectionStateChange with state 'denied', event tokenExpired, event connectionError).
3722
- *
3723
- * @param fpaToken Access token
3724
- * @param options Options to customize the Client
3725
- * @returns A not yet fully-initialized client.
3726
- */
3727
- constructor(fpaToken, options = {}) {
3728
- var _a, _b, _c, _d, _e;
3729
- super();
3730
- /**
3731
- * Client connection state.
3732
- */
3733
- this.connectionState = 'unknown';
3734
- this.conversationsPromise = null;
3735
- this._ensureReady = null;
3736
- this._resolveEnsureReady = null;
3737
- this._rejectEnsureReady = null;
3738
- /**
3739
- * Current version of the Conversations client.
3740
- */
3741
- this.version = SDK_VERSION;
3742
- this.parsePushNotification = Client_1.parsePushNotification;
3743
- this.fpaToken = fpaToken;
3744
- this.options = options;
3745
- if (!this.options.disableDeepClone) {
3746
- let options = Object.assign(Object.assign({}, this.options), { transport: undefined, twilsockClient: undefined });
3747
- options = deepClone(options);
3748
- options.transport = this.options.transport;
3749
- options.twilsockClient = this.options.twilsockClient;
3750
- this.options = options;
3751
- }
3752
- this.options.logLevel = (_a = this.options.logLevel) !== null && _a !== void 0 ? _a : 'silent';
3753
- log.setLevel(this.options.logLevel);
3754
- const productId = this.options.productId = 'ip_messaging';
3755
- // Filling ClientMetadata
3756
- this.options.clientMetadata = this.options.clientMetadata || {};
3757
- if (!this.options.clientMetadata.hasOwnProperty('type')) {
3758
- this.options.clientMetadata.type = 'conversations';
3759
- }
3760
- if (!this.options.clientMetadata.hasOwnProperty('sdk')) {
3761
- this.options.clientMetadata.sdk = 'JS';
3762
- this.options.clientMetadata.sdkv = SDK_VERSION;
3763
- }
3764
- // Enable session local storage for Sync
3765
- this.options.Sync = this.options.Sync || {};
3766
- if (typeof this.options.Sync.enableSessionStorage === 'undefined') {
3767
- this.options.Sync.enableSessionStorage = true;
3768
- }
3769
- if (this.options.region) {
3770
- this.options.Sync.region = this.options.region;
3771
- }
3772
- if (!fpaToken) {
3773
- throw new Error('A valid Twilio token should be provided');
3774
- }
3775
- this.services = new ClientServices();
3776
- const startTwilsock = !this.options.twilsockClient;
3777
- // Create default init registrations if none were provided.
3778
- // Otherwise, the outside party have to list all the init registrations they
3779
- // need.
3780
- // Init registrations passed to the Conversations client will be passed down
3781
- // to the Sync client as well.
3782
- if (!this.options.initRegistrations) {
3783
- const initRegistration = new twilsock.InitRegistration(productId);
3784
- Client_1.populateInitRegistrations(initRegistration);
3785
- this.options.initRegistrations = [initRegistration];
3786
- }
3787
- this.services.twilsockClient = (this.options.twilsockClient = (_b = this.options.twilsockClient) !== null && _b !== void 0 ? _b : new twilsock.TwilsockClient(fpaToken, productId, this.options));
3788
- this.services.twilsockClient.on('tokenAboutToExpire', ttl => this.emit('tokenAboutToExpire', ttl));
3789
- this.services.twilsockClient.on('tokenExpired', () => this.emit('tokenExpired'));
3790
- this.services.twilsockClient.on('connectionError', (error) => this.emit('connectionError', error));
3791
- this.services.twilsockClient.on('stateChanged', (state) => {
3792
- log.debug(`Handling stateChanged for ConversationsClient: new state ${state}`);
3793
- if (state !== this.connectionState) {
3794
- this.connectionState = state;
3795
- this.emit('connectionStateChanged', this.connectionState);
3796
- }
3797
- });
3798
- this.services.transport = (this.options.transport = ((_c = this.options.transport) !== null && _c !== void 0 ? _c : this.options.twilsockClient));
3799
- this.services.notificationClient = (this.options.notificationsClient = (_d = this.options.notificationsClient) !== null && _d !== void 0 ? _d : new notifications.Notifications(fpaToken, this.options));
3800
- this.services.syncClient = (this.options.syncClient = (_e = this.options.syncClient) !== null && _e !== void 0 ? _e : new twilioSync.SyncClient(fpaToken, this.options));
3801
- const configurationOptions = options.Chat || options.IPMessaging || options || {};
3802
- const region = configurationOptions.region || options.region;
3803
- const baseUrl = configurationOptions.apiUri
3804
- || configurationOptions.typingUri
3805
- || `https://aim.${region || 'us1'}.twilio.com`;
3806
- this.services.commandExecutor = new CommandExecutor(baseUrl, { transport: this.options.transport }, productId);
3807
- const emitFailed = (err) => {
3808
- this._rejectEnsureReady(err);
3809
- this.emit('stateChanged', 'failed');
3810
- };
3811
- this.services.twilsockClient.once('connectionError', emitFailed);
3812
- this.services.twilsockClient.once('disconnected', emitFailed);
3813
- // ConversationsClient will be able to initialize only after twilsock is connected
3814
- this.services.twilsockClient.once('connected', async () => {
3815
- log.debug(`ConversationsClient started INITIALIZING`);
3816
- this.services.twilsockClient.off('connectionError', emitFailed);
3817
- this.services.twilsockClient.off('disconnected', emitFailed);
3818
- try {
3819
- const startupEvent = 'conversations.client.startup';
3820
- this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription(startupEvent, 'Conversations client startup', new Date()), startupEvent, twilsock.TelemetryPoint.Start);
3821
- await this._initialize();
3822
- this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription('', '', new Date()), startupEvent, twilsock.TelemetryPoint.End);
3823
- }
3824
- catch (err) {
3825
- // Fail ChatClient if initialization is incomplete
3826
- this._rejectEnsureReady(err);
3827
- this.emit('stateChanged', 'failed');
3828
- }
3829
- });
3830
- this._ensureReady = new Promise((resolve, reject) => {
3831
- this._resolveEnsureReady = resolve;
3832
- this._rejectEnsureReady = reject;
3833
- }).catch((err) => { }); // @todo How to process unhandled rejection here?
3834
- if (startTwilsock) {
3835
- this.services.twilsockClient.connect();
3836
- }
3837
- }
3838
- static populateInitRegistrations(reg) {
3839
- reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]);
3840
- twilioSync.SyncClient.populateInitRegistrations(reg);
3841
- }
3842
- /**
3843
- * @deprecated Call constructor directly.
3844
- *
3845
- * Factory method to create a Conversations client instance.
3846
- *
3847
- * The factory method will automatically trigger connection.
3848
- * Do not use it if you need finer-grained control.
3849
- *
3850
- * @param token Access token.
3851
- * @param options Options to customize the client.
3852
- * @returns Returns a fully initialized client.
3853
- */
3854
- static async create(token, options) {
3855
- // The logic is as follows:
3856
- // - If twilsock is not passed in, then the ConversationsClient constructor will call twilsock.connect() by itself
3857
- // and we do not need to do it here.
3858
- // - If twilsock was passed in from the outside, but customer called ConversationsClient.create() then they are
3859
- // using an obsolete workflow and the startup sequence will never complete.
3860
- if (options === null || options === void 0 ? void 0 : options.twilsockClient) {
3861
- throw new Error('Obsolete usage of ConversationsClient.create() ' +
3862
- 'factory method: if you pass twilsock from the outside then you must ' +
3863
- 'use ConversationsClient constructor and be prepared to work with ' +
3864
- 'uninitialized client.');
3865
- }
3866
- const client = new Client_1(token, options);
3867
- await client._ensureReady;
3868
- return client;
3869
- }
3870
- /**
3871
- * Information of the logged-in user.
3872
- */
3873
- get user() { return this.services.users.myself; }
3874
- /**
3875
- * Client reachability state.
3876
- */
3877
- get reachabilityEnabled() { return this.configuration.reachabilityEnabled; }
3878
- get token() { return this.fpaToken; }
3879
- _subscribeToPushNotifications(channelType) {
3880
- [NotificationTypes.NEW_MESSAGE,
3881
- NotificationTypes.ADDED_TO_CONVERSATION,
3882
- NotificationTypes.REMOVED_FROM_CONVERSATION,
3883
- NotificationTypes.TYPING_INDICATOR,
3884
- NotificationTypes.CONSUMPTION_UPDATE]
3885
- .forEach(messageType => {
3886
- this.services.notificationClient.subscribe(channelType, messageType);
3887
- });
3888
- }
3889
- _unsubscribeFromPushNotifications(channelType) {
3890
- [NotificationTypes.NEW_MESSAGE,
3891
- NotificationTypes.ADDED_TO_CONVERSATION,
3892
- NotificationTypes.REMOVED_FROM_CONVERSATION,
3893
- NotificationTypes.TYPING_INDICATOR,
3894
- NotificationTypes.CONSUMPTION_UPDATE]
3895
- .forEach(messageType => {
3896
- this.services.notificationClient.unsubscribe(channelType, messageType);
3897
- });
3898
- }
3899
- async _initialize() {
3900
- const configurationResponse = await this.services.commandExecutor.fetchResource('Client/v2/Configuration');
3901
- this.configuration = new Configuration(this.options, configurationResponse, log);
3902
- this.services.typingIndicator = new TypingIndicator(this.getConversationBySid.bind(this), this.configuration, this.services);
3903
- this.services.network = new Network(this.configuration, this.services);
3904
- this.services.users = new Users(this.configuration, this.services);
3905
- this.services.users.on('userSubscribed', this.emit.bind(this, 'userSubscribed'));
3906
- this.services.users.on('userUpdated', (args) => this.emit('userUpdated', args));
3907
- this.services.users.on('userUnsubscribed', this.emit.bind(this, 'userUnsubscribed'));
3908
- this.conversations = new Conversations(this.configuration, this.services);
3909
- this.conversations.on('conversationAdded', this.emit.bind(this, 'conversationAdded'));
3910
- this.conversations.on('conversationRemoved', this.emit.bind(this, 'conversationRemoved'));
3911
- this.conversations.on('conversationJoined', this.emit.bind(this, 'conversationJoined'));
3912
- this.conversations.on('conversationLeft', this.emit.bind(this, 'conversationLeft'));
3913
- this.conversations.on('conversationUpdated', (args) => this.emit('conversationUpdated', args));
3914
- this.conversations.on('participantJoined', this.emit.bind(this, 'participantJoined'));
3915
- this.conversations.on('participantLeft', this.emit.bind(this, 'participantLeft'));
3916
- this.conversations.on('participantUpdated', (args) => this.emit('participantUpdated', args));
3917
- this.conversations.on('messageAdded', this.emit.bind(this, 'messageAdded'));
3918
- this.conversations.on('messageUpdated', (args) => this.emit('messageUpdated', args));
3919
- this.conversations.on('messageRemoved', this.emit.bind(this, 'messageRemoved'));
3920
- this.conversations.on('typingStarted', this.emit.bind(this, 'typingStarted'));
3921
- this.conversations.on('typingEnded', this.emit.bind(this, 'typingEnded'));
3922
- this.conversationsPromise = this.conversations.fetchConversations()
3923
- .then(() => this.conversations)
3924
- .catch((error) => {
3925
- throw error;
3926
- });
3927
- await this.services.users.myself._ensureFetched();
3928
- Client_1.supportedPushChannels.forEach(channelType => this._subscribeToPushNotifications(channelType));
3929
- this.services.typingIndicator.initialize();
3930
- this.services.mcsClient = new mcsClient.McsClient(this.fpaToken, this.configuration.links.mediaService, this.configuration.links.mediaSetService, Object.assign(Object.assign({}, this.options), { transport: null }));
3931
- this._resolveEnsureReady();
3932
- this.emit('stateChanged', 'initialized');
3933
- }
3934
- /**
3935
- * Gracefully shut down the client.
3936
- */
3937
- async shutdown() {
3938
- await this._ensureReady;
3939
- await this.services.twilsockClient.disconnect();
3940
- }
3941
- /**
3942
- * Update the token used by the client and re-register with the Conversations services.
3943
- * @param token New access token.
3944
- */
3945
- async updateToken(token) {
3946
- await this._ensureReady;
3947
- log.info('updateToken');
3948
- if (this.fpaToken === token) {
3949
- return this;
3950
- }
3951
- await this.services.twilsockClient.updateToken(token);
3952
- await this.services.notificationClient.updateToken(token);
3953
- await this.services.mcsClient.updateToken(token);
3954
- this.fpaToken = token;
3955
- return this;
3956
- }
3957
- /**
3958
- * Get a known conversation by its SID.
3959
- * @param conversationSid Conversation sid
3960
- */
3961
- async getConversationBySid(conversationSid) {
3962
- await this._ensureReady;
3963
- await this.conversations.myConversationsRead.promise;
3964
- let conversation = await this.conversations.getConversation(conversationSid);
3965
- if (!conversation) {
3966
- conversation = await this.conversations.peekConversation(conversationSid);
3967
- }
3968
- if (!conversation) {
3969
- throw new Error(`Conversation with SID ${conversationSid} is not found.`);
3970
- }
3971
- return conversation;
3972
- }
3973
- /**
3974
- * Get a known conversation by its unique identifier name.
3975
- * @param uniqueName The unique identifier name of the conversation.
3976
- */
3977
- async getConversationByUniqueName(uniqueName) {
3978
- await this._ensureReady;
3979
- await this.conversations.myConversationsRead.promise;
3980
- const conversation = await this.conversations.getConversationByUniqueName(uniqueName);
3981
- if (!conversation) {
3982
- throw new Error(`Conversation with unique name ${uniqueName} is not found.`);
3983
- }
3984
- return conversation;
3985
- }
3986
- /**
3987
- * Get the current list of all the subscribed conversations.
3988
- */
3989
- async getSubscribedConversations(args) {
3990
- await this._ensureReady;
3991
- return this.conversationsPromise.then(conversations => conversations.getConversations(args));
3992
- }
3993
- /**
3994
- * Create a conversation on the server and subscribe to its events.
3995
- * The default is a conversation with an empty friendly name.
3996
- * @param options Options for the conversation.
3997
- */
3998
- async createConversation(options) {
3999
- await this._ensureReady;
4000
- options = options || {};
4001
- return this.conversationsPromise.then(conversationsEntity => conversationsEntity.addConversation(options));
4002
- }
4003
- /**
4004
- * Register for push notifications.
4005
- * @param channelType Channel type.
4006
- * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
4007
- */
4008
- async setPushRegistrationId(channelType, registrationId) {
4009
- await this._ensureReady;
4010
- this.services.notificationClient.setPushRegistrationId(channelType, registrationId);
4011
- await this.services.notificationClient.commitChanges(); // Committing before this point is useless because we have no push id
4012
- }
4013
- /**
4014
- * Unregister from push notifications.
4015
- * @param channelType Channel type.
4016
- * @deprecated Use removePushRegistrations() instead.
4017
- */
4018
- async unsetPushRegistrationId(channelType) {
4019
- await this._ensureReady;
4020
- this._unsubscribeFromPushNotifications(channelType);
4021
- await this.services.notificationClient.commitChanges();
4022
- }
4023
- /**
4024
- * Clear existing registrations directly using provided device token.
4025
- * This is useful to ensure stopped subscriptions without resubscribing.
4026
- *
4027
- * This function goes completely beside the state machine and removes all registrations.
4028
- * Use with caution: if it races with current state machine operations, madness will ensue.
4029
- *
4030
- * @param channelType Channel type.
4031
- * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
4032
- */
4033
- async removePushRegistrations(channelType, registrationId) {
4034
- // do not await this._ensureReady() here - it could be called at any moment
4035
- await this.services.notificationClient.removeRegistrations(channelType, registrationId);
4036
- }
4037
- static parsePushNotificationChatData(data) {
4038
- const result = {};
4039
- for (let key in Client_1.supportedPushDataFields) {
4040
- if (typeof data[key] === 'undefined' || data[key] === null) {
4041
- continue;
4042
- }
4043
- if (key !== 'message_index') {
4044
- result[Client_1.supportedPushDataFields[key]] = data[key];
4045
- continue;
4046
- }
4047
- if (parseToNumber(data[key]) !== null) {
4048
- result[Client_1.supportedPushDataFields[key]] = Number(data[key]);
4049
- }
4050
- }
4051
- return result;
4052
- }
4053
- /**
4054
- * Static method for push notification payload parsing. Returns parsed push as a {@link PushNotification} object.
4055
- * @param notificationPayload Push notification payload.
4056
- */
4057
- static parsePushNotification(notificationPayload) {
4058
- log.debug('parsePushNotification, notificationPayload=', notificationPayload);
4059
- // APNS specifics
4060
- if (typeof notificationPayload.aps !== 'undefined') {
4061
- if (!notificationPayload.twi_message_type) {
4062
- throw new Error('Provided push notification payload does not contain Programmable Chat push notification type');
4063
- }
4064
- let data = Client_1.parsePushNotificationChatData(notificationPayload);
4065
- let apsPayload = notificationPayload.aps;
4066
- let body = null;
4067
- let title = null;
4068
- if (typeof apsPayload.alert === 'string') {
4069
- body = apsPayload.alert || null;
4070
- }
4071
- else {
4072
- body = apsPayload.alert.body || null;
4073
- title = apsPayload.alert.title || null;
4074
- }
4075
- return new PushNotification({
4076
- title: title,
4077
- body: body,
4078
- sound: apsPayload.sound || null,
4079
- badge: apsPayload.badge || null,
4080
- action: apsPayload.category || null,
4081
- type: notificationPayload.twi_message_type,
4082
- data: data
4083
- });
4084
- }
4085
- // FCM specifics
4086
- if (typeof notificationPayload.data !== 'undefined') {
4087
- let dataPayload = notificationPayload.data;
4088
- if (!dataPayload.twi_message_type) {
4089
- throw new Error('Provided push notification payload does not contain Programmable Chat push notification type');
4090
- }
4091
- let data = Client_1.parsePushNotificationChatData(notificationPayload.data);
4092
- return new PushNotification({
4093
- title: dataPayload.twi_title || null,
4094
- body: dataPayload.twi_body || null,
4095
- sound: dataPayload.twi_sound || null,
4096
- badge: null,
4097
- action: dataPayload.twi_action || null,
4098
- type: dataPayload.twi_message_type,
4099
- data: data
4100
- });
4101
- }
4102
- throw new Error('Provided push notification payload is not Programmable Chat notification');
4103
- }
4104
- /**
4105
- * Handle push notification payload parsing and emit the {@link Client.pushNotification} event on this {@link Client} instance.
4106
- * @param notificationPayload Push notification payload
4107
- */
4108
- async handlePushNotification(notificationPayload) {
4109
- await this._ensureReady;
4110
- log.debug('handlePushNotification, notificationPayload=', notificationPayload);
4111
- this.emit('pushNotification', Client_1.parsePushNotification(notificationPayload));
4112
- }
4113
- /**
4114
- * Gets a user with the given identity. If it's in the subscribed list, then return the user object from it;
4115
- * if not, then subscribe and add user to the subscribed list.
4116
- * @param identity Identity of the user.
4117
- * @returns A fully initialized user.
4118
- */
4119
- async getUser(identity) {
4120
- await this._ensureReady;
4121
- return this.services.users.getUser(identity);
4122
- }
4123
- /**
4124
- * Get a list of subscribed user objects.
4125
- */
4126
- async getSubscribedUsers() {
4127
- await this._ensureReady;
4128
- return this.services.users.getSubscribedUsers();
4129
- }
4130
- };
4131
- /**
4132
- * Current version of the Conversations client.
4133
- */
4134
- exports.Client.version = SDK_VERSION;
4135
- exports.Client.supportedPushChannels = ['fcm', 'apn'];
4136
- exports.Client.supportedPushDataFields = {
4137
- 'conversation_sid': 'conversationSid',
4138
- 'message_sid': 'messageSid',
4139
- 'message_index': 'messageIndex'
4140
- };
4141
- /**
4142
- * Fired when a conversation becomes visible to the client. The event is also triggered when the client creates a new conversation.
4143
- * Fired for all conversations client has joined.
4144
- *
4145
- * Parameters:
4146
- * 1. {@link Conversation} `conversation` - the conversation in question
4147
- * @event
4148
- */
4149
- exports.Client.conversationAdded = 'conversationAdded';
4150
- /**
4151
- * Fired when the client joins a conversation.
4152
- *
4153
- * Parameters:
4154
- * 1. {@link Conversation} `conversation` - the conversation in question
4155
- * @event
4156
- */
4157
- exports.Client.conversationJoined = 'conversationJoined';
4158
- /**
4159
- * Fired when the client leaves a conversation.
4160
- *
4161
- * Parameters:
4162
- * 1. {@link Conversation} `conversation` - the conversation in question
4163
- * @event
4164
- */
4165
- exports.Client.conversationLeft = 'conversationLeft';
4166
- /**
4167
- * Fired when a conversation is no longer visible to the client.
4168
- *
4169
- * Parameters:
4170
- * 1. {@link Conversation} `conversation` - the conversation in question
4171
- * @event
4172
- */
4173
- exports.Client.conversationRemoved = 'conversationRemoved';
4174
- /**
4175
- * Fired when the attributes or the metadata of a conversation have been updated.
4176
- * During conversation's {@link Client.create| creation and initialization}, this event might be fired multiple times
4177
- * for same joined or created conversation as new data is arriving from different sources.
4178
- *
4179
- * Parameters:
4180
- * 1. object `data` - info object provided with the event. It has the following properties:
4181
- * * {@link Conversation} `conversation` - the conversation in question
4182
- * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for the update
4183
- * @event
4184
- */
4185
- exports.Client.conversationUpdated = 'conversationUpdated';
4186
- /**
4187
- * Fired when the connection state of the client has been changed.
4188
- *
4189
- * Parameters:
4190
- * 1. {@link Conversation} `conversation` - the conversation in question
4191
- * @event
4192
- */
4193
- exports.Client.conversationStateChanged = 'connectionStateChanged';
4194
- /**
4195
- * Fired when a participant has joined a conversation.
4196
- *
4197
- * Parameters:
4198
- * 1. {@link Participant} `participant` - the participant in question
4199
- * @event
4200
- */
4201
- exports.Client.participantJoined = 'participantJoined';
4202
- /**
4203
- * Fired when a participant has left a conversation.
4204
- *
4205
- * Parameters:
4206
- * 1. {@link Participant} `participant` - the participant in question
4207
- * @event
4208
- */
4209
- exports.Client.participantLeft = 'participantLeft';
4210
- /**
4211
- * Fired when a participant's fields have been updated.
4212
- *
4213
- * Parameters:
4214
- * 1. object `data` - info object provided with the event. It has the following properties:
4215
- * * {@link Participant} `participant` - the participant in question
4216
- * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for the update
4217
- * @event
4218
- */
4219
- exports.Client.participantUpdated = 'participantUpdated';
4220
- /**
4221
- * Fired when a new message has been added to the conversation on the server.
4222
- *
4223
- * Parameters:
4224
- * 1. {@link Message} `message` - the message in question
4225
- * @event
4226
- */
4227
- exports.Client.messageAdded = 'messageAdded';
4228
- /**
4229
- * Fired when a message is removed from the message list of a conversation.
4230
- *
4231
- * Parameters:
4232
- * 1. {@link Message} `message` - the message in question
4233
- * @event
4234
- */
4235
- exports.Client.messageRemoved = 'messageRemoved';
4236
- /**
4237
- * Fired when the fields of an existing message are updated with new values.
4238
- *
4239
- * Parameters:
4240
- * 1. object `data` - info object provided with the event. It has the following properties:
4241
- * * {@link Message} `message` - the message in question
4242
- * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for the update
4243
- * @event
4244
- */
4245
- exports.Client.messageUpdated = 'messageUpdated';
4246
- /**
4247
- * Fired when the token is about to expire and needs to be updated.
4248
- * @event
4249
- */
4250
- exports.Client.tokenAboutToExpire = 'tokenAboutToExpire';
4251
- /**
4252
- * Fired when the token has expired.
4253
- * @event
4254
- */
4255
- exports.Client.tokenExpired = 'tokenExpired';
4256
- /**
4257
- * Fired when a participant has stopped typing.
4258
- *
4259
- * Parameters:
4260
- * 1. {@link Participant} `participant` - the participant in question
4261
- * @event
4262
- */
4263
- exports.Client.typingEnded = 'typingEnded';
4264
- /**
4265
- * Fired when a participant has started typing.
4266
- *
4267
- * Parameters:
4268
- * 1. {@link Participant} `participant` - the participant in question
4269
- * @event
4270
- */
4271
- exports.Client.typingStarted = 'typingStarted';
4272
- /**
4273
- * Fired when the client has received (and parsed) a push notification via one of the push channels (apn or fcm).
4274
- *
4275
- * Parameters:
4276
- * 1. {@link PushNotification} `pushNotification` - the push notification in question
4277
- * @event
4278
- */
4279
- exports.Client.pushNotification = 'pushNotification';
4280
- /**
4281
- * Fired when the client has subscribed to a user.
4282
- *
4283
- * Parameters:
4284
- * 1. {@link User} `user` - the user in question
4285
- * @event
4286
- */
4287
- exports.Client.userSubscribed = 'userSubscribed';
4288
- /**
4289
- * Fired when the client has unsubscribed from a user.
4290
- *
4291
- * Parameters:
4292
- * 1. {@link User} `user` - the user in question
4293
- * @event
4294
- */
4295
- exports.Client.userUnsubscribed = 'userUnsubscribed';
4296
- /**
4297
- * Fired when the properties or the reachability status of a user have been updated.
4298
- *
4299
- * Parameters:
4300
- * 1. object `data` - info object provided with the event. It has the following properties:
4301
- * * {@link User} `user` - the user in question
4302
- * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update
4303
- * @event
4304
- */
4305
- exports.Client.userUpdated = 'userUpdated';
4306
- /**
4307
- * Fired when the connection is interrupted for an unexpected reason.
4308
- *
4309
- * Parameters:
4310
- * 1. object `data` - info object provided with the event. It has the following properties:
4311
- * * boolean `terminal` - Twilsock will stop connection attempts if true
4312
- * * string `message` - the error message of the root cause
4313
- * * number? `httpStatusCode` - http status code if available
4314
- * * number? `errorCode` - Twilio public error code if available
4315
- * @event
4316
- */
4317
- exports.Client.connectionError = 'connectionError';
4318
- __decorate([
4319
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
4320
- __metadata("design:type", Function),
4321
- __metadata("design:paramtypes", [String]),
4322
- __metadata("design:returntype", Promise)
4323
- ], exports.Client.prototype, "updateToken", null);
4324
- __decorate([
4325
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
4326
- __metadata("design:type", Function),
4327
- __metadata("design:paramtypes", [String]),
4328
- __metadata("design:returntype", Promise)
4329
- ], exports.Client.prototype, "getConversationBySid", null);
4330
- __decorate([
4331
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
4332
- __metadata("design:type", Function),
4333
- __metadata("design:paramtypes", [String]),
4334
- __metadata("design:returntype", Promise)
4335
- ], exports.Client.prototype, "getConversationByUniqueName", null);
4336
- __decorate([
4337
- declarativeTypeValidator.validateTypesAsync([
4338
- 'undefined',
4339
- declarativeTypeValidator.objectSchema('conversation options', {
4340
- friendlyName: ['string', 'undefined'],
4341
- isPrivate: ['boolean', 'undefined'],
4342
- uniqueName: ['string', 'undefined']
4343
- })
4344
- ]),
4345
- __metadata("design:type", Function),
4346
- __metadata("design:paramtypes", [Object]),
4347
- __metadata("design:returntype", Promise)
4348
- ], exports.Client.prototype, "createConversation", null);
4349
- __decorate([
4350
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('fcm', 'apn'), 'string'),
4351
- __metadata("design:type", Function),
4352
- __metadata("design:paramtypes", [String, String]),
4353
- __metadata("design:returntype", Promise)
4354
- ], exports.Client.prototype, "setPushRegistrationId", null);
4355
- __decorate([
4356
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('fcm', 'apn')),
4357
- __metadata("design:type", Function),
4358
- __metadata("design:paramtypes", [String]),
4359
- __metadata("design:returntype", Promise)
4360
- ], exports.Client.prototype, "unsetPushRegistrationId", null);
4361
- __decorate([
4362
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.literal('fcm', 'apn'), declarativeTypeValidator.nonEmptyString),
4363
- __metadata("design:type", Function),
4364
- __metadata("design:paramtypes", [String, String]),
4365
- __metadata("design:returntype", Promise)
4366
- ], exports.Client.prototype, "removePushRegistrations", null);
4367
- __decorate([
4368
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.pureObject),
4369
- __metadata("design:type", Function),
4370
- __metadata("design:paramtypes", [Object]),
4371
- __metadata("design:returntype", Promise)
4372
- ], exports.Client.prototype, "handlePushNotification", null);
4373
- __decorate([
4374
- declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
4375
- __metadata("design:type", Function),
4376
- __metadata("design:paramtypes", [String]),
4377
- __metadata("design:returntype", Promise)
4378
- ], exports.Client.prototype, "getUser", null);
4379
- __decorate([
4380
- declarativeTypeValidator.validateTypesAsync('string', ['undefined', declarativeTypeValidator.pureObject]),
4381
- __metadata("design:type", Function),
4382
- __metadata("design:paramtypes", [String, Object]),
4383
- __metadata("design:returntype", Promise)
4384
- ], exports.Client, "create", null);
4385
- __decorate([
4386
- declarativeTypeValidator.validateTypes(declarativeTypeValidator.pureObject),
4387
- __metadata("design:type", Function),
4388
- __metadata("design:paramtypes", [Object]),
4389
- __metadata("design:returntype", PushNotification)
4390
- ], exports.Client, "parsePushNotification", null);
4391
- exports.Client = Client_1 = __decorate([
4392
- declarativeTypeValidator.validateConstructorTypes(declarativeTypeValidator.nonEmptyString, [
4393
- declarativeTypeValidator.pureObject,
4394
- 'undefined',
4395
- declarativeTypeValidator.literal(null),
4396
- ]),
4397
- __metadata("design:paramtypes", [String, Object])
4398
- ], exports.Client);
4399
-
4400
- var Client = exports.Client;
4401
-
4402
- exports.AggregatedDeliveryReceipt = AggregatedDeliveryReceipt;
4403
- exports.Conversation = Conversation;
4404
- exports.DetailedDeliveryReceipt = DetailedDeliveryReceipt;
4405
- exports.Media = Media;
4406
- exports.Message = Message;
4407
- exports.Participant = Participant;
4408
- exports.PushNotification = PushNotification;
4409
- exports.RestPaginator = RestPaginator;
4410
- exports.User = User;
4411
- exports.default = Client;
4412
- //# sourceMappingURL=react-native.js.map