-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathmessageThreadSelector.ts
More file actions
417 lines (394 loc) · 15.6 KB
/
messageThreadSelector.ts
File metadata and controls
417 lines (394 loc) · 15.6 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import {
ChatBaseSelectorProps,
getChatMessages,
getIsLargeGroup,
getLatestReadTime,
getParticipants,
getReadReceipts,
getUserId
} from './baseSelectors';
import { toFlatCommunicationIdentifier } from '@internal/acs-ui-common';
import { ChatClientState, ChatMessageWithStatus, ResourceFetchResult } from '@internal/chat-stateful-client';
import { memoizeFnAll } from '@internal/acs-ui-common';
import {
ChatMessage,
Message,
CommunicationParticipant,
SystemMessage,
MessageContentType,
ReadReceiptsBySenderId
} from '@internal/react-components';
/* @conditional-compile-remove(data-loss-prevention) */
import { BlockedMessage } from '@internal/react-components';
import { createSelector } from 'reselect';
/* @conditional-compile-remove(data-loss-prevention) */
import { DEFAULT_DATA_LOSS_PREVENTION_POLICY_URL } from './utils/constants';
import { ACSKnownMessageType } from './utils/constants';
import { updateMessagesWithAttached } from './utils/updateMessagesWithAttached';
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
import { AttachmentMetadata } from '@internal/acs-ui-common';
import { ChatAttachment } from '@azure/communication-chat';
import type { ChatParticipant } from '@azure/communication-chat';
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
import { ChatAttachmentType } from '@internal/react-components';
const memoizedAllConvertChatMessage = memoizeFnAll(
(
_key: string,
chatMessage: ChatMessageWithStatus,
userId: string,
isSeen: boolean,
isLargeGroup: boolean
): Message => {
const messageType = chatMessage.type.toLowerCase();
/* @conditional-compile-remove(data-loss-prevention) */
if (chatMessage.policyViolation?.result === 'contentBlocked') {
return convertToUiBlockedMessage(chatMessage, userId, isSeen, isLargeGroup);
}
if (
messageType === ACSKnownMessageType.text ||
messageType === ACSKnownMessageType.richtextHtml ||
messageType === ACSKnownMessageType.html
) {
return convertToUiChatMessage(chatMessage, userId, isSeen, isLargeGroup);
} else {
return convertToUiSystemMessage(chatMessage);
}
}
);
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
const extractAttachmentMetadata = (metadata: Record<string, string>): AttachmentMetadata[] => {
const attachmentMetadata = metadata.fileSharingMetadata;
if (!attachmentMetadata) {
return [];
}
try {
return JSON.parse(attachmentMetadata);
} catch (e) {
console.error(e);
return [];
}
};
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
const extractTeamsAttachmentsMetadata = (
rawAttachments: ChatAttachment[]
): {
attachments: AttachmentMetadata[];
} => {
const attachments: AttachmentMetadata[] = [];
rawAttachments.forEach((rawAttachment) => {
const attachmentType = rawAttachment.attachmentType as ChatAttachmentType;
if (attachmentType === 'file') {
attachments.push({
id: rawAttachment.id,
name: rawAttachment.name ?? '',
url: extractAttachmentUrl(rawAttachment)
});
}
});
return {
attachments
};
};
/* @conditional-compile-remove(data-loss-prevention) */
const convertToUiBlockedMessage = (
message: ChatMessageWithStatus,
userId: string,
isSeen: boolean,
isLargeGroup: boolean
): BlockedMessage => {
const messageSenderId = message.sender !== undefined ? toFlatCommunicationIdentifier(message.sender) : userId;
return {
messageType: 'blocked',
createdOn: message.createdOn,
warningText: undefined,
status: !isLargeGroup && message.status === 'delivered' && isSeen ? 'seen' : message.status,
senderDisplayName: message.senderDisplayName,
senderId: messageSenderId,
messageId: message.id,
deletedOn: message.deletedOn,
mine: messageSenderId === userId,
link: DEFAULT_DATA_LOSS_PREVENTION_POLICY_URL
};
};
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
const extractAttachmentUrl = (attachment: ChatAttachment): string => {
return attachment.previewUrl ? attachment.previewUrl : attachment.url || '';
};
const processChatMessageContent = (message: ChatMessageWithStatus): string | undefined => {
let content = message.content?.message;
if (
message.content?.attachments &&
message.content?.attachments.length > 0 &&
sanitizedMessageContentType(message.type).includes('html')
) {
const attachments: ChatAttachment[] = message.content?.attachments;
// Fill in the src here
if (content) {
const document = new DOMParser().parseFromString(content ?? '', 'text/html');
document.querySelectorAll('img').forEach((img) => {
const attachmentPreviewUrl = attachments.find((attachment) => attachment.id === img.id)?.previewUrl;
if (attachmentPreviewUrl) {
const resourceCache = message.resourceCache?.[attachmentPreviewUrl];
const src = getResourceSourceUrl(resourceCache);
// if in error state
if (src === undefined) {
const brokenImageView = getBrokenImageViewNode(img);
img.parentElement?.replaceChild(brokenImageView, img);
} else {
// else in loading or success state
img.setAttribute('src', src);
}
setImageWidthAndHeight(img);
}
});
content = document.body.innerHTML;
}
const teamsImageHtmlContent = attachments
.filter(
(attachment) =>
attachment.attachmentType === 'image' &&
attachment.previewUrl !== undefined &&
!message.content?.message?.includes(attachment.id)
)
.map((attachment) => generateImageAttachmentImgHtml(message, attachment))
.join('');
if (teamsImageHtmlContent) {
return (content ?? '') + teamsImageHtmlContent;
}
}
return content;
};
const generateImageAttachmentImgHtml = (message: ChatMessageWithStatus, attachment: ChatAttachment): string => {
if (attachment.previewUrl !== undefined) {
const contentType = extractAttachmentContentTypeFromName(attachment.name);
const resourceCache = message.resourceCache?.[attachment.previewUrl];
const src = getResourceSourceUrl(resourceCache);
// if in error state
if (src === undefined) {
return `\r\n<p>${getBrokenImageViewNode()}</p>`;
}
// else in loading or success state
return `\r\n<p><img alt="image" src="${src}" itemscope="${contentType}" id="${attachment.id}"></p>`;
}
return '';
};
const getResourceSourceUrl = (result?: ResourceFetchResult): string | undefined => {
if (result) {
if (!result.error && result.sourceUrl) {
// return sourceUrl for success state
return result.sourceUrl;
} else {
// return undefined for error state
return undefined;
}
}
// return empty string for loading state
return '';
};
const extractAttachmentContentTypeFromName = (name?: string): string => {
if (name === undefined) {
return '';
}
const indexOfLastDot = name.lastIndexOf('.');
if (indexOfLastDot === undefined || indexOfLastDot < 0) {
return '';
}
const contentType = name.substring(indexOfLastDot + 1);
return contentType;
};
const setImageWidthAndHeight = (img?: HTMLImageElement): void => {
if (img) {
// define aspect ratio explicitly to prevent image not being displayed correctly
// in safari, this includes image placeholder for loading state
const width = img.width;
const height = img.height;
img.style.aspectRatio = `${width}/${height}`;
}
};
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
const extractAttachmentsMetadata = (message: ChatMessageWithStatus): { attachments?: AttachmentMetadata[] } => {
let attachments: AttachmentMetadata[] = [];
if (message.metadata) {
attachments = attachments.concat(extractAttachmentMetadata(message.metadata));
}
if (message.content?.attachments) {
const teamsAttachments = extractTeamsAttachmentsMetadata(message.content?.attachments);
attachments = attachments.concat(teamsAttachments.attachments);
}
return { attachments: attachments.length > 0 ? attachments : undefined };
};
const convertToUiChatMessage = (
message: ChatMessageWithStatus,
userId: string,
isSeen: boolean,
isLargeGroup: boolean
): ChatMessage => {
const messageSenderId = message.sender !== undefined ? toFlatCommunicationIdentifier(message.sender) : userId;
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
const { attachments } = extractAttachmentsMetadata(message);
return {
messageType: 'chat',
createdOn: message.createdOn,
content: processChatMessageContent(message),
contentType: sanitizedMessageContentType(message.type),
status: !isLargeGroup && message.status === 'delivered' && isSeen ? 'seen' : message.status,
senderDisplayName: message.senderDisplayName,
senderId: messageSenderId,
messageId: message.id,
clientMessageId: message.clientMessageId,
editedOn: message.editedOn,
deletedOn: message.deletedOn,
mine: messageSenderId === userId,
metadata: message.metadata,
/* @conditional-compile-remove(file-sharing-teams-interop) @conditional-compile-remove(file-sharing-acs) */
attachments
};
};
const convertToUiSystemMessage = (message: ChatMessageWithStatus): SystemMessage => {
const systemMessageType = message.type;
if (systemMessageType === 'participantAdded' || systemMessageType === 'participantRemoved') {
return {
messageType: 'system',
systemMessageType,
createdOn: message.createdOn,
participants:
message.content?.participants
// TODO: In our moderator logic, we use undefined name as our displayName for moderator, which should be filtered out
// Once we have a better solution to identify the moderator, remove this line
?.filter((participant: ChatParticipant) => participant.displayName && participant.displayName !== '')
.map(
(participant: ChatParticipant): CommunicationParticipant => ({
userId: toFlatCommunicationIdentifier(participant.id),
displayName: participant.displayName
})
) ?? [],
messageId: message.id,
iconName: systemMessageType === 'participantAdded' ? 'PeopleAdd' : 'PeopleBlock'
};
} else {
// Only topic updated type left, according to ACSKnown type
return {
messageType: 'system',
systemMessageType: 'topicUpdated',
createdOn: message.createdOn,
topic: message.content?.topic ?? '',
messageId: message.id,
iconName: 'Edit'
};
}
};
/**
* Selector type for {@link MessageThread} component.
*
* @public
*/
export type MessageThreadSelector = (
state: ChatClientState,
props: ChatBaseSelectorProps
) => {
userId: string;
showMessageStatus: boolean;
messages: Message[];
};
/** Returns `true` if the message has participants and at least one participant has a display name. */
const hasValidParticipant = (chatMessage: ChatMessageWithStatus): boolean =>
!!chatMessage.content?.participants && chatMessage.content.participants.some((p: ChatParticipant) => !!p.displayName);
/**
*
* @private
*/
export const messageThreadSelectorWithThread: () => MessageThreadSelector = () =>
createSelector(
[getUserId, getChatMessages, getLatestReadTime, getIsLargeGroup, getReadReceipts, getParticipants],
(userId, chatMessages, latestReadTime, isLargeGroup, readReceipts, participants) => {
// We can't get displayName in teams meeting interop for now, disable rr feature when it is teams interop
const isTeamsInterop = Object.values(participants).find((p) => 'microsoftTeamsUserId' in p.id) !== undefined;
// get number of participants
// filter out the non valid participants (no display name)
// Read Receipt details will be disabled when participant count is 0
const participantCount = isTeamsInterop
? undefined
: Object.values(participants).filter((p) => p.displayName && p.displayName !== '').length;
// creating key value pairs of senderID: last read message information
const readReceiptsBySenderId: ReadReceiptsBySenderId = {};
// readReceiptsBySenderId[senderID] gets updated every time a new message is read by this sender
// in this way we can make sure that we are only saving the latest read message id and read on time for each sender
readReceipts
.filter((r) => r.sender && toFlatCommunicationIdentifier(r.sender) !== userId)
.forEach((r) => {
readReceiptsBySenderId[toFlatCommunicationIdentifier(r.sender)] = {
lastReadMessage: r.chatMessageId,
displayName: participants[toFlatCommunicationIdentifier(r.sender)]?.displayName ?? ''
};
});
// A function takes parameter above and generate return value
const convertedMessages = memoizedAllConvertChatMessage((memoizedFn) =>
Object.values(chatMessages)
.filter(
(message) =>
message.type.toLowerCase() === ACSKnownMessageType.text ||
message.type.toLowerCase() === ACSKnownMessageType.richtextHtml ||
message.type.toLowerCase() === ACSKnownMessageType.html ||
(message.type === ACSKnownMessageType.participantAdded && hasValidParticipant(message)) ||
(message.type === ACSKnownMessageType.participantRemoved && hasValidParticipant(message)) ||
// TODO: Add support for topicUpdated system messages in MessageThread component.
// message.type === ACSKnownMessageType.topicUpdated ||
message.clientMessageId !== undefined
)
.filter(isMessageValidToRender)
.map((message) => {
return memoizedFn(
message.id ?? message.clientMessageId,
message,
userId,
message.createdOn <= latestReadTime,
isLargeGroup
);
})
);
updateMessagesWithAttached(convertedMessages);
return {
userId,
showMessageStatus: true,
messages: convertedMessages,
participantCount,
readReceiptsBySenderId
};
}
);
const sanitizedMessageContentType = (type: string): MessageContentType => {
const lowerCaseType = type.toLowerCase();
return lowerCaseType === 'text' || lowerCaseType === 'html' || lowerCaseType === 'richtext/html'
? lowerCaseType
: 'unknown';
};
const getBrokenImageViewNode = (img?: HTMLDivElement): HTMLDivElement => {
const wrapper = document.createElement('div');
Array.from(img?.attributes ?? []).forEach((attr) => {
wrapper.setAttribute(attr.nodeName, attr.nodeValue ?? '');
});
wrapper.setAttribute('class', 'broken-image-wrapper');
wrapper.setAttribute('data-ui-id', 'broken-image-icon');
return wrapper;
};
const isMessageValidToRender = (message: ChatMessageWithStatus): boolean => {
if (message.deletedOn) {
return false;
}
if (message.metadata?.fileSharingMetadata || message.content?.attachments?.length) {
return true;
}
/* @conditional-compile-remove(data-loss-prevention) */
if (message.policyViolation?.result === 'contentBlocked') {
return true;
}
return !!(message.content && message.content?.message !== '');
};
/**
* Selector for {@link MessageThread} component.
*
* @public
*/
export const messageThreadSelector: MessageThreadSelector = messageThreadSelectorWithThread();