Skip to content
This repository was archived by the owner on Oct 22, 2024. It is now read-only.

Commit d16dfc8

Browse files
committed
Use new crypto api to send to-device messages from widgets
1 parent 1e76313 commit d16dfc8

File tree

1 file changed

+22
-27
lines changed

1 file changed

+22
-27
lines changed

src/stores/widgets/StopGapWidgetDriver.ts

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -422,33 +422,28 @@ export class StopGapWidgetDriver extends WidgetDriver {
422422
const client = MatrixClientPeg.safeGet();
423423

424424
if (encrypted) {
425-
const deviceInfoMap = await client.crypto!.deviceList.downloadKeys(Object.keys(contentMap), false);
426-
427-
await Promise.all(
428-
Object.entries(contentMap).flatMap(([userId, userContentMap]) =>
429-
Object.entries(userContentMap).map(async ([deviceId, content]): Promise<void> => {
430-
const devices = deviceInfoMap.get(userId);
431-
if (!devices) return;
432-
433-
if (deviceId === "*") {
434-
// Send the message to all devices we have keys for
435-
await client.encryptAndSendToDevices(
436-
Array.from(devices.values()).map((deviceInfo) => ({
437-
userId,
438-
deviceInfo,
439-
})),
440-
content,
441-
);
442-
} else if (devices.has(deviceId)) {
443-
// Send the message to a specific device
444-
await client.encryptAndSendToDevices(
445-
[{ userId, deviceInfo: devices.get(deviceId)! }],
446-
content,
447-
);
448-
}
449-
}),
450-
),
451-
);
425+
const crypto = client.getCrypto();
426+
if (!crypto) throw new Error("E2EE not enabled");
427+
428+
// attempt to re-batch these up into a single request
429+
const invertedContentMap: { [content: string]: { userId: string; deviceId: string }[] } = {};
430+
431+
Object.entries(contentMap).forEach(([userId, userContentMap]) =>
432+
Object.entries(userContentMap).forEach(([deviceId, content]) => {
433+
const stringifiedContent = JSON.stringify(content);
434+
invertedContentMap[stringifiedContent] = invertedContentMap[stringifiedContent] || [];
435+
436+
invertedContentMap[stringifiedContent].push({ userId, deviceId });
437+
}),
438+
),
439+
440+
await Promise.all(Object.entries(invertedContentMap).map(
441+
async ([stringifiedContent, recipients]) => {
442+
const batch = await crypto.encryptToDeviceMessages(eventType, recipients, JSON.parse(stringifiedContent));
443+
444+
await client.queueToDevice(batch);
445+
},
446+
));
452447
} else {
453448
await client.queueToDevice({
454449
eventType,

0 commit comments

Comments
 (0)