Search in sources :

Example 11 with IMXStore

use of org.matrix.androidsdk.data.store.IMXStore in project matrix-android-sdk by matrix-org.

the class MXSession method toggleDirectChatRoom.

/**
 * Toggles the direct chat status of a room.<br>
 * Create a new direct chat room in the account data section if the room does not exist,
 * otherwise the room is removed from the account data section.
 * Direct chat room user ID choice algorithm:<br>
 * 1- oldest joined room member
 * 2- oldest invited room member
 * 3- the user himself
 *
 * @param roomId             the room roomId
 * @param aParticipantUserId the participant user id
 * @param callback           the asynchronous callback
 */
public void toggleDirectChatRoom(String roomId, String aParticipantUserId, ApiCallback<Void> callback) {
    IMXStore store = getDataHandler().getStore();
    Room room = store.getRoom(roomId);
    if (null != room) {
        HashMap<String, List<String>> params;
        if (null != store.getDirectChatRoomsDict()) {
            params = new HashMap<>(store.getDirectChatRoomsDict());
        } else {
            params = new HashMap<>();
        }
        // if the room was not yet seen as direct chat
        if (!getDataHandler().getDirectChatRoomIdsList().contains(roomId)) {
            List<String> roomIdsList = new ArrayList<>();
            RoomMember directChatMember = null;
            String chosenUserId;
            if (null == aParticipantUserId) {
                List<RoomMember> members = new ArrayList<>(room.getActiveMembers());
                // should never happen but it was reported by a GA issue
                if (members.isEmpty()) {
                    return;
                }
                if (members.size() > 1) {
                    // sort algo: oldest join first, then oldest invited
                    Collections.sort(members, new Comparator<RoomMember>() {

                        @Override
                        public int compare(RoomMember r1, RoomMember r2) {
                            int res;
                            long diff;
                            if (RoomMember.MEMBERSHIP_JOIN.equals(r2.membership) && RoomMember.MEMBERSHIP_INVITE.equals(r1.membership)) {
                                res = 1;
                            } else if (r2.membership.equals(r1.membership)) {
                                diff = r1.getOriginServerTs() - r2.getOriginServerTs();
                                res = (0 == diff) ? 0 : ((diff > 0) ? 1 : -1);
                            } else {
                                res = -1;
                            }
                            return res;
                        }
                    });
                    int nextIndexSearch = 0;
                    // take the oldest join member
                    if (!TextUtils.equals(members.get(0).getUserId(), getMyUserId())) {
                        if (RoomMember.MEMBERSHIP_JOIN.equals(members.get(0).membership)) {
                            directChatMember = members.get(0);
                        }
                    } else {
                        nextIndexSearch = 1;
                        if (RoomMember.MEMBERSHIP_JOIN.equals(members.get(1).membership)) {
                            directChatMember = members.get(1);
                        }
                    }
                    // no join member found, test the oldest join member
                    if (null == directChatMember) {
                        if (RoomMember.MEMBERSHIP_INVITE.equals(members.get(nextIndexSearch).membership)) {
                            directChatMember = members.get(nextIndexSearch);
                        }
                    }
                }
                // last option: get the logged user
                if (null == directChatMember) {
                    directChatMember = members.get(0);
                }
                chosenUserId = directChatMember.getUserId();
            } else {
                chosenUserId = aParticipantUserId;
            }
            // search if there is an entry with the same user
            if (params.containsKey(chosenUserId)) {
                roomIdsList = new ArrayList<>(params.get(chosenUserId));
            }
            // update room list with the new room
            roomIdsList.add(roomId);
            params.put(chosenUserId, roomIdsList);
        } else {
            // remove the current room from the direct chat list rooms
            if (null != store.getDirectChatRoomsDict()) {
                List<String> keysList = new ArrayList<>(params.keySet());
                for (String key : keysList) {
                    List<String> roomIdsList = params.get(key);
                    if (roomIdsList.contains(roomId)) {
                        roomIdsList.remove(roomId);
                        if (roomIdsList.isEmpty()) {
                            // Remove this entry
                            params.remove(key);
                        }
                    }
                }
            } else {
                // should not happen: if the room has to be removed, it means the room has been
                // previously detected as being part of the listOfList
                Log.e(LOG_TAG, "## toggleDirectChatRoom(): failed to remove a direct chat room (not seen as direct chat room)");
                return;
            }
        }
        // Store and upload the updated map
        getDataHandler().setDirectChatRoomsMap(params, callback);
    }
}
Also used : IMXStore(org.matrix.androidsdk.data.store.IMXStore) ArrayList(java.util.ArrayList) RoomMember(org.matrix.androidsdk.rest.model.RoomMember) List(java.util.List) ArrayList(java.util.ArrayList) Room(org.matrix.androidsdk.data.Room)

