-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
sendStoryMessage.ts
335 lines (293 loc) · 10.6 KB
/
sendStoryMessage.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
// Copyright 2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import type { AttachmentType } from '../types/Attachment';
import type { MessageAttributesType } from '../model-types.d';
import type { SendStateByConversationId } from '../messages/MessageSendState';
import type { UUIDStringType } from '../types/UUID';
import * as log from '../logging/log';
import dataInterface from '../sql/Client';
import { DAY, SECOND } from './durations';
import { MY_STORIES_ID } from '../types/Stories';
import { getStoriesBlocked } from './stories';
import { ReadStatus } from '../messages/MessageReadStatus';
import { SeenStatus } from '../MessageSeenStatus';
import { SendStatus } from '../messages/MessageSendState';
import { UUID } from '../types/UUID';
import {
conversationJobQueue,
conversationQueueJobEnum,
} from '../jobs/conversationJobQueue';
import { getRecipients } from './getRecipients';
import { getSignalConnections } from './getSignalConnections';
import { incrementMessageCounter } from './incrementMessageCounter';
import { isGroupV2 } from './whatTypeOfConversation';
import { isNotNil } from './isNotNil';
export async function sendStoryMessage(
listIds: Array<string>,
conversationIds: Array<string>,
attachment: AttachmentType
): Promise<void> {
if (getStoriesBlocked()) {
log.warn('stories.sendStoryMessage: stories disabled, returning early');
return;
}
const { messaging } = window.textsecure;
if (!messaging) {
log.warn(
'stories.sendStoryMessage: messaging not available, returning early'
);
return;
}
const distributionLists = (
await Promise.all(
listIds.map(listId =>
dataInterface.getStoryDistributionWithMembers(listId)
)
)
).filter(isNotNil);
if (!distributionLists.length && !conversationIds.length) {
log.warn(
'stories.sendStoryMessage: Dropping send. no conversations to send to and no distribution lists found for',
listIds
);
return;
}
const ourConversation =
window.ConversationController.getOurConversationOrThrow();
const timestamp = Date.now();
const sendStateByListId = new Map<
UUIDStringType,
SendStateByConversationId
>();
const recipientsAlreadySentTo = new Map<UUIDStringType, boolean>();
// * Create the custom sendStateByConversationId for each distribution list
// * De-dupe members to make sure they're only sent to once
// * Figure out who can reply/who can't
distributionLists
.sort(list => (list.allowsReplies ? -1 : 1))
.forEach(distributionList => {
const sendStateByConversationId: SendStateByConversationId = {};
let distributionListMembers: Array<UUIDStringType> = [];
if (
distributionList.id === MY_STORIES_ID &&
distributionList.isBlockList
) {
const inBlockList = new Set<UUIDStringType>(distributionList.members);
distributionListMembers = getSignalConnections().reduce(
(acc, convo) => {
const id = convo.get('uuid');
if (!id) {
return acc;
}
const uuid = UUID.cast(id);
if (inBlockList.has(uuid)) {
return acc;
}
acc.push(uuid);
return acc;
},
[] as Array<UUIDStringType>
);
} else {
distributionListMembers = distributionList.members;
}
distributionListMembers.forEach(destinationUuid => {
const conversation = window.ConversationController.get(destinationUuid);
if (!conversation) {
return;
}
sendStateByConversationId[conversation.id] = {
isAllowedToReplyToStory:
recipientsAlreadySentTo.get(destinationUuid) ||
distributionList.allowsReplies,
isAlreadyIncludedInAnotherDistributionList:
recipientsAlreadySentTo.has(destinationUuid),
status: SendStatus.Pending,
updatedAt: timestamp,
};
if (!recipientsAlreadySentTo.has(destinationUuid)) {
recipientsAlreadySentTo.set(
destinationUuid,
distributionList.allowsReplies
);
}
});
sendStateByListId.set(distributionList.id, sendStateByConversationId);
});
const attachments: Array<AttachmentType> = [attachment];
// * Gather all the job data we'll be sending to the sendStory job
// * Create the message for each distribution list
const distributionListMessages: Array<MessageAttributesType> =
await Promise.all(
distributionLists.map(async distributionList => {
const sendStateByConversationId = sendStateByListId.get(
distributionList.id
);
if (!sendStateByConversationId) {
log.warn(
'stories.sendStoryMessage: No sendStateByConversationId for distribution list',
distributionList.id
);
}
// Note: we use the same sent_at for these messages because we want de-duplication
// on the receiver side.
return window.Signal.Migrations.upgradeMessageSchema({
attachments,
conversationId: ourConversation.id,
expireTimer: DAY / SECOND,
expirationStartTimestamp: Date.now(),
id: UUID.generate().toString(),
readStatus: ReadStatus.Read,
received_at: incrementMessageCounter(),
received_at_ms: timestamp,
seenStatus: SeenStatus.NotApplicable,
sendStateByConversationId,
sent_at: timestamp,
source: window.textsecure.storage.user.getNumber(),
sourceUuid: window.textsecure.storage.user.getUuid()?.toString(),
sourceDevice: window.textsecure.storage.user.getDeviceId(),
storyDistributionListId: distributionList.id,
timestamp,
type: 'story',
});
})
);
const groupV2MessagesByConversationId = new Map<
string,
MessageAttributesType
>();
await Promise.all(
conversationIds.map(async (conversationId, index) => {
const group = window.ConversationController.get(conversationId);
if (!group) {
log.warn(
'stories.sendStoryMessage: No group found for id',
conversationId
);
return;
}
if (!isGroupV2(group.attributes)) {
log.warn(
'stories.sendStoryMessage: Conversation we tried to send to is not a groupV2',
conversationId
);
return;
}
if (group.get('announcementsOnly') && !group.areWeAdmin()) {
log.warn(
'stories.sendStoryMessage: cannot send to an announcement only group as a non-admin',
conversationId
);
return;
}
// We want all of these timestamps to be different from the My Story timestamp.
const groupTimestamp = timestamp + index + 1;
const myId = window.ConversationController.getOurConversationIdOrThrow();
const sendState = {
status: SendStatus.Pending,
updatedAt: groupTimestamp,
};
const sendStateByConversationId = getRecipients(group.attributes).reduce(
(acc, id) => {
const conversation = window.ConversationController.get(id);
if (!conversation) {
return acc;
}
return {
...acc,
[conversation.id]: sendState,
};
},
{
[myId]: sendState,
}
);
const messageAttributes =
await window.Signal.Migrations.upgradeMessageSchema({
attachments,
canReplyToStory: true,
conversationId,
expireTimer: DAY / SECOND,
expirationStartTimestamp: Date.now(),
id: UUID.generate().toString(),
readStatus: ReadStatus.Read,
received_at: incrementMessageCounter(),
received_at_ms: groupTimestamp,
seenStatus: SeenStatus.NotApplicable,
sendStateByConversationId,
sent_at: groupTimestamp,
source: window.textsecure.storage.user.getNumber(),
sourceUuid: window.textsecure.storage.user.getUuid()?.toString(),
sourceDevice: window.textsecure.storage.user.getDeviceId(),
timestamp: groupTimestamp,
type: 'story',
});
groupV2MessagesByConversationId.set(conversationId, messageAttributes);
})
);
// For distribution lists:
// * Save the message model
// * Add the message to the conversation
await Promise.all(
distributionListMessages.map(messageAttributes => {
const model = new window.Whisper.Message(messageAttributes);
const message = window.MessageController.register(model.id, model);
ourConversation.addSingleMessage(model, { isJustSent: true });
log.info(
`stories.sendStoryMessage: saving message ${messageAttributes.timestamp}`
);
return dataInterface.saveMessage(message.attributes, {
forceSave: true,
ourUuid: window.textsecure.storage.user.getCheckedUuid().toString(),
});
})
);
// * Send to the distribution lists
// * Place into job queue
// * Save the job
await conversationJobQueue.add({
type: conversationQueueJobEnum.enum.Story,
conversationId: ourConversation.id,
messageIds: distributionListMessages.map(m => m.id),
timestamp,
});
// * Send to groups
// * Save the message models
// * Add message to group conversation
await Promise.all(
conversationIds.map(conversationId => {
const messageAttributes =
groupV2MessagesByConversationId.get(conversationId);
if (!messageAttributes) {
log.warn(
'stories.sendStoryMessage: Trying to send a group story but it did not exist? This is unexpected. Not sending.',
conversationId
);
return;
}
return conversationJobQueue.add(
{
type: conversationQueueJobEnum.enum.Story,
conversationId,
messageIds: [messageAttributes.id],
// using the group timestamp, which will differ from the 1:1 timestamp
timestamp: messageAttributes.timestamp,
},
async jobToInsert => {
const model = new window.Whisper.Message(messageAttributes);
const message = window.MessageController.register(model.id, model);
const conversation = message.getConversation();
conversation?.addSingleMessage(model, { isJustSent: true });
log.info(
`stories.sendStoryMessage: saving message ${messageAttributes.timestamp}`
);
await dataInterface.saveMessage(message.attributes, {
forceSave: true,
jobToInsert,
ourUuid: window.textsecure.storage.user.getCheckedUuid().toString(),
});
}
);
})
);
}