@@ -430,33 +430,28 @@ export class StopGapWidgetDriver extends WidgetDriver {
430
430
const client = MatrixClientPeg . safeGet ( ) ;
431
431
432
432
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
+ ) ) ;
460
455
} else {
461
456
await client . queueToDevice ( {
462
457
eventType,
0 commit comments