From 1822fc4fbbecda71485177a9c604f4955488f7ab Mon Sep 17 00:00:00 2001 From: Dominic Fischer Date: Sat, 13 Jul 2019 15:35:10 +0100 Subject: [PATCH] Some more kotlinification Signed-off-by: Dominic Fischer --- .../android/internal/crypto/CryptoManager.kt | 54 ++++++++----------- .../algorithms/megolm/MXMegolmDecryption.kt | 9 ++-- 2 files changed, 24 insertions(+), 39 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/CryptoManager.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/CryptoManager.kt index 9f92ff3671..3fadb09bc0 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/CryptoManager.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/CryptoManager.kt @@ -79,7 +79,6 @@ import im.vector.matrix.android.internal.util.fetchCopied import kotlinx.coroutines.* import org.matrix.olm.OlmManager import timber.log.Timber -import java.util.* import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject import kotlin.math.max @@ -339,7 +338,7 @@ internal class CryptoManager @Inject constructor( * @return the device info, or null if not found / unsupported algorithm / crypto released */ override fun deviceWithIdentityKey(senderKey: String, algorithm: String): MXDeviceInfo? { - return if (!TextUtils.equals(algorithm, MXCRYPTO_ALGORITHM_MEGOLM) && !TextUtils.equals(algorithm, MXCRYPTO_ALGORITHM_OLM)) { + return if (algorithm != MXCRYPTO_ALGORITHM_MEGOLM && algorithm != MXCRYPTO_ALGORITHM_OLM) { // We only deal in olm keys null } else cryptoStore.deviceWithIdentityKey(senderKey) @@ -352,8 +351,8 @@ internal class CryptoManager @Inject constructor( * @param deviceId the device id */ override fun getDeviceInfo(userId: String, deviceId: String?): MXDeviceInfo? { - return if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(deviceId)) { - cryptoStore.getUserDevice(deviceId!!, userId) + return if (userId.isNotEmpty() && !deviceId.isNullOrEmpty()) { + cryptoStore.getUserDevice(deviceId, userId) } else { null } @@ -438,7 +437,7 @@ internal class CryptoManager @Inject constructor( // (for now at least. Maybe we should alert the user somehow?) val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId) - if (!TextUtils.isEmpty(existingAlgorithm) && !TextUtils.equals(existingAlgorithm, algorithm)) { + if (!existingAlgorithm.isNullOrEmpty() && existingAlgorithm != algorithm) { Timber.e("## setEncryptionInRoom() : Ignoring m.room.encryption event which requests a change of config in $roomId") return false } @@ -670,7 +669,7 @@ internal class CryptoManager @Inject constructor( */ private fun onRoomKeyEvent(event: Event) { val roomKeyContent = event.getClearContent().toModel() ?: return - if (TextUtils.isEmpty(roomKeyContent.roomId) || TextUtils.isEmpty(roomKeyContent.algorithm)) { + if (roomKeyContent.roomId.isNullOrEmpty() || roomKeyContent.algorithm.isNullOrEmpty()) { Timber.e("## onRoomKeyEvent() : missing fields") return } @@ -737,7 +736,7 @@ internal class CryptoManager @Inject constructor( val membership = roomMember?.membership if (membership == Membership.JOIN) { // make sure we are tracking the deviceList for this user. - deviceListManager.startTrackingDeviceList(Arrays.asList(userId)) + deviceListManager.startTrackingDeviceList(listOf(userId)) } else if (membership == Membership.INVITE && shouldEncryptForInvitedMembers(roomId) && cryptoConfig.enableEncryptionForInvitedMembers) { @@ -746,7 +745,7 @@ internal class CryptoManager @Inject constructor( // know what other servers are in the room at the time they've been invited. // They therefore will not send device updates if a user logs in whilst // their state is invite. - deviceListManager.startTrackingDeviceList(Arrays.asList(userId)) + deviceListManager.startTrackingDeviceList(listOf(userId)) } } } @@ -781,7 +780,11 @@ internal class CryptoManager @Inject constructor( * @param callback the exported keys */ override fun exportRoomKeys(password: String, callback: MatrixCallback) { - exportRoomKeys(password, MXMegolmExportEncryption.DEFAULT_ITERATION_COUNT, callback) + GlobalScope.launch(coroutineDispatchers.main) { + runCatching { + exportRoomKeys(password, MXMegolmExportEncryption.DEFAULT_ITERATION_COUNT) + }.fold(callback::onSuccess, callback::onFailure) + } } /** @@ -791,30 +794,16 @@ internal class CryptoManager @Inject constructor( * @param anIterationCount the encryption iteration count (0 means no encryption) * @param callback the exported keys */ - private fun exportRoomKeys(password: String, anIterationCount: Int, callback: MatrixCallback) { - GlobalScope.launch(coroutineDispatchers.main) { - withContext(coroutineDispatchers.crypto) { - Try { - val iterationCount = Math.max(0, anIterationCount) + private suspend fun exportRoomKeys(password: String, anIterationCount: Int): ByteArray { + return withContext(coroutineDispatchers.crypto) { + val iterationCount = max(0, anIterationCount) - val exportedSessions = ArrayList() + val exportedSessions = cryptoStore.getInboundGroupSessions().mapNotNull { it.exportKeys() } - val inboundGroupSessions = cryptoStore.getInboundGroupSessions() + val adapter = MoshiProvider.providesMoshi() + .adapter(List::class.java) - for (session in inboundGroupSessions) { - val megolmSessionData = session.exportKeys() - - if (null != megolmSessionData) { - exportedSessions.add(megolmSessionData) - } - } - - val adapter = MoshiProvider.providesMoshi() - .adapter(List::class.java) - - MXMegolmExportEncryption.encryptMegolmKeyFile(adapter.toJson(exportedSessions), password, iterationCount) - } - }.foldToCallback(callback) + MXMegolmExportEncryption.encryptMegolmKeyFile(adapter.toJson(exportedSessions), password, iterationCount) } } @@ -943,7 +932,7 @@ internal class CryptoManager @Inject constructor( val roomIds = cryptoStore.getRoomsListBlacklistUnverifiedDevices().toMutableList() if (add) { - if (!roomIds.contains(roomId)) { + if (roomId !in roomIds) { roomIds.add(roomId) } } else { @@ -1032,8 +1021,7 @@ internal class CryptoManager @Inject constructor( val unknownDevices = MXUsersDevicesMap() val userIds = devicesInRoom.userIds for (userId in userIds) { - val deviceIds = devicesInRoom.getUserDeviceIds(userId) - deviceIds?.forEach { deviceId -> + devicesInRoom.getUserDeviceIds(userId)?.forEach { deviceId -> devicesInRoom.getObject(userId, deviceId) ?.takeIf { it.isUnknown } ?.let { diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt index dfea1f86f2..b30176b2c4 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/megolm/MXMegolmDecryption.kt @@ -40,7 +40,6 @@ import im.vector.matrix.android.internal.util.MatrixCoroutineDispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import timber.log.Timber -import java.util.* import kotlin.collections.HashMap internal class MXMegolmDecryption(private val credentials: Credentials, @@ -320,8 +319,7 @@ internal class MXMegolmDecryption(private val credentials: Credentials, if (deviceInfo == null) { throw RuntimeException() } else { - val devicesByUser = HashMap>() - devicesByUser[userId] = ArrayList(Arrays.asList(deviceInfo)) + val devicesByUser = mapOf(userId to listOf(deviceInfo)) ensureOlmSessionsForDevicesAction .handle(devicesByUser) .flatMap { @@ -335,8 +333,7 @@ internal class MXMegolmDecryption(private val credentials: Credentials, Timber.v("## shareKeysWithDevice() : sharing keys for session" + " ${body?.senderKey}|${body?.sessionId} with device $userId:$deviceId") - val payloadJson = HashMap() - payloadJson["type"] = EventType.FORWARDED_ROOM_KEY + val payloadJson = mutableMapOf("type" to EventType.FORWARDED_ROOM_KEY) olmDevice.getInboundGroupSession(body?.sessionId, body?.senderKey, body?.roomId) .fold( @@ -349,7 +346,7 @@ internal class MXMegolmDecryption(private val credentials: Credentials, } ) - val encodedPayload = messageEncrypter.encryptMessage(payloadJson, Arrays.asList(deviceInfo)) + val encodedPayload = messageEncrypter.encryptMessage(payloadJson, listOf(deviceInfo)) val sendToDeviceMap = MXUsersDevicesMap() sendToDeviceMap.setObject(userId, deviceId, encodedPayload) Timber.v("## shareKeysWithDevice() : sending to $userId:$deviceId")