-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathInviteDialog.tsx
More file actions
1505 lines (1330 loc) · 58.9 KB
/
InviteDialog.tsx
File metadata and controls
1505 lines (1330 loc) · 58.9 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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024 New Vector Ltd.
Copyright 2019-2023 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
import React, { createRef, type JSX, type ReactNode, type SyntheticEvent } from "react";
import { EventType, MatrixError, type Room, RoomMember } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import { type MatrixCall } from "matrix-js-sdk/src/webrtc/call";
import { logger } from "matrix-js-sdk/src/logger";
import { uniqBy } from "lodash";
import { Icon as EmailPillAvatarIcon } from "../../../../res/img/icon-email-pill-avatar.svg";
import { _t, _td } from "../../../languageHandler";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import { makeRoomPermalink, makeUserPermalink } from "../../../utils/permalinks/Permalinks";
import DMRoomMap from "../../../utils/DMRoomMap";
import * as Email from "../../../email";
import { getDefaultIdentityServerUrl, setToDefaultIdentityServer } from "../../../utils/IdentityServerUtils";
import { buildActivityScores, buildMemberScores, compareMembers } from "../../../utils/SortMembers";
import { abbreviateUrl } from "../../../utils/UrlUtils";
import IdentityAuthClient from "../../../IdentityAuthClient";
import { type IInviteResult, inviteMultipleToRoom, showAnyInviteErrors } from "../../../RoomInvite";
import { Action } from "../../../dispatcher/actions";
import { DefaultTagID } from "../../../stores/room-list/models";
import RoomListStore from "../../../stores/room-list/RoomListStore";
import SettingsStore from "../../../settings/SettingsStore";
import { UIFeature } from "../../../settings/UIFeature";
import { mediaFromMxc } from "../../../customisations/Media";
import BaseAvatar from "../avatars/BaseAvatar";
import { SearchResultAvatar } from "../avatars/SearchResultAvatar";
import AccessibleButton, { type ButtonEvent } from "../elements/AccessibleButton";
import { selectText } from "../../../utils/strings";
import Field from "../elements/Field";
import TabbedView, { Tab, TabLocation } from "../../structures/TabbedView";
import Dialpad from "../voip/DialPad";
import QuestionDialog from "./QuestionDialog";
import BaseDialog from "./BaseDialog";
import DialPadBackspaceButton from "../elements/DialPadBackspaceButton";
import LegacyCallHandler from "../../../LegacyCallHandler";
import UserIdentifierCustomisations from "../../../customisations/UserIdentifier";
import CopyableText from "../elements/CopyableText";
import { type ScreenName } from "../../../PosthogTrackers";
import { KeyBindingAction } from "../../../accessibility/KeyboardShortcuts";
import { getKeyBindingsManager } from "../../../KeyBindingsManager";
import {
DirectoryMember,
type IDMUserTileProps,
type Member,
startDmOnFirstMessage,
ThreepidMember,
} from "../../../utils/direct-messages";
import { InviteKind } from "./InviteDialogTypes";
import Modal from "../../../Modal";
import dis from "../../../dispatcher/dispatcher";
import { privateShouldBeEncrypted } from "../../../utils/rooms";
import { type NonEmptyArray } from "../../../@types/common";
import { UNKNOWN_PROFILE_ERRORS } from "../../../utils/MultiInviter";
import AskInviteAnywayDialog, { type UnknownProfiles } from "./AskInviteAnywayDialog";
import { SdkContextClass } from "../../../contexts/SDKContext";
import { type UserProfilesStore } from "../../../stores/UserProfilesStore";
import InviteProgressBody from "./InviteProgressBody.tsx";
import { RichList } from "../../../shared-components/rich-list/RichList";
import { RichItem } from "../../../shared-components/rich-list/RichItem";
import { PillInput } from "../../../shared-components/pill-input/PillInput";
import { Pill } from "../../../shared-components/pill-input/Pill";
// we have a number of types defined from the Matrix spec which can't reasonably be altered here.
/* eslint-disable camelcase */
const extractTargetUnknownProfiles = async (
targets: Member[],
profilesStores: UserProfilesStore,
): Promise<UnknownProfiles> => {
const directoryMembers = targets.filter((t): t is DirectoryMember => t instanceof DirectoryMember);
await Promise.all(directoryMembers.map((t) => profilesStores.getOrFetchProfile(t.userId)));
return directoryMembers.reduce<UnknownProfiles>((unknownProfiles: UnknownProfiles, target: DirectoryMember) => {
const lookupError = profilesStores.getProfileLookupError(target.userId);
if (
lookupError instanceof MatrixError &&
lookupError.errcode &&
UNKNOWN_PROFILE_ERRORS.includes(lookupError.errcode)
) {
unknownProfiles.push({
userId: target.userId,
errorText: lookupError.data.error || "",
});
}
return unknownProfiles;
}, []);
};
interface Result {
userId: string;
user: Member;
lastActive?: number;
}
const INITIAL_ROOMS_SHOWN = 3; // Number of rooms to show at first
const INCREMENT_ROOMS_SHOWN = 5; // Number of rooms to add when 'show more' is clicked
enum TabId {
UserDirectory = "users",
DialPad = "dialpad",
}
class DMUserTile extends React.PureComponent<IDMUserTileProps> {
private onRemove = (e: ButtonEvent): void => {
// Stop the browser from highlighting text
e.preventDefault();
e.stopPropagation();
this.props.onRemove!(this.props.member);
};
public render(): React.ReactNode {
const avatarSize = "20px";
const avatar = <SearchResultAvatar user={this.props.member} size={avatarSize} />;
return (
<Pill label={this.props.member.name} onClick={this.onRemove}>
{avatar}
</Pill>
);
}
}
/**
* Converts a RoomMember to a Member.
* Returns the Member if it is already a Member.
*/
const toMember = (member: RoomMember | Member): Member => {
return member instanceof RoomMember
? new DirectoryMember({
user_id: member.userId,
display_name: member.name,
avatar_url: member.getMxcAvatarUrl(),
})
: member;
};
interface IDMRoomTileProps {
member: Member;
lastActiveTs?: number;
onToggle(member: Member): void;
isSelected: boolean;
}
class DMRoomTile extends React.PureComponent<IDMRoomTileProps> {
private onClick = (e: ButtonEvent): void => {
// Stop the browser from highlighting text
e.preventDefault();
e.stopPropagation();
this.props.onToggle(this.props.member);
};
public render(): React.ReactNode {
const avatarSize = "32px";
const avatar = (this.props.member as ThreepidMember).isEmail ? (
<EmailPillAvatarIcon width={avatarSize} height={avatarSize} />
) : (
<BaseAvatar
url={
this.props.member.getMxcAvatarUrl()
? mediaFromMxc(this.props.member.getMxcAvatarUrl()!).getSquareThumbnailHttp(
parseInt(avatarSize, 10),
)
: null
}
name={this.props.member.name}
idName={this.props.member.userId}
size={avatarSize}
/>
);
const userIdentifier = UserIdentifierCustomisations.getDisplayUserIdentifier(this.props.member.userId, {
withDisplayName: true,
});
const caption = (this.props.member as ThreepidMember).isEmail
? _t("invite|email_caption")
: userIdentifier || this.props.member.userId;
return (
<RichItem
avatar={avatar}
title={this.props.member.name}
description={caption}
timestamp={this.props.lastActiveTs}
onClick={this.onClick}
selected={this.props.isSelected}
/>
);
}
}
interface BaseProps {
// Takes a boolean which is true if a user / users were invited /
// a call transfer was initiated or false if the dialog was cancelled
// with no action taken.
onFinished: (success?: boolean) => void;
// Initial value to populate the filter with
initialText?: string;
}
interface InviteDMProps extends BaseProps {
// The kind of invite being performed. Assumed to be InviteKind.Dm if not provided.
kind?: InviteKind.Dm;
}
interface InviteRoomProps extends BaseProps {
kind: InviteKind.Invite;
// The room ID this dialog is for. Only required for InviteKind.Invite.
roomId: string;
}
function isRoomInvite(props: Props): props is InviteRoomProps {
return props.kind === InviteKind.Invite;
}
interface InviteCallProps extends BaseProps {
kind: InviteKind.CallTransfer;
// The call to transfer. Only required for InviteKind.CallTransfer.
call: MatrixCall;
}
type Props = InviteDMProps | InviteRoomProps | InviteCallProps;
interface IInviteDialogState {
targets: Member[]; // array of Member objects (see interface above)
filterText: string;
recents: Result[];
numRecentsShown: number;
suggestions: Result[];
numSuggestionsShown: number;
serverResultsMixin: Result[];
threepidResultsMixin: Result[];
canUseIdentityServer: boolean;
tryingIdentityServer: boolean;
consultFirst: boolean;
dialPadValue: string;
currentTabId: TabId;
/**
* True if we are sending the invites.
*
* We will grey out the action button, hide the suggestions, and display a spinner.
*/
busy: boolean;
/** Error from the last attempt to send invites. */
errorText?: string;
}
export default class InviteDialog extends React.PureComponent<Props, IInviteDialogState> {
public static defaultProps: Partial<Props> = {
kind: InviteKind.Dm,
initialText: "",
};
private debounceTimer: number | null = null; // actually number because we're in the browser
private editorRef = createRef<HTMLInputElement>();
private numberEntryFieldRef = createRef<Field>();
private unmounted = false;
private encryptionByDefault = false;
private profilesStore: UserProfilesStore;
public constructor(props: Props) {
super(props);
if (props.kind === InviteKind.Invite && !props.roomId) {
throw new Error("When using InviteKind.Invite a roomId is required for an InviteDialog");
} else if (props.kind === InviteKind.CallTransfer && !props.call) {
throw new Error("When using InviteKind.CallTransfer a call is required for an InviteDialog");
}
this.profilesStore = SdkContextClass.instance.userProfilesStore;
const cli = MatrixClientPeg.safeGet();
const excludedIds = new Set([cli.getSafeUserId()]);
if (isRoomInvite(props)) {
const room = cli.getRoom(props.roomId);
if (!room) throw new Error("Room ID given to InviteDialog does not look like a room");
const isFederated = room?.currentState.getStateEvents(EventType.RoomCreate, "")?.getContent()["m.federate"];
room.getMembersWithMembership(KnownMembership.Invite).forEach((m) => excludedIds.add(m.userId));
room.getMembersWithMembership(KnownMembership.Join).forEach((m) => excludedIds.add(m.userId));
// add banned users, so we don't try to invite them
room.getMembersWithMembership(KnownMembership.Ban).forEach((m) => excludedIds.add(m.userId));
const ourHomeserver = cli.getDomain();
if (isFederated === false && ourHomeserver) {
// If this room isn't federated, we must be on the same server.
// exclude users from external servers
this.excludeExternals(ourHomeserver, excludedIds);
}
}
this.state = {
targets: [], // array of Member objects (see interface above)
filterText: this.props.initialText || "",
// Mutates alreadyInvited set so that buildSuggestions doesn't duplicate any users
recents: InviteDialog.buildRecents(excludedIds),
numRecentsShown: INITIAL_ROOMS_SHOWN,
suggestions: this.buildSuggestions(excludedIds),
numSuggestionsShown: INITIAL_ROOMS_SHOWN,
serverResultsMixin: [],
threepidResultsMixin: [],
canUseIdentityServer: !!cli.getIdentityServerUrl(),
tryingIdentityServer: false,
consultFirst: false,
dialPadValue: "",
currentTabId: TabId.UserDirectory,
// These two flags are used for the 'Go' button to communicate what is going on.
busy: false,
};
}
public componentDidMount(): void {
this.unmounted = false;
this.encryptionByDefault = privateShouldBeEncrypted(MatrixClientPeg.safeGet());
if (this.props.initialText) {
this.updateSuggestions(this.props.initialText);
}
}
public componentWillUnmount(): void {
this.unmounted = true;
}
private onConsultFirstChange = (ev: React.ChangeEvent<HTMLInputElement>): void => {
this.setState({ consultFirst: ev.target.checked });
};
private excludeExternals(homeserver: string, excludedTargetIds: Set<string>): void {
const client = MatrixClientPeg.safeGet();
// users with room membership
const members = Object.values(buildMemberScores(client)).map(({ member }) => member.userId);
// users with dm membership
const roomMembers = Object.keys(DMRoomMap.shared().getUniqueRoomsWithIndividuals());
roomMembers.forEach((id) => members.push(id));
// filter duplicates and user IDs from external servers
const externals = new Set(members.filter((id) => !id.includes(homeserver)));
externals.forEach((id) => excludedTargetIds.add(id));
}
public static buildRecents(excludedTargetIds: Set<string>): Result[] {
const rooms = DMRoomMap.shared().getUniqueRoomsWithIndividuals(); // map of userId => js-sdk Room
// Also pull in all the rooms tagged as DefaultTagID.DM so we don't miss anything. Sometimes the
// room list doesn't tag the room for the DMRoomMap, but does for the room list.
const dmTaggedRooms = RoomListStore.instance.orderedLists[DefaultTagID.DM] || [];
const myUserId = MatrixClientPeg.safeGet().getUserId();
for (const dmRoom of dmTaggedRooms) {
const otherMembers = dmRoom.getJoinedMembers().filter((u) => u.userId !== myUserId);
for (const member of otherMembers) {
if (rooms[member.userId]) continue; // already have a room
logger.warn(`Adding DM room for ${member.userId} as ${dmRoom.roomId} from tag, not DM map`);
rooms[member.userId] = dmRoom;
}
}
const recents: {
userId: string;
user: Member;
lastActive: number;
}[] = [];
for (const userId in rooms) {
// Filter out user IDs that are already in the room / should be excluded
if (excludedTargetIds.has(userId)) {
logger.warn(`[Invite:Recents] Excluding ${userId} from recents`);
continue;
}
const room = rooms[userId];
const roomMember = room.getMember(userId);
if (!roomMember) {
// just skip people who don't have memberships for some reason
logger.warn(`[Invite:Recents] ${userId} is missing a member object in their own DM (${room.roomId})`);
continue;
}
// Find the last timestamp for a message event
const searchTypes = ["m.room.message", "m.room.encrypted", "m.sticker"];
const maxSearchEvents = 20; // to prevent traversing history
let lastEventTs = 0;
if (room.timeline && room.timeline.length) {
for (let i = room.timeline.length - 1; i >= 0; i--) {
const ev = room.timeline[i];
if (searchTypes.includes(ev.getType())) {
lastEventTs = ev.getTs();
break;
}
if (room.timeline.length - i > maxSearchEvents) break;
}
}
if (!lastEventTs) {
// something weird is going on with this room
logger.warn(`[Invite:Recents] ${userId} (${room.roomId}) has a weird last timestamp: ${lastEventTs}`);
continue;
}
recents.push({ userId, user: toMember(roomMember), lastActive: lastEventTs });
// We mutate the given set so that any later callers avoid duplicating these users
excludedTargetIds.add(userId);
}
if (!recents) logger.warn("[Invite:Recents] No recents to suggest!");
// Sort the recents by last active to save us time later
recents.sort((a, b) => b.lastActive - a.lastActive);
return recents;
}
private buildSuggestions(excludedTargetIds: Set<string>): { userId: string; user: Member }[] {
const cli = MatrixClientPeg.safeGet();
const activityScores = buildActivityScores(cli);
const memberScores = buildMemberScores(cli);
const memberComparator = compareMembers(activityScores, memberScores);
return Object.values(memberScores)
.map(({ member }) => member)
.filter((member) => !excludedTargetIds.has(member.userId))
.sort(memberComparator)
.map((member) => ({ userId: member.userId, user: toMember(member) }));
}
private shouldAbortAfterInviteError(result: IInviteResult, room: Room): boolean {
this.setState({ busy: false });
const userMap = new Map<string, Member>(this.state.targets.map((member) => [member.userId, member]));
return !showAnyInviteErrors(result.states, room, result.inviter, userMap);
}
private convertFilter(): Member[] {
// Check to see if there's anything to convert first
if (!this.state.filterText || !this.state.filterText.includes("@")) return this.state.targets || [];
if (!this.canInviteMore()) {
// There should only be one third-party invite → do not allow more targets
return this.state.targets;
}
let newMember: Member | undefined;
if (this.state.filterText.startsWith("@")) {
// Assume mxid
newMember = new DirectoryMember({ user_id: this.state.filterText });
} else if (SettingsStore.getValue(UIFeature.IdentityServer)) {
// Assume email
if (this.canInviteThirdParty()) {
newMember = new ThreepidMember(this.state.filterText);
}
}
if (!newMember) return this.state.targets;
const newTargets = [...(this.state.targets || []), newMember];
this.setState({ targets: newTargets, filterText: "" });
return newTargets;
}
/**
* Check if there are unknown profiles if promptBeforeInviteUnknownUsers setting is enabled.
* If so show the "invite anyway?" dialog. Otherwise directly create the DM local room.
*/
private checkProfileAndStartDm = async (): Promise<void> => {
this.setBusy(true);
const targets = this.convertFilter();
if (SettingsStore.getValue("promptBeforeInviteUnknownUsers")) {
const unknownProfileUsers = await extractTargetUnknownProfiles(targets, this.profilesStore);
if (unknownProfileUsers.length) {
this.showAskInviteAnywayDialog(unknownProfileUsers);
return;
}
}
await this.startDm();
};
private startDm = async (): Promise<void> => {
this.setBusy(true);
try {
const cli = MatrixClientPeg.safeGet();
const targets = this.convertFilter();
await startDmOnFirstMessage(cli, targets);
this.props.onFinished(true);
} catch (err) {
logger.error(err);
this.setState({
busy: false,
errorText: _t("invite|error_dm"),
});
}
};
private setBusy(busy: boolean): void {
this.setState({
busy,
});
}
private showAskInviteAnywayDialog(unknownProfileUsers: { userId: string; errorText: string }[]): void {
Modal.createDialog(AskInviteAnywayDialog, {
unknownProfileUsers,
onInviteAnyways: () => this.startDm(),
onGiveUp: () => {
this.setBusy(false);
},
description: _t("invite|ask_anyway_description"),
inviteNeverWarnLabel: _t("invite|ask_anyway_never_warn_label"),
inviteLabel: _t("invite|ask_anyway_label"),
});
}
private inviteUsers = async (): Promise<void> => {
if (this.props.kind !== InviteKind.Invite) return;
this.setState({ busy: true });
this.convertFilter();
const targets = this.convertFilter();
const targetIds = targets.map((t) => t.userId);
const cli = MatrixClientPeg.safeGet();
const room = cli.getRoom(this.props.roomId);
if (!room) {
logger.error("Failed to find the room to invite users to");
this.setState({
busy: false,
errorText: _t("invite|error_find_room"),
});
return;
}
try {
const result = await inviteMultipleToRoom(cli, this.props.roomId, targetIds, {
// We show our own progress body, so don't pop up a separate dialog.
inhibitProgressDialog: true,
});
if (!this.shouldAbortAfterInviteError(result, room)) {
// handles setting error message too
this.props.onFinished(true);
}
} catch (err) {
logger.error(err);
this.setState({
busy: false,
errorText: _t("invite|error_invite"),
});
}
};
private transferCall = async (): Promise<void> => {
if (this.props.kind !== InviteKind.CallTransfer) return;
if (this.state.currentTabId == TabId.UserDirectory) {
this.convertFilter();
const targets = this.convertFilter();
const targetIds = targets.map((t) => t.userId);
if (targetIds.length > 1) {
this.setState({
errorText: _t("invite|error_transfer_multiple_target"),
});
return;
}
LegacyCallHandler.instance.startTransferToMatrixID(this.props.call, targetIds[0], this.state.consultFirst);
} else {
LegacyCallHandler.instance.startTransferToPhoneNumber(
this.props.call,
this.state.dialPadValue,
this.state.consultFirst,
);
}
this.props.onFinished(true);
};
private onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>): void => {
if (this.state.busy) return;
let handled = false;
const value = e.currentTarget.value.trim();
const action = getKeyBindingsManager().getAccessibilityAction(e);
switch (action) {
case KeyBindingAction.Space:
if (!value || !value.includes("@") || value.includes(" ")) break;
// when the user hits space and their input looks like an e-mail/MXID then try to convert it
this.convertFilter();
handled = true;
break;
case KeyBindingAction.Enter:
if (!value) break;
// when the user hits enter with something in their field try to convert it
this.convertFilter();
handled = true;
break;
}
if (handled) {
e.preventDefault();
}
};
private onCancel = (): void => {
this.props.onFinished(false);
};
private updateSuggestions = async (term: string): Promise<void> => {
MatrixClientPeg.safeGet()
.searchUserDirectory({ term })
.then(async (r): Promise<void> => {
if (term !== this.state.filterText) {
// Discard the results - we were probably too slow on the server-side to make
// these results useful. This is a race we want to avoid because we could overwrite
// more accurate results.
return;
}
if (!r.results) r.results = [];
// While we're here, try and autocomplete a search result for the mxid itself
// if there's no matches (and the input looks like a mxid).
if (term[0] === "@" && term.indexOf(":") > 1) {
try {
const profile = await this.profilesStore.getOrFetchProfile(term, { shouldThrow: true });
if (profile) {
// If we have a profile, we have enough information to assume that
// the mxid can be invited - add it to the list. We stick it at the
// top so it is most obviously presented to the user.
r.results.splice(0, 0, {
user_id: term,
display_name: profile["displayname"],
avatar_url: profile["avatar_url"],
});
}
} catch (e) {
logger.warn("Non-fatal error trying to make an invite for a user ID", e);
}
}
this.setState({
serverResultsMixin: r.results.map((u) => ({
userId: u.user_id,
user: new DirectoryMember(u),
})),
});
})
.catch((e) => {
logger.error("Error searching user directory:");
logger.error(e);
this.setState({ serverResultsMixin: [] }); // clear results because it's moderately fatal
});
// Whenever we search the directory, also try to search the identity server. It's
// all debounced the same anyways.
if (!this.state.canUseIdentityServer) {
// The user doesn't have an identity server set - warn them of that.
this.setState({ tryingIdentityServer: true });
return;
}
if (Email.looksValid(term) && this.canInviteThirdParty() && SettingsStore.getValue(UIFeature.IdentityServer)) {
// Start off by suggesting the plain email while we try and resolve it
// to a real account.
this.setState({
// per above: the userId is a lie here - it's just a regular identifier
threepidResultsMixin: [{ user: new ThreepidMember(term), userId: term }],
});
try {
const authClient = new IdentityAuthClient();
const token = await authClient.getAccessToken();
// No token → unable to try a lookup
if (!token) return;
if (term !== this.state.filterText) return; // abandon hope
const lookup = await MatrixClientPeg.safeGet().lookupThreePid("email", term, token);
if (term !== this.state.filterText) return; // abandon hope
if (!lookup || !("mxid" in lookup)) {
// We weren't able to find anyone - we're already suggesting the plain email
// as an alternative, so do nothing.
return;
}
// We append the user suggestion to give the user an option to click
// the email anyways, and so we don't cause things to jump around. In
// theory, the user would see the user pop up and think "ah yes, that
// person!"
const profile = await this.profilesStore.getOrFetchProfile(lookup.mxid);
if (term !== this.state.filterText || !profile) return; // abandon hope
this.setState({
threepidResultsMixin: [
...this.state.threepidResultsMixin,
{
user: new DirectoryMember({
user_id: lookup.mxid,
display_name: profile.displayname,
avatar_url: profile.avatar_url,
}),
// Use the search term as identifier, so that it shows up in suggestions.
userId: term,
},
],
});
} catch (e) {
logger.error("Error searching identity server:");
logger.error(e);
this.setState({ threepidResultsMixin: [] }); // clear results because it's moderately fatal
}
}
};
private updateFilter = (e: React.ChangeEvent<HTMLInputElement>): void => {
const term = e.target.value;
this.setState({ filterText: term });
// Debounce server lookups to reduce spam. We don't clear the existing server
// results because they might still be vaguely accurate, likewise for races which
// could happen here.
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
this.debounceTimer = window.setTimeout(() => {
this.updateSuggestions(term);
}, 150); // 150ms debounce (human reaction time + some)
};
private showMoreRecents = (): void => {
this.setState({ numRecentsShown: this.state.numRecentsShown + INCREMENT_ROOMS_SHOWN });
};
private showMoreSuggestions = (): void => {
this.setState({ numSuggestionsShown: this.state.numSuggestionsShown + INCREMENT_ROOMS_SHOWN });
};
private toggleMember = (member: Member): void => {
if (!this.state.busy) {
let filterText = this.state.filterText;
let targets = this.state.targets.map((t) => t); // cheap clone for mutation
const idx = targets.findIndex((m) => m.userId === member.userId);
if (idx >= 0) {
targets.splice(idx, 1);
} else {
if (this.props.kind === InviteKind.CallTransfer && targets.length > 0) {
targets = [];
}
targets.push(member);
filterText = ""; // clear the filter when the user accepts a suggestion
}
this.setState({ targets, filterText });
if (this.editorRef && this.editorRef.current) {
this.editorRef.current.focus();
}
}
};
private removeMember = (member: Member): void => {
const targets = this.state.targets.map((t) => t); // cheap clone for mutation
const idx = targets.indexOf(member);
if (idx >= 0) {
targets.splice(idx, 1);
this.setState({ targets });
}
if (this.editorRef && this.editorRef.current) {
this.editorRef.current.focus();
}
};
private parseFilter(filter: string): string[] {
return filter
.split(/[\s,]+/)
.map((p) => p.trim())
.filter((p) => !!p); // filter empty strings
}
private onPaste = async (e: React.ClipboardEvent): Promise<void> => {
if (this.state.filterText) {
// if the user has already typed something, just let them
// paste normally.
return;
}
const text = e.clipboardData.getData("text");
const potentialAddresses = this.parseFilter(text);
// one search term which is not a mxid or email address
if (potentialAddresses.length === 1 && !potentialAddresses[0].includes("@")) {
return;
}
// Prevent the text being pasted into the input
e.preventDefault();
// Process it as a list of addresses to add instead
const possibleMembers = [
// If we can avoid hitting the profile endpoint, we should.
...this.state.recents,
...this.state.suggestions,
...this.state.serverResultsMixin,
...this.state.threepidResultsMixin,
];
const toAdd: Member[] = [];
const failed: string[] = [];
// Addresses that could not be added.
// Will be displayed as filter text to provide feedback.
const unableToAddMore: string[] = [];
for (const address of potentialAddresses) {
const member = possibleMembers.find((m) => m.userId === address);
if (member) {
if (this.canInviteMore([...this.state.targets, ...toAdd])) {
toAdd.push(member.user);
} else {
// Invite not possible for current targets and pasted targets.
unableToAddMore.push(address);
}
continue;
}
if (Email.looksValid(address)) {
if (this.canInviteThirdParty([...this.state.targets, ...toAdd])) {
toAdd.push(new ThreepidMember(address));
} else {
// Third-party invite not possible for current targets and pasted targets.
unableToAddMore.push(address);
}
continue;
}
if (address[0] !== "@") {
failed.push(address); // not a user ID
continue;
}
try {
const profile = await this.profilesStore.getOrFetchProfile(address);
toAdd.push(
new DirectoryMember({
user_id: address,
display_name: profile?.displayname,
avatar_url: profile?.avatar_url,
}),
);
} catch (e) {
logger.error("Error looking up profile for " + address);
logger.error(e);
failed.push(address);
}
}
if (this.unmounted) return;
if (failed.length > 0) {
Modal.createDialog(QuestionDialog, {
title: _t("invite|error_find_user_title"),
description: _t("invite|error_find_user_description", { csvNames: failed.join(", ") }),
button: _t("action|ok"),
});
}
if (unableToAddMore) {
this.setState({
filterText: unableToAddMore.join(" "),
targets: uniqBy([...this.state.targets, ...toAdd], (t) => t.userId),
});
} else {
this.setState({
targets: uniqBy([...this.state.targets, ...toAdd], (t) => t.userId),
});
}
};
private onUseDefaultIdentityServerClick = (e: ButtonEvent): void => {
e.preventDefault();
// Update the IS in account data. Actually using it may trigger terms.
// eslint-disable-next-line react-hooks/rules-of-hooks
setToDefaultIdentityServer(MatrixClientPeg.safeGet());
this.setState({ canUseIdentityServer: true, tryingIdentityServer: false });
};
private onManageSettingsClick = (e: ButtonEvent): void => {
e.preventDefault();
dis.fire(Action.ViewUserSettings);
this.props.onFinished(false);
};
private renderSection(kind: "recents" | "suggestions"): ReactNode {
let sourceMembers = kind === "recents" ? this.state.recents : this.state.suggestions;
let showNum = kind === "recents" ? this.state.numRecentsShown : this.state.numSuggestionsShown;
const showMoreFn = kind === "recents" ? this.showMoreRecents.bind(this) : this.showMoreSuggestions.bind(this);
const lastActive = (m: Result): number | undefined => (kind === "recents" ? m.lastActive : undefined);
let sectionName = kind === "recents" ? _t("invite|recents_section") : _t("common|suggestions");
if (this.props.kind === InviteKind.Invite) {
sectionName = kind === "recents" ? _t("invite|suggestions_section") : _t("common|suggestions");
}
// Mix in the server results if we have any, but only if we're searching. We track the additional
// members separately because we want to filter sourceMembers but trust the mixin arrays to have
// the right members in them.
let priorityAdditionalMembers: Result[] = []; // Shows up before our own suggestions, higher quality
let otherAdditionalMembers: Result[] = []; // Shows up after our own suggestions, lower quality
const hasMixins = this.state.serverResultsMixin || this.state.threepidResultsMixin;
if (this.state.filterText && hasMixins && kind === "suggestions") {
// We don't want to duplicate members though, so just exclude anyone we've already seen.
// The type of u is a pain to define but members of both mixins have the 'userId' property
const notAlreadyExists = (u: any): boolean => {
return (
!this.state.recents.some((m) => m.userId === u.userId) &&
!sourceMembers.some((m) => m.userId === u.userId) &&
!priorityAdditionalMembers.some((m) => m.userId === u.userId) &&
!otherAdditionalMembers.some((m) => m.userId === u.userId)
);
};
otherAdditionalMembers = this.state.serverResultsMixin.filter(notAlreadyExists);
priorityAdditionalMembers = this.state.threepidResultsMixin.filter(notAlreadyExists);
}
const hasAdditionalMembers = priorityAdditionalMembers.length > 0 || otherAdditionalMembers.length > 0;
// Hide the section if there's nothing to filter by
if (sourceMembers.length === 0 && !hasAdditionalMembers) return null;
if (!this.canInviteThirdParty()) {
// It is currently not allowed to add more third-party invites. Filter them out.
priorityAdditionalMembers = priorityAdditionalMembers.filter((s) => s instanceof ThreepidMember);
}
// Do some simple filtering on the input before going much further. If we get no results, say so.
if (this.state.filterText) {
const filterBy = this.state.filterText.toLowerCase();
sourceMembers = sourceMembers.filter(
(m) => m.user.name.toLowerCase().includes(filterBy) || m.userId.toLowerCase().includes(filterBy),
);
if (sourceMembers.length === 0 && !hasAdditionalMembers) {
return (
<div className="mx_InviteDialog_section">
<RichList
title={sectionName}
titleAttributes={{ "role": "heading", "aria-level": 3 }}
isEmpty={true}
>
{_t("common|no_results")}
</RichList>
</div>
);
}
}
// Now we mix in the additional members. Again, we presume these have already been filtered. We
// also assume they are more relevant than our suggestions and prepend them to the list.
sourceMembers = [...priorityAdditionalMembers, ...sourceMembers, ...otherAdditionalMembers];
// If we're going to hide one member behind 'show more', just use up the space of the button
// with the member's tile instead.
if (showNum === sourceMembers.length - 1) showNum++;
// .slice() will return an incomplete array but won't error on us if we go too far
const toRender = sourceMembers.slice(0, showNum);
const hasMore = toRender.length < sourceMembers.length;
let showMore: JSX.Element | undefined;
if (hasMore) {
showMore = (
<div className="mx_InviteDialog_section_showMore">
<AccessibleButton onClick={showMoreFn} kind="link">
{_t("common|show_more")}
</AccessibleButton>
</div>
);
}
const tiles = toRender.map((r) => (
<DMRoomTile
member={r.user}
lastActiveTs={lastActive(r)}
key={r.user.userId}
onToggle={this.toggleMember}
isSelected={this.state.targets.some((t) => t.userId === r.userId)}
/>
));
return (