/
contactSync.ts
199 lines (171 loc) · 6.16 KB
/
contactSync.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
// Copyright 2020-2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import PQueue from 'p-queue';
import type { ContactSyncEvent } from '../textsecure/messageReceiverEvents';
import type { ModifiedContactDetails } from '../textsecure/ContactsParser';
import { UUID } from '../types/UUID';
import * as Conversation from '../types/Conversation';
import * as Errors from '../types/errors';
import type { ValidateConversationType } from '../model-types.d';
import type { ConversationModel } from '../models/conversations';
import { validateConversation } from '../util/validateConversation';
import { strictAssert } from '../util/assert';
import { isDirectConversation, isMe } from '../util/whatTypeOfConversation';
import { normalizeUuid } from '../util/normalizeUuid';
import * as log from '../logging/log';
// When true - we are running the very first storage and contact sync after
// linking.
let isInitialSync = false;
export function setIsInitialSync(newValue: boolean): void {
log.info(`setIsInitialSync(${newValue})`);
isInitialSync = newValue;
}
async function updateConversationFromContactSync(
conversation: ConversationModel,
details: ModifiedContactDetails,
receivedAtCounter: number,
sentAt: number
): Promise<void> {
const { writeNewAttachmentData, deleteAttachmentData, doesAttachmentExist } =
window.Signal.Migrations;
conversation.set({
name: details.name,
inbox_position: details.inboxPosition,
});
// Update the conversation avatar only if new avatar exists and hash differs
const { avatar } = details;
if (avatar && avatar.data) {
const newAttributes = await Conversation.maybeUpdateAvatar(
conversation.attributes,
avatar.data,
{
writeNewAttachmentData,
deleteAttachmentData,
doesAttachmentExist,
}
);
conversation.set(newAttributes);
} else {
const { attributes } = conversation;
if (attributes.avatar && attributes.avatar.path) {
await deleteAttachmentData(attributes.avatar.path);
}
conversation.set({ avatar: null });
}
// expireTimer isn't in Storage Service so we have to rely on contact sync.
await conversation.updateExpirationTimer(details.expireTimer, {
// Note: because it's our conversationId, this notification will be marked read. But
// setting this will make 'isSetByOther' check true.
source: window.ConversationController.getOurConversationId(),
receivedAt: receivedAtCounter,
fromSync: true,
isInitialSync,
reason: `contact sync (sent=${sentAt})`,
});
window.Whisper.events.trigger('incrementProgress');
}
const queue = new PQueue({ concurrency: 1 });
async function doContactSync({
contacts,
complete,
receivedAtCounter,
sentAt,
}: ContactSyncEvent): Promise<void> {
// iOS sets `syncMessage.contacts.complete` flag to `true` unconditionally
// and so we have to employ tricks to figure out whether the sync is full or
// partial. Thankfully, iOS sends only two kinds of contact syncs: full or
// local sync. Local sync is always a single our own contact so we can do an
// UUID check.
const isFullSync =
complete &&
!(
contacts.length === 1 &&
normalizeUuid(contacts[0].uuid, 'doContactSync') ===
window.storage.user.getUuid()?.toString()
);
const logId = `doContactSync(sent=${sentAt}, receivedAt=${receivedAtCounter}, isFullSync=${isFullSync})`;
log.info(`${logId}: got ${contacts.length} contacts`);
const updatedConversations = new Set<ConversationModel>();
let promises = new Array<Promise<void>>();
for (const details of contacts) {
const partialConversation: ValidateConversationType = {
e164: details.number,
uuid: UUID.cast(details.uuid),
type: 'private',
};
const validationError = validateConversation(partialConversation);
if (validationError) {
log.error(
`${logId}: Invalid contact received`,
Errors.toLogFormat(validationError)
);
continue;
}
const conversation = window.ConversationController.maybeMergeContacts({
e164: details.number,
aci: details.uuid,
reason: logId,
});
strictAssert(conversation, 'need conversation to queue the job!');
// It's important to use queueJob here because we might update the expiration timer
// and we don't want conflicts with incoming message processing happening on the
// conversation queue.
const job = conversation.queueJob(`${logId}.set`, async () => {
try {
await updateConversationFromContactSync(
conversation,
details,
receivedAtCounter,
sentAt
);
updatedConversations.add(conversation);
} catch (error) {
log.error(
'updateConversationFromContactSync error:',
Errors.toLogFormat(error)
);
}
});
promises.push(job);
}
// updatedConversations are not populated until the promises are resolved
await Promise.all(promises);
promises = [];
// Erase data in conversations that are not the part of contact sync only
// if we received a full contact sync (and not a one-off contact update).
const notUpdated = isFullSync
? window.ConversationController.getAll().filter(
convo =>
!updatedConversations.has(convo) &&
isDirectConversation(convo.attributes) &&
!isMe(convo.attributes)
)
: [];
log.info(
`${logId}: ` +
`updated ${updatedConversations.size} ` +
`resetting ${notUpdated.length}`
);
for (const conversation of notUpdated) {
conversation.set({
name: undefined,
inbox_position: undefined,
});
}
// Save new conversation attributes
promises.push(
window.Signal.Data.updateConversations(
[...updatedConversations, ...notUpdated].map(convo => convo.attributes)
)
);
await Promise.all(promises);
await window.storage.put('synced_at', Date.now());
window.Whisper.events.trigger('contactSync:complete');
log.info(`${logId}: done`);
}
export async function onContactSync(ev: ContactSyncEvent): Promise<void> {
log.info(
`onContactSync(sent=${ev.sentAt}, receivedAt=${ev.receivedAtCounter}): queueing sync`
);
await queue.add(() => doContactSync(ev));
}