use of org.matrix.androidsdk.data.store.IMXStore 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);
}
use of org.matrix.androidsdk.data.store.IMXStore 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);
}
use of org.matrix.androidsdk.data.store.IMXStore 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);
}
use of org.matrix.androidsdk.data.store.IMXStore 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;
}
use of org.matrix.androidsdk.data.store.IMXStore in project matrix-android-sdk by matrix-org.
the class MXDataHandler method manageResponse.
/**
* Manage the sync response in the UI thread.
*
* @param syncResponse the syncResponse to manage.
* @param fromToken the start sync token
* @param isCatchingUp true when there is a pending catch-up
*/
private void manageResponse(final SyncResponse syncResponse, final String fromToken, final boolean isCatchingUp) {
if (!isAlive()) {
Log.e(LOG_TAG, "manageResponse : ignored because the session has been closed");
return;
}
boolean isInitialSync = (null == fromToken);
boolean isEmptyResponse = true;
// sanity check
if (null != syncResponse) {
Log.d(LOG_TAG, "onSyncComplete");
// to ensure to decrypt them properly
if ((null != syncResponse.toDevice) && (null != syncResponse.toDevice.events) && (syncResponse.toDevice.events.size() > 0)) {
Log.d(LOG_TAG, "manageResponse : receives " + syncResponse.toDevice.events.size() + " toDevice events");
for (Event toDeviceEvent : syncResponse.toDevice.events) {
handleToDeviceEvent(toDeviceEvent);
}
}
// to be able to update direct chats dictionary during invites handling.
if (null != syncResponse.accountData) {
Log.d(LOG_TAG, "Received " + syncResponse.accountData.size() + " accountData events");
manageAccountData(syncResponse.accountData, isInitialSync);
}
// sanity check
if (null != syncResponse.rooms) {
// joined rooms events
if ((null != syncResponse.rooms.join) && (syncResponse.rooms.join.size() > 0)) {
Log.d(LOG_TAG, "Received " + syncResponse.rooms.join.size() + " joined rooms");
Set<String> roomIds = syncResponse.rooms.join.keySet();
// Handle first joined rooms
for (String roomId : roomIds) {
try {
if (null != mLeftRoomsStore.getRoom(roomId)) {
Log.d(LOG_TAG, "the room " + roomId + " moves from left to the joined ones");
mLeftRoomsStore.deleteRoom(roomId);
}
getRoom(roomId).handleJoinedRoomSync(syncResponse.rooms.join.get(roomId), isInitialSync);
} catch (Exception e) {
Log.e(LOG_TAG, "## manageResponse() : handleJoinedRoomSync failed " + e.getMessage() + " for room " + roomId);
}
}
isEmptyResponse = false;
}
// invited room management
if ((null != syncResponse.rooms.invite) && (syncResponse.rooms.invite.size() > 0)) {
Log.d(LOG_TAG, "Received " + syncResponse.rooms.invite.size() + " invited rooms");
Set<String> roomIds = syncResponse.rooms.invite.keySet();
HashMap<String, List<String>> updatedDirectChatRoomsDict = null;
boolean hasChanged = false;
for (String roomId : roomIds) {
try {
Log.d(LOG_TAG, "## manageResponse() : the user has been invited to " + roomId);
if (null != mLeftRoomsStore.getRoom(roomId)) {
Log.d(LOG_TAG, "the room " + roomId + " moves from left to the invited ones");
mLeftRoomsStore.deleteRoom(roomId);
}
Room room = getRoom(roomId);
InvitedRoomSync invitedRoomSync = syncResponse.rooms.invite.get(roomId);
room.handleInvitedRoomSync(invitedRoomSync);
// Handle here the invites to a direct chat.
if (room.isDirectChatInvitation()) {
// Retrieve the inviter user id.
String participantUserId = null;
for (Event event : invitedRoomSync.inviteState.events) {
if (null != event.sender) {
participantUserId = event.sender;
break;
}
}
if (null != participantUserId) {
// Prepare the updated dictionary.
if (null == updatedDirectChatRoomsDict) {
if (null != this.getStore().getDirectChatRoomsDict()) {
// Consider the current dictionary.
updatedDirectChatRoomsDict = new HashMap<>(this.getStore().getDirectChatRoomsDict());
} else {
updatedDirectChatRoomsDict = new HashMap<>();
}
}
ArrayList<String> roomIdsList;
if (updatedDirectChatRoomsDict.containsKey(participantUserId)) {
roomIdsList = new ArrayList<>(updatedDirectChatRoomsDict.get(participantUserId));
} else {
roomIdsList = new ArrayList<>();
}
// Check whether the room was not yet seen as direct chat
if (roomIdsList.indexOf(roomId) < 0) {
Log.d(LOG_TAG, "## manageResponse() : add this new invite in direct chats");
// update room list with the new room
roomIdsList.add(roomId);
updatedDirectChatRoomsDict.put(participantUserId, roomIdsList);
hasChanged = true;
}
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "## manageResponse() : handleInvitedRoomSync failed " + e.getMessage() + " for room " + roomId);
}
}
isEmptyResponse = false;
if (hasChanged) {
mAccountDataRestClient.setAccountData(mCredentials.userId, AccountDataRestClient.ACCOUNT_DATA_TYPE_DIRECT_MESSAGES, updatedDirectChatRoomsDict, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
Log.d(LOG_TAG, "## manageResponse() : succeeds");
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## manageResponse() : update account data failed " + e.getMessage());
// TODO: we should try again.
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## manageResponse() : update account data failed " + e.getMessage());
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## manageResponse() : update account data failed " + e.getMessage());
}
});
}
}
// when inviting after leaving a room, the room is defined in the both leave & invite rooms list.
if ((null != syncResponse.rooms.leave) && (syncResponse.rooms.leave.size() > 0)) {
Log.d(LOG_TAG, "Received " + syncResponse.rooms.leave.size() + " left rooms");
Set<String> roomIds = syncResponse.rooms.leave.keySet();
for (String roomId : roomIds) {
// RoomSync leftRoomSync = syncResponse.rooms.leave.get(roomId);
// Presently we remove the existing room from the rooms list.
// FIXME SYNC V2 Archive/Display the left rooms!
// For that create 'handleArchivedRoomSync' method
String membership = RoomMember.MEMBERSHIP_LEAVE;
Room room = getRoom(roomId);
// check if the room still exists.
if (null != room) {
// use 'handleJoinedRoomSync' to pass the last events to the room before leaving it.
// The room will then able to notify its listeners.
room.handleJoinedRoomSync(syncResponse.rooms.leave.get(roomId), isInitialSync);
RoomMember member = room.getMember(getUserId());
if (null != member) {
membership = member.membership;
}
Log.d(LOG_TAG, "## manageResponse() : leave the room " + roomId);
}
if (!TextUtils.equals(membership, RoomMember.MEMBERSHIP_KICK) && !TextUtils.equals(membership, RoomMember.MEMBERSHIP_BAN)) {
// ensure that the room data are properly deleted
this.getStore().deleteRoom(roomId);
onLeaveRoom(roomId);
} else {
onRoomKick(roomId);
}
// don't add to the left rooms if the user has been kicked / banned
if ((mAreLeftRoomsSynced) && TextUtils.equals(membership, RoomMember.MEMBERSHIP_LEAVE)) {
Room leftRoom = getRoom(mLeftRoomsStore, roomId, true);
leftRoom.handleJoinedRoomSync(syncResponse.rooms.leave.get(roomId), isInitialSync);
}
}
isEmptyResponse = false;
}
}
// groups
if (null != syncResponse.groups) {
// Handle invited groups
if ((null != syncResponse.groups.invite) && !syncResponse.groups.invite.isEmpty()) {
// Handle invited groups
for (String groupId : syncResponse.groups.invite.keySet()) {
InvitedGroupSync invitedGroupSync = syncResponse.groups.invite.get(groupId);
mGroupsManager.onNewGroupInvitation(groupId, invitedGroupSync.profile, invitedGroupSync.inviter, !isInitialSync);
}
}
// Handle joined groups
if ((null != syncResponse.groups.join) && !syncResponse.groups.join.isEmpty()) {
for (String groupId : syncResponse.groups.join.keySet()) {
mGroupsManager.onJoinGroup(groupId, !isInitialSync);
}
}
// Handle left groups
if ((null != syncResponse.groups.leave) && !syncResponse.groups.leave.isEmpty()) {
// Handle joined groups
for (String groupId : syncResponse.groups.leave.keySet()) {
mGroupsManager.onLeaveGroup(groupId, !isInitialSync);
}
}
}
// Handle presence of other users
if ((null != syncResponse.presence) && (null != syncResponse.presence.events)) {
Log.d(LOG_TAG, "Received " + syncResponse.presence.events.size() + " presence events");
for (Event presenceEvent : syncResponse.presence.events) {
handlePresenceEvent(presenceEvent);
}
}
if (null != mCrypto) {
mCrypto.onSyncCompleted(syncResponse, fromToken, isCatchingUp);
}
IMXStore store = getStore();
if (!isEmptyResponse && (null != store)) {
store.setEventStreamToken(syncResponse.nextBatch);
store.commit();
}
}
if (isInitialSync) {
if (!isCatchingUp) {
startCrypto(true);
} else {
// the events thread sends a dummy initial sync event
// when the application is restarted.
mIsStartingCryptoWithInitialSync = !isEmptyResponse;
}
onInitialSyncComplete((null != syncResponse) ? syncResponse.nextBatch : null);
} else {
if (!isCatchingUp) {
startCrypto(mIsStartingCryptoWithInitialSync);
}
try {
onLiveEventsChunkProcessed(fromToken, (null != syncResponse) ? syncResponse.nextBatch : fromToken);
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEventsChunkProcessed failed " + e.getMessage());
}
try {
// check if an incoming call has been received
mCallsManager.checkPendingIncomingCalls();
} catch (Exception e) {
Log.e(LOG_TAG, "checkPendingIncomingCalls failed " + e + " " + e.getMessage());
}
}
}
Aggregations