Search in sources :

Example 11 with SimpleApiCallback

use of org.matrix.androidsdk.core.callback.SimpleApiCallback in project matrix-android-sdk by matrix-org.

the class MXCryptoImpl method encryptEventContent.

/**
 * Encrypt an event content according to the configuration of the room.
 *
 * @param eventContent the content of the event.
 * @param eventType    the type of the event.
 * @param room         the room the event will be sent.
 * @param callback     the asynchronous callback
 */
@Override
public void encryptEventContent(final JsonElement eventContent, final String eventType, final CryptoRoom room, final ApiCallback<MXEncryptEventContentResult> callback) {
    // wait that the crypto is really started
    if (!isStarted()) {
        Log.d(LOG_TAG, "## encryptEventContent() : wait after e2e init");
        start(false, new ApiCallback<Void>() {

            @Override
            public void onSuccess(Void info) {
                encryptEventContent(eventContent, eventType, room, callback);
            }

            @Override
            public void onNetworkError(Exception e) {
                Log.e(LOG_TAG, "## encryptEventContent() : onNetworkError while waiting to start e2e : " + e.getMessage(), e);
                if (null != callback) {
                    callback.onNetworkError(e);
                }
            }

            @Override
            public void onMatrixError(MatrixError e) {
                Log.e(LOG_TAG, "## encryptEventContent() : onMatrixError while waiting to start e2e : " + e.getMessage());
                if (null != callback) {
                    callback.onMatrixError(e);
                }
            }

            @Override
            public void onUnexpectedError(Exception e) {
                Log.e(LOG_TAG, "## encryptEventContent() : onUnexpectedError while waiting to start e2e : " + e.getMessage(), e);
                if (null != callback) {
                    callback.onUnexpectedError(e);
                }
            }
        });
        return;
    }
    final ApiCallback<List<CryptoRoomMember>> apiCallback = new SimpleApiCallback<List<CryptoRoomMember>>(callback) {

        @Override
        public void onSuccess(final List<CryptoRoomMember> members) {
            // just as you are sending a secret message?
            final List<String> userIds = new ArrayList<>();
            for (CryptoRoomMember m : members) {
                userIds.add(m.getUserId());
            }
            getEncryptingThreadHandler().post(new Runnable() {

                @Override
                public void run() {
                    IMXEncrypting alg;
                    synchronized (mRoomEncryptors) {
                        alg = mRoomEncryptors.get(room.getRoomId());
                    }
                    if (null == alg) {
                        String algorithm = room.getState().encryptionAlgorithm();
                        if (null != algorithm) {
                            if (setEncryptionInRoom(room.getRoomId(), algorithm, false, members)) {
                                synchronized (mRoomEncryptors) {
                                    alg = mRoomEncryptors.get(room.getRoomId());
                                }
                            }
                        }
                    }
                    if (null != alg) {
                        final long t0 = System.currentTimeMillis();
                        Log.d(LOG_TAG, "## encryptEventContent() starts");
                        alg.encryptEventContent(eventContent, eventType, userIds, new ApiCallback<JsonElement>() {

                            @Override
                            public void onSuccess(final JsonElement encryptedContent) {
                                Log.d(LOG_TAG, "## encryptEventContent() : succeeds after " + (System.currentTimeMillis() - t0) + " ms");
                                if (null != callback) {
                                    callback.onSuccess(new MXEncryptEventContentResult(encryptedContent, CryptoEvent.EVENT_TYPE_MESSAGE_ENCRYPTED));
                                }
                            }

                            @Override
                            public void onNetworkError(final Exception e) {
                                Log.e(LOG_TAG, "## encryptEventContent() : onNetworkError " + e.getMessage(), e);
                                if (null != callback) {
                                    callback.onNetworkError(e);
                                }
                            }

                            @Override
                            public void onMatrixError(final MatrixError e) {
                                Log.e(LOG_TAG, "## encryptEventContent() : onMatrixError " + e.getMessage());
                                if (null != callback) {
                                    callback.onMatrixError(e);
                                }
                            }

                            @Override
                            public void onUnexpectedError(final Exception e) {
                                Log.e(LOG_TAG, "## encryptEventContent() : onUnexpectedError " + e.getMessage(), e);
                                if (null != callback) {
                                    callback.onUnexpectedError(e);
                                }
                            }
                        });
                    } else {
                        final String algorithm = room.getState().encryptionAlgorithm();
                        final String reason = String.format(MXCryptoError.UNABLE_TO_ENCRYPT_REASON, (null == algorithm) ? MXCryptoError.NO_MORE_ALGORITHM_REASON : algorithm);
                        Log.e(LOG_TAG, "## encryptEventContent() : " + reason);
                        if (null != callback) {
                            getUIHandler().post(new Runnable() {

                                @Override
                                public void run() {
                                    callback.onMatrixError(new MXCryptoError(MXCryptoError.UNABLE_TO_ENCRYPT_ERROR_CODE, MXCryptoError.UNABLE_TO_ENCRYPT, reason));
                                }
                            });
                        }
                    }
                }
            });
        }
    };
    // Check whether the event content must be encrypted for the invited members.
    boolean encryptForInvitedMembers = mCryptoConfig.mEnableEncryptionForInvitedMembers && room.shouldEncryptForInvitedMembers();
    if (encryptForInvitedMembers) {
        room.getActiveMembersAsyncCrypto(apiCallback);
    } else {
        room.getJoinedMembersAsyncCrypto(apiCallback);
    }
}
Also used : IMXEncrypting(org.matrix.androidsdk.crypto.algorithms.IMXEncrypting) CryptoRoomMember(org.matrix.androidsdk.crypto.interfaces.CryptoRoomMember) SimpleApiCallback(org.matrix.androidsdk.core.callback.SimpleApiCallback) ApiCallback(org.matrix.androidsdk.core.callback.ApiCallback) ArrayList(java.util.ArrayList) MXDecryptionException(org.matrix.androidsdk.crypto.MXDecryptionException) MXEncryptEventContentResult(org.matrix.androidsdk.crypto.data.MXEncryptEventContentResult) JsonElement(com.google.gson.JsonElement) MXDeviceList(org.matrix.androidsdk.crypto.MXDeviceList) List(java.util.List) ArrayList(java.util.ArrayList) MatrixError(org.matrix.androidsdk.core.model.MatrixError) SimpleApiCallback(org.matrix.androidsdk.core.callback.SimpleApiCallback) MXCryptoError(org.matrix.androidsdk.crypto.MXCryptoError)

