@@ -422,33 +422,28 @@ export class StopGapWidgetDriver extends WidgetDriver {
422
422
const client = MatrixClientPeg . safeGet ( ) ;
423
423
424
424
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
+ ) ) ;
452
447
} else {
453
448
await client . queueToDevice ( {
454
449
eventType,
0 commit comments