-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathSessionConversation.tsx
More file actions
705 lines (623 loc) · 22.2 KB
/
SessionConversation.tsx
File metadata and controls
705 lines (623 loc) · 22.2 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
import _ from 'lodash';
import clsx from 'clsx';
import autoBind from 'auto-bind';
import { blobToArrayBuffer } from 'blob-util';
import { Component, RefObject, createRef } from 'react';
import styled from 'styled-components';
import { getAppDispatch } from '../../state/dispatch';
import {
CompositionBox,
SendMessageType,
StagedAttachmentType,
} from './composition/CompositionBox';
import { SessionMessagesListContainer } from './SessionMessagesListContainer';
import { SessionFileDropzone } from './SessionFileDropzone';
import { Data } from '../../data/data';
import { markAllReadByConvoId } from '../../interactions/conversationInteractions';
import { MAX_ATTACHMENT_FILESIZE_BYTES } from '../../session/constants';
import { ConvoHub } from '../../session/conversations';
import { ToastUtils } from '../../session/utils';
import {
ReduxConversationType,
SortedMessageModelProps,
openConversationToSpecificMessage,
quoteMessage,
resetSelectedMessageIds,
updateMentionsMembers,
} from '../../state/ducks/conversations';
import { updateConfirmModal } from '../../state/ducks/modalDialog';
import { addStagedAttachmentsInConversation } from '../../state/ducks/stagedAttachments';
import { MIME } from '../../types';
import {
THUMBNAIL_CONTENT_TYPE,
getAudioDuration,
getVideoDuration,
makeImageThumbnailBuffer,
makeVideoScreenshot,
} from '../../types/attachments/VisualAttachment';
import { AttachmentUtil, GoogleChrome, arrayBufferToObjectURL } from '../../util';
import { getCurrentRecoveryPhrase } from '../../util/storage';
import { EmptyMessageView } from '../EmptyMessageView';
import { SplitViewContainer } from '../SplitViewContainer';
import { SessionButtonColor } from '../basic/SessionButton';
import { InConversationCallContainer } from '../calling/InConversationCallContainer';
import { ConversationHeaderWithDetails } from './header/ConversationHeader';
import { isAudio } from '../../types/MIME';
import { NoticeBanner } from '../NoticeBanner';
import { SessionSpinner } from '../loading';
import { ConversationMessageRequestButtons } from './MessageRequestButtons';
import { RightPanel } from './right-panel/RightPanel';
import { HTMLDirection } from '../../util/i18n/rtlSupport';
import { showLinkVisitWarningDialog } from '../dialog/OpenUrlModal';
import { InvitedToGroup, NoMessageInConversation } from './SubtleNotification';
import { PubKey } from '../../session/types';
import { isUsAnySogsFromCache } from '../../session/apis/open_group_api/sogsv3/knownBlindedkeys';
import { tr } from '../../localization/localeTools';
import {
useConversationIsExpired03Group,
useSelectedConversationKey,
useSelectedIsPrivate,
useSelectedIsPublic,
useSelectedWeAreAdmin,
} from '../../state/selectors/selectedConversation';
import { LUCIDE_ICONS_UNICODE } from '../icon/lucide';
import { sleepFor } from '../../session/utils/Promise';
interface State {
isDraggingFile: boolean;
}
interface Props {
ourNumber: string;
selectedConversationKey: string;
selectedConversation?: ReduxConversationType;
messagesProps: Array<SortedMessageModelProps>;
selectedMessages: Array<string>;
isRightPanelShowing: boolean;
hasOngoingCallWithFocusedConvo: boolean;
htmlDirection: HTMLDirection;
stagedAttachments: Array<StagedAttachmentType>;
isSelectedConvoInitialLoadingInProgress: boolean;
}
const StyledSpinnerContainer = styled.div`
display: flex;
justify-content: center;
width: 100%;
height: 100%;
align-items: center;
`;
const ConvoLoadingSpinner = () => {
return (
<StyledSpinnerContainer>
<SessionSpinner $loading={true} />
</StyledSpinnerContainer>
);
};
const GroupMarkedAsExpired = () => {
const selectedConvo = useSelectedConversationKey();
const isExpired03Group = useConversationIsExpired03Group(selectedConvo);
if (!selectedConvo || !PubKey.is03Pubkey(selectedConvo) || !isExpired03Group) {
return null;
}
return (
<NoticeBanner
text={tr('groupNotUpdatedWarning')}
dataTestId="group-not-updated-30-days-banner"
/>
);
};
export class SessionConversation extends Component<Props, State> {
private readonly messageContainerRef: RefObject<HTMLDivElement | null>;
private dragCounter: number;
private publicMembersRefreshTimeout?: NodeJS.Timeout;
private readonly updateMemberList: () => any;
constructor(props: any) {
super(props);
this.state = {
isDraggingFile: false,
};
this.messageContainerRef = createRef();
this.dragCounter = 0;
this.updateMemberList = _.debounce(this.updateMemberListBouncy.bind(this), 10000);
autoBind(this);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~ LIFE CYCLES ~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public componentDidUpdate(prevProps: Props, _prevState: State) {
const { selectedConversationKey: newConversationKey, selectedConversation: newConversation } =
this.props;
const { selectedConversationKey: oldConversationKey } = prevProps;
// if the convo is valid, and it changed, register for drag events
if (newConversationKey && newConversation && newConversationKey !== oldConversationKey) {
// Pause thread to wait for rendering to complete
setTimeout(() => {
const div = this.messageContainerRef.current;
div?.addEventListener('dragenter', this.handleDragIn);
div?.addEventListener('dragleave', this.handleDragOut);
div?.addEventListener('dragover', this.handleDrag);
div?.addEventListener('drop', this.handleDrop);
}, 100);
// if the conversation changed, we have to stop our refresh of member list
if (this.publicMembersRefreshTimeout) {
global.clearInterval(this.publicMembersRefreshTimeout);
this.publicMembersRefreshTimeout = undefined;
}
// if the newConversation changed, and is public, start our refresh members list
if (newConversation.isPublic) {
// this is a debounced call.
void this.updateMemberListBouncy();
// run this only once every minute if we don't change the visible conversation.
// this is a heavy operation (like a few thousands members can be here)
this.publicMembersRefreshTimeout = global.setInterval(this.updateMemberList, 60000);
}
}
// if we do not have a model, unregister for events
if (!newConversation) {
const div = this.messageContainerRef.current;
div?.removeEventListener('dragenter', this.handleDragIn);
div?.removeEventListener('dragleave', this.handleDragOut);
div?.removeEventListener('dragover', this.handleDrag);
div?.removeEventListener('drop', this.handleDrop);
if (this.publicMembersRefreshTimeout) {
global.clearInterval(this.publicMembersRefreshTimeout);
this.publicMembersRefreshTimeout = undefined;
}
}
if (newConversationKey !== oldConversationKey) {
this.setState({
isDraggingFile: false,
});
}
}
public componentWillUnmount() {
const div = this.messageContainerRef.current;
div?.removeEventListener('dragenter', this.handleDragIn);
div?.removeEventListener('dragleave', this.handleDragOut);
div?.removeEventListener('dragover', this.handleDrag);
div?.removeEventListener('drop', this.handleDrop);
if (this.publicMembersRefreshTimeout) {
global.clearInterval(this.publicMembersRefreshTimeout);
this.publicMembersRefreshTimeout = undefined;
}
}
public sendMessageFn(msg: SendMessageType) {
if (!msg.conversationId) {
return;
}
const conversationModel = ConvoHub.use().get(msg.conversationId);
if (!conversationModel) {
return;
}
const sendAndScroll = async () => {
// this needs to be awaited otherwise, the scrollToNow won't find the new message in the db.
// and this make the showScrollButton to be visible (even if we just scrolled to now)
await conversationModel.sendMessage(msg);
await this.scrollToNowWithRetries(5);
};
const recoveryPhrase = getCurrentRecoveryPhrase();
// string replace to fix case where pasted text contains invisible characters causing false negatives
if (msg.body.replace(/\s/g, '').includes(recoveryPhrase.replace(/\s/g, ''))) {
window.inboxStore?.dispatch(
updateConfirmModal({
title: { token: 'warning' },
i18nMessage: { token: 'recoveryPasswordWarningSendDescription' },
okTheme: SessionButtonColor.Danger,
okText: { token: 'send' },
onClickOk: () => {
void sendAndScroll();
},
onClickClose: () => {
window.inboxStore?.dispatch(updateConfirmModal(null));
},
})
);
} else {
void sendAndScroll();
}
window.inboxStore?.dispatch(quoteMessage(undefined));
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~ RENDER METHODS ~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public render() {
const { isDraggingFile } = this.state;
const {
selectedConversation,
messagesProps,
selectedMessages,
isRightPanelShowing,
isSelectedConvoInitialLoadingInProgress,
} = this.props;
if (!selectedConversation || !messagesProps) {
return <EmptyMessageView />;
}
// TODO break selectionMode into it's own container component so we can use hooks to fetch relevant state from the store
const selectionMode = selectedMessages.length > 0;
return (
<>
<div className="conversation-header">
<ConversationHeaderWithDetails />
<GroupMarkedAsExpired />
<OutdatedLegacyGroupBanner />
</div>
{isSelectedConvoInitialLoadingInProgress ? (
<ConvoLoadingSpinner />
) : (
<>
<div
// if you change the class name, also update it on onKeyDown
className={clsx('conversation-content', selectionMode && 'selection-mode')}
onKeyDown={this.onKeyDown}
>
<div className="conversation-messages">
<NoMessageInConversation />
<InvitedToGroup />
<SplitViewContainer
top={<InConversationCallContainer />}
bottom={
<SessionMessagesListContainer
messageContainerRef={this.messageContainerRef}
scrollToNow={this.scrollToNow}
/>
}
disableTop={!this.props.hasOngoingCallWithFocusedConvo}
/>
{isDraggingFile && <SessionFileDropzone />}
</div>
<ConversationMessageRequestButtons />
<CompositionBox
sendMessage={this.sendMessageFn}
stagedAttachments={this.props.stagedAttachments}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
onChoseAttachments={this.onChoseAttachments}
htmlDirection={this.props.htmlDirection}
/>
</div>
<RightPanel open={isRightPanelShowing} />
</>
)}
</>
);
}
/** There is a race condition after sending a message where the most recent
* message from the db exists but that message has not been rendered in the DOM
* yet. This function will scroll even if the message is not in the DOM yet as
* it could also not be in the DOM because the virtualised message list is
* scrolled up too high.
* Returns a duration in milliseconds to wait before re-attempting the function.
* 0 means don't retry.
*/
private async scrollToNow(): Promise<number> {
const conversationKey = this.props.selectedConversationKey;
if (!conversationKey) {
return 0;
}
await markAllReadByConvoId(conversationKey);
const mostRecentMessage = await Data.getLastMessageInConversation(conversationKey);
if (mostRecentMessage) {
const messageContainer = this.messageContainerRef.current;
if (!messageContainer) {
return 100;
}
messageContainer.scrollTop = messageContainer.scrollHeight - messageContainer.clientHeight;
const targetElement = document.getElementById(`msg-${mostRecentMessage.id}`);
if (!targetElement) {
await openConversationToSpecificMessage({
conversationKey,
messageIdToNavigateTo: mostRecentMessage.id,
shouldHighlightMessage: false,
});
return 100;
}
}
return 0;
}
private async scrollToNowWithRetries(maxRetries = 5) {
for (let retryCount = 0, retryTimeMs = 0; retryCount < maxRetries; retryCount++) {
// eslint-disable-next-line no-await-in-loop
retryTimeMs = await this.scrollToNow();
if (retryTimeMs) {
// eslint-disable-next-line no-await-in-loop
await sleepFor(retryTimeMs);
} else {
break;
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~ KEYBOARD NAVIGATION ~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private onKeyDown(event: any) {
const selectionMode = !!this.props.selectedMessages.length;
if (event.target.classList.contains('conversation-content')) {
switch (event.key) {
case 'Escape':
if (selectionMode) {
window.inboxStore?.dispatch(resetSelectedMessageIds());
}
break;
default:
break;
}
}
}
private async onChoseAttachments(attachmentsFileList: Array<File>) {
if (!attachmentsFileList || attachmentsFileList.length === 0) {
return;
}
for (let i = 0; i < attachmentsFileList.length; i++) {
// eslint-disable-next-line no-await-in-loop
await this.maybeAddAttachment(attachmentsFileList[i]);
}
}
private async maybeAddAttachment(file: File) {
if (!file) {
return;
}
const fileName = file.name;
const contentType = file.type;
const { stagedAttachments } = this.props;
if (stagedAttachments.length >= 32) {
ToastUtils.pushMaximumAttachmentsError();
return;
}
const haveNonImage = _.some(
stagedAttachments,
attachment => !MIME.isImage(attachment.contentType)
);
// You can't add another attachment if you already have a non-image staged
if (haveNonImage) {
ToastUtils.pushMultipleNonImageError();
return;
}
// You can't add a non-image attachment if you already have attachments staged
if (!MIME.isImage(contentType) && stagedAttachments.length > 0) {
ToastUtils.pushCannotMixError();
return;
}
try {
// Here, we just try to scale the attachment to something that is not too big for the file server.
// If we can, we use the scaled version, otherwise we use the original (and the filesize check will fail)
//
// Note: we do not save that scaled version here,
// we just check if it will be fine when sending the attachment.
// Later, when the message is being sent, we will fetch the
// file again and scale it down again for upload.
//
// The reason is simply that we'd need to store that scaled blob in memory for the lifetime
// of the app if we were, as the user could switch conversations
// before sending a message with attachments.
const scaledOrNot = await AttachmentUtil.autoScaleFile(file);
// `autoScaleFile` either
// - returns null if it cannot process the file (i.e. not an image for instance)
// - returns a scaled down images if it could process and resize it down, or the size was fine to begin with
const failedToResizeAndOversized = !scaledOrNot && file.size > MAX_ATTACHMENT_FILESIZE_BYTES;
const resizedAndOverSized = scaledOrNot && scaledOrNot.size > MAX_ATTACHMENT_FILESIZE_BYTES;
if (failedToResizeAndOversized || resizedAndOverSized) {
ToastUtils.pushFileSizeErrorAsByte();
return;
}
} catch (error) {
window?.log?.error(
'Error ensuring that image is properly sized:',
error && error.stack ? error.stack : error
);
ToastUtils.pushLoadAttachmentFailure(error?.message);
return;
}
try {
if (GoogleChrome.isImageTypeSupported(contentType)) {
// this does not add the preview to the message outgoing
// this is just for us, for the list of attachments we are sending
// the files are scaled down under getFiles()
const attachmentWithPreview = await renderImagePreview(contentType, file, fileName);
this.addAttachments([attachmentWithPreview]);
} else if (GoogleChrome.isVideoTypeSupported(contentType)) {
const attachmentWithVideoPreview = await renderVideoPreview(contentType, file, fileName);
this.addAttachments([attachmentWithVideoPreview]);
} else {
const attachment: StagedAttachmentType = {
file,
size: file.size,
contentType,
fileName,
url: '',
isVoiceMessage: false,
fileSize: null,
screenshot: null,
thumbnail: null,
};
if (isAudio(contentType)) {
const objectUrl = URL.createObjectURL(file);
try {
const duration = await getAudioDuration({ objectUrl, contentType });
attachment.duration = duration;
} finally {
URL.revokeObjectURL(objectUrl);
}
}
this.addAttachments([attachment]);
}
} catch (e) {
window?.log?.error(
`Was unable to generate thumbnail for file type ${contentType}`,
e && e.stack ? e.stack : e
);
this.addAttachments([
{
file,
size: file.size,
contentType,
fileName,
isVoiceMessage: false,
url: '',
fileSize: null,
screenshot: null,
thumbnail: null,
},
]);
}
}
private addAttachments(newAttachments: Array<StagedAttachmentType>) {
window.inboxStore?.dispatch(
addStagedAttachmentsInConversation({
conversationKey: this.props.selectedConversationKey,
newAttachments,
})
);
}
private handleDrag(e: any) {
e.preventDefault();
e.stopPropagation();
}
private handleDragIn(e: any) {
e.preventDefault();
e.stopPropagation();
this.dragCounter++;
if (
e.dataTransfer.items &&
e.dataTransfer.items.length > 0 &&
e.dataTransfer.items[0]?.kind === 'file'
) {
this.setState({ isDraggingFile: true });
}
}
private handleDragOut(e: any) {
e.preventDefault();
e.stopPropagation();
this.dragCounter--;
if (this.dragCounter === 0) {
this.setState({ isDraggingFile: false });
}
}
private handleDrop(e: DragEvent) {
e.preventDefault();
e.stopPropagation();
if (e?.dataTransfer?.files && e.dataTransfer.files.length > 0) {
void this.onChoseAttachments(Array.from(e.dataTransfer.files));
e.dataTransfer.clearData();
}
this.dragCounter = 0;
this.setState({ isDraggingFile: false });
}
private async updateMemberListBouncy() {
const start = Date.now();
const allPubKeys = await Data.getPubkeysInPublicConversation(
this.props.selectedConversationKey
);
window?.log?.debug(
`[perf] getPubkeysInPublicConversation returned '${
allPubKeys?.length
}' members in ${Date.now() - start}ms`
);
const allMembers = allPubKeys.map((pubKey: string) => {
return {
id: pubKey,
display: isUsAnySogsFromCache(pubKey)
? tr('you')
: ConvoHub.use().get(pubKey)?.getNicknameOrRealUsernameOrPlaceholder() ||
PubKey.shorten(pubKey),
};
});
window.inboxStore?.dispatch(updateMentionsMembers(allMembers));
}
}
const renderVideoPreview = async (contentType: string, file: File, fileName: string) => {
const objectUrl = URL.createObjectURL(file);
try {
const type = THUMBNAIL_CONTENT_TYPE;
const thumbnail = await makeVideoScreenshot({
objectUrl,
contentType: type,
});
const duration = await getVideoDuration({
objectUrl,
contentType: type,
});
const data = await blobToArrayBuffer(thumbnail);
const url = arrayBufferToObjectURL({
data,
type,
});
return {
file,
size: file.size,
fileName,
contentType,
duration,
videoUrl: objectUrl,
url,
isVoiceMessage: false,
fileSize: null,
screenshot: null,
thumbnail: null,
};
} catch (error) {
URL.revokeObjectURL(objectUrl);
throw error;
}
};
const renderImagePreview = async (contentType: string, file: File, fileName: string) => {
if (!MIME.isJPEG(contentType)) {
const urlImage = URL.createObjectURL(file);
if (!urlImage) {
throw new Error('Failed to create object url for image!');
}
return {
file,
size: file.size,
fileName,
contentType,
url: urlImage,
isVoiceMessage: false,
fileSize: null,
screenshot: null,
thumbnail: null,
};
}
const urlImage = URL.createObjectURL(file);
// orientating the image based on EXIF data is done as part of the sharp call in makeImageThumbnailBuffer
const thumbnailBuffer = await makeImageThumbnailBuffer({
objectUrl: urlImage,
contentType,
});
const url = arrayBufferToObjectURL({
data: thumbnailBuffer,
type: THUMBNAIL_CONTENT_TYPE,
});
return {
file,
size: file.size,
fileName,
contentType,
url,
isVoiceMessage: false,
fileSize: null,
screenshot: null,
thumbnail: null,
};
};
function OutdatedLegacyGroupBanner() {
const dispatch = getAppDispatch();
const weAreAdmin = useSelectedWeAreAdmin();
const selectedConversationKey = useSelectedConversationKey();
const isPrivate = useSelectedIsPrivate();
const isPublic = useSelectedIsPublic();
const isLegacyGroup =
!isPrivate &&
!isPublic &&
selectedConversationKey &&
PubKey.is05Pubkey(selectedConversationKey);
const text = tr(
weAreAdmin ? 'legacyGroupAfterDeprecationAdmin' : 'legacyGroupAfterDeprecationMember'
);
return isLegacyGroup ? (
<NoticeBanner
text={text}
onBannerClick={() => {
showLinkVisitWarningDialog('https://getsession.org/groups', dispatch);
}}
unicode={LUCIDE_ICONS_UNICODE.EXTERNAL_LINK_ICON}
dataTestId="legacy-group-banner"
/>
) : null;
}