Example 12 with SimpleApiCallback

use of org.matrix.androidsdk.core.callback.SimpleApiCallback in project matrix-android-sdk by matrix-org.

the class RoomStateTest method RoomState_PermalinkWithForwardPagination.

// Test lazy loaded members sent by the HS when paginating forward
// - Come back to Bob message
// - We should only know Bob membership
// - Paginate forward to get Alice next message
// - We should know Alice membership now
private void RoomState_PermalinkWithForwardPagination(final boolean withLazyLoading) throws Exception {
    final LazyLoadingScenarioData data = mLazyLoadingTestHelper.createScenario(withLazyLoading);
    mTestHelper.syncSession(data.aliceSession, false);
    final CountDownLatch lock = new CountDownLatch(1);
    final EventTimeline eventTimeline = EventTimelineFactory.pastTimeline(data.aliceSession.getDataHandler(), data.roomId, data.bobMessageId);
    eventTimeline.addEventTimelineListener(new EventTimeline.Listener() {

        int messageCount = 0;

        @Override
        public void onEvent(Event event, EventTimeline.Direction direction, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                messageCount++;
                Log.d("TAG", "Receiving message #" + messageCount + ": " + JsonUtils.toMessage(event.getContent()).body);
                if (messageCount == 1) {
                    // We received the Event from bob
                    Assert.assertEquals(event.sender, data.bobSession.getMyUserId());
                    // Bob is known
                    Assert.assertNotNull(eventTimeline.getState().getMember(data.bobSession.getMyUserId()));
                    // With LazyLoading, Alice and Sam are not known by Alice yet
                    Assert.assertEquals(withLazyLoading, eventTimeline.getState().getMember(data.aliceSession.getMyUserId()) == null);
                    Assert.assertEquals(withLazyLoading, eventTimeline.getState().getMember(data.samSession.getMyUserId()) == null);
                } else if (messageCount == 2) {
                    // We received the Event from Alice
                    Assert.assertEquals(event.sender, data.aliceSession.getMyUserId());
                    // Alice and Bob are known
                    Assert.assertNotNull(eventTimeline.getState().getMember(data.aliceSession.getMyUserId()));
                    Assert.assertNotNull(eventTimeline.getState().getMember(data.bobSession.getMyUserId()));
                    // With LazyLoading, Sam is not known by Alice yet
                    Assert.assertEquals(withLazyLoading, eventTimeline.getState().getMember(data.samSession.getMyUserId()) == null);
                    lock.countDown();
                }
            } else {
                Log.d("TAG", "Receiving other event: " + event.getType());
            }
        }
    });
    eventTimeline.resetPaginationAroundInitialEvent(0, new SimpleApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            eventTimeline.forwardPaginate(new SimpleApiCallback<Integer>() {

                @Override
                public void onSuccess(Integer info) {
                // Ignore
                }
            });
        }
    });
    mTestHelper.await(lock);
    mLazyLoadingTestHelper.clearAllSessions(data);
}
Also used : EventTimeline(org.matrix.androidsdk.data.timeline.EventTimeline) CountDownLatch(java.util.concurrent.CountDownLatch) Event(org.matrix.androidsdk.rest.model.Event) SimpleApiCallback(org.matrix.androidsdk.core.callback.SimpleApiCallback) RoomState(org.matrix.androidsdk.data.RoomState)

