From 3acfda3a5609e977f60ce2ad5ad4f178e65ad3d6 Mon Sep 17 00:00:00 2001
From: lilia <liliakai@gmail.com>
Date: Mon, 19 Jun 2017 12:26:00 -0700
Subject: [PATCH] Archive sessions on key changes after profile fetch

// FREEBIE
---
 js/models/conversations.js  |  8 ++++++--
 js/signal_protocol_store.js | 10 ++++++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/js/models/conversations.js b/js/models/conversations.js
index 79716b48a..2135b36e9 100644
--- a/js/models/conversations.js
+++ b/js/models/conversations.js
@@ -589,8 +589,12 @@
             var identityKey = dcodeIO.ByteBuffer.wrap(profile.identityKey, 'base64').toArrayBuffer();
 
             return textsecure.storage.protocol.saveIdentity(
-              id, identityKey, false
-            );
+                id, identityKey, false
+            ).then(function(isIdentityChange) {
+                if (isIdentityChange) {
+                    return textsecure.storage.protocol.archiveAllSessions(id);
+                }
+            });
         });
     },
 
diff --git a/js/signal_protocol_store.js b/js/signal_protocol_store.js
index 058bb5184..bcb8359fc 100644
--- a/js/signal_protocol_store.js
+++ b/js/signal_protocol_store.js
@@ -338,6 +338,16 @@
                 });
             });
         },
+        archiveAllSessions: function(number) {
+            return this.getDeviceIds(number).then(function(deviceIds) {
+                return Promise.all(deviceIds.map(function(deviceId) {
+                    var address = new libsignal.SignalProtocolAddress(number, deviceId);
+                    console.log('closing session for', address.toString());
+                    var sessionCipher = new libsignal.SessionCipher(textsecure.storage.protocol, address);
+                    return sessionCipher.closeOpenSessionForDevice();
+                }));
+            });
+        },
         clearSessionStore: function() {
             return new Promise(function(resolve) {
                 var sessions = new SessionCollection();