/
ConversationController.ts
1173 lines (1004 loc) · 35.2 KB
/
ConversationController.ts
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 2020-2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { debounce, pick, uniq, without } from 'lodash';
import PQueue from 'p-queue';
import type {
ConversationModelCollectionType,
ConversationAttributesType,
ConversationAttributesTypeType,
} from './model-types.d';
import type { ConversationModel } from './models/conversations';
import type { MessageModel } from './models/messages';
import type { UUIDStringType } from './types/UUID';
import dataInterface from './sql/Client';
import * as log from './logging/log';
import * as Errors from './types/errors';
import { getContactId } from './messages/helpers';
import { maybeDeriveGroupV2Id } from './groups';
import { assert, strictAssert } from './util/assert';
import { isGroupV1, isGroupV2 } from './util/whatTypeOfConversation';
import { getConversationUnreadCountForAppBadge } from './util/getConversationUnreadCountForAppBadge';
import { UUID, isValidUuid, UUIDKind } from './types/UUID';
import { Address } from './types/Address';
import { QualifiedAddress } from './types/QualifiedAddress';
import { sleep } from './util/sleep';
import { isNotNil } from './util/isNotNil';
import { MINUTE, SECOND } from './util/durations';
type ConvoMatchType =
| {
key: 'uuid' | 'pni';
value: UUIDStringType | undefined;
match: ConversationModel | undefined;
}
| {
key: 'e164';
value: string | undefined;
match: ConversationModel | undefined;
};
const { hasOwnProperty } = Object.prototype;
function applyChangeToConversation(
conversation: ConversationModel,
suggestedChange: Partial<
Pick<ConversationAttributesType, 'uuid' | 'e164' | 'pni'>
>
) {
const change = { ...suggestedChange };
// Clear PNI if changing e164 without associated PNI
if (hasOwnProperty.call(change, 'e164') && !change.pni) {
change.pni = undefined;
}
// If we have a PNI but not an ACI, then the PNI will go in the UUID field
// Tricky: We need a special check here, because the PNI can be in the uuid slot
if (
change.pni &&
!change.uuid &&
(!conversation.get('uuid') ||
conversation.get('uuid') === conversation.get('pni'))
) {
change.uuid = change.pni;
}
// If we're clearing a PNI, but we didn't have an ACI - we need to clear UUID field
if (
!change.uuid &&
hasOwnProperty.call(change, 'pni') &&
!change.pni &&
conversation.get('uuid') === conversation.get('pni')
) {
change.uuid = undefined;
}
if (hasOwnProperty.call(change, 'uuid')) {
conversation.updateUuid(change.uuid);
}
if (hasOwnProperty.call(change, 'e164')) {
conversation.updateE164(change.e164);
}
if (hasOwnProperty.call(change, 'pni')) {
conversation.updatePni(change.pni);
}
// Note: we don't do a conversation.set here, because change is limited to these fields
}
async function safeCombineConversations({
logId,
oldConversation,
newConversation,
}: {
logId: string;
oldConversation: ConversationModel;
newConversation: ConversationModel;
}) {
try {
await window.ConversationController.combineConversations(
newConversation,
oldConversation
);
} catch (error) {
log.warn(
`${logId}: error combining contacts: ${Errors.toLogFormat(error)}`
);
}
}
const MAX_MESSAGE_BODY_LENGTH = 64 * 1024;
const {
getAllConversations,
getAllGroupsInvolvingUuid,
getMessagesBySentAt,
migrateConversationMessages,
removeConversation,
saveConversation,
updateConversation,
} = dataInterface;
// We have to run this in background.js, after all backbone models and collections on
// Whisper.* have been created. Once those are in typescript we can use more reasonable
// require statements for referencing these things, giving us more flexibility here.
export function start(): void {
const conversations = new window.Whisper.ConversationCollection();
window.getConversations = () => conversations;
window.ConversationController = new ConversationController(conversations);
}
export class ConversationController {
private _initialFetchComplete = false;
private _initialPromise: undefined | Promise<void>;
private _conversationOpenStart = new Map<string, number>();
private _hasQueueEmptied = false;
private _combineConversationsQueue = new PQueue({ concurrency: 1 });
constructor(private _conversations: ConversationModelCollectionType) {
const debouncedUpdateUnreadCount = debounce(
this.updateUnreadCount.bind(this),
SECOND,
{
leading: true,
maxWait: SECOND,
trailing: true,
}
);
// A few things can cause us to update the app-level unread count
window.Whisper.events.on('updateUnreadCount', debouncedUpdateUnreadCount);
this._conversations.on(
'add remove change:active_at change:unreadCount change:markedUnread change:isArchived change:muteExpiresAt',
debouncedUpdateUnreadCount
);
// If the conversation is muted we set a timeout so when the mute expires
// we can reset the mute state on the model. If the mute has already expired
// then we reset the state right away.
this._conversations.on('add', (model: ConversationModel): void => {
model.startMuteTimer();
});
}
updateUnreadCount(): void {
if (!this._hasQueueEmptied) {
return;
}
const canCountMutedConversations =
window.storage.get('badge-count-muted-conversations') || false;
const newUnreadCount = this._conversations.reduce(
(result: number, conversation: ConversationModel) =>
result +
getConversationUnreadCountForAppBadge(
conversation.attributes,
canCountMutedConversations
),
0
);
window.storage.put('unreadCount', newUnreadCount);
if (newUnreadCount > 0) {
window.setBadgeCount(newUnreadCount);
window.document.title = `${window.getTitle()} (${newUnreadCount})`;
} else {
window.setBadgeCount(0);
window.document.title = window.getTitle();
}
window.updateTrayIcon(newUnreadCount);
}
onEmpty(): void {
this._hasQueueEmptied = true;
this.updateUnreadCount();
}
get(id?: string | null): ConversationModel | undefined {
if (!this._initialFetchComplete) {
throw new Error(
'ConversationController.get() needs complete initial fetch'
);
}
// This function takes null just fine. Backbone typings are too restrictive.
return this._conversations.get(id as string);
}
getAll(): Array<ConversationModel> {
return this._conversations.models;
}
dangerouslyCreateAndAdd(
attributes: Partial<ConversationAttributesType>
): ConversationModel {
return this._conversations.add(attributes);
}
dangerouslyRemoveById(id: string): void {
this._conversations.remove(id);
this._conversations.resetLookups();
}
getOrCreate(
identifier: string | null,
type: ConversationAttributesTypeType,
additionalInitialProps = {}
): ConversationModel {
if (typeof identifier !== 'string') {
throw new TypeError("'id' must be a string");
}
if (type !== 'private' && type !== 'group') {
throw new TypeError(
`'type' must be 'private' or 'group'; got: '${type}'`
);
}
if (!this._initialFetchComplete) {
throw new Error(
'ConversationController.get() needs complete initial fetch'
);
}
let conversation = this._conversations.get(identifier);
if (conversation) {
return conversation;
}
const id = UUID.generate().toString();
if (type === 'group') {
conversation = this._conversations.add({
id,
uuid: undefined,
e164: undefined,
groupId: identifier,
type,
version: 2,
...additionalInitialProps,
});
} else if (isValidUuid(identifier)) {
conversation = this._conversations.add({
id,
uuid: identifier,
e164: undefined,
groupId: undefined,
type,
version: 2,
...additionalInitialProps,
});
} else {
conversation = this._conversations.add({
id,
uuid: undefined,
e164: identifier,
groupId: undefined,
type,
version: 2,
...additionalInitialProps,
});
}
const create = async () => {
if (!conversation.isValid()) {
const validationError = conversation.validationError || {};
log.error(
'Contact is not valid. Not saving, but adding to collection:',
conversation.idForLogging(),
validationError.stack
);
return conversation;
}
try {
if (isGroupV1(conversation.attributes)) {
maybeDeriveGroupV2Id(conversation);
}
await saveConversation(conversation.attributes);
} catch (error) {
log.error(
'Conversation save failed! ',
identifier,
type,
'Error:',
error && error.stack ? error.stack : error
);
throw error;
}
return conversation;
};
conversation.initialPromise = create();
return conversation;
}
async getOrCreateAndWait(
id: string | null,
type: ConversationAttributesTypeType,
additionalInitialProps = {}
): Promise<ConversationModel> {
await this.load();
const conversation = this.getOrCreate(id, type, additionalInitialProps);
if (conversation) {
await conversation.initialPromise;
return conversation;
}
throw new Error('getOrCreateAndWait: did not get conversation');
}
getConversationId(address: string | null): string | null {
if (!address) {
return null;
}
const [id] = window.textsecure.utils.unencodeNumber(address);
const conv = this.get(id);
if (conv) {
return conv.get('id');
}
return null;
}
getOurConversationId(): string | undefined {
const e164 = window.textsecure.storage.user.getNumber();
const aci = window.textsecure.storage.user
.getUuid(UUIDKind.ACI)
?.toString();
const pni = window.textsecure.storage.user
.getUuid(UUIDKind.PNI)
?.toString();
if (!e164 && !aci && !pni) {
return undefined;
}
const conversation = this.maybeMergeContacts({
aci,
e164,
pni,
reason: 'getOurConversationId',
});
return conversation?.id;
}
getOurConversationIdOrThrow(): string {
const conversationId = this.getOurConversationId();
if (!conversationId) {
throw new Error(
'getOurConversationIdOrThrow: Failed to fetch ourConversationId'
);
}
return conversationId;
}
getOurConversation(): ConversationModel | undefined {
const conversationId = this.getOurConversationId();
return conversationId ? this.get(conversationId) : undefined;
}
getOurConversationOrThrow(): ConversationModel {
const conversation = this.getOurConversation();
if (!conversation) {
throw new Error(
'getOurConversationOrThrow: Failed to fetch our own conversation'
);
}
return conversation;
}
areWePrimaryDevice(): boolean {
const ourDeviceId = window.textsecure.storage.user.getDeviceId();
return ourDeviceId === 1;
}
// Note: If you don't know what kind of UUID it is, put it in the 'aci' param.
maybeMergeContacts({
aci: providedAci,
e164,
pni: providedPni,
reason,
mergeOldAndNew = safeCombineConversations,
}: {
aci?: string;
e164?: string;
pni?: string;
reason: string;
recursionCount?: number;
mergeOldAndNew?: (options: {
logId: string;
oldConversation: ConversationModel;
newConversation: ConversationModel;
}) => Promise<void>;
}): ConversationModel | undefined {
const dataProvided = [];
if (providedAci) {
dataProvided.push('aci');
}
if (e164) {
dataProvided.push('e164');
}
if (providedPni) {
dataProvided.push('pni');
}
const logId = `maybeMergeContacts/${reason}/${dataProvided.join('+')}`;
const aci = providedAci ? UUID.cast(providedAci) : undefined;
const pni = providedPni ? UUID.cast(providedPni) : undefined;
if (!aci && !e164 && !pni) {
throw new Error(
`${logId}: Need to provide at least one of: aci, e164, pni`
);
}
const identifier = aci || e164 || pni;
strictAssert(identifier, `${logId}: identifier must be truthy!`);
const matches: Array<ConvoMatchType> = [
{
key: 'uuid',
value: aci,
match: window.ConversationController.get(aci),
},
{
key: 'e164',
value: e164,
match: window.ConversationController.get(e164),
},
{ key: 'pni', value: pni, match: window.ConversationController.get(pni) },
];
let unusedMatches: Array<ConvoMatchType> = [];
let targetConversation: ConversationModel | undefined;
let matchCount = 0;
matches.forEach(item => {
const { key, value, match } = item;
if (!value) {
return;
}
if (!match) {
if (targetConversation) {
log.info(
`${logId}: No match for ${key}, applying to target conversation`
);
// Note: This line might erase a known e164 or PNI
applyChangeToConversation(targetConversation, {
[key]: value,
});
} else {
unusedMatches.push(item);
}
return;
}
matchCount += 1;
unusedMatches.forEach(unused => {
strictAssert(unused.value, 'An unused value should always be truthy');
// Example: If we find that our PNI match has no ACI, then it will be our target.
// Tricky: PNI can end up in UUID slot, so we need to special-case it
if (
!targetConversation &&
(!match.get(unused.key) ||
(unused.key === 'uuid' && match.get(unused.key) === pni))
) {
log.info(
`${logId}: Match on ${key} does not have ${unused.key}, ` +
`so it will be our target conversation - ${match.idForLogging()}`
);
targetConversation = match;
}
// If PNI match already has an ACI, then we need to create a new one
if (!targetConversation) {
targetConversation = this.getOrCreate(unused.value, 'private');
log.info(
`${logId}: Match on ${key} already had ${unused.key}, ` +
`so created new target conversation - ${targetConversation.idForLogging()}`
);
}
log.info(
`${logId}: Applying new value for ${unused.key} to target conversation`
);
applyChangeToConversation(targetConversation, {
[unused.key]: unused.value,
});
});
unusedMatches = [];
if (targetConversation && targetConversation !== match) {
// Clear the value on the current match, since it belongs on targetConversation!
// Note: we need to do the remove first, because it will clear the lookup!
log.info(
`${logId}: Clearing ${key} on match, and adding it to target conversation`
);
const change: Pick<
Partial<ConversationAttributesType>,
'uuid' | 'e164' | 'pni'
> = {
[key]: undefined,
};
// When the PNI is being used in the uuid field alone, we need to clear it
if (key === 'pni' && match.get('uuid') === pni) {
change.uuid = undefined;
}
applyChangeToConversation(match, change);
applyChangeToConversation(targetConversation, {
[key]: value,
});
// Note: The PNI check here is just to be bulletproof; if we know a UUID is a PNI,
// then that should be put in the UUID field as well!
if (!match.get('uuid') && !match.get('e164') && !match.get('pni')) {
log.warn(
`${logId}: Removing old conversation which matched on ${key}. ` +
'Merging with target conversation.'
);
mergeOldAndNew({
logId,
oldConversation: match,
newConversation: targetConversation,
});
}
} else if (targetConversation && !targetConversation?.get(key)) {
// This is mostly for the situation where PNI was erased when updating e164
log.debug(`${logId}: Re-adding ${key} on target conversation`);
applyChangeToConversation(targetConversation, {
[key]: value,
});
}
if (!targetConversation) {
// log.debug(
// `${logId}: Match on ${key} is target conversation - ${match.idForLogging()}`
// );
targetConversation = match;
}
});
if (targetConversation) {
return targetConversation;
}
strictAssert(
matchCount === 0,
`${logId}: should be no matches if no targetConversation`
);
log.info(`${logId}: Creating a new conversation with all inputs`);
return this.getOrCreate(identifier, 'private', { e164, pni });
}
/**
* Given a UUID and/or an E164, returns a string representing the local
* database id of the given contact. Will create a new conversation if none exists;
* otherwise will return whatever is found.
*/
lookupOrCreate({
e164,
uuid,
}: {
e164?: string | null;
uuid?: string | null;
}): ConversationModel | undefined {
const normalizedUuid = uuid ? uuid.toLowerCase() : undefined;
const identifier = normalizedUuid || e164;
if ((!e164 && !uuid) || !identifier) {
log.warn('lookupOrCreate: Called with neither e164 nor uuid!');
return undefined;
}
const convoE164 = this.get(e164);
const convoUuid = this.get(normalizedUuid);
// 1. Handle no match at all
if (!convoE164 && !convoUuid) {
log.info('lookupOrCreate: Creating new contact, no matches found');
const newConvo = this.getOrCreate(identifier, 'private');
// `identifier` would resolve to uuid if we had both, so fix up e164
if (normalizedUuid && e164) {
newConvo.updateE164(e164);
}
return newConvo;
}
// 2. Handle match on only UUID
if (!convoE164 && convoUuid) {
return convoUuid;
}
// 3. Handle match on only E164
if (convoE164 && !convoUuid) {
return convoE164;
}
// For some reason, TypeScript doesn't believe that we can trust that these two values
// are truthy by this point. So we'll throw if that isn't the case.
if (!convoE164 || !convoUuid) {
throw new Error(
'lookupOrCreate: convoE164 or convoUuid are falsey but should both be true!'
);
}
// 4. If the two lookups agree, return that conversation
if (convoE164 === convoUuid) {
return convoUuid;
}
// 5. If the two lookups disagree, log and return the UUID match
log.warn(
`lookupOrCreate: Found a split contact - UUID ${normalizedUuid} and E164 ${e164}. Returning UUID match.`
);
return convoUuid;
}
async checkForConflicts(): Promise<void> {
log.info('checkForConflicts: starting...');
const byUuid = Object.create(null);
const byE164 = Object.create(null);
const byPni = Object.create(null);
const byGroupV2Id = Object.create(null);
// We also want to find duplicate GV1 IDs. You might expect to see a "byGroupV1Id" map
// here. Instead, we check for duplicates on the derived GV2 ID.
const { models } = this._conversations;
// We iterate from the oldest conversations to the newest. This allows us, in a
// conflict case, to keep the one with activity the most recently.
for (let i = models.length - 1; i >= 0; i -= 1) {
const conversation = models[i];
assert(
conversation,
'Expected conversation to be found in array during iteration'
);
const uuid = conversation.get('uuid');
const pni = conversation.get('pni');
const e164 = conversation.get('e164');
if (uuid) {
const existing = byUuid[uuid];
if (!existing) {
byUuid[uuid] = conversation;
} else {
log.warn(`checkForConflicts: Found conflict with uuid ${uuid}`);
// Keep the newer one if it has an e164, otherwise keep existing
if (conversation.get('e164')) {
// Keep new one
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(conversation, existing);
byUuid[uuid] = conversation;
} else {
// Keep existing - note that this applies if neither had an e164
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(existing, conversation);
}
}
}
if (pni) {
const existing = byPni[pni];
if (!existing) {
byPni[pni] = conversation;
} else {
log.warn(`checkForConflicts: Found conflict with pni ${pni}`);
// Keep the newer one if it has a uuid, otherwise keep existing
if (conversation.get('uuid')) {
// Keep new one
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(conversation, existing);
byPni[pni] = conversation;
} else {
// Keep existing - note that this applies if neither had an e164
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(existing, conversation);
}
}
}
if (e164) {
const existing = byE164[e164];
if (!existing) {
byE164[e164] = conversation;
} else {
// If we have two contacts with the same e164 but different truthy UUIDs, then
// we'll delete the e164 on the older one
if (
conversation.get('uuid') &&
existing.get('uuid') &&
conversation.get('uuid') !== existing.get('uuid')
) {
log.warn(
`checkForConflicts: Found two matches on e164 ${e164} with different truthy UUIDs. Dropping e164 on older.`
);
existing.set({ e164: undefined });
updateConversation(existing.attributes);
byE164[e164] = conversation;
continue;
}
log.warn(`checkForConflicts: Found conflict with e164 ${e164}`);
// Keep the newer one if it has a UUID, otherwise keep existing
if (conversation.get('uuid')) {
// Keep new one
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(conversation, existing);
byE164[e164] = conversation;
} else {
// Keep existing - note that this applies if neither had a UUID
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(existing, conversation);
}
}
}
let groupV2Id: undefined | string;
if (isGroupV1(conversation.attributes)) {
maybeDeriveGroupV2Id(conversation);
groupV2Id = conversation.get('derivedGroupV2Id');
assert(
groupV2Id,
'checkForConflicts: expected the group V2 ID to have been derived, but it was falsy'
);
} else if (isGroupV2(conversation.attributes)) {
groupV2Id = conversation.get('groupId');
}
if (groupV2Id) {
const existing = byGroupV2Id[groupV2Id];
if (!existing) {
byGroupV2Id[groupV2Id] = conversation;
} else {
const logParenthetical = isGroupV1(conversation.attributes)
? ' (derived from a GV1 group ID)'
: '';
log.warn(
`checkForConflicts: Found conflict with group V2 ID ${groupV2Id}${logParenthetical}`
);
// Prefer the GV2 group.
if (
isGroupV2(conversation.attributes) &&
!isGroupV2(existing.attributes)
) {
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(conversation, existing);
byGroupV2Id[groupV2Id] = conversation;
} else {
// eslint-disable-next-line no-await-in-loop
await this.combineConversations(existing, conversation);
}
}
}
}
log.info('checkForConflicts: complete!');
}
async combineConversations(
current: ConversationModel,
obsolete: ConversationModel
): Promise<void> {
const logId = `combineConversations/${obsolete.id}->${current.id}`;
return this._combineConversationsQueue.add(async () => {
const conversationType = current.get('type');
if (!this.get(obsolete.id)) {
log.warn(`${logId}: Already combined obsolete conversation`);
}
if (obsolete.get('type') !== conversationType) {
assert(
false,
`${logId}: cannot combine a private and group conversation. Doing nothing`
);
return;
}
const dataToCopy: Partial<ConversationAttributesType> = pick(
obsolete.attributes,
[
'conversationColor',
'customColor',
'customColorId',
'draftAttachments',
'draftBodyRanges',
'draftTimestamp',
'messageCount',
'messageRequestResponseType',
'quotedMessageId',
'sentMessageCount',
]
);
const keys = Object.keys(dataToCopy) as Array<
keyof ConversationAttributesType
>;
keys.forEach(key => {
if (current.get(key) === undefined) {
current.set(key, dataToCopy[key]);
// To ensure that any files on disk don't get deleted out from under us
if (key === 'draftAttachments') {
obsolete.set(key, undefined);
}
}
});
const obsoleteId = obsolete.get('id');
const obsoleteUuid = obsolete.getUuid();
const currentId = current.get('id');
log.warn(`${logId}: Combining two conversations...`);
if (conversationType === 'private' && obsoleteUuid) {
if (!current.get('profileKey') && obsolete.get('profileKey')) {
log.warn(`${logId}: Copying profile key from old to new contact`);
const profileKey = obsolete.get('profileKey');
if (profileKey) {
await current.setProfileKey(profileKey);
}
}
log.warn(`${logId}: Delete all sessions tied to old conversationId`);
const ourACI = window.textsecure.storage.user.getUuid(UUIDKind.ACI);
const ourPNI = window.textsecure.storage.user.getUuid(UUIDKind.PNI);
await Promise.all(
[ourACI, ourPNI].map(async ourUuid => {
if (!ourUuid) {
return;
}
const deviceIds =
await window.textsecure.storage.protocol.getDeviceIds({
ourUuid,
identifier: obsoleteUuid.toString(),
});
await Promise.all(
deviceIds.map(async deviceId => {
const addr = new QualifiedAddress(
ourUuid,
new Address(obsoleteUuid, deviceId)
);
await window.textsecure.storage.protocol.removeSession(addr);
})
);
})
);
log.warn(
`${logId}: Delete all identity information tied to old conversationId`
);
if (obsoleteUuid) {
await window.textsecure.storage.protocol.removeIdentityKey(
obsoleteUuid
);
}
log.warn(
`${logId}: Ensure that all V1 groups have new conversationId instead of old`
);
const groups = await this.getAllGroupsInvolvingUuid(obsoleteUuid);
groups.forEach(group => {
const members = group.get('members');
const withoutObsolete = without(members, obsoleteId);
const currentAdded = uniq([...withoutObsolete, currentId]);
group.set({
members: currentAdded,
});
updateConversation(group.attributes);
});
}
// Note: we explicitly don't want to update V2 groups
log.warn(`${logId}: Delete the obsolete conversation from the database`);
await removeConversation(obsoleteId);
log.warn(`${logId}: Update cached messages in MessageController`);
window.MessageController.update((message: MessageModel) => {
if (message.get('conversationId') === obsoleteId) {
message.set({ conversationId: currentId });
}
});
log.warn(`${logId}: Update messages table`);
await migrateConversationMessages(obsoleteId, currentId);
log.warn(
`${logId}: Emit refreshConversation event to close old/open new`
);
window.Whisper.events.trigger('refreshConversation', {
newId: currentId,
oldId: obsoleteId,
});
log.warn(
`${logId}: Eliminate old conversation from ConversationController lookups`
);
this._conversations.remove(obsolete);
this._conversations.resetLookups();
log.warn(`${logId}: Complete!`);
});
}
/**
* Given a groupId and optional additional initialization properties,
* ensures the existence of a group conversation and returns a string
* representing the local database ID of the group conversation.
*/
ensureGroup(groupId: string, additionalInitProps = {}): string {
return this.getOrCreate(groupId, 'group', additionalInitProps).get('id');
}
/**
* Given certain metadata about a message (an identifier of who wrote the
* message and the sent_at timestamp of the message) returns the
* conversation the message belongs to OR null if a conversation isn't
* found.
*/
async getConversationForTargetMessage(
targetFromId: string,
targetTimestamp: number
): Promise<ConversationModel | null | undefined> {
const messages = await getMessagesBySentAt(targetTimestamp);
const targetMessage = messages.find(m => getContactId(m) === targetFromId);
if (targetMessage) {
return this.get(targetMessage.conversationId);
}
return null;
}
async getAllGroupsInvolvingUuid(
uuid: UUID
): Promise<Array<ConversationModel>> {
const groups = await getAllGroupsInvolvingUuid(uuid.toString());
return groups.map(group => {
const existing = this.get(group.id);
if (existing) {
return existing;
}