-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathAzureCommunicationChatAdapter.ts
More file actions
738 lines (652 loc) · 26.8 KB
/
AzureCommunicationChatAdapter.ts
File metadata and controls
738 lines (652 loc) · 26.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import {
_createStatefulChatClientInner,
ChatClientState,
ChatError,
StatefulChatClient
} from '@internal/chat-stateful-client';
import { ChatHandlers, createDefaultChatHandlers } from '@internal/chat-component-bindings';
import { ChatMessage, ChatMessageType, ChatThreadClient, SendMessageOptions } from '@azure/communication-chat';
import { CommunicationTokenCredential, CommunicationUserIdentifier } from '@azure/communication-common';
import type {
ChatMessageDeletedEvent,
ChatMessageEditedEvent,
ChatMessageReceivedEvent,
ChatThreadPropertiesUpdatedEvent,
ParticipantsAddedEvent,
ParticipantsRemovedEvent,
ReadReceiptReceivedEvent
} from '@azure/communication-chat';
import { toFlatCommunicationIdentifier, _TelemetryImplementationHint } from '@internal/acs-ui-common';
import EventEmitter from 'events';
import {
ChatAdapter,
ChatAdapterState,
MessageDeletedListener,
MessageEditedListener,
MessageReadListener,
MessageReceivedListener,
ParticipantsAddedListener,
ParticipantsRemovedListener,
TopicChangedListener
} from './ChatAdapter';
import { AdapterError } from '../../common/adapters';
/* @conditional-compile-remove(file-sharing) */
import { FileUploadAdapter, convertFileUploadsUiStateToMessageMetadata } from './AzureCommunicationFileUploadAdapter';
/* @conditional-compile-remove(file-sharing) */
import { AzureCommunicationFileUploadAdapter } from './AzureCommunicationFileUploadAdapter';
import { useEffect, useRef, useState } from 'react';
import { _isValidIdentifier } from '@internal/acs-ui-common';
import { AttachmentDownloadResult } from '@internal/react-components';
/* @conditional-compile-remove(file-sharing) */
import { AttachmentMetadata } from '@internal/react-components';
/* @conditional-compile-remove(file-sharing) */
import { FileUploadManager } from '../file-sharing';
/**
* Context of Chat, which is a centralized context for all state updates
* @private
*/
export class ChatContext {
private emitter: EventEmitter = new EventEmitter();
private state: ChatAdapterState;
private threadId: string;
constructor(clientState: ChatClientState, threadId: string) {
const thread = clientState.threads[threadId];
this.threadId = threadId;
if (!thread) {
throw 'Cannot find threadId, please initialize thread before use!';
}
this.state = {
userId: clientState.userId,
displayName: clientState.displayName,
thread,
latestErrors: clientState.latestErrors
};
}
public onStateChange(handler: (_uiState: ChatAdapterState) => void): void {
this.emitter.on('stateChanged', handler);
}
public offStateChange(handler: (_uiState: ChatAdapterState) => void): void {
this.emitter.off('stateChanged', handler);
}
public setState(state: ChatAdapterState): void {
this.state = state;
this.emitter.emit('stateChanged', this.state);
}
public getState(): ChatAdapterState {
return this.state;
}
public setError(error: Error): void {
this.setState({ ...this.state, error });
}
public updateClientState(clientState: ChatClientState): void {
const thread = clientState.threads[this.threadId];
if (!thread) {
throw 'Cannot find threadId, please make sure thread state is still in Stateful ChatClient.';
}
let updatedState: ChatAdapterState = {
userId: clientState.userId,
displayName: clientState.displayName,
thread,
latestErrors: clientState.latestErrors
};
/* @conditional-compile-remove(file-sharing) */
updatedState = { ...updatedState, fileUploads: this.state.fileUploads };
this.setState(updatedState);
}
}
/**
* @private
*/
export class AzureCommunicationChatAdapter implements ChatAdapter {
private chatClient: StatefulChatClient;
private chatThreadClient: ChatThreadClient;
private context: ChatContext;
private credential?: CommunicationTokenCredential = undefined;
/* @conditional-compile-remove(file-sharing) */
private fileUploadAdapter: FileUploadAdapter;
private handlers: ChatHandlers;
private emitter: EventEmitter = new EventEmitter();
constructor(
chatClient: StatefulChatClient,
chatThreadClient: ChatThreadClient,
options?: {
credential?: CommunicationTokenCredential;
}
) {
this.bindAllPublicMethods();
this.chatClient = chatClient;
this.chatThreadClient = chatThreadClient;
this.context = new ChatContext(chatClient.getState(), chatThreadClient.threadId);
if (options && options.credential) {
this.credential = options.credential;
}
/* @conditional-compile-remove(file-sharing) */
this.fileUploadAdapter = new AzureCommunicationFileUploadAdapter(this.context);
const onStateChange = (clientState: ChatClientState): void => {
// unsubscribe when the instance gets disposed
if (!this) {
chatClient.offStateChange(onStateChange);
return;
}
this.context.updateClientState(clientState);
};
this.handlers = createDefaultChatHandlers(chatClient, chatThreadClient);
this.chatClient.onStateChange(onStateChange);
this.subscribeAllEvents();
}
private bindAllPublicMethods(): void {
this.onStateChange = this.onStateChange.bind(this);
this.offStateChange = this.offStateChange.bind(this);
this.getState = this.getState.bind(this);
this.dispose = this.dispose.bind(this);
this.fetchInitialData = this.fetchInitialData.bind(this);
this.sendMessage = this.sendMessage.bind(this);
this.sendReadReceipt = this.sendReadReceipt.bind(this);
this.sendTypingIndicator = this.sendTypingIndicator.bind(this);
this.updateMessage = this.updateMessage.bind(this);
this.deleteMessage = this.deleteMessage.bind(this);
this.removeParticipant = this.removeParticipant.bind(this);
this.setTopic = this.setTopic.bind(this);
this.loadPreviousChatMessages = this.loadPreviousChatMessages.bind(this);
this.on = this.on.bind(this);
this.off = this.off.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.registerActiveFileUploads = this.registerActiveFileUploads.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.registerCompletedFileUploads = this.registerCompletedFileUploads.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.clearFileUploads = this.clearFileUploads.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.cancelFileUpload = this.cancelFileUpload.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.updateFileUploadProgress = this.updateFileUploadProgress.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.updateFileUploadErrorMessage = this.updateFileUploadErrorMessage.bind(this);
/* @conditional-compile-remove(file-sharing) */
this.updateFileUploadMetadata = this.updateFileUploadMetadata.bind(this);
this.downloadAttachments = this.downloadAttachments.bind(this);
}
dispose(): void {
this.unsubscribeAllEvents();
}
async fetchInitialData(): Promise<void> {
// If get properties fails we dont want to try to get the participants after.
await this.asyncTeeErrorToEventEmitter(async () => {
await this.chatThreadClient.getProperties();
// Fetch all participants who joined before the local user.
for await (const _page of this.chatThreadClient.listParticipants().byPage({
// Fetch 100 participants per page by default.
maxPageSize: 100
// eslint-disable-next-line curly
}));
});
}
getState(): ChatAdapterState {
return this.context.getState();
}
onStateChange(handler: (state: ChatAdapterState) => void): void {
this.context.onStateChange(handler);
}
offStateChange(handler: (state: ChatAdapterState) => void): void {
this.context.offStateChange(handler);
}
async sendMessage(content: string, options: SendMessageOptions = {}): Promise<void> {
await this.asyncTeeErrorToEventEmitter(async () => {
/* @conditional-compile-remove(file-sharing) */
options.metadata = {
...options.metadata,
...convertFileUploadsUiStateToMessageMetadata(this.context.getState().fileUploads)
};
/* @conditional-compile-remove(file-sharing) */
/**
* All the current uploads need to be clear from the state before a message has been sent.
* This ensures the following behavior:
* 1. File Upload cards are removed from sendbox at the same time text in sendbox is removed.
* 2. any component rendering these file uploads doesn't continue to do so.
* 3. Cleans the state for new file uploads with a fresh message.
*/
this.fileUploadAdapter.clearFileUploads();
await this.handlers.onSendMessage(content, options);
});
}
async sendReadReceipt(chatMessageId: string): Promise<void> {
await this.asyncTeeErrorToEventEmitter(async () => {
await this.handlers.onMessageSeen(chatMessageId);
});
}
async sendTypingIndicator(): Promise<void> {
await this.asyncTeeErrorToEventEmitter(async () => {
await this.handlers.onTyping();
});
}
async removeParticipant(userId: string): Promise<void> {
await this.asyncTeeErrorToEventEmitter(async () => {
await this.handlers.onRemoveParticipant(userId);
});
}
async setTopic(topicName: string): Promise<void> {
await this.asyncTeeErrorToEventEmitter(async () => {
await this.handlers.updateThreadTopicName(topicName);
});
}
async loadPreviousChatMessages(messagesToLoad: number): Promise<boolean> {
return await this.asyncTeeErrorToEventEmitter(async () => {
return await this.handlers.onLoadPreviousChatMessages(messagesToLoad);
});
}
async updateMessage(
messageId: string,
content: string,
metadata?: Record<string, string>,
options?: {
/* @conditional-compile-remove(file-sharing) */
attachmentMetadata?: AttachmentMetadata[];
}
): Promise<void> {
return await this.asyncTeeErrorToEventEmitter(async () => {
/* @conditional-compile-remove(file-sharing) */
const updatedOptions = options ? { attachmentMetadata: options.attachmentMetadata, metadata: metadata } : {};
/* @conditional-compile-remove(file-sharing) */
return await this.handlers.onUpdateMessage(messageId, content, updatedOptions);
return await this.handlers.onUpdateMessage(messageId, content);
});
}
async deleteMessage(messageId: string): Promise<void> {
return await this.asyncTeeErrorToEventEmitter(async () => {
return await this.handlers.onDeleteMessage(messageId);
});
}
/* @conditional-compile-remove(file-sharing) */
registerActiveFileUploads(files: File[]): FileUploadManager[] {
return this.fileUploadAdapter.registerActiveFileUploads(files);
}
/* @conditional-compile-remove(file-sharing) */
registerCompletedFileUploads(metadata: AttachmentMetadata[]): FileUploadManager[] {
return this.fileUploadAdapter.registerCompletedFileUploads(metadata);
}
/* @conditional-compile-remove(file-sharing) */
clearFileUploads(): void {
this.fileUploadAdapter.clearFileUploads();
}
/* @conditional-compile-remove(file-sharing) */
cancelFileUpload(id: string): void {
this.fileUploadAdapter.cancelFileUpload(id);
}
/* @conditional-compile-remove(file-sharing) */
updateFileUploadProgress(id: string, progress: number): void {
this.fileUploadAdapter.updateFileUploadProgress(id, progress);
}
/* @conditional-compile-remove(file-sharing) */
updateFileUploadErrorMessage(id: string, errorMessage: string): void {
this.fileUploadAdapter.updateFileUploadErrorMessage(id, errorMessage);
}
/* @conditional-compile-remove(file-sharing) */
updateFileUploadMetadata(id: string, metadata: AttachmentMetadata): void {
this.fileUploadAdapter.updateFileUploadMetadata(id, metadata);
}
async downloadAttachments(options: { attachmentUrls: Record<string, string> }): Promise<AttachmentDownloadResult[]> {
return this.asyncTeeErrorToEventEmitter(async () => {
if (this.credential === undefined) {
const e = new Error();
e['target'] = 'ChatThreadClient.getMessage';
e['innerError'] = new Error('AccessToken is null');
throw e;
}
const accessToken = await this.credential.getToken();
if (!accessToken) {
const e = new Error();
e['target'] = 'ChatThreadClient.getMessage';
e['innerError'] = new Error('AccessToken is null');
throw e;
}
return this.downloadAuthenticatedFile(accessToken.token, options);
});
}
private async downloadAuthenticatedFile(
accessToken: string,
options: { attachmentUrls: Record<string, string> }
): Promise<AttachmentDownloadResult[]> {
async function fetchWithAuthentication(url: string, token: string): Promise<Response> {
const headers = new Headers();
headers.append('Authorization', `Bearer ${token}`);
try {
return await fetch(url, { headers });
} catch (err) {
const e = new Error();
e['target'] = 'ChatThreadClient.getMessage';
e['innerError'] = err;
throw e;
}
}
const attachmentDownloadResults: AttachmentDownloadResult[] = [];
for (const id in options.attachmentUrls) {
const response = await fetchWithAuthentication(options.attachmentUrls[id], accessToken);
const blob = await response.blob();
attachmentDownloadResults.push({ attachmentId: id, blobUrl: URL.createObjectURL(blob) });
}
return attachmentDownloadResults;
}
private messageReceivedListener(event: ChatMessageReceivedEvent): void {
const isCurrentChatAdapterThread = event.threadId === this.chatThreadClient.threadId;
if (!isCurrentChatAdapterThread) {
return;
}
const message = convertEventToChatMessage(event);
this.emitter.emit('messageReceived', { message });
const currentUserId = toFlatCommunicationIdentifier(this.chatClient.getState().userId);
if (message?.sender && toFlatCommunicationIdentifier(message.sender) === currentUserId) {
this.emitter.emit('messageSent', { message });
}
}
private messageEditedListener(event: ChatMessageEditedEvent): void {
const isCurrentChatAdapterThread = event.threadId === this.chatThreadClient.threadId;
if (!isCurrentChatAdapterThread) {
return;
}
const message = convertEventToChatMessage(event);
this.emitter.emit('messageEdited', { message, editedOn: event.editedOn });
}
private messageDeletedListener(event: ChatMessageDeletedEvent): void {
const isCurrentChatAdapterThread = event.threadId === this.chatThreadClient.threadId;
if (!isCurrentChatAdapterThread) {
return;
}
const message = convertEventToChatMessage(event);
this.emitter.emit('messageDeleted', { message });
}
private messageReadListener({ chatMessageId, recipient }: ReadReceiptReceivedEvent): void {
const message = this.getState().thread.chatMessages[chatMessageId];
if (message) {
this.emitter.emit('messageRead', { message, readBy: recipient });
}
}
private participantsAddedListener({ addedBy, participantsAdded }: ParticipantsAddedEvent): void {
this.emitter.emit('participantsAdded', { addedBy, participantsAdded });
}
private participantsRemovedListener({ removedBy, participantsRemoved }: ParticipantsRemovedEvent): void {
this.emitter.emit('participantsRemoved', { removedBy, participantsRemoved });
}
private chatThreadPropertiesUpdatedListener(event: ChatThreadPropertiesUpdatedEvent): void {
this.emitter.emit('topicChanged', { topic: event.properties.topic });
}
private subscribeAllEvents(): void {
this.chatClient.on('chatThreadPropertiesUpdated', this.chatThreadPropertiesUpdatedListener.bind(this));
this.chatClient.on('participantsAdded', this.participantsAddedListener.bind(this));
this.chatClient.on('participantsRemoved', this.participantsRemovedListener.bind(this));
this.chatClient.on('chatMessageReceived', this.messageReceivedListener.bind(this));
this.chatClient.on('chatMessageEdited', this.messageEditedListener.bind(this));
this.chatClient.on('chatMessageDeleted', this.messageDeletedListener.bind(this));
this.chatClient.on('readReceiptReceived', this.messageReadListener.bind(this));
this.chatClient.on('participantsRemoved', this.participantsRemovedListener.bind(this));
}
private unsubscribeAllEvents(): void {
this.chatClient.off('chatThreadPropertiesUpdated', this.chatThreadPropertiesUpdatedListener.bind(this));
this.chatClient.off('participantsAdded', this.participantsAddedListener.bind(this));
this.chatClient.off('participantsRemoved', this.participantsRemovedListener.bind(this));
this.chatClient.off('chatMessageReceived', this.messageReceivedListener.bind(this));
this.chatClient.off('chatMessageEdited', this.messageEditedListener.bind(this));
this.chatClient.off('chatMessageDeleted', this.messageDeletedListener.bind(this));
this.chatClient.off('readReceiptReceived', this.messageReadListener.bind(this));
this.chatClient.off('participantsRemoved', this.participantsRemovedListener.bind(this));
}
on(event: 'messageReceived', listener: MessageReceivedListener): void;
on(event: 'messageEdited', listener: MessageEditedListener): void;
on(event: 'messageDeleted', listener: MessageDeletedListener): void;
on(event: 'messageSent', listener: MessageReceivedListener): void;
on(event: 'messageRead', listener: MessageReadListener): void;
on(event: 'participantsAdded', listener: ParticipantsAddedListener): void;
on(event: 'participantsRemoved', listener: ParticipantsRemovedListener): void;
on(event: 'topicChanged', listener: TopicChangedListener): void;
on(event: 'error', listener: (e: AdapterError) => void): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
on(event: string, listener: (e: any) => void): void {
this.emitter.on(event, listener);
}
off(event: 'messageReceived', listener: MessageReceivedListener): void;
off(event: 'messageEdited', listener: MessageEditedListener): void;
off(event: 'messageDeleted', listener: MessageDeletedListener): void;
off(event: 'messageSent', listener: MessageReceivedListener): void;
off(event: 'messageRead', listener: MessageReadListener): void;
off(event: 'participantsAdded', listener: ParticipantsAddedListener): void;
off(event: 'participantsRemoved', listener: ParticipantsRemovedListener): void;
off(event: 'topicChanged', listener: TopicChangedListener): void;
off(event: 'error', listener: (e: AdapterError) => void): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
off(event: string, listener: (e: any) => void): void {
this.emitter.off(event, listener);
}
private async asyncTeeErrorToEventEmitter<T>(f: () => Promise<T>): Promise<T> {
try {
return await f();
} catch (error) {
if (isChatError(error as Error)) {
this.emitter.emit('error', error as AdapterError);
}
throw error;
}
}
}
const convertEventToChatMessage = (
event: ChatMessageReceivedEvent | ChatMessageEditedEvent | ChatMessageDeletedEvent
): ChatMessage => {
return {
id: event.id,
version: event.version,
content: isChatMessageDeletedEvent(event) ? undefined : { message: event.message },
type: convertEventType(event.type),
sender: event.sender,
senderDisplayName: event.senderDisplayName,
sequenceId: '',
createdOn: new Date(event.createdOn),
editedOn: isChatMessageEditedEvent(event) ? event.editedOn : undefined,
deletedOn: isChatMessageDeletedEvent(event) ? event.deletedOn : undefined
};
};
const isChatMessageEditedEvent = (
event: ChatMessageReceivedEvent | ChatMessageEditedEvent | ChatMessageDeletedEvent
): event is ChatMessageEditedEvent => {
return event['editedOn'] !== undefined;
};
const isChatMessageDeletedEvent = (
event: ChatMessageReceivedEvent | ChatMessageEditedEvent | ChatMessageDeletedEvent
): event is ChatMessageDeletedEvent => {
return event['deletedOn'] !== undefined;
};
// only text/html message type will be received from event
const convertEventType = (type: string): ChatMessageType => {
const lowerCaseType = type.toLowerCase();
if (lowerCaseType === 'richtext/html' || lowerCaseType === 'html') {
return 'html';
} else {
return 'text';
}
};
/**
* Configuration options to include when creating AzureCommunicationChatAdapter.
*
* @public
*/
export type AzureCommunicationChatAdapterOptions = {
credential?: CommunicationTokenCredential;
};
/**
* Arguments for creating the Azure Communication Services implementation of {@link ChatAdapter}.
*
* @public
*/
export type AzureCommunicationChatAdapterArgs = {
endpoint: string;
userId: CommunicationUserIdentifier;
displayName: string;
credential: CommunicationTokenCredential;
threadId: string;
};
/**
* Create a {@link ChatAdapter} backed by Azure Communication Services.
*
* This is the default implementation of {@link ChatAdapter} provided by this library.
*
* @public
*/
export const createAzureCommunicationChatAdapter = async ({
endpoint: endpointUrl,
userId,
displayName,
credential,
threadId
}: AzureCommunicationChatAdapterArgs): Promise<ChatAdapter> => {
return _createAzureCommunicationChatAdapterInner(endpointUrl, userId, displayName, credential, threadId);
};
/**
* This inner function is used to allow injection of TelemetryImplementationHint without changing the public API.
*
* @internal
*/
export const _createAzureCommunicationChatAdapterInner = async (
endpoint: string,
userId: CommunicationUserIdentifier,
displayName: string,
credential: CommunicationTokenCredential,
threadId: string,
telemetryImplementationHint: _TelemetryImplementationHint = 'Chat'
): Promise<ChatAdapter> => {
if (!_isValidIdentifier(userId)) {
throw new Error('Provided userId is invalid. Please provide valid identifier object.');
}
const chatClient = _createStatefulChatClientInner(
{
userId,
displayName,
endpoint,
credential
},
undefined,
telemetryImplementationHint
);
const chatThreadClient = await chatClient.getChatThreadClient(threadId);
await chatClient.startRealtimeNotifications();
const options = { credential: credential };
const adapter = await createAzureCommunicationChatAdapterFromClient(chatClient, chatThreadClient, options);
return adapter;
};
/**
* A custom React hook to simplify the creation of {@link ChatAdapter}.
*
* Similar to {@link createAzureCommunicationChatAdapter}, but takes care of asynchronous
* creation of the adapter internally.
*
* Allows arguments to be undefined so that you can respect the rule-of-hooks and pass in arguments
* as they are created. The adapter is only created when all arguments are defined.
*
* Note that you must memoize the arguments to avoid recreating adapter on each render.
* See storybook for typical usage examples.
*
* @public
*/
export const useAzureCommunicationChatAdapter = (
/**
* Arguments to be passed to {@link createAzureCommunicationChatAdapter}.
*
* Allows arguments to be undefined so that you can respect the rule-of-hooks and pass in arguments
* as they are created. The adapter is only created when all arguments are defined.
*/
args: Partial<AzureCommunicationChatAdapterArgs>,
/**
* Optional callback to modify the adapter once it is created.
*
* If set, must return the modified adapter.
*/
afterCreate?: (adapter: ChatAdapter) => Promise<ChatAdapter>,
/**
* Optional callback called before the adapter is disposed.
*
* This is useful for clean up tasks, e.g., leaving any ongoing calls.
*/
beforeDispose?: (adapter: ChatAdapter) => Promise<void>
): ChatAdapter | undefined => {
const { credential, displayName, endpoint, threadId, userId } = args;
// State update needed to rerender the parent component when a new adapter is created.
const [adapter, setAdapter] = useState<ChatAdapter | undefined>(undefined);
// Ref needed for cleanup to access the old adapter created asynchronously.
const adapterRef = useRef<ChatAdapter | undefined>(undefined);
const afterCreateRef = useRef<((adapter: ChatAdapter) => Promise<ChatAdapter>) | undefined>(undefined);
const beforeDisposeRef = useRef<((adapter: ChatAdapter) => Promise<void>) | undefined>(undefined);
// These refs are updated on *each* render, so that the latest values
// are used in the `useEffect` closures below.
// Using a Ref ensures that new values for the callbacks do not trigger the
// useEffect blocks, and a new adapter creation / distruction is not triggered.
afterCreateRef.current = afterCreate;
beforeDisposeRef.current = beforeDispose;
useEffect(
() => {
if (!credential || !displayName || !endpoint || !threadId || !userId) {
return;
}
(async () => {
if (adapterRef.current) {
// Dispose the old adapter when a new one is created.
//
// This clean up function uses `adapterRef` because `adapter` can not be added to the dependency array of
// this `useEffect` -- we do not want to trigger a new adapter creation because of the first adapter
// creation.
if (beforeDisposeRef.current) {
await beforeDisposeRef.current(adapterRef.current);
}
adapterRef.current.dispose();
adapterRef.current = undefined;
}
let newAdapter = await createAzureCommunicationChatAdapter({
credential,
displayName,
endpoint,
threadId,
userId
});
if (afterCreateRef.current) {
newAdapter = await afterCreateRef.current(newAdapter);
}
adapterRef.current = newAdapter;
setAdapter(newAdapter);
})();
},
// Explicitly list all arguments so that caller doesn't have to memoize the `args` object.
[adapterRef, afterCreateRef, beforeDisposeRef, credential, displayName, endpoint, threadId, userId]
);
// Dispose any existing adapter when the component unmounts.
useEffect(() => {
return () => {
(async () => {
if (adapterRef.current) {
if (beforeDisposeRef.current) {
await beforeDisposeRef.current(adapterRef.current);
}
adapterRef.current.dispose();
adapterRef.current = undefined;
}
})();
};
}, []);
return adapter;
};
/**
* Create a {@link ChatAdapter} using the provided {@link StatefulChatClient}.
*
* Useful if you want to keep a reference to {@link StatefulChatClient}.
* Consider using {@link createAzureCommunicationChatAdapter} for a simpler API.
*
* @public
*/
export async function createAzureCommunicationChatAdapterFromClient(
chatClient: StatefulChatClient,
chatThreadClient: ChatThreadClient,
options?: {
credential?: CommunicationTokenCredential;
}
): Promise<ChatAdapter> {
return new AzureCommunicationChatAdapter(chatClient, chatThreadClient, options);
}
const isChatError = (e: Error): e is ChatError => {
return e['target'] !== undefined && e['innerError'] !== undefined;
};