Search in sources :

Example 1 with Credentials

use of org.matrix.androidsdk.rest.model.login.Credentials in project matrix-android-sdk by matrix-org.

the class CryptoTest method test27_testEnableEncryptionAfterNonCryptedMessages.

@Test
public // -> Bob must be able to decrypt this message
void test27_testEnableEncryptionAfterNonCryptedMessages() throws Exception {
    Log.e(LOG_TAG, "test27_testEnableEncryptionAfterNonCryptedMessages");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    final String messageFromAlice = "Hello I'm Alice!";
    final String message2FromAlice = "I'm still Alice!";
    createAliceAccount();
    createBobAccount();
    final CountDownLatch lock00b = new CountDownLatch(2);
    mAliceSession.enableCrypto(true, new ApiCallback<Void>() {

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

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

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

        @Override
        public void onUnexpectedError(Exception e) {
            lock00b.countDown();
        }
    });
    mBobSession.enableCrypto(true, new ApiCallback<Void>() {

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

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

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

        @Override
        public void onUnexpectedError(Exception e) {
            lock00b.countDown();
        }
    });
    lock00b.await(5000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableCrypto2"));
    assertTrue(results.containsKey("enableCrypto1"));
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    mBobSession.getCrypto().setWarnOnUnknownDevices(false);
    final CountDownLatch lock0 = new CountDownLatch(1);
    mAliceSession.createRoom(null, null, RoomState.DIRECTORY_VISIBILITY_PUBLIC, null, RoomState.GUEST_ACCESS_CAN_JOIN, RoomState.HISTORY_VISIBILITY_SHARED, null, new ApiCallback<String>() {

        @Override
        public void onSuccess(String roomId) {
            results.put("roomId", roomId);
            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(2000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("roomId"));
    mRoomId = (String) results.get("roomId");
    final CountDownLatch lock1 = new CountDownLatch(1);
    mBobSession.joinRoom(mRoomId, new ApiCallback<String>() {

        @Override
        public void onSuccess(String info) {
            results.put("joinRoom", "joinRoom");
            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(2000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("joinRoom"));
    Room roomFromAlicePOV = mAliceSession.getDataHandler().getRoom(mRoomId);
    final CountDownLatch lock2 = new CountDownLatch(1);
    roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, mAliceSession), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent1", "sendEvent1");
            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(2000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("sendEvent1"));
    // Make Bob come back to the room with a new device
    Credentials bobCredentials = mBobSession.getCredentials();
    mBobSession.clear(context);
    MXSession bobSession2 = CryptoTestHelper.logAccountAndSync(context, bobCredentials.userId, MXTESTS_BOB_PWD);
    assertTrue(null != bobSession2);
    assertTrue(bobSession2.isCryptoEnabled());
    assertTrue(!TextUtils.equals(bobSession2.getCrypto().getMyDevice().deviceId, bobCredentials.deviceId));
    bobSession2.getCrypto().setWarnOnUnknownDevices(false);
    final CountDownLatch lock3 = new CountDownLatch(1);
    roomFromAlicePOV.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm");
            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(5000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableEncryptionWithAlgorithm"));
    Room roomFromBobPOV2 = bobSession2.getDataHandler().getRoom(mRoomId);
    final CountDownLatch lock4 = new CountDownLatch(1);
    final ArrayList<Event> receivedEvents2 = new ArrayList<>();
    EventTimeline.EventTimelineListener eventTimelineListener2 = new EventTimeline.EventTimelineListener() {

        public void onEvent(Event event, EventTimeline.Direction direction, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                receivedEvents2.add(event);
                lock4.countDown();
            } else if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE_ENCRYPTED)) {
                lock4.countDown();
            }
        }
    };
    roomFromBobPOV2.getLiveTimeLine().addEventTimelineListener(eventTimelineListener2);
    roomFromAlicePOV.sendEvent(buildTextEvent(message2FromAlice, mAliceSession), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
        }

        @Override
        public void onNetworkError(Exception e) {
        }

        @Override
        public void onMatrixError(MatrixError e) {
        }

        @Override
        public void onUnexpectedError(Exception e) {
        }
    });
    lock4.await(5000, TimeUnit.MILLISECONDS);
    assertTrue(1 == receivedEvents2.size());
    Event event = receivedEvents2.get(0);
    assertTrue(checkEncryptedEvent(event, mRoomId, message2FromAlice, mAliceSession));
    bobSession2.clear(context);
    mAliceSession.clear(context);
}
Also used : Context(android.content.Context) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EventTimeline(org.matrix.androidsdk.data.EventTimeline) CountDownLatch(java.util.concurrent.CountDownLatch) 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) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 2 with Credentials

use of org.matrix.androidsdk.rest.model.login.Credentials in project matrix-android-sdk by matrix-org.

the class CryptoTest method test10_testAliceDecryptOldMessageWithANewDeviceInACryptedRoom.

@Test
public void test10_testAliceDecryptOldMessageWithANewDeviceInACryptedRoom() throws Exception {
    Log.e(LOG_TAG, "test10_testAliceDecryptOldMessageWithANewDeviceInACryptedRoom");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    doE2ETestWithAliceInARoom();
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    String message = "Hello myself!";
    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();
    // 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));
    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 3 with Credentials

use of org.matrix.androidsdk.rest.model.login.Credentials in project matrix-android-sdk by matrix-org.

the class CryptoTest method test03_testKeysUploadAndDownload.

@Test
public void test03_testKeysUploadAndDownload() throws Exception {
    Log.e(LOG_TAG, "test03_testKeysUploadAndDownload");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    createAliceAccount();
    mAliceSession.getCredentials().deviceId = "AliceDevice";
    final CountDownLatch lock0 = new CountDownLatch(1);
    mAliceSession.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"));
    createBobAccount();
    final CountDownLatch lock2 = new CountDownLatch(1);
    mBobSession.getCredentials().deviceId = "BobDevice";
    mBobSession.enableCrypto(true, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCrypto2", "enableCrypto2");
            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("enableCrypto2"));
    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> info) {
            results.put("downloadKeys", info);
            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"));
    MXUsersDevicesMap<MXDeviceInfo> usersDevicesInfoMap = (MXUsersDevicesMap<MXDeviceInfo>) results.get("downloadKeys");
    assertTrue(2 == usersDevicesInfoMap.getUserIds().size());
    assertTrue(1 == usersDevicesInfoMap.getUserDeviceIds(mAliceSession.getMyUserId()).size());
    MXDeviceInfo aliceDeviceFromBobPOV = usersDevicesInfoMap.getObject("AliceDevice", mAliceSession.getMyUserId());
    assertTrue(null != aliceDeviceFromBobPOV);
    assertTrue(TextUtils.equals(aliceDeviceFromBobPOV.fingerprint(), mAliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()));
    // Continue testing other methods
    assertTrue(null != mBobSession.getCrypto().deviceWithIdentityKey(mAliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), mAliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM));
    assertTrue(aliceDeviceFromBobPOV.isUnknown());
    final CountDownLatch lock3a = new CountDownLatch(1);
    mBobSession.getCrypto().setDevicesKnown(Arrays.asList(aliceDeviceFromBobPOV), new ApiCallback<Void>() {

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

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

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

        @Override
        public void onUnexpectedError(Exception e) {
            lock3a.countDown();
        }
    });
    lock3a.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("setDevicesKnown"));
    assertTrue(aliceDeviceFromBobPOV.isUnverified());
    final CountDownLatch lock3b = new CountDownLatch(1);
    mBobSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, aliceDeviceFromBobPOV.deviceId, mAliceSession.getMyUserId(), new ApiCallback<Void>() {

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

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

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

        @Override
        public void onUnexpectedError(Exception e) {
            lock3b.countDown();
        }
    });
    lock3b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("setDeviceVerification1"));
    assertTrue(aliceDeviceFromBobPOV.isBlocked());
    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 lock4 = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

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

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

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

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

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock4b.countDown();
        }
    };
    bobSession2.getDataHandler().addListener(eventListener);
    bobSession2.startEventStream(null);
    lock4b.await(2000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    MXDeviceInfo aliceDeviceFromBobPOV2 = bobSession2.getCrypto().deviceWithIdentityKey(mAliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), mAliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM);
    assertTrue(null != aliceDeviceFromBobPOV2);
    assertTrue(TextUtils.equals(aliceDeviceFromBobPOV2.fingerprint(), mAliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()));
    assertTrue(aliceDeviceFromBobPOV2.mVerified + " instead of " + MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, aliceDeviceFromBobPOV2.mVerified == MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED);
    // Download again alice device
    final CountDownLatch lock5 = new CountDownLatch(1);
    bobSession2.getCrypto().getDeviceList().downloadKeys(Arrays.asList(mAliceSession.getMyUserId()), true, new ApiCallback<MXUsersDevicesMap<MXDeviceInfo>>() {

        @Override
        public void onSuccess(MXUsersDevicesMap<MXDeviceInfo> info) {
            results.put("downloadKeys2", info);
            lock5.countDown();
        }

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

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

        @Override
        public void onUnexpectedError(Exception e) {
            lock5.countDown();
        }
    });
    lock5.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("downloadKeys2"));
    MXDeviceInfo aliceDeviceFromBobPOV3 = bobSession2.getCrypto().deviceWithIdentityKey(mAliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), mAliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM);
    assertTrue(null != aliceDeviceFromBobPOV3);
    assertTrue(TextUtils.equals(aliceDeviceFromBobPOV3.fingerprint(), mAliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()));
    assertTrue(aliceDeviceFromBobPOV3.isBlocked());
    mAliceSession.clear(context);
    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) MXUsersDevicesMap(org.matrix.androidsdk.crypto.data.MXUsersDevicesMap) 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) Test(org.junit.Test)

Example 4 with Credentials

use of org.matrix.androidsdk.rest.model.login.Credentials in project matrix-android-sdk by matrix-org.

the class CryptoTest method test09_testAliceInACryptedRoomAfterInitialSync.

@Test
public void test09_testAliceInACryptedRoomAfterInitialSync() throws Exception {
    Log.e(LOG_TAG, "test09_testAliceInACryptedRoomAfterInitialSync");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    doE2ETestWithAliceInARoom();
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    final String message = "Hello myself!";
    Credentials aliceCredentials = mAliceSession.getCredentials();
    mAliceSession.clear(context);
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(aliceCredentials);
    IMXStore store = new MXFileStore(hs, context);
    final CountDownLatch lock1 = new CountDownLatch(1);
    final MXSession aliceSession2 = new MXSession(hs, new MXDataHandler(store, aliceCredentials), context);
    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();
        }
    };
    aliceSession2.getDataHandler().getStore().addMXStoreListener(listener);
    aliceSession2.getDataHandler().getStore().open();
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock1b = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

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

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock1b.countDown();
        }
    };
    aliceSession2.getDataHandler().addListener(eventListener);
    aliceSession2.startEventStream(null);
    lock1b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    Room roomFromAlicePOV2 = aliceSession2.getDataHandler().getRoom(mRoomId);
    assertTrue(roomFromAlicePOV2.isEncrypted());
    final CountDownLatch lock2 = new CountDownLatch(1);
    if (false) {
        // The android client does not echo its own message
        MXEventListener aliceEventListener = new MXEventListener() {

            @Override
            public void onLiveEvent(Event event, RoomState roomState) {
                if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                    try {
                        if (checkEncryptedEvent(event, mRoomId, message, aliceSession2)) {
                            lock2.countDown();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        };
        roomFromAlicePOV2.addEventListener(aliceEventListener);
    }
    // the IOS client echoes the message
    // the android client does not
    roomFromAlicePOV2.sendEvent(buildTextEvent(message, aliceSession2), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent", "sendEvent");
            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("sendEvent"));
    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) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 5 with Credentials

use of org.matrix.androidsdk.rest.model.login.Credentials in project matrix-android-sdk by matrix-org.

the class CryptoTestHelper method createAccountAndSync.

/**
 * Create an account and a dedicated session
 * @param context the context
 * @param userName the account username
 * @param password the password
 * @param startSession true to perform an initial sync
 * @throws Exception an exception if the account creation failed
 */
public static MXSession createAccountAndSync(Context context, String userName, String password, boolean startSession) throws Exception {
    Uri uri = Uri.parse(TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    LoginRestClient loginRestClient = new LoginRestClient(hs);
    final HashMap<String, Object> params = new HashMap<>();
    RegistrationParams registrationParams = new RegistrationParams();
    mLock = new CountDownLatch(1);
    // get the registration session id
    loginRestClient.register(registrationParams, new ApiCallback<Credentials>() {

        @Override
        public void onSuccess(Credentials credentials) {
            mLock.countDown();
        }

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

        @Override
        public void onMatrixError(MatrixError e) {
            // detect if a parameter is expected
            RegistrationFlowResponse registrationFlowResponse = null;
            // when a response is not completed the server returns an error message
            if ((null != e.mStatus) && (e.mStatus == 401)) {
                try {
                    registrationFlowResponse = JsonUtils.toRegistrationFlowResponse(e.mErrorBodyAsString);
                } catch (Exception castExcept) {
                }
            }
            // check if the server response can be casted
            if (null != registrationFlowResponse) {
                params.put("session", registrationFlowResponse.session);
            }
            mLock.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            mLock.countDown();
        }
    });
    mLock.await(10000, TimeUnit.MILLISECONDS);
    String session = (String) params.get("session");
    assertTrue(null != session);
    registrationParams.username = userName;
    registrationParams.password = password;
    HashMap<String, Object> authParams = new HashMap<>();
    authParams.put("session", session);
    authParams.put("type", LoginRestClient.LOGIN_FLOW_TYPE_DUMMY);
    registrationParams.auth = authParams;
    mLock = new CountDownLatch(1);
    loginRestClient.register(registrationParams, new ApiCallback<Credentials>() {

        @Override
        public void onSuccess(Credentials credentials) {
            params.put("credentials", credentials);
            mLock.countDown();
        }

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

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

        @Override
        public void onUnexpectedError(Exception e) {
            mLock.countDown();
        }
    });
    mLock.await(10000, TimeUnit.MILLISECONDS);
    Credentials credentials = (Credentials) params.get("credentials");
    assertTrue(null != credentials);
    hs.setCredentials(credentials);
    IMXStore store = new MXFileStore(hs, context);
    MXSession mxSession = new MXSession(hs, new MXDataHandler(store, credentials), context);
    if (!startSession) {
        return mxSession;
    }
    mxSession.getDataHandler().getStore().open();
    mxSession.startEventStream(null);
    mLock = new CountDownLatch(1);
    mxSession.getDataHandler().addListener(new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            params.put("isInit", true);
            mLock.countDown();
        }
    });
    mLock.await(100000, TimeUnit.MILLISECONDS);
    assertTrue(params.containsKey("isInit"));
    return mxSession;
}
Also used : HashMap(java.util.HashMap) RegistrationFlowResponse(org.matrix.androidsdk.rest.model.login.RegistrationFlowResponse) 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) RegistrationParams(org.matrix.androidsdk.rest.model.login.RegistrationParams) LoginRestClient(org.matrix.androidsdk.rest.client.LoginRestClient) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials)

Aggregations

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