@twilio/conversations 2.1.0 → 3.0.0-rc.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.
package/dist/client.js CHANGED
@@ -151,8 +151,9 @@ var commandExecutor = require('./command-executor.js');
151
151
  var replayEventEmitter = require('@twilio/replay-event-emitter');
152
152
 
153
153
  var Client_1;
154
- const log = logger.Logger.scope("Client");
155
- const SDK_VERSION = _package.version;
154
+ /**
155
+ * Client services.
156
+ */
156
157
  class ClientServices {
157
158
  }
158
159
  /**
@@ -160,9 +161,11 @@ class ClientServices {
160
161
  */
161
162
  exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventEmitter {
162
163
  /**
163
- * Returned Conversations instance is not yet fully initialized. Calling any operations will block until it is.
164
- * Use connection events to monitor when client becomes fully available (connectionStateChanged with state
165
- * 'connected') or not available (connectionStateChange with state 'denied', event tokenExpired, event connectionError).
164
+ * Returned Conversations instance is not yet fully initialized. Calling any
165
+ * operations will block until it is. Use connection events to monitor when
166
+ * client becomes fully available (connectionStateChanged with state
167
+ * 'connected') or not available (connectionStateChange with state 'denied',
168
+ * event tokenExpired, event connectionError).
166
169
  *
167
170
  * @param fpaToken Access token
168
171
  * @param options Options to customize the Client
@@ -171,6 +174,10 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
171
174
  constructor(fpaToken, options = {}) {
172
175
  var _a, _b, _c, _d, _e;
173
176
  super();
177
+ /**
178
+ * Current version of the Conversations client.
179
+ */
180
+ this.version = _package.version;
174
181
  /**
175
182
  * Client connection state.
176
183
  */
@@ -178,98 +185,97 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
178
185
  /**
179
186
  * Current version of the Conversations client.
180
187
  */
181
- this.version = SDK_VERSION;
182
188
  this.parsePushNotification = Client_1.parsePushNotification;
183
- this.fpaToken = fpaToken !== null && fpaToken !== void 0 ? fpaToken : "";
184
- this.options = options !== null && options !== void 0 ? options : {};
185
- if (!this.options.disableDeepClone) {
186
- let options = Object.assign(Object.assign({}, this.options), { transport: undefined, twilsockClient: undefined });
189
+ this._fpaToken = fpaToken !== null && fpaToken !== void 0 ? fpaToken : "";
190
+ this._options = options !== null && options !== void 0 ? options : {};
191
+ if (!this._options.disableDeepClone) {
192
+ let options = Object.assign(Object.assign({}, this._options), { transport: undefined, twilsockClient: undefined });
187
193
  options = index.deepClone(options);
188
- options.transport = this.options.transport;
189
- options.twilsockClient = this.options.twilsockClient;
190
- this.options = options;
194
+ options.transport = this._options.transport;
195
+ options.twilsockClient = this._options.twilsockClient;
196
+ this._options = options;
191
197
  }
192
- this.options.logLevel = (_a = this.options.logLevel) !== null && _a !== void 0 ? _a : "silent";
193
- log.setLevel(this.options.logLevel);
194
- const productId = (this.options.productId = "ip_messaging");
198
+ this._options.logLevel = (_a = this._options.logLevel) !== null && _a !== void 0 ? _a : "silent";
199
+ Client_1._logger.setLevel(this._options.logLevel);
200
+ const productId = (this._options.productId = "ip_messaging");
195
201
  // Filling ClientMetadata
196
- this.options.clientMetadata = this.options.clientMetadata || {};
197
- if (!this.options.clientMetadata.hasOwnProperty("type")) {
198
- this.options.clientMetadata.type = "conversations";
202
+ this._options.clientMetadata = this._options.clientMetadata || {};
203
+ if (!this._options.clientMetadata.hasOwnProperty("type")) {
204
+ this._options.clientMetadata.type = "conversations";
199
205
  }
200
- if (!this.options.clientMetadata.hasOwnProperty("sdk")) {
201
- this.options.clientMetadata.sdk = "JS";
202
- this.options.clientMetadata.sdkv = SDK_VERSION;
206
+ if (!this._options.clientMetadata.hasOwnProperty("sdk")) {
207
+ this._options.clientMetadata.sdk = "JS";
208
+ this._options.clientMetadata.sdkv = _package.version;
203
209
  }
204
210
  // Enable session local storage for Sync
205
- this.options.Sync = this.options.Sync || {};
206
- if (typeof this.options.Sync.enableSessionStorage === "undefined") {
207
- this.options.Sync.enableSessionStorage = true;
211
+ this._options.Sync = this._options.Sync || {};
212
+ if (typeof this._options.Sync.enableSessionStorage === "undefined") {
213
+ this._options.Sync.enableSessionStorage = true;
208
214
  }
209
- if (this.options.region) {
210
- this.options.Sync.region = this.options.region;
215
+ if (this._options.region) {
216
+ this._options.Sync.region = this._options.region;
211
217
  }
212
218
  if (!fpaToken) {
213
219
  throw new Error("A valid Twilio token should be provided");
214
220
  }
215
- this.services = new ClientServices();
216
- this._myself = new user.User("", "", null, this.services);
217
- const startTwilsock = !this.options.twilsockClient;
221
+ this._services = new ClientServices();
222
+ this._myself = new user.User("", "", null, this._services);
223
+ const startTwilsock = !this._options.twilsockClient;
218
224
  // Create default init registrations if none were provided.
219
225
  // Otherwise, the outside party have to list all the init registrations they
220
226
  // need.
221
227
  // Init registrations passed to the Conversations client will be passed down
222
228
  // to the Sync client as well.
223
- if (!this.options.initRegistrations) {
229
+ if (!this._options.initRegistrations) {
224
230
  const initRegistration = new twilsock.InitRegistration(productId);
225
231
  Client_1.populateInitRegistrations(initRegistration);
226
- this.options.initRegistrations = [initRegistration];
232
+ this._options.initRegistrations = [initRegistration];
227
233
  }
228
- this.services.twilsockClient = this.options.twilsockClient =
229
- (_b = this.options.twilsockClient) !== null && _b !== void 0 ? _b : new twilsock.TwilsockClient(fpaToken, productId, this.options);
230
- this.services.twilsockClient.on("tokenAboutToExpire", (ttl) => this.emit("tokenAboutToExpire", ttl));
231
- this.services.twilsockClient.on("tokenExpired", () => this.emit("tokenExpired"));
232
- this.services.twilsockClient.on("connectionError", (error) => this.emit("connectionError", error));
233
- this.services.twilsockClient.on("stateChanged", (state) => {
234
- log.debug(`Handling stateChanged for ConversationsClient: new state ${state}`);
234
+ this._services.twilsockClient = this._options.twilsockClient =
235
+ (_b = this._options.twilsockClient) !== null && _b !== void 0 ? _b : new twilsock.TwilsockClient(fpaToken, productId, this._options);
236
+ this._services.twilsockClient.on("tokenAboutToExpire", (ttl) => this.emit("tokenAboutToExpire", ttl));
237
+ this._services.twilsockClient.on("tokenExpired", () => this.emit("tokenExpired"));
238
+ this._services.twilsockClient.on("connectionError", (error) => this.emit("connectionError", error));
239
+ this._services.twilsockClient.on("stateChanged", (state) => {
240
+ Client_1._logger.debug(`Handling stateChanged for ConversationsClient: new state ${state}`);
235
241
  if (state !== this.connectionState) {
236
242
  this.connectionState = state;
237
243
  this.emit("connectionStateChanged", this.connectionState);
238
244
  }
239
245
  });
240
- this.services.transport = this.options.transport = ((_c = this.options
241
- .transport) !== null && _c !== void 0 ? _c : this.options.twilsockClient);
242
- this.services.notificationClient = this.options.notificationsClient =
243
- (_d = this.options.notificationsClient) !== null && _d !== void 0 ? _d : new notifications.Notifications(fpaToken, this.options);
244
- this.services.syncClient = this.options.syncClient =
245
- (_e = this.options.syncClient) !== null && _e !== void 0 ? _e : new twilioSync.SyncClient(fpaToken, this.options);
246
+ this._services.transport = this._options.transport = ((_c = this._options
247
+ .transport) !== null && _c !== void 0 ? _c : this._options.twilsockClient);
248
+ this._services.notificationClient = this._options.notificationsClient =
249
+ (_d = this._options.notificationsClient) !== null && _d !== void 0 ? _d : new notifications.Notifications(fpaToken, this._options);
250
+ this._services.syncClient = this._options.syncClient =
251
+ (_e = this._options.syncClient) !== null && _e !== void 0 ? _e : new twilioSync.SyncClient(fpaToken, this._options);
246
252
  const configurationOptions = (options === null || options === void 0 ? void 0 : options.Chat) || (options === null || options === void 0 ? void 0 : options.IPMessaging) || options || {};
247
253
  const region = configurationOptions.region || (options === null || options === void 0 ? void 0 : options.region);
248
254
  const baseUrl = configurationOptions.apiUri ||
249
255
  configurationOptions.typingUri ||
250
256
  `https://aim.${region || "us1"}.twilio.com`;
251
- this.services.commandExecutor = new commandExecutor.CommandExecutor(baseUrl, { transport: this.options.transport }, productId);
252
- const emitFailed = (err) => {
253
- this._rejectEnsureReady(err);
254
- this.emit("stateChanged", "failed");
257
+ this._services.commandExecutor = new commandExecutor.CommandExecutor(baseUrl, { transport: this._options.transport }, productId);
258
+ const emitFailed = (error) => {
259
+ this._rejectEnsureReady(error);
260
+ this.emit("stateChanged", { state: "failed", error });
255
261
  };
256
- this.services.twilsockClient.once("connectionError", emitFailed);
257
- this.services.twilsockClient.once("disconnected", emitFailed);
258
- // ConversationsClient will be able to initialize only after twilsock is connected
259
- this.services.twilsockClient.once("connected", async () => {
260
- log.debug(`ConversationsClient started INITIALIZING`);
261
- this.services.twilsockClient.off("connectionError", emitFailed);
262
- this.services.twilsockClient.off("disconnected", emitFailed);
262
+ this._services.twilsockClient.once("connectionError", emitFailed);
263
+ this._services.twilsockClient.once("disconnected", emitFailed);
264
+ // The client will be able to initialize only after Twilsock is connected
265
+ this._services.twilsockClient.once("connected", async () => {
266
+ Client_1._logger.debug(`ConversationsClient started INITIALIZING`);
267
+ this._services.twilsockClient.off("connectionError", emitFailed);
268
+ this._services.twilsockClient.off("disconnected", emitFailed);
263
269
  try {
264
270
  const startupEvent = "conversations.client.startup";
265
- this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription(startupEvent, "Conversations client startup", new Date()), startupEvent, twilsock.TelemetryPoint.Start);
271
+ this._services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription(startupEvent, "Conversations client startup", new Date()), startupEvent, twilsock.TelemetryPoint.Start);
266
272
  await this._initialize();
267
- this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription("", "", new Date()), startupEvent, twilsock.TelemetryPoint.End);
273
+ this._services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription("", "", new Date()), startupEvent, twilsock.TelemetryPoint.End);
268
274
  }
269
275
  catch (err) {
270
276
  // Fail ChatClient if initialization is incomplete
271
277
  this._rejectEnsureReady(err);
272
- this.emit("stateChanged", "failed");
278
+ this.emit("stateChanged", { state: "failed", error: err });
273
279
  }
274
280
  });
275
281
  this._ensureReady = new Promise((resolve, reject) => {
@@ -277,12 +283,28 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
277
283
  this._rejectEnsureReady = reject;
278
284
  }).catch(() => void 0); // @todo How to process unhandled rejection here?
279
285
  if (startTwilsock) {
280
- this.services.twilsockClient.connect();
286
+ this._services.twilsockClient.connect();
281
287
  }
282
288
  }
283
- static populateInitRegistrations(reg) {
284
- reg.populateInitRegistrations([notificationTypes.NotificationTypes.TYPING_INDICATOR]);
285
- twilioSync.SyncClient.populateInitRegistrations(reg);
289
+ /**
290
+ * Information of the logged-in user. Before client initialization, returns an
291
+ * uninitialized user. Will trigger a {@link Client.userUpdated} event after
292
+ * initialization.
293
+ */
294
+ get user() {
295
+ return this._myself;
296
+ }
297
+ /**
298
+ * Client reachability state. Throws an error if accessed before the client
299
+ * initialization was completed.
300
+ */
301
+ get reachabilityEnabled() {
302
+ if (!this._configuration) {
303
+ throw new Error("Reachability information could not yet be accessed as the client " +
304
+ "has not yet been initialized. Subscribe to the 'stateChanged' event " +
305
+ "to properly react to the client initialization.");
306
+ }
307
+ return this._configuration.reachabilityEnabled;
286
308
  }
287
309
  /**
288
310
  * @deprecated Call constructor directly.
@@ -320,109 +342,104 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
320
342
  return client;
321
343
  }
322
344
  /**
323
- * Information of the logged-in user. Before client initialization, returns an
324
- * uninitialized user. Will trigger a {@link Client.userUpdated} event after
325
- * initialization.
345
+ * Static method for push notification payload parsing. Returns parsed push as
346
+ * a {@link PushNotification} object.
347
+ * @param notificationPayload Push notification payload.
326
348
  */
327
- get user() {
328
- return this._myself;
349
+ static parsePushNotification(notificationPayload) {
350
+ Client_1._logger.debug("parsePushNotification, notificationPayload=", notificationPayload);
351
+ // APNS specifics
352
+ if (typeof notificationPayload.aps !== "undefined") {
353
+ if (!notificationPayload.twi_message_type) {
354
+ throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");
355
+ }
356
+ const data = Client_1._parsePushNotificationChatData(notificationPayload);
357
+ const apsPayload = notificationPayload.aps;
358
+ let body;
359
+ let title = null;
360
+ if (typeof apsPayload.alert === "string") {
361
+ body = apsPayload.alert || null;
362
+ }
363
+ else {
364
+ body = apsPayload.alert.body || null;
365
+ title = apsPayload.alert.title || null;
366
+ }
367
+ return new pushNotification.PushNotification({
368
+ title,
369
+ body,
370
+ sound: apsPayload.sound || null,
371
+ badge: apsPayload.badge || null,
372
+ action: apsPayload.category || null,
373
+ type: notificationPayload.twi_message_type,
374
+ data: data,
375
+ });
376
+ }
377
+ // FCM specifics
378
+ if (typeof notificationPayload.data !== "undefined") {
379
+ const dataPayload = notificationPayload.data;
380
+ if (!dataPayload.twi_message_type) {
381
+ throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");
382
+ }
383
+ const data = Client_1._parsePushNotificationChatData(notificationPayload.data);
384
+ return new pushNotification.PushNotification({
385
+ title: dataPayload.twi_title || null,
386
+ body: dataPayload.twi_body || null,
387
+ sound: dataPayload.twi_sound || null,
388
+ badge: null,
389
+ action: dataPayload.twi_action || null,
390
+ type: dataPayload.twi_message_type,
391
+ data: data,
392
+ });
393
+ }
394
+ throw new Error("Provided push notification payload is not Programmable Chat notification");
329
395
  }
330
396
  /**
331
- * Client reachability state. Throws if accessed before the client
332
- * initialization was completed.
397
+ * Static method for parsing push notification chat data.
398
+ * @param data Data to parse
333
399
  */
334
- get reachabilityEnabled() {
335
- if (!this.configuration) {
336
- throw new Error("Reachability information could not yet be accessed as the client " +
337
- "has not yet been initialized. Subscribe to the 'stateChanged' event " +
338
- "to properly react to the client initialization.");
400
+ static _parsePushNotificationChatData(data) {
401
+ const result = {};
402
+ for (const key in Client_1._supportedPushDataFields) {
403
+ const value = data[key];
404
+ if (typeof value === "undefined" || value === null) {
405
+ continue;
406
+ }
407
+ if (key === "message_index" || key === "media_count") {
408
+ const number = index.parseToNumber(value);
409
+ if (number !== null) {
410
+ result[Client_1._supportedPushDataFields[key]] = number;
411
+ }
412
+ continue;
413
+ }
414
+ if (key === "media") {
415
+ if (typeof value === "string") {
416
+ try {
417
+ result[Client_1._supportedPushDataFields[key]] = JSON.parse(value);
418
+ }
419
+ catch (_a) {
420
+ Client_1._logger.debug("Media message notification parsing error");
421
+ }
422
+ }
423
+ continue;
424
+ }
425
+ result[Client_1._supportedPushDataFields[key]] = value;
339
426
  }
340
- return this.configuration.reachabilityEnabled;
341
- }
342
- get token() {
343
- return this.fpaToken;
344
- }
345
- _subscribeToPushNotifications(channelType) {
346
- [
347
- notificationTypes.NotificationTypes.NEW_MESSAGE,
348
- notificationTypes.NotificationTypes.ADDED_TO_CONVERSATION,
349
- notificationTypes.NotificationTypes.REMOVED_FROM_CONVERSATION,
350
- notificationTypes.NotificationTypes.TYPING_INDICATOR,
351
- notificationTypes.NotificationTypes.CONSUMPTION_UPDATE,
352
- ].forEach((messageType) => {
353
- this.services.notificationClient.subscribe(channelType, messageType);
354
- });
355
- }
356
- _unsubscribeFromPushNotifications(channelType) {
357
- [
358
- notificationTypes.NotificationTypes.NEW_MESSAGE,
359
- notificationTypes.NotificationTypes.ADDED_TO_CONVERSATION,
360
- notificationTypes.NotificationTypes.REMOVED_FROM_CONVERSATION,
361
- notificationTypes.NotificationTypes.TYPING_INDICATOR,
362
- notificationTypes.NotificationTypes.CONSUMPTION_UPDATE,
363
- ].forEach((messageType) => {
364
- this.services.notificationClient.unsubscribe(channelType, messageType);
365
- });
427
+ return result;
366
428
  }
367
- async _initialize() {
368
- const configurationResponse = await this.services.commandExecutor.fetchResource("Client/v2/Configuration");
369
- this.configuration = new configuration.Configuration(this.options, configurationResponse, log);
370
- this._myself._resolveInitialization(this.configuration, this.configuration.userIdentity, this.configuration.userInfo, true);
371
- this.services.typingIndicator = new typingIndicator.TypingIndicator(this.getConversationBySid.bind(this), this.configuration, this.services);
372
- this.services.network = new network.Network(this.configuration, this.services);
373
- this.services.users = new users.Users(this._myself, this.configuration, this.services);
374
- this.services.users.on("userSubscribed", (user) => {
375
- this.emit("userSubscribed", user);
376
- });
377
- this.services.users.on("userUpdated", (args) => this.emit("userUpdated", args));
378
- this.services.users.on("userUnsubscribed", (user) => {
379
- this.emit("userUnsubscribed", user);
380
- });
381
- this.conversations = new conversations.Conversations(this.configuration, this.services);
382
- this.conversations.on("conversationAdded", (conversation) => {
383
- this.emit("conversationAdded", conversation);
384
- });
385
- this.conversations.on("conversationRemoved", (conversation) => {
386
- this.emit("conversationRemoved", conversation);
387
- });
388
- this.conversations.on("conversationJoined", (conversation) => {
389
- this.emit("conversationJoined", conversation);
390
- });
391
- this.conversations.on("conversationLeft", (conversation) => {
392
- this.emit("conversationLeft", conversation);
393
- });
394
- this.conversations.on("conversationUpdated", (args) => this.emit("conversationUpdated", args));
395
- this.conversations.on("participantJoined", (participant) => {
396
- this.emit("participantJoined", participant);
397
- });
398
- this.conversations.on("participantLeft", (participant) => {
399
- this.emit("participantLeft", participant);
400
- });
401
- this.conversations.on("participantUpdated", (args) => this.emit("participantUpdated", args));
402
- this.conversations.on("messageAdded", (message) => this.emit("messageAdded", message));
403
- this.conversations.on("messageUpdated", (args) => this.emit("messageUpdated", args));
404
- this.conversations.on("messageRemoved", (message) => this.emit("messageRemoved", message));
405
- this.conversations.on("typingStarted", (participant) => this.emit("typingStarted", participant));
406
- this.conversations.on("typingEnded", (participant) => this.emit("typingEnded", participant));
407
- this.conversationsPromise = this.conversations
408
- .fetchConversations()
409
- .then(() => this.conversations)
410
- .catch((error) => {
411
- throw error;
412
- });
413
- await this.services.users.myself._ensureFetched();
414
- Client_1.supportedPushChannels.forEach((channelType) => this._subscribeToPushNotifications(channelType));
415
- this.services.typingIndicator.initialize();
416
- this.services.mcsClient = new mcsClient.McsClient(this.fpaToken, this.configuration.links.mediaService, this.configuration.links.mediaSetService, Object.assign(Object.assign({}, this.options), { transport: undefined }));
417
- this._resolveEnsureReady();
418
- this.emit("stateChanged", "initialized");
429
+ /**
430
+ * Populate the client with init registrations.
431
+ * @param reg The init registration to populate.
432
+ */
433
+ static populateInitRegistrations(reg) {
434
+ reg.populateInitRegistrations([notificationTypes.NotificationTypes.TYPING_INDICATOR]);
435
+ twilioSync.SyncClient.populateInitRegistrations(reg);
419
436
  }
420
437
  /**
421
438
  * Gracefully shut down the client.
422
439
  */
423
440
  async shutdown() {
424
441
  await this._ensureReady;
425
- await this.services.twilsockClient.disconnect();
442
+ await this._services.twilsockClient.disconnect();
426
443
  }
427
444
  /**
428
445
  * Update the token used by the client and re-register with the Conversations services.
@@ -430,14 +447,14 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
430
447
  */
431
448
  async updateToken(token) {
432
449
  await this._ensureReady;
433
- log.info("updateToken");
434
- if (this.fpaToken === token) {
450
+ Client_1._logger.info("updateToken");
451
+ if (this._fpaToken === token) {
435
452
  return this;
436
453
  }
437
- await this.services.twilsockClient.updateToken(token);
438
- await this.services.notificationClient.updateToken(token);
439
- await this.services.mcsClient.updateToken(token);
440
- this.fpaToken = token;
454
+ await this._services.twilsockClient.updateToken(token);
455
+ await this._services.notificationClient.updateToken(token);
456
+ await this._services.mcsClient.updateToken(token);
457
+ this._fpaToken = token;
441
458
  return this;
442
459
  }
443
460
  /**
@@ -446,11 +463,21 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
446
463
  */
447
464
  async getConversationBySid(conversationSid) {
448
465
  await this._ensureReady;
449
- await this.conversations.myConversationsRead.promise;
450
- let conversation = await this.conversations.getConversation(conversationSid);
466
+ await this._conversations.myConversationsRead.promise;
467
+ const conversation = await this._conversations.getConversation(conversationSid);
451
468
  if (!conversation) {
452
- conversation = await this.conversations.peekConversation(conversationSid);
469
+ throw new Error(`Conversation with SID ${conversationSid} is not found.`);
453
470
  }
471
+ return conversation;
472
+ }
473
+ /**
474
+ * Peek a conversation by its SID.
475
+ * @param conversationSid Conversation sid
476
+ * @internal
477
+ */
478
+ async peekConversationBySid(conversationSid) {
479
+ await this._ensureReady;
480
+ const conversation = await this._conversations.peekConversation(conversationSid);
454
481
  if (!conversation) {
455
482
  throw new Error(`Conversation with SID ${conversationSid} is not found.`);
456
483
  }
@@ -462,8 +489,8 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
462
489
  */
463
490
  async getConversationByUniqueName(uniqueName) {
464
491
  await this._ensureReady;
465
- await this.conversations.myConversationsRead.promise;
466
- const conversation = await this.conversations.getConversationByUniqueName(uniqueName);
492
+ await this._conversations.myConversationsRead.promise;
493
+ const conversation = await this._conversations.getConversationByUniqueName(uniqueName);
467
494
  if (!conversation) {
468
495
  throw new Error(`Conversation with unique name ${uniqueName} is not found.`);
469
496
  }
@@ -474,7 +501,7 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
474
501
  */
475
502
  async getSubscribedConversations() {
476
503
  await this._ensureReady;
477
- return this.conversationsPromise.then((conversations) => conversations.getConversations());
504
+ return this._conversationsPromise.then((conversations) => conversations.getConversations());
478
505
  }
479
506
  /**
480
507
  * Create a conversation on the server and subscribe to its events.
@@ -484,18 +511,19 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
484
511
  async createConversation(options) {
485
512
  await this._ensureReady;
486
513
  options = options || {};
487
- return this.conversationsPromise.then((conversationsEntity) => conversationsEntity.addConversation(options));
514
+ return this._conversationsPromise.then((conversationsEntity) => conversationsEntity.addConversation(options));
488
515
  }
489
516
  /**
490
517
  * Register for push notifications.
491
518
  * @param channelType Channel type.
492
- * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
519
+ * @param registrationId Push notification ID provided by the FCM/APNS service
520
+ * on the platform.
493
521
  */
494
522
  async setPushRegistrationId(channelType, registrationId) {
495
523
  await this._ensureReady;
496
524
  this._subscribeToPushNotifications(channelType);
497
- this.services.notificationClient.setPushRegistrationId(channelType, registrationId);
498
- await this.services.notificationClient.commitChanges(); // Committing before this point is useless because we have no push id
525
+ this._services.notificationClient.setPushRegistrationId(channelType, registrationId);
526
+ await this._services.notificationClient.commitChanges(); // Committing before this point is useless because we have no push id
499
527
  }
500
528
  /**
501
529
  * Unregister from push notifications.
@@ -505,132 +533,180 @@ exports.Client = Client_1 = class Client extends replayEventEmitter.ReplayEventE
505
533
  async unsetPushRegistrationId(channelType) {
506
534
  await this._ensureReady;
507
535
  this._unsubscribeFromPushNotifications(channelType);
508
- await this.services.notificationClient.commitChanges();
536
+ await this._services.notificationClient.commitChanges();
509
537
  }
510
538
  /**
511
539
  * Clear existing registrations directly using provided device token.
512
540
  * This is useful to ensure stopped subscriptions without resubscribing.
513
541
  *
514
- * This function goes completely beside the state machine and removes all registrations.
515
- * Use with caution: if it races with current state machine operations, madness will ensue.
542
+ * This function goes completely beside the state machine and removes all
543
+ * registrations.
544
+ * Use with caution: if it races with current state machine operations,
545
+ * madness will ensue.
516
546
  *
517
547
  * @param channelType Channel type.
518
- * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
548
+ * @param registrationId Push notification ID provided by the FCM/APNS service
549
+ * on the platform.
519
550
  */
520
551
  async removePushRegistrations(channelType, registrationId) {
521
552
  // do not await this._ensureReady() here - it could be called at any moment
522
- await this.services.notificationClient.removeRegistrations(channelType, registrationId);
523
- }
524
- static parsePushNotificationChatData(data) {
525
- const result = {};
526
- for (const key in Client_1.supportedPushDataFields) {
527
- if (typeof data[key] === "undefined" || data[key] === null) {
528
- continue;
529
- }
530
- if (key !== "message_index") {
531
- result[Client_1.supportedPushDataFields[key]] = data[key];
532
- continue;
533
- }
534
- if (index.parseToNumber(data[key]) !== null) {
535
- result[Client_1.supportedPushDataFields[key]] = Number(data[key]);
536
- }
537
- }
538
- return result;
553
+ await this._services.notificationClient.removeRegistrations(channelType, registrationId);
539
554
  }
540
555
  /**
541
- * Static method for push notification payload parsing. Returns parsed push as a {@link PushNotification} object.
542
- * @param notificationPayload Push notification payload.
543
- */
544
- static parsePushNotification(notificationPayload) {
545
- log.debug("parsePushNotification, notificationPayload=", notificationPayload);
546
- // APNS specifics
547
- if (typeof notificationPayload.aps !== "undefined") {
548
- if (!notificationPayload.twi_message_type) {
549
- throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");
550
- }
551
- const data = Client_1.parsePushNotificationChatData(notificationPayload);
552
- const apsPayload = notificationPayload.aps;
553
- let body;
554
- let title = null;
555
- if (typeof apsPayload.alert === "string") {
556
- body = apsPayload.alert || null;
557
- }
558
- else {
559
- body = apsPayload.alert.body || null;
560
- title = apsPayload.alert.title || null;
561
- }
562
- return new pushNotification.PushNotification({
563
- title,
564
- body,
565
- sound: apsPayload.sound || null,
566
- badge: apsPayload.badge || null,
567
- action: apsPayload.category || null,
568
- type: notificationPayload.twi_message_type,
569
- data: data,
570
- });
571
- }
572
- // FCM specifics
573
- if (typeof notificationPayload.data !== "undefined") {
574
- const dataPayload = notificationPayload.data;
575
- if (!dataPayload.twi_message_type) {
576
- throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");
577
- }
578
- const data = Client_1.parsePushNotificationChatData(notificationPayload.data);
579
- return new pushNotification.PushNotification({
580
- title: dataPayload.twi_title || null,
581
- body: dataPayload.twi_body || null,
582
- sound: dataPayload.twi_sound || null,
583
- badge: null,
584
- action: dataPayload.twi_action || null,
585
- type: dataPayload.twi_message_type,
586
- data: data,
587
- });
588
- }
589
- throw new Error("Provided push notification payload is not Programmable Chat notification");
590
- }
591
- /**
592
- * Handle push notification payload parsing and emit the {@link Client.pushNotification} event on this {@link Client} instance.
556
+ * Handle push notification payload parsing and emit the
557
+ * {@link Client.pushNotification} event on this {@link Client} instance.
593
558
  * @param notificationPayload Push notification payload
594
559
  */
595
560
  async handlePushNotification(notificationPayload) {
596
561
  await this._ensureReady;
597
- log.debug("handlePushNotification, notificationPayload=", notificationPayload);
562
+ Client_1._logger.debug("handlePushNotification, notificationPayload=", notificationPayload);
598
563
  this.emit("pushNotification", Client_1.parsePushNotification(notificationPayload));
599
564
  }
600
565
  /**
601
- * Gets a user with the given identity. If it's in the subscribed list, then return the user object from it;
566
+ * Gets a user with the given identity. If it's in the subscribed list, then
567
+ * return the user object from it;
602
568
  * if not, then subscribe and add user to the subscribed list.
603
569
  * @param identity Identity of the user.
604
570
  * @returns A fully initialized user.
605
571
  */
606
572
  async getUser(identity) {
607
573
  await this._ensureReady;
608
- return this.services.users.getUser(identity);
574
+ return this._services.users.getUser(identity);
609
575
  }
610
576
  /**
611
577
  * Get a list of subscribed user objects.
612
578
  */
613
579
  async getSubscribedUsers() {
614
580
  await this._ensureReady;
615
- return this.services.users.getSubscribedUsers();
581
+ return this._services.users.getSubscribedUsers();
582
+ }
583
+ /**
584
+ * Get content URLs for all media attachments in the given set of media sids
585
+ * using a single operation.
586
+ * @param mediaSids Set of media sids to query for the content URL.
587
+ */
588
+ getTemporaryContentUrlsForMediaSids(mediaSids) {
589
+ return new mcsClient.CancellablePromise(async (resolve, reject, onCancel) => {
590
+ if (!this._services.mcsClient || !mediaSids) {
591
+ reject(new Error("Media Content Service is unavailable"));
592
+ return;
593
+ }
594
+ const request = this._services.mcsClient.mediaSetGetContentUrls(mediaSids);
595
+ onCancel(() => {
596
+ request.cancel();
597
+ });
598
+ try {
599
+ const urls = await request;
600
+ resolve(urls);
601
+ }
602
+ catch (e) {
603
+ reject(e);
604
+ }
605
+ });
606
+ }
607
+ /**
608
+ * Get content URLs for all media attachments in the given set using a single
609
+ * operation.
610
+ * @param contentSet Set of media attachments to query content URLs.
611
+ */
612
+ getTemporaryContentUrlsForMedia(contentSet) {
613
+ // We ignore existing mcsMedia members of each of the media entries.
614
+ // Instead, we just collect their sids and pull new descriptors from a
615
+ // mediaSet GET endpoint.
616
+ const sids = contentSet.map((m) => m.sid);
617
+ return this.getTemporaryContentUrlsForMediaSids(sids);
618
+ }
619
+ /**
620
+ * Initialize the client.
621
+ */
622
+ async _initialize() {
623
+ const configurationResponse = await this._services.commandExecutor.fetchResource("Client/v2/Configuration");
624
+ this._configuration = new configuration.Configuration(this._options, configurationResponse, Client_1._logger);
625
+ this._myself._resolveInitialization(this._configuration, this._configuration.userIdentity, this._configuration.userInfo, true);
626
+ this._services.typingIndicator = new typingIndicator.TypingIndicator(this.getConversationBySid.bind(this), this._configuration, this._services);
627
+ this._services.network = new network.Network(this._configuration, this._services);
628
+ this._services.users = new users.Users(this._myself, this._configuration, this._services);
629
+ this._services.users.on("userSubscribed", (user) => {
630
+ this.emit("userSubscribed", user);
631
+ });
632
+ this._services.users.on("userUpdated", (args) => this.emit("userUpdated", args));
633
+ this._services.users.on("userUnsubscribed", (user) => {
634
+ this.emit("userUnsubscribed", user);
635
+ });
636
+ this._conversations = new conversations.Conversations(this._configuration, this._services);
637
+ this._conversations.on("conversationAdded", (conversation) => {
638
+ this.emit("conversationAdded", conversation);
639
+ });
640
+ this._conversations.on("conversationRemoved", (conversation) => {
641
+ this.emit("conversationRemoved", conversation);
642
+ });
643
+ this._conversations.on("conversationJoined", (conversation) => {
644
+ this.emit("conversationJoined", conversation);
645
+ });
646
+ this._conversations.on("conversationLeft", (conversation) => {
647
+ this.emit("conversationLeft", conversation);
648
+ });
649
+ this._conversations.on("conversationUpdated", (args) => this.emit("conversationUpdated", args));
650
+ this._conversations.on("participantJoined", (participant) => {
651
+ this.emit("participantJoined", participant);
652
+ });
653
+ this._conversations.on("participantLeft", (participant) => {
654
+ this.emit("participantLeft", participant);
655
+ });
656
+ this._conversations.on("participantUpdated", (args) => this.emit("participantUpdated", args));
657
+ this._conversations.on("messageAdded", (message) => this.emit("messageAdded", message));
658
+ this._conversations.on("messageUpdated", (args) => this.emit("messageUpdated", args));
659
+ this._conversations.on("messageRemoved", (message) => this.emit("messageRemoved", message));
660
+ this._conversations.on("typingStarted", (participant) => this.emit("typingStarted", participant));
661
+ this._conversations.on("typingEnded", (participant) => this.emit("typingEnded", participant));
662
+ this._conversationsPromise = this._conversations
663
+ .fetchConversations()
664
+ .then(() => this._conversations)
665
+ .catch((error) => {
666
+ throw error;
667
+ });
668
+ await this._services.users.myself._ensureFetched();
669
+ Client_1._supportedPushChannels.forEach((channelType) => this._subscribeToPushNotifications(channelType));
670
+ this._services.typingIndicator.initialize();
671
+ this._services.mcsClient = new mcsClient.McsClient(this._fpaToken, this._configuration.links.mediaService, this._configuration.links.mediaSetService, Object.assign(Object.assign({}, this._options), { transport: undefined }));
672
+ this._resolveEnsureReady();
673
+ this.emit("stateChanged", { state: "initialized" });
674
+ }
675
+ /**
676
+ * Subscribe to push notifications.
677
+ * @param channelType The channel type to subscribe to.
678
+ */
679
+ _subscribeToPushNotifications(channelType) {
680
+ [
681
+ notificationTypes.NotificationTypes.NEW_MESSAGE,
682
+ notificationTypes.NotificationTypes.ADDED_TO_CONVERSATION,
683
+ notificationTypes.NotificationTypes.REMOVED_FROM_CONVERSATION,
684
+ notificationTypes.NotificationTypes.TYPING_INDICATOR,
685
+ notificationTypes.NotificationTypes.CONSUMPTION_UPDATE,
686
+ ].forEach((messageType) => {
687
+ this._services.notificationClient.subscribe(channelType, messageType);
688
+ });
689
+ }
690
+ /**
691
+ * Unsubscribe from push notifications.
692
+ * @param channelType The channel type to unsubscribe from.
693
+ */
694
+ _unsubscribeFromPushNotifications(channelType) {
695
+ [
696
+ notificationTypes.NotificationTypes.NEW_MESSAGE,
697
+ notificationTypes.NotificationTypes.ADDED_TO_CONVERSATION,
698
+ notificationTypes.NotificationTypes.REMOVED_FROM_CONVERSATION,
699
+ notificationTypes.NotificationTypes.TYPING_INDICATOR,
700
+ notificationTypes.NotificationTypes.CONSUMPTION_UPDATE,
701
+ ].forEach((messageType) => {
702
+ this._services.notificationClient.unsubscribe(channelType, messageType);
703
+ });
616
704
  }
617
705
  };
618
706
  /**
619
- * Current version of the Conversations client.
620
- */
621
- exports.Client.version = SDK_VERSION;
622
- exports.Client.supportedPushChannels = [
623
- "fcm",
624
- "apn",
625
- ];
626
- exports.Client.supportedPushDataFields = {
627
- conversation_sid: "conversationSid",
628
- message_sid: "messageSid",
629
- message_index: "messageIndex",
630
- };
631
- /**
632
- * Fired when a conversation becomes visible to the client. The event is also triggered when the client creates a new conversation.
633
- * Fired for all conversations client has joined.
707
+ * Fired when a conversation becomes visible to the client. The event is also
708
+ * triggered when the client creates a new conversation.
709
+ * Fired for all conversations that the client has joined.
634
710
  *
635
711
  * Parameters:
636
712
  * 1. {@link Conversation} `conversation` - the conversation in question
@@ -662,14 +738,17 @@ exports.Client.conversationLeft = "conversationLeft";
662
738
  */
663
739
  exports.Client.conversationRemoved = "conversationRemoved";
664
740
  /**
665
- * Fired when the attributes or the metadata of a conversation have been updated.
666
- * During conversation's creation and initialization, this event might be fired multiple times
667
- * for same joined or created conversation as new data is arriving from different sources.
741
+ * Fired when the attributes or the metadata of a conversation have been
742
+ * updated. During conversation's creation and initialization, this event
743
+ * might be fired multiple times for same joined or created conversation as
744
+ * new data is arriving from different sources.
668
745
  *
669
746
  * Parameters:
670
- * 1. object `data` - info object provided with the event. It has the following properties:
747
+ * 1. object `data` - info object provided with the event. It has the
748
+ * following properties:
671
749
  * * {@link Conversation} `conversation` - the conversation in question
672
- * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons for the update
750
+ * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons
751
+ * for the update
673
752
  * @event
674
753
  */
675
754
  exports.Client.conversationUpdated = "conversationUpdated";
@@ -693,9 +772,11 @@ exports.Client.participantLeft = "participantLeft";
693
772
  * Fired when a participant's fields have been updated.
694
773
  *
695
774
  * Parameters:
696
- * 1. object `data` - info object provided with the event. It has the following properties:
775
+ * 1. object `data` - info object provided with the event. It has the
776
+ * following properties:
697
777
  * * {@link Participant} `participant` - the participant in question
698
- * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons for the update
778
+ * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons
779
+ * for the update
699
780
  * @event
700
781
  */
701
782
  exports.Client.participantUpdated = "participantUpdated";
@@ -719,9 +800,11 @@ exports.Client.messageRemoved = "messageRemoved";
719
800
  * Fired when the fields of an existing message are updated with new values.
720
801
  *
721
802
  * Parameters:
722
- * 1. object `data` - info object provided with the event. It has the following properties:
803
+ * 1. object `data` - info object provided with the event. It has the
804
+ * following properties:
723
805
  * * {@link Message} `message` - the message in question
724
- * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for the update
806
+ * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for
807
+ * the update
725
808
  * @event
726
809
  */
727
810
  exports.Client.messageUpdated = "messageUpdated";
@@ -754,10 +837,12 @@ exports.Client.typingEnded = "typingEnded";
754
837
  */
755
838
  exports.Client.typingStarted = "typingStarted";
756
839
  /**
757
- * Fired when the client has received (and parsed) a push notification via one of the push channels (apn or fcm).
840
+ * Fired when the client has received (and parsed) a push notification via one
841
+ * of the push channels (apn or fcm).
758
842
  *
759
843
  * Parameters:
760
- * 1. {@link PushNotification} `pushNotification` - the push notification in question
844
+ * 1. {@link PushNotification} `pushNotification` - the push notification in
845
+ * question
761
846
  * @event
762
847
  */
763
848
  exports.Client.pushNotification = "pushNotification";
@@ -778,12 +863,15 @@ exports.Client.userSubscribed = "userSubscribed";
778
863
  */
779
864
  exports.Client.userUnsubscribed = "userUnsubscribed";
780
865
  /**
781
- * Fired when the properties or the reachability status of a user have been updated.
866
+ * Fired when the properties or the reachability status of a user have been
867
+ * updated.
782
868
  *
783
869
  * Parameters:
784
- * 1. object `data` - info object provided with the event. It has the following properties:
870
+ * 1. object `data` - info object provided with the event. It has the
871
+ * following properties:
785
872
  * * {@link User} `user` - the user in question
786
- * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the update
873
+ * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the
874
+ * update
787
875
  * @event
788
876
  */
789
877
  exports.Client.userUpdated = "userUpdated";
@@ -791,14 +879,17 @@ exports.Client.userUpdated = "userUpdated";
791
879
  * Fired when the state of the client has been changed.
792
880
  *
793
881
  * Parameters:
794
- * 1. {@link State} `state` - the new client state
882
+ * 1. object `data` - info object provided with the event. It has the
883
+ * following properties:
884
+ * * {@link State} `state` - the new client state
885
+ * * Error? `error` - the initialization error if present
795
886
  * @event
796
887
  */
797
888
  exports.Client.stateChanged = "stateChanged";
798
889
  /**
799
890
  * Fired when the connection state of the client has been changed.
800
891
  *
801
- * Paremeters:
892
+ * Parameters:
802
893
  * 1. {@link ConnectionState} `state` - the new connection state
803
894
  * @event
804
895
  */
@@ -807,7 +898,8 @@ exports.Client.connectionStateChanged = "connectionStateChanged";
807
898
  * Fired when the connection is interrupted for an unexpected reason.
808
899
  *
809
900
  * Parameters:
810
- * 1. object `data` - info object provided with the event. It has the following properties:
901
+ * 1. object `data` - info object provided with the event. It has the
902
+ * following properties:
811
903
  * * boolean `terminal` - Twilsock will stop connection attempts if true
812
904
  * * string `message` - the error message of the root cause
813
905
  * * number? `httpStatusCode` - http status code if available
@@ -815,6 +907,32 @@ exports.Client.connectionStateChanged = "connectionStateChanged";
815
907
  * @event
816
908
  */
817
909
  exports.Client.connectionError = "connectionError";
910
+ /**
911
+ * Current version of the Conversations client.
912
+ */
913
+ exports.Client.version = _package.version;
914
+ /**
915
+ * Logger instance.
916
+ */
917
+ exports.Client._logger = logger.Logger.scope("Client");
918
+ /**
919
+ * Supported push notification channels.
920
+ */
921
+ exports.Client._supportedPushChannels = [
922
+ "fcm",
923
+ "apn",
924
+ ];
925
+ /**
926
+ * Supported push data fields.
927
+ */
928
+ exports.Client._supportedPushDataFields = {
929
+ conversation_sid: "conversationSid",
930
+ conversation_title: "conversationTitle",
931
+ message_sid: "messageSid",
932
+ message_index: "messageIndex",
933
+ media_count: "mediaCount",
934
+ media: "media", // object
935
+ };
818
936
  tslib_es6.__decorate([
819
937
  declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
820
938
  tslib_es6.__metadata("design:type", Function),
@@ -827,6 +945,12 @@ tslib_es6.__decorate([
827
945
  tslib_es6.__metadata("design:paramtypes", [String]),
828
946
  tslib_es6.__metadata("design:returntype", Promise)
829
947
  ], exports.Client.prototype, "getConversationBySid", null);
948
+ tslib_es6.__decorate([
949
+ declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
950
+ tslib_es6.__metadata("design:type", Function),
951
+ tslib_es6.__metadata("design:paramtypes", [String]),
952
+ tslib_es6.__metadata("design:returntype", Promise)
953
+ ], exports.Client.prototype, "peekConversationBySid", null);
830
954
  tslib_es6.__decorate([
831
955
  declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString),
832
956
  tslib_es6.__metadata("design:type", Function),