use of org.matrix.androidsdk.data.Room 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);
}
}
use of org.matrix.androidsdk.data.Room in project matrix-android-sdk by matrix-org.
the class MXSession method tagOrderToBeAtIndex.
/**
* Compute the tag order to use for a room tag so that the room will appear in the expected position
* in the list of rooms stamped with this tag.
*
* @param index the targeted index of the room in the list of rooms with the tag `tag`.
* @param originIndex the origin index. Integer.MAX_VALUE if there is none.
* @param tag the tag
* @return the tag order to apply to get the expected position.
*/
public Double tagOrderToBeAtIndex(int index, int originIndex, String tag) {
// Algo (and the [0.0, 1.0] assumption) inspired from matrix-react-sdk:
// We sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
// For convenience, we calculate this for now a floating point number between 0.0 and 1.0.
// by default we're next to the beginning of the list
Double orderA = 0.0;
// by default we're next to the end of the list too
Double orderB = 1.0;
List<Room> roomsWithTag = roomsWithTag(tag);
if (roomsWithTag.size() > 0) {
// because the object will be removed from the list to be inserted after its destination
if ((originIndex != Integer.MAX_VALUE) && (originIndex < index)) {
index++;
}
if (index > 0) {
// Bound max index to the array size
int prevIndex = (index < roomsWithTag.size()) ? index : roomsWithTag.size();
RoomTag prevTag = roomsWithTag.get(prevIndex - 1).getAccountData().roomTag(tag);
if (null == prevTag.mOrder) {
Log.e(LOG_TAG, "computeTagOrderForRoom: Previous room in sublist has no ordering metadata. This should never happen.");
} else {
orderA = prevTag.mOrder;
}
}
if (index <= roomsWithTag.size() - 1) {
RoomTag nextTag = roomsWithTag.get(index).getAccountData().roomTag(tag);
if (null == nextTag.mOrder) {
Log.e(LOG_TAG, "computeTagOrderForRoom: Next room in sublist has no ordering metadata. This should never happen.");
} else {
orderB = nextTag.mOrder;
}
}
}
return (orderA + orderB) / 2.0;
}
use of org.matrix.androidsdk.data.Room in project matrix-android-sdk by matrix-org.
the class CryptoTest method doE2ETestWithAliceAndBobAndSamInARoom.
private void doE2ETestWithAliceAndBobAndSamInARoom() throws Exception {
final HashMap<String, String> statuses = new HashMap<>();
doE2ETestWithAliceAndBobInARoom(true);
Room room = mAliceSession.getDataHandler().getRoom(mRoomId);
createSamAccount();
final CountDownLatch lock0 = new CountDownLatch(1);
mSamSession.enableCrypto(true, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
statuses.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);
final CountDownLatch lock1 = new CountDownLatch(2);
MXEventListener samEventListener = new MXEventListener() {
@Override
public void onNewRoom(String roomId) {
if (TextUtils.equals(roomId, mRoomId)) {
if (!statuses.containsKey("onNewRoom")) {
statuses.put("onNewRoom", "onNewRoom");
lock1.countDown();
}
}
}
};
mSamSession.getDataHandler().addListener(samEventListener);
room.invite(mSamSession.getMyUserId(), new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
statuses.put("invite", "invite");
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(statuses.containsKey("invite") && statuses.containsKey("onNewRoom"));
mSamSession.getDataHandler().removeListener(samEventListener);
final CountDownLatch lock2 = new CountDownLatch(1);
mSamSession.joinRoom(mRoomId, new ApiCallback<String>() {
@Override
public void onSuccess(String info) {
statuses.put("joinRoom", "joinRoom");
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(statuses.containsKey("joinRoom"));
// wait the initial sync
SystemClock.sleep(1000);
mSamSession.getDataHandler().removeListener(samEventListener);
}
use of org.matrix.androidsdk.data.Room in project matrix-android-sdk by matrix-org.
the class CryptoTest method test25_testLeftAndJoinedBob.
@Test
public // issue https://github.com/vector-im/riot-web/issues/2305
void test25_testLeftAndJoinedBob() throws Exception {
Log.e(LOG_TAG, "test25_testLeftAndJoinedBob");
Context context = InstrumentationRegistry.getContext();
final String messageFromAlice = "Hello I'm Alice!";
final String message2FromAlice = "I'm still Alice!";
final HashMap<String, Object> results = new HashMap<>();
createAliceAccount();
createBobAccount();
final CountDownLatch lock_1 = new CountDownLatch(2);
mAliceSession.enableCrypto(true, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
lock_1.countDown();
}
@Override
public void onNetworkError(Exception e) {
lock_1.countDown();
}
@Override
public void onMatrixError(MatrixError e) {
lock_1.countDown();
}
@Override
public void onUnexpectedError(Exception e) {
lock_1.countDown();
}
});
mBobSession.enableCrypto(true, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
lock_1.countDown();
}
@Override
public void onNetworkError(Exception e) {
lock_1.countDown();
}
@Override
public void onMatrixError(MatrixError e) {
lock_1.countDown();
}
@Override
public void onUnexpectedError(Exception e) {
lock_1.countDown();
}
});
lock_1.await(2000, TimeUnit.MILLISECONDS);
assertTrue(null != mAliceSession.getCrypto());
assertTrue(null != mBobSession.getCrypto());
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");
Room roomFromAlicePOV = mAliceSession.getDataHandler().getRoom(mRoomId);
final CountDownLatch lock1 = new CountDownLatch(1);
roomFromAlicePOV.enableEncryptionWithAlgorithm(MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm");
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("enableEncryptionWithAlgorithm"));
final CountDownLatch lock2 = new CountDownLatch(1);
mBobSession.joinRoom(mRoomId, new ApiCallback<String>() {
@Override
public void onSuccess(String info) {
results.put("joinRoom", "joinRoom");
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("joinRoom"));
Room roomFromBobPOV = mBobSession.getDataHandler().getRoom(mRoomId);
final CountDownLatch lock3 = new CountDownLatch(1);
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);
lock3.countDown();
}
}
};
roomFromBobPOV.getLiveTimeLine().addEventTimelineListener(eventTimelineListener);
roomFromAlicePOV.sendEvent(buildTextEvent(messageFromAlice, 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) {
}
});
lock3.await(2000, TimeUnit.MILLISECONDS);
assertTrue(1 == receivedEvents.size());
Event event = receivedEvents.get(0);
assertTrue(checkEncryptedEvent(event, mRoomId, messageFromAlice, mAliceSession));
final CountDownLatch lock4 = new CountDownLatch(1);
roomFromBobPOV.leave(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
results.put("leave", "leave");
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(2000, TimeUnit.MILLISECONDS);
assertTrue(results.containsKey("leave"));
// 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 lock5 = new CountDownLatch(1);
bobSession2.joinRoom(mRoomId, new ApiCallback<String>() {
@Override
public void onSuccess(String info) {
results.put("joinRoom2", "joinRoom2");
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(5000, TimeUnit.MILLISECONDS);
assertTrue(results.containsKey("joinRoom2"));
Room roomFromBobPOV2 = bobSession2.getDataHandler().getRoom(mRoomId);
final CountDownLatch lock6 = 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);
lock6.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) {
}
});
lock6.await(5000, TimeUnit.MILLISECONDS);
assertTrue(1 == receivedEvents2.size());
event = receivedEvents2.get(0);
assertTrue(checkEncryptedEvent(event, mRoomId, message2FromAlice, mAliceSession));
bobSession2.clear(context);
mAliceSession.clear(context);
}
use of org.matrix.androidsdk.data.Room in project matrix-android-sdk by matrix-org.
the class CryptoTest method test08_testAliceAndBobInACryptedRoom2.
@Test
public void test08_testAliceAndBobInACryptedRoom2() throws Exception {
Log.e(LOG_TAG, "test08_testAliceAndBobInACryptedRoom2");
doE2ETestWithAliceAndBobInARoom(true);
mBobSession.getCrypto().setWarnOnUnknownDevices(false);
mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
final Room roomFromBobPOV = mBobSession.getDataHandler().getRoom(mRoomId);
final Room roomFromAlicePOV = mAliceSession.getDataHandler().getRoom(mRoomId);
assertTrue(roomFromBobPOV.isEncrypted());
assertTrue(roomFromAlicePOV.isEncrypted());
mReceivedMessagesFromAlice = 0;
mReceivedMessagesFromBob = 0;
final ArrayList<CountDownLatch> list = new ArrayList<>();
MXEventListener bobEventListener = new MXEventListener() {
@Override
public void onLiveEvent(Event event, RoomState roomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), mBobSession.getMyUserId())) {
try {
if (checkEncryptedEvent(event, mRoomId, messagesFromAlice.get(mReceivedMessagesFromAlice), mAliceSession)) {
mReceivedMessagesFromAlice++;
list.get(list.size() - 1).countDown();
}
} catch (Exception e) {
}
}
}
};
MXEventListener aliceEventListener = new MXEventListener() {
@Override
public void onLiveEvent(Event event, RoomState roomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE) && !TextUtils.equals(event.getSender(), mAliceSession.getMyUserId())) {
try {
if (checkEncryptedEvent(event, mRoomId, messagesFromBob.get(mReceivedMessagesFromBob), mBobSession)) {
mReceivedMessagesFromBob++;
}
list.get(list.size() - 1).countDown();
} catch (Exception e) {
}
}
}
};
ApiCallback<Void> callback = 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) {
}
};
roomFromBobPOV.addEventListener(bobEventListener);
roomFromAlicePOV.addEventListener(aliceEventListener);
list.add(new CountDownLatch(2));
final HashMap<String, Object> results = new HashMap<>();
mBobSession.getDataHandler().addListener(new MXEventListener() {
@Override
public void onToDeviceEvent(Event event) {
results.put("onToDeviceEvent", event);
list.get(0).countDown();
}
});
roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(mReceivedMessagesFromAlice), mAliceSession), callback);
list.get(list.size() - 1).await(1000, TimeUnit.MILLISECONDS);
assertTrue(results.containsKey("onToDeviceEvent"));
assertTrue(1 == mReceivedMessagesFromAlice);
list.add(new CountDownLatch(1));
roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(mReceivedMessagesFromBob), mBobSession), callback);
list.get(list.size() - 1).await(1000, TimeUnit.MILLISECONDS);
assertTrue(1 == mReceivedMessagesFromBob);
list.add(new CountDownLatch(1));
roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(mReceivedMessagesFromBob), mBobSession), callback);
list.get(list.size() - 1).await(1000, TimeUnit.MILLISECONDS);
assertTrue(2 == mReceivedMessagesFromBob);
list.add(new CountDownLatch(1));
roomFromBobPOV.sendEvent(buildTextEvent(messagesFromBob.get(mReceivedMessagesFromBob), mBobSession), callback);
list.get(list.size() - 1).await(1000, TimeUnit.MILLISECONDS);
assertTrue(3 == mReceivedMessagesFromBob);
list.add(new CountDownLatch(1));
roomFromAlicePOV.sendEvent(buildTextEvent(messagesFromAlice.get(mReceivedMessagesFromAlice), mAliceSession), callback);
list.get(list.size() - 1).await(1000, TimeUnit.MILLISECONDS);
assertTrue(2 == mReceivedMessagesFromAlice);
}
Aggregations