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

Commit 1233d6a

Browse files
committed
Use new crypto api to send to-device messages from widgets
1 parent b67a230 commit 1233d6a

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
@@ -430,33 +430,28 @@ export class StopGapWidgetDriver extends WidgetDriver {
430430
const client = MatrixClientPeg.safeGet();
431431

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

0 commit comments

Comments
 (0)