@@ -558,13 +558,20 @@ OlmDevice.prototype.getSessionIdsForDevice = async function(theirDeviceIdentityK
558
558
* @return {Promise<?string> } session id, or null if no established session
559
559
*/
560
560
OlmDevice . prototype . getSessionIdForDevice = async function ( theirDeviceIdentityKey ) {
561
- const sessionIds = await this . getSessionIdsForDevice ( theirDeviceIdentityKey ) ;
562
- if ( sessionIds . length === 0 ) {
561
+ const sessionInfos = await this . getSessionInfoForDevice ( theirDeviceIdentityKey ) ;
562
+ if ( sessionInfos . length === 0 ) {
563
563
return null ;
564
564
}
565
- // Use the session with the lowest ID.
566
- sessionIds . sort ( ) ;
567
- return sessionIds [ 0 ] ;
565
+ // Use the session that has most recently received a message
566
+ sessionInfos . sort ( ( a , b ) => {
567
+ if ( a . lastReceivedMessageTs !== b . lastReceivedMessageTs ) {
568
+ return a . lastReceivedMessageTs - b . lastReceivedMessageTs ;
569
+ } else {
570
+ if ( a . sessionId === b . sessionId ) return 0 ;
571
+ return a . sessionId < b . sessionId ? - 1 : 1 ;
572
+ }
573
+ } ) ;
574
+ return sessionInfos [ sessionInfos . length - 1 ] . sessionId ;
568
575
} ;
569
576
570
577
/**
@@ -589,6 +596,7 @@ OlmDevice.prototype.getSessionInfoForDevice = async function(deviceIdentityKey)
589
596
for ( const sessionId of sessionIds ) {
590
597
this . _unpickleSession ( sessions [ sessionId ] , ( session ) => {
591
598
info . push ( {
599
+ lastReceivedMessageTs : session . last_received_message_ts ( ) ,
592
600
hasReceivedMessage : session . has_received_message ( ) ,
593
601
sessionId : sessionId ,
594
602
} ) ;
@@ -649,6 +657,7 @@ OlmDevice.prototype.decryptMessage = async function(
649
657
( txn ) => {
650
658
this . _getSession ( theirDeviceIdentityKey , sessionId , txn , ( session ) => {
651
659
payloadString = session . decrypt ( messageType , ciphertext ) ;
660
+ session . set_last_received_message_ts ( Date . now ( ) ) ;
652
661
this . _saveSession ( theirDeviceIdentityKey , session , txn ) ;
653
662
} ) ;
654
663
} ,
0 commit comments