Example 12 with IMXStore

use of org.matrix.androidsdk.data.store.IMXStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test24_testExportImport.

@Test
public void test24_testExportImport() throws Exception {
    Log.e(LOG_TAG, "test24_testExportImport");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    doE2ETestWithAliceInARoom();
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    String message = "Hello myself!";
    String password = "hello";
    Room roomFromAlicePOV = mAliceSession.getDataHandler().getRoom(mRoomId);
    final CountDownLatch lock1 = new CountDownLatch(1);
    roomFromAlicePOV.sendEvent(buildTextEvent(message, mAliceSession), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent", "sendEvent");
            lock1.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock1.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock1.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock1.countDown();
        }
    });
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("sendEvent"));
    Credentials aliceCredentials = mAliceSession.getCredentials();
    Credentials aliceCredentials2 = new Credentials();
    final CountDownLatch lock1a = new CountDownLatch(1);
    mAliceSession.getCrypto().exportRoomKeys(password, new ApiCallback<byte[]>() {

        @Override
        public void onSuccess(byte[] info) {
            results.put("exportRoomKeys", info);
            lock1a.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock1a.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock1a.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock1a.countDown();
        }
    });
    lock1a.await(10000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("exportRoomKeys"));
    // close the session and clear the data
    mAliceSession.clear(context);
    aliceCredentials2.userId = aliceCredentials.userId;
    aliceCredentials2.homeServer = aliceCredentials.homeServer;
    aliceCredentials2.accessToken = aliceCredentials.accessToken;
    aliceCredentials2.refreshToken = aliceCredentials.refreshToken;
    aliceCredentials2.deviceId = "AliceNewDevice";
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(aliceCredentials2);
    IMXStore store = new MXFileStore(hs, context);
    MXSession aliceSession2 = new MXSession(hs, new MXDataHandler(store, aliceCredentials2), context);
    aliceSession2.enableCryptoWhenStarting();
    final CountDownLatch lock1b = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock1b.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock1b.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock1b.countDown();
        }
    };
    aliceSession2.getDataHandler().getStore().addMXStoreListener(listener);
    aliceSession2.getDataHandler().getStore().open();
    lock1b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock2 = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock2.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock2.countDown();
        }
    };
    aliceSession2.getDataHandler().addListener(eventListener);
    aliceSession2.startEventStream(null);
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    Room roomFromAlicePOV2 = aliceSession2.getDataHandler().getRoom(mRoomId);
    assertTrue(null != roomFromAlicePOV2);
    assertTrue(roomFromAlicePOV2.getLiveState().isEncrypted());
    Event event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null == event.getClearEvent());
    assertTrue(null != event.getCryptoError());
    assertTrue(TextUtils.equals(event.getCryptoError().errcode, MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE));
    // import the e2e keys
    // test with a wrong password
    final CountDownLatch lock3 = new CountDownLatch(1);
    aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), "wrong password", new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("importRoomKeys", "importRoomKeys");
            lock3.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            results.put("importRoomKeys_failed", "importRoomKeys_failed");
            lock3.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            results.put("importRoomKeys_failed", "importRoomKeys_failed");
            lock3.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            results.put("importRoomKeys_failed", "importRoomKeys_failed");
            lock3.countDown();
        }
    });
    lock3.await(10000, TimeUnit.MILLISECONDS);
    assertTrue(!results.containsKey("importRoomKeys"));
    assertTrue(results.containsKey("importRoomKeys_failed"));
    // check that the message cannot be decrypted
    event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null == event.getClearEvent());
    assertTrue(null != event.getCryptoError());
    assertTrue(TextUtils.equals(event.getCryptoError().errcode, MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE));
    final CountDownLatch lock4 = new CountDownLatch(1);
    aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), password, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("importRoomKeys", "importRoomKeys");
            lock4.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock4.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock4.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock4.countDown();
        }
    });
    lock4.await(10000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("importRoomKeys"));
    // check that the message CAN be decrypted
    event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null != event.getClearEvent());
    assertTrue(null == event.getCryptoError());
    assertTrue(checkEncryptedEvent(event, mRoomId, message, mAliceSession));
    aliceSession2.clear(context);
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Room(org.matrix.androidsdk.data.Room) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) Test(org.junit.Test)

Example 13 with IMXStore

use of org.matrix.androidsdk.data.store.IMXStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test11_testAliceAndBobInACryptedRoomBackPaginationFromMemoryStore.

@Test
public void test11_testAliceAndBobInACryptedRoomBackPaginationFromMemoryStore() throws Exception {
    Log.e(LOG_TAG, "test11_testAliceAndBobInACryptedRoomBackPaginationFromMemoryStore");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap();
    doE2ETestWithAliceAndBobInARoomWithCryptedMessages(true);
    Credentials bobCredentials = mBobSession.getCredentials();
    mBobSession.clear(context);
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(bobCredentials);
    IMXStore store = new MXFileStore(hs, context);
    final CountDownLatch lock1 = new CountDownLatch(2);
    MXSession bobSession2 = new MXSession(hs, new MXDataHandler(store, bobCredentials), context);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock1.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock1.countDown();
        }
    };
    bobSession2.getDataHandler().addListener(eventListener);
    bobSession2.getDataHandler().getStore().open();
    bobSession2.startEventStream(null);
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    assertTrue(null != bobSession2.getCrypto());
    Room roomFromBobPOV = bobSession2.getDataHandler().getRoom(mRoomId);
    final CountDownLatch lock2 = new CountDownLatch(6);
    final ArrayList<Event> receivedEvents = new ArrayList<>();
    EventTimeline.EventTimelineListener eventTimelineListener = new EventTimeline.EventTimelineListener() {

        public void onEvent(Event event, EventTimeline.Direction direction, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                receivedEvents.add(event);
                lock2.countDown();
            }
        }
    };
    roomFromBobPOV.getLiveTimeLine().addEventTimelineListener(eventTimelineListener);
    roomFromBobPOV.getLiveTimeLine().backPaginate(new ApiCallback<Integer>() {

        @Override
        public void onSuccess(Integer info) {
            results.put("backPaginate", "backPaginate");
            lock2.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
        }

        @Override
        public void onMatrixError(MatrixError e) {
        }

        @Override
        public void onUnexpectedError(Exception e) {
        }
    });
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("backPaginate"));
    assertTrue(receivedEvents.size() + " instead of 5", 5 == receivedEvents.size());
    checkEncryptedEvent(receivedEvents.get(0), mRoomId, messagesFromAlice.get(1), mAliceSession);
    checkEncryptedEvent(receivedEvents.get(1), mRoomId, messagesFromBob.get(2), mBobSession);
    checkEncryptedEvent(receivedEvents.get(2), mRoomId, messagesFromBob.get(1), mBobSession);
    checkEncryptedEvent(receivedEvents.get(3), mRoomId, messagesFromBob.get(0), mBobSession);
    checkEncryptedEvent(receivedEvents.get(4), mRoomId, messagesFromAlice.get(0), mAliceSession);
    bobSession2.clear(context);
    mAliceSession.clear(context);
}
Also used : HashMap(java.util.HashMap) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) ArrayList(java.util.ArrayList) EventTimeline(org.matrix.androidsdk.data.EventTimeline) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Room(org.matrix.androidsdk.data.Room) Context(android.content.Context) IMXStore(org.matrix.androidsdk.data.store.IMXStore) CountDownLatch(java.util.concurrent.CountDownLatch) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 14 with IMXStore

use of org.matrix.androidsdk.data.store.IMXStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test04_testEnsureOlmSessionsForUsers.

@Test
public void test04_testEnsureOlmSessionsForUsers() throws Exception {
    Log.e(LOG_TAG, "test04_testEnsureOlmSessionsForUsers");
    Context context = InstrumentationRegistry.getContext();
    createAliceAccount();
    final HashMap<String, Object> results = new HashMap<>();
    mAliceSession.getCredentials().deviceId = "AliceDevice";
    final CountDownLatch lock0 = new CountDownLatch(1);
    mAliceSession.enableCrypto(true, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCryptoAlice", "enableCryptoAlice");
            lock0.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock0.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock0.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock0.countDown();
        }
    });
    lock0.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableCryptoAlice"));
    createBobAccount();
    final CountDownLatch lock2 = new CountDownLatch(1);
    mBobSession.enableCrypto(true, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCryptoBob", "enableCryptoAlice");
            lock2.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock2.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock2.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock2.countDown();
        }
    });
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableCryptoBob"));
    final CountDownLatch lock3 = new CountDownLatch(1);
    mBobSession.getCrypto().getDeviceList().downloadKeys(Arrays.asList(mBobSession.getMyUserId(), mAliceSession.getMyUserId()), false, new ApiCallback<MXUsersDevicesMap<MXDeviceInfo>>() {

        @Override
        public void onSuccess(MXUsersDevicesMap<MXDeviceInfo> map) {
            results.put("downloadKeys", map);
            lock3.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock3.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock3.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock3.countDown();
        }
    });
    lock3.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("downloadKeys"));
    final CountDownLatch lock4 = new CountDownLatch(1);
    mBobSession.getCrypto().ensureOlmSessionsForUsers(Arrays.asList(mBobSession.getMyUserId(), mAliceSession.getMyUserId()), new ApiCallback<MXUsersDevicesMap<MXOlmSessionResult>>() {

        @Override
        public void onSuccess(MXUsersDevicesMap<MXOlmSessionResult> info) {
            results.put("ensureOlmSessionsForUsers", info);
            lock4.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock4.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock4.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock4.countDown();
        }
    });
    lock4.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("ensureOlmSessionsForUsers"));
    MXUsersDevicesMap<MXOlmSessionResult> result = (MXUsersDevicesMap<MXOlmSessionResult>) results.get("ensureOlmSessionsForUsers");
    assertTrue(result.getUserIds().size() == 1);
    MXOlmSessionResult sessionWithAliceDevice = result.getObject("AliceDevice", mAliceSession.getMyUserId());
    assertTrue(null != sessionWithAliceDevice);
    assertTrue(null != sessionWithAliceDevice.mSessionId);
    assertTrue(TextUtils.equals(sessionWithAliceDevice.mDevice.deviceId, "AliceDevice"));
    Credentials bobCredentials = mBobSession.getCredentials();
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(bobCredentials);
    IMXStore store = new MXFileStore(hs, context);
    MXSession bobSession2 = new MXSession(hs, new MXDataHandler(store, bobCredentials), context);
    final CountDownLatch lock5 = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock5.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock5.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock5.countDown();
        }
    };
    bobSession2.getDataHandler().getStore().addMXStoreListener(listener);
    bobSession2.getDataHandler().getStore().open();
    bobSession2.getDataHandler().addListener(new MXEventListener() {

        @Override
        public void onStoreReady() {
            lock5.countDown();
        }
    });
    lock5.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock5b = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock5b.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock5b.countDown();
        }
    };
    bobSession2.getDataHandler().addListener(eventListener);
    bobSession2.startEventStream(null);
    lock5b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    final CountDownLatch lock6 = new CountDownLatch(1);
    bobSession2.getCrypto().ensureOlmSessionsForUsers(Arrays.asList(bobSession2.getMyUserId(), mAliceSession.getMyUserId()), new ApiCallback<MXUsersDevicesMap<MXOlmSessionResult>>() {

        @Override
        public void onSuccess(MXUsersDevicesMap<MXOlmSessionResult> info) {
            results.put("ensureOlmSessionsForUsers2", info);
            lock6.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock6.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock6.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock6.countDown();
        }
    });
    lock6.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("ensureOlmSessionsForUsers2"));
    MXUsersDevicesMap<MXOlmSessionResult> result2 = (MXUsersDevicesMap<MXOlmSessionResult>) results.get("ensureOlmSessionsForUsers2");
    MXOlmSessionResult sessionWithAliceDevice2 = result2.getObject("AliceDevice", mAliceSession.getMyUserId());
    assertTrue(null != sessionWithAliceDevice2);
    assertTrue(null != sessionWithAliceDevice2.mSessionId);
    assertTrue(TextUtils.equals(sessionWithAliceDevice2.mDevice.deviceId, "AliceDevice"));
    mBobSession.clear(context);
    mAliceSession.clear(context);
    bobSession2.clear(context);
}
Also used : HashMap(java.util.HashMap) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) MXDeviceInfo(org.matrix.androidsdk.crypto.data.MXDeviceInfo) MXUsersDevicesMap(org.matrix.androidsdk.crypto.data.MXUsersDevicesMap) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXOlmSessionResult(org.matrix.androidsdk.crypto.data.MXOlmSessionResult) CountDownLatch(java.util.concurrent.CountDownLatch) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) Test(org.junit.Test)

Example 15 with IMXStore

use of org.matrix.androidsdk.data.store.IMXStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test02_testCryptoPersistenceInStore.

@Test
public void test02_testCryptoPersistenceInStore() throws Exception {
    Log.e(LOG_TAG, "test02_testCryptoPersistenceInStore");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    createBobAccount();
    mBobSession.getCredentials().deviceId = "BobDevice";
    assertTrue(null == mBobSession.getCrypto());
    final CountDownLatch lock0 = new CountDownLatch(1);
    mBobSession.enableCrypto(true, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCrypto", "enableCrypto");
            lock0.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock0.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock0.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock0.countDown();
        }
    });
    lock0.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableCrypto"));
    assertTrue(null != mBobSession.getCrypto());
    SystemClock.sleep(1000);
    final String deviceCurve25519Key = mBobSession.getCrypto().getOlmDevice().getDeviceCurve25519Key();
    final String deviceEd25519Key = mBobSession.getCrypto().getOlmDevice().getDeviceEd25519Key();
    final List<MXDeviceInfo> myUserDevices = mBobSession.getCrypto().getUserDevices(mBobSession.getMyUserId());
    assertTrue(null != myUserDevices);
    assertTrue(1 == myUserDevices.size());
    final Credentials bobCredentials = mBobSession.getCredentials();
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(bobCredentials);
    IMXStore store = new MXFileStore(hs, context);
    MXSession bobSession2 = new MXSession(hs, new MXDataHandler(store, bobCredentials), context);
    final CountDownLatch lock1 = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock1.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock1.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock1.countDown();
        }
    };
    bobSession2.getDataHandler().getStore().addMXStoreListener(listener);
    bobSession2.getDataHandler().getStore().open();
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    assertTrue(bobSession2.isCryptoEnabled());
    final CountDownLatch lock2 = new CountDownLatch(2);
    MXEventListener eventsListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock2.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock2.countDown();
        }
    };
    bobSession2.getDataHandler().addListener(eventsListener);
    bobSession2.startEventStream(null);
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    MXCrypto crypto = bobSession2.getCrypto();
    assertNotNull(crypto);
    assertTrue(TextUtils.equals(deviceCurve25519Key, crypto.getOlmDevice().getDeviceCurve25519Key()));
    assertTrue(TextUtils.equals(deviceEd25519Key, crypto.getOlmDevice().getDeviceEd25519Key()));
    List<MXDeviceInfo> myUserDevices2 = bobSession2.getCrypto().getUserDevices(bobSession2.getMyUserId());
    assertTrue(1 == myUserDevices2.size());
    assertTrue(TextUtils.equals(myUserDevices2.get(0).deviceId, myUserDevices.get(0).deviceId));
    mBobSession.clear(context);
    bobSession2.clear(context);
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) MXDeviceInfo(org.matrix.androidsdk.crypto.data.MXDeviceInfo) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) MXCrypto(org.matrix.androidsdk.crypto.MXCrypto) Test(org.junit.Test)

Aggregations

IMXStore (org.matrix.androidsdk.data.store.IMXStore)18 MatrixError (org.matrix.androidsdk.rest.model.MatrixError)12 Uri (android.net.Uri)10 HashMap (java.util.HashMap)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 MXFileStore (org.matrix.androidsdk.data.store.MXFileStore)10 MXEventListener (org.matrix.androidsdk.listeners.MXEventListener)10 Credentials (org.matrix.androidsdk.rest.model.login.Credentials)10 Room (org.matrix.androidsdk.data.Room)8 Context (android.content.Context)7 JsonObject (com.google.gson.JsonObject)7 Test (org.junit.Test)7 Event (org.matrix.androidsdk.rest.model.Event)7 ArrayList (java.util.ArrayList)6 MXStoreListener (org.matrix.androidsdk.data.store.MXStoreListener)6 List (java.util.List)4 MXDeviceInfo (org.matrix.androidsdk.crypto.data.MXDeviceInfo)3 LoginRestClient (org.matrix.androidsdk.rest.client.LoginRestClient)3 MXDecryptionException (org.matrix.androidsdk.crypto.MXDecryptionException)2 MXUsersDevicesMap (org.matrix.androidsdk.crypto.data.MXUsersDevicesMap)2