Example 13 with SimpleApiCallback

use of org.matrix.androidsdk.core.callback.SimpleApiCallback in project matrix-android-sdk by matrix-org.

the class RoomStateTest method RoomState_PermalinkWithBackPagination.

// Test lazy loaded members sent by the HS when paginating backward
// - Come back to Bob message
// - We should only know Bob membership
// - Paginate backward to get Alice next message
// - We should know Alice membership now
private void RoomState_PermalinkWithBackPagination(final boolean withLazyLoading) throws Exception {
    final LazyLoadingScenarioData data = mLazyLoadingTestHelper.createScenario(withLazyLoading);
    mTestHelper.syncSession(data.aliceSession, false);
    final CountDownLatch lock = new CountDownLatch(1);
    final EventTimeline eventTimeline = EventTimelineFactory.pastTimeline(data.aliceSession.getDataHandler(), data.roomId, data.bobMessageId);
    eventTimeline.addEventTimelineListener(new EventTimeline.Listener() {

        int messageCount = 0;

        @Override
        public void onEvent(Event event, EventTimeline.Direction direction, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                messageCount++;
                Log.d("TAG", "Receiving message #" + messageCount + ": " + JsonUtils.toMessage(event.getContent()).body);
                if (messageCount == 1) {
                    // We received the Event from bob
                    Assert.assertEquals(event.sender, data.bobSession.getMyUserId());
                    // Bob is known
                    Assert.assertNotNull(eventTimeline.getState().getMember(data.bobSession.getMyUserId()));
                    // With LazyLoading, Alice and Sam are not known by Alice yet
                    Assert.assertEquals(withLazyLoading, eventTimeline.getState().getMember(data.aliceSession.getMyUserId()) == null);
                    Assert.assertEquals(withLazyLoading, eventTimeline.getState().getMember(data.samSession.getMyUserId()) == null);
                } else if (messageCount == 2) {
                    // We received the Event from Alice
                    Assert.assertEquals(event.sender, data.aliceSession.getMyUserId());
                    // Alice and Bob are known
                    Assert.assertNotNull(eventTimeline.getState().getMember(data.aliceSession.getMyUserId()));
                    Assert.assertNotNull(eventTimeline.getState().getMember(data.bobSession.getMyUserId()));
                    // With LazyLoading, Sam is not known by Alice yet
                    Assert.assertEquals(withLazyLoading, eventTimeline.getState().getMember(data.samSession.getMyUserId()) == null);
                    lock.countDown();
                }
            } else {
                Log.d("TAG", "Receiving other event: " + event.getType());
            }
        }
    });
    eventTimeline.resetPaginationAroundInitialEvent(0, new SimpleApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            eventTimeline.backPaginate(new SimpleApiCallback<Integer>() {

                @Override
                public void onSuccess(Integer info) {
                // ignore
                }
            });
        }
    });
    mTestHelper.await(lock);
    mLazyLoadingTestHelper.clearAllSessions(data);
}
Also used : EventTimeline(org.matrix.androidsdk.data.timeline.EventTimeline) CountDownLatch(java.util.concurrent.CountDownLatch) Event(org.matrix.androidsdk.rest.model.Event) SimpleApiCallback(org.matrix.androidsdk.core.callback.SimpleApiCallback) RoomState(org.matrix.androidsdk.data.RoomState)

Example 14 with SimpleApiCallback

use of org.matrix.androidsdk.core.callback.SimpleApiCallback in project matrix-android-sdk by matrix-org.

the class EventsRestClient method getURLPreview.

/**
 * Retrieve the URL preview information.
 *
 * @param url      the URL
 * @param ts       the timestamp
 * @param callback the asynchronous callback
 */
public void getURLPreview(final String url, final long ts, final ApiCallback<URLPreview> callback) {
    final String description = "getURLPreview : URL " + url + " with ts " + ts;
    mApi.getURLPreview(url, ts).enqueue(new RestAdapterCallback<Map<String, Object>>(description, null, false, new SimpleApiCallback<Map<String, Object>>(callback) {

        @Override
        public void onSuccess(Map<String, Object> map) {
            if (null != callback) {
                callback.onSuccess(new URLPreview(map, url));
            }
        }
    }, new RestAdapterCallback.RequestRetryCallBack() {

        @Override
        public void onRetry() {
            getURLPreview(url, ts, callback);
        }
    }));
}
Also used : URLPreview(org.matrix.androidsdk.rest.model.URLPreview) HashMap(java.util.HashMap) Map(java.util.Map) SimpleApiCallback(org.matrix.androidsdk.core.callback.SimpleApiCallback)

Example 15 with SimpleApiCallback

use of org.matrix.androidsdk.core.callback.SimpleApiCallback in project matrix-android-sdk by matrix-org.

the class ThirdPidRestClient method lookup3PidsV2.

/**
 * Retrieve user matrix id from a 3rd party id.
 *
 * @param addresses 3rd party ids
 * @param mediums   the media.
 * @param callback  the 3rd parties callback
 */
public void lookup3PidsV2(final HashDetailResponse hashDetailResponse, final List<String> addresses, final List<String> mediums, final ApiCallback<List<String>> callback) {
    // sanity checks
    if ((null == addresses) || (null == mediums) || (addresses.size() != mediums.size())) {
        callback.onUnexpectedError(new Exception("invalid params"));
        return;
    }
    // nothing to check
    if (0 == mediums.size()) {
        callback.onSuccess(new ArrayList<>());
        return;
    }
    // Check that hashDetailResponse support sha256
    if (!hashDetailResponse.algorithms.contains("sha256")) {
        // We wont do better on the legacy SDK, in particular, we do not support "none"
        callback.onUnexpectedError(new Exception("sha256 is not supported"));
        return;
    }
    OlmUtility olmUtility;
    try {
        olmUtility = new OlmUtility();
    } catch (Exception e) {
        callback.onUnexpectedError(e);
        return;
    }
    final List<String> hashedPids = new ArrayList<>();
    for (int i = 0; i < addresses.size(); i++) {
        hashedPids.add(StringUtilsKt.base64ToBase64Url(olmUtility.sha256(addresses.get(i).toLowerCase(Locale.ROOT) + " " + mediums.get(i) + " " + hashDetailResponse.pepper)));
    }
    olmUtility.releaseUtility();
    LookUpV2Params lookUpV2Params = new LookUpV2Params(hashedPids, "sha256", hashDetailResponse.pepper);
    mApi.bulkLookupV2(lookUpV2Params).enqueue(new RestAdapterCallback<>("bulkLookupV2", null, new SimpleApiCallback<LookUpV2Response>(callback) {

        @Override
        public void onSuccess(LookUpV2Response info) {
            handleLookupV2Success(info, hashedPids, callback);
        }
    }, null));
}
Also used : LookUpV2Response(org.matrix.androidsdk.rest.model.identityserver.LookUpV2Response) ArrayList(java.util.ArrayList) LookUpV2Params(org.matrix.androidsdk.rest.model.identityserver.LookUpV2Params) OlmUtility(org.matrix.olm.OlmUtility) SimpleApiCallback(org.matrix.androidsdk.core.callback.SimpleApiCallback)

Aggregations

SimpleApiCallback (org.matrix.androidsdk.core.callback.SimpleApiCallback)17 ArrayList (java.util.ArrayList)7 MatrixError (org.matrix.androidsdk.core.model.MatrixError)5 Room (org.matrix.androidsdk.data.Room)5 List (java.util.List)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 RoomState (org.matrix.androidsdk.data.RoomState)4 Event (org.matrix.androidsdk.rest.model.Event)4 HashMap (java.util.HashMap)3 ApiCallback (org.matrix.androidsdk.core.callback.ApiCallback)3 Context (android.content.Context)2 JsonObject (com.google.gson.JsonObject)2 Test (org.junit.Test)2 MXSession (org.matrix.androidsdk.MXSession)2 CryptoTestData (org.matrix.androidsdk.common.CryptoTestData)2 MXCryptoError (org.matrix.androidsdk.crypto.MXCryptoError)2 EventTimeline (org.matrix.androidsdk.data.timeline.EventTimeline)2 MXEventListener (org.matrix.androidsdk.listeners.MXEventListener)2 IdentityServerRequest3PIDValidationParams (org.matrix.androidsdk.rest.model.IdentityServerRequest3PIDValidationParams)2 IdentityServerRequestTokenResponse (org.matrix.androidsdk.rest.model.IdentityServerRequestTokenResponse)2