diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/util/SecretStoringUtils.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/util/SecretStoringUtils.kt index 6dc0d789cc..4e36506e73 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/util/SecretStoringUtils.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/util/SecretStoringUtils.kt @@ -479,12 +479,7 @@ object SecretStoringUtils { val output = Cipher.getInstance(RSA_MODE) output.init(Cipher.DECRYPT_MODE, privateKeyEntry.privateKey) - val bos = ByteArrayOutputStream() - CipherInputStream(encrypted, output).use { - it.copyTo(bos) - } - - return bos.toByteArray() + return CipherInputStream(encrypted, output).use { it.readBytes() } } private fun formatMExtract(bis: InputStream): Pair { @@ -495,14 +490,7 @@ object SecretStoringUtils { val iv = ByteArray(ivSize) bis.read(iv, 0, ivSize) - - val bos = ByteArrayOutputStream() - var next = bis.read() - while (next != -1) { - bos.write(next) - next = bis.read() - } - val encrypted = bos.toByteArray() + val encrypted = bis.readBytes() return Pair(iv, encrypted) } @@ -530,14 +518,7 @@ object SecretStoringUtils { val iv = ByteArray(ivSize) bis.read(iv) - val bos = ByteArrayOutputStream() - - var next = bis.read() - while (next != -1) { - bos.write(next) - next = bis.read() - } - val encrypted = bos.toByteArray() + val encrypted = bis.readBytes() return Triple(encryptedKey, iv, encrypted) } @@ -579,14 +560,7 @@ object SecretStoringUtils { val iv = ByteArray(ivSize) bis.read(iv) - val bos = ByteArrayOutputStream() - - var next = bis.read() - while (next != -1) { - bos.write(next) - next = bis.read() - } - val encrypted = bos.toByteArray() + val encrypted = bis.readBytes() return Triple(salt, iv, encrypted) } } \ No newline at end of file diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt index 7b5a8cd498..05f0b71e32 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/algorithms/olm/MXOlmDecryption.kt @@ -165,33 +165,14 @@ internal class MXOlmDecryption( * @return payload, if decrypted successfully. */ private fun decryptMessage(message: JsonDict, theirDeviceIdentityKey: String): String? { - val sessionIdsSet = olmDevice.getSessionIds(theirDeviceIdentityKey) + val sessionIds = olmDevice.getSessionIds(theirDeviceIdentityKey) ?: emptySet() - val sessionIds: List - - if (null == sessionIdsSet) { - sessionIds = ArrayList() - } else { - sessionIds = ArrayList(sessionIdsSet) - } - - val messageBody = message["body"] as? String - var messageType: Int? = null - - val typeAsVoid = message["type"] - - if (null != typeAsVoid) { - if (typeAsVoid is Double) { - messageType = typeAsVoid.toInt() - } else if (typeAsVoid is Int) { - messageType = typeAsVoid - } else if (typeAsVoid is Long) { - messageType = typeAsVoid.toInt() - } - } - - if (null == messageBody || null == messageType) { - return null + val messageBody = message["body"] as? String ?: return null + val messageType = when (val typeAsVoid = message["type"]) { + is Double -> typeAsVoid.toInt() + is Int -> typeAsVoid + is Long -> typeAsVoid.toInt() + else -> return null } // Try each session in turn diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/attachments/MXEncryptedAttachments.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/attachments/MXEncryptedAttachments.kt index d8c627097d..e9193fa436 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/attachments/MXEncryptedAttachments.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/attachments/MXEncryptedAttachments.kt @@ -115,7 +115,7 @@ object MXEncryptedAttachments { encryptedByteArray = outStream.toByteArray() ) - Timber.v("Encrypt in " + (System.currentTimeMillis() - t0) + " ms") + Timber.v("Encrypt in ${System.currentTimeMillis() - t0} ms") return Try.just(result) } catch (oom: OutOfMemoryError) { Timber.e(oom, "## encryptAttachment failed") @@ -206,13 +206,13 @@ object MXEncryptedAttachments { val decryptedStream = ByteArrayInputStream(outStream.toByteArray()) outStream.close() - Timber.v("Decrypt in " + (System.currentTimeMillis() - t0) + " ms") + Timber.v("Decrypt in ${System.currentTimeMillis() - t0} ms") return decryptedStream } catch (oom: OutOfMemoryError) { - Timber.e(oom, "## decryptAttachment() : failed " + oom.message) + Timber.e(oom, "## decryptAttachment() : failed ${oom.message}") } catch (e: Exception) { - Timber.e(e, "## decryptAttachment() : failed " + e.message) + Timber.e(e, "## decryptAttachment() : failed ${e.message}") } try { @@ -228,34 +228,20 @@ object MXEncryptedAttachments { * Base64 URL conversion methods */ - private fun base64UrlToBase64(base64Url: String?): String? { - var result = base64Url - if (null != result) { - result = result.replace("-".toRegex(), "+") - result = result.replace("_".toRegex(), "/") - } - - return result + private fun base64UrlToBase64(base64Url: String): String { + return base64Url.replace('-', '+') + .replace('_', '/') } - private fun base64ToBase64Url(base64: String?): String? { - var result = base64 - if (null != result) { - result = result.replace("\n".toRegex(), "") - result = result.replace("\\+".toRegex(), "-") - result = result.replace("/".toRegex(), "_") - result = result.replace("=".toRegex(), "") - } - return result + private fun base64ToBase64Url(base64: String): String { + return base64.replace("\n".toRegex(), "") + .replace("\\+".toRegex(), "-") + .replace('/', '_') + .replace("=", "") } - private fun base64ToUnpaddedBase64(base64: String?): String? { - var result = base64 - if (null != result) { - result = result.replace("\n".toRegex(), "") - result = result.replace("=".toRegex(), "") - } - - return result + private fun base64ToUnpaddedBase64(base64: String): String { + return base64.replace("\n".toRegex(), "") + .replace("=", "") } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXKey.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXKey.kt index 69019fbbaa..1469feea7d 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXKey.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXKey.kt @@ -46,11 +46,7 @@ data class MXKey( * @return the signed data map */ fun signalableJSONDictionary(): Map { - val map = HashMap() - - map["key"] = value - - return map + return mapOf("key" to value) } /** diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXUsersDevicesMap.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXUsersDevicesMap.kt index a4b6e247a6..13078d64af 100755 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXUsersDevicesMap.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/model/MXUsersDevicesMap.kt @@ -27,7 +27,7 @@ class MXUsersDevicesMap { * @return the user Ids */ val userIds: List - get() = ArrayList(map.keys) + get() = map.keys.toList() val isEmpty: Boolean get() = map.isEmpty() @@ -40,7 +40,7 @@ class MXUsersDevicesMap { * @return the device ids list */ fun getUserDeviceIds(userId: String?): List? { - return if (userId?.isNotBlank() == true && map.containsKey(userId)) { + return if (!userId.isNullOrBlank() && map.containsKey(userId)) { map[userId]!!.keys.toList() } else null } @@ -53,7 +53,7 @@ class MXUsersDevicesMap { * @return the object */ fun getObject(userId: String?, deviceId: String?): E? { - return if (userId?.isNotBlank() == true && deviceId?.isNotBlank() == true && map.containsKey(userId)) { + return if (!userId.isNullOrBlank() && !deviceId.isNullOrBlank()) { map[userId]?.get(deviceId) } else null } @@ -67,11 +67,8 @@ class MXUsersDevicesMap { */ fun setObject(userId: String?, deviceId: String?, o: E?) { if (null != o && userId?.isNotBlank() == true && deviceId?.isNotBlank() == true) { - if (map[userId] == null) { - map[userId] = HashMap() - } - - map[userId]?.put(deviceId, o) + val devices = map.getOrPut(userId) { HashMap() } + devices[deviceId] = o } } @@ -82,7 +79,7 @@ class MXUsersDevicesMap { * @param userId the user id */ fun setObjects(userId: String?, objectsPerDevices: Map?) { - if (userId?.isNotBlank() == true) { + if (!userId.isNullOrBlank()) { if (null == objectsPerDevices) { map.remove(userId) } else { @@ -97,7 +94,7 @@ class MXUsersDevicesMap { * @param userId the user id. */ fun removeUserObjects(userId: String?) { - if (userId?.isNotBlank() == true) { + if (!userId.isNullOrBlank()) { map.remove(userId) } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt index 54a4e14dc8..f3cfa42946 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/DefaultSasVerificationService.kt @@ -160,7 +160,7 @@ internal class DefaultSasVerificationService @Inject constructor(private val cre cancelTransaction( startReq.transactionID!!, otherUserId!!, - startReq?.fromDevice ?: event.getSenderKey()!!, + startReq.fromDevice ?: event.getSenderKey()!!, CancelCode.UnknownMethod ) } @@ -384,14 +384,13 @@ internal class DefaultSasVerificationService @Inject constructor(private val cre * This string must be unique for the pair of users performing verification for the duration that the transaction is valid */ private fun createUniqueIDForTransaction(userId: String, deviceID: String): String { - val buff = StringBuffer() - buff - .append(credentials.userId).append("|") - .append(credentials.deviceId).append("|") - .append(userId).append("|") - .append(deviceID).append("|") - .append(UUID.randomUUID().toString()) - return buff.toString() + return buildString { + append(credentials.userId).append("|") + append(credentials.deviceId).append("|") + append(userId).append("|") + append(deviceID).append("|") + append(UUID.randomUUID().toString()) + } } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/ssl/TLSSocketFactory.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/ssl/TLSSocketFactory.kt index e249ed74c8..243c9950b6 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/ssl/TLSSocketFactory.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/network/ssl/TLSSocketFactory.kt @@ -101,25 +101,16 @@ constructor(trustPinned: Array, acceptedTlsVersions: List() - - for (protocol in enabledProtocols) { - if (supportedProtocols.contains(protocol)) { - filteredEnabledProtocols.add(protocol) - } - } - - if (!filteredEnabledProtocols.isEmpty()) { + if (filteredEnabledProtocols.isNotEmpty()) { try { - sslSocket.enabledProtocols = filteredEnabledProtocols.toTypedArray() + socket.enabledProtocols = filteredEnabledProtocols.toTypedArray() } catch (e: Exception) { Timber.e(e) } - } } return socket diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt index df79d62e8b..f932c3c924 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/room/send/LocalEchoEventFactory.kt @@ -305,17 +305,22 @@ internal class LocalEchoEventFactory @Inject constructor(private val credentials } private fun buildReplyFallback(body: TextContent, originalSenderId: String?, newBodyText: String): String { - val lines = body.text.split("\n") - val replyFallback = StringBuffer("> <$originalSenderId>") - lines.forEachIndexed { index, s -> - if (index == 0) { - replyFallback.append(" $s") - } else { - replyFallback.append("\n> $s") + return buildString { + append("> <") + append(originalSenderId) + append(">") + + val lines = body.text.split("\n") + lines.forEachIndexed { index, s -> + if (index == 0) { + append(" $s") + } else { + append("\n> $s") + } } + append("\n\n") + append(newBodyText) } - replyFallback.append("\n\n").append(newBodyText) - return replyFallback.toString() } /** diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/RoomTagHandler.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/RoomTagHandler.kt index 49038eed3d..4d363af635 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/RoomTagHandler.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/RoomTagHandler.kt @@ -31,16 +31,8 @@ internal class RoomTagHandler @Inject constructor() { if (content == null) { return } - val tags = ArrayList() - for (tagName in content.tags.keys) { - val params = content.tags[tagName] - val order = params?.get("order") - val tag = if (order is Double) { - RoomTagEntity(tagName, order) - } else { - RoomTagEntity(tagName, null) - } - tags.add(tag) + val tags = content.tags.entries.map { (tagName, params) -> + RoomTagEntity(tagName, params["order"] as? Double) } val roomSummaryEntity = RoomSummaryEntity.where(realm, roomId).findFirst() ?: RoomSummaryEntity(roomId) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/JsonCanonicalizer.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/JsonCanonicalizer.kt index 36c1ba1553..42f82db8a1 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/JsonCanonicalizer.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/util/JsonCanonicalizer.kt @@ -60,43 +60,33 @@ object JsonCanonicalizer { when (any) { is JSONArray -> { // Canonicalize each element of the array - val result = StringBuilder("[") - - for (i in 0 until any.length()) { - result.append(canonicalizeRecursive(any.get(i))) - if (i < any.length() - 1) { - result.append(",") - } + return (0 until any.length()).joinToString(separator = ",", prefix = "[", postfix = "]") { + canonicalizeRecursive(any.get(it)) } - - result.append("]") - - return result.toString() } is JSONObject -> { // Sort the attributes by name, and the canonicalize each element of the JSONObject - val result = StringBuilder("{") val attributes = TreeSet() for (entry in any.keys()) { attributes.add(entry) } - for (attribute in attributes.withIndex()) { - result.append("\"") - .append(attribute.value) - .append("\"") - .append(":") - .append(canonicalizeRecursive(any[attribute.value])) + return buildString { + append("{") + for ((index, value) in attributes.withIndex()) { + append("\"") + append(value) + append("\"") + append(":") + append(canonicalizeRecursive(any[value])) - if (attribute.index < attributes.size - 1) { - result.append(",") + if (index < attributes.size - 1) { + append(",") + } } + append("}") } - - result.append("}") - - return result.toString() } is String -> return JSONObject.quote(any) else -> return any.toString()