Merge pull request #418 from Dominaezzz/kotlinify-1

Some more kotlinification
This commit is contained in:
Benoit Marty 2019-09-05 16:02:30 +02:00 committed by GitHub
commit fe931b5361
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 77 additions and 166 deletions

View File

@ -479,12 +479,7 @@ object SecretStoringUtils {
val output = Cipher.getInstance(RSA_MODE) val output = Cipher.getInstance(RSA_MODE)
output.init(Cipher.DECRYPT_MODE, privateKeyEntry.privateKey) output.init(Cipher.DECRYPT_MODE, privateKeyEntry.privateKey)


val bos = ByteArrayOutputStream() return CipherInputStream(encrypted, output).use { it.readBytes() }
CipherInputStream(encrypted, output).use {
it.copyTo(bos)
}

return bos.toByteArray()
} }


private fun formatMExtract(bis: InputStream): Pair<ByteArray, ByteArray> { private fun formatMExtract(bis: InputStream): Pair<ByteArray, ByteArray> {
@ -495,14 +490,7 @@ object SecretStoringUtils {
val iv = ByteArray(ivSize) val iv = ByteArray(ivSize)
bis.read(iv, 0, ivSize) bis.read(iv, 0, ivSize)



val encrypted = bis.readBytes()
val bos = ByteArrayOutputStream()
var next = bis.read()
while (next != -1) {
bos.write(next)
next = bis.read()
}
val encrypted = bos.toByteArray()
return Pair(iv, encrypted) return Pair(iv, encrypted)
} }


@ -530,14 +518,7 @@ object SecretStoringUtils {
val iv = ByteArray(ivSize) val iv = ByteArray(ivSize)
bis.read(iv) bis.read(iv)


val bos = ByteArrayOutputStream() val encrypted = bis.readBytes()

var next = bis.read()
while (next != -1) {
bos.write(next)
next = bis.read()
}
val encrypted = bos.toByteArray()
return Triple(encryptedKey, iv, encrypted) return Triple(encryptedKey, iv, encrypted)
} }


@ -579,14 +560,7 @@ object SecretStoringUtils {
val iv = ByteArray(ivSize) val iv = ByteArray(ivSize)
bis.read(iv) bis.read(iv)


val bos = ByteArrayOutputStream() val encrypted = bis.readBytes()

var next = bis.read()
while (next != -1) {
bos.write(next)
next = bis.read()
}
val encrypted = bos.toByteArray()
return Triple(salt, iv, encrypted) return Triple(salt, iv, encrypted)
} }
} }

View File

@ -157,33 +157,14 @@ internal class MXOlmDecryption(
* @return payload, if decrypted successfully. * @return payload, if decrypted successfully.
*/ */
private fun decryptMessage(message: JsonDict, theirDeviceIdentityKey: String): String? { private fun decryptMessage(message: JsonDict, theirDeviceIdentityKey: String): String? {
val sessionIdsSet = olmDevice.getSessionIds(theirDeviceIdentityKey) val sessionIds = olmDevice.getSessionIds(theirDeviceIdentityKey) ?: emptySet()


val sessionIds: List<String> val messageBody = message["body"] as? String ?: return null

val messageType = when (val typeAsVoid = message["type"]) {
if (null == sessionIdsSet) { is Double -> typeAsVoid.toInt()
sessionIds = ArrayList() is Int -> typeAsVoid
} else { is Long -> typeAsVoid.toInt()
sessionIds = ArrayList(sessionIdsSet) else -> return null
}

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
} }


// Try each session in turn // Try each session in turn

View File

@ -113,7 +113,7 @@ object MXEncryptedAttachments {
encryptedByteArray = outStream.toByteArray() encryptedByteArray = outStream.toByteArray()
) )


Timber.v("Encrypt in " + (System.currentTimeMillis() - t0) + " ms") Timber.v("Encrypt in ${System.currentTimeMillis() - t0} ms")
return Try.just(result) return Try.just(result)
} catch (oom: OutOfMemoryError) { } catch (oom: OutOfMemoryError) {
Timber.e(oom, "## encryptAttachment failed") Timber.e(oom, "## encryptAttachment failed")
@ -204,13 +204,13 @@ object MXEncryptedAttachments {
val decryptedStream = ByteArrayInputStream(outStream.toByteArray()) val decryptedStream = ByteArrayInputStream(outStream.toByteArray())
outStream.close() outStream.close()


Timber.v("Decrypt in " + (System.currentTimeMillis() - t0) + " ms") Timber.v("Decrypt in ${System.currentTimeMillis() - t0} ms")


return decryptedStream return decryptedStream
} catch (oom: OutOfMemoryError) { } catch (oom: OutOfMemoryError) {
Timber.e(oom, "## decryptAttachment() : failed " + oom.message) Timber.e(oom, "## decryptAttachment() : failed ${oom.message}")
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e, "## decryptAttachment() : failed " + e.message) Timber.e(e, "## decryptAttachment() : failed ${e.message}")
} }


try { try {
@ -226,34 +226,20 @@ object MXEncryptedAttachments {
* Base64 URL conversion methods * Base64 URL conversion methods
*/ */


private fun base64UrlToBase64(base64Url: String?): String? { private fun base64UrlToBase64(base64Url: String): String {
var result = base64Url return base64Url.replace('-', '+')
if (null != result) { .replace('_', '/')
result = result.replace("-".toRegex(), "+")
result = result.replace("_".toRegex(), "/")
}

return result
} }


private fun base64ToBase64Url(base64: String?): String? { private fun base64ToBase64Url(base64: String): String {
var result = base64 return base64.replace("\n".toRegex(), "")
if (null != result) { .replace("\\+".toRegex(), "-")
result = result.replace("\n".toRegex(), "") .replace('/', '_')
result = result.replace("\\+".toRegex(), "-") .replace("=", "")
result = result.replace("/".toRegex(), "_")
result = result.replace("=".toRegex(), "")
}
return result
} }


private fun base64ToUnpaddedBase64(base64: String?): String? { private fun base64ToUnpaddedBase64(base64: String): String {
var result = base64 return base64.replace("\n".toRegex(), "")
if (null != result) { .replace("=", "")
result = result.replace("\n".toRegex(), "")
result = result.replace("=".toRegex(), "")
}

return result
} }
} }

View File

@ -45,11 +45,7 @@ data class MXKey(
* @return the signed data map * @return the signed data map
*/ */
fun signalableJSONDictionary(): Map<String, Any> { fun signalableJSONDictionary(): Map<String, Any> {
val map = HashMap<String, Any>() return mapOf("key" to value)

map["key"] = value

return map
} }


/** /**

View File

@ -26,7 +26,7 @@ class MXUsersDevicesMap<E> {
* @return the user Ids * @return the user Ids
*/ */
val userIds: List<String> val userIds: List<String>
get() = ArrayList(map.keys) get() = map.keys.toList()


val isEmpty: Boolean val isEmpty: Boolean
get() = map.isEmpty() get() = map.isEmpty()
@ -39,7 +39,7 @@ class MXUsersDevicesMap<E> {
* @return the device ids list * @return the device ids list
*/ */
fun getUserDeviceIds(userId: String?): List<String>? { fun getUserDeviceIds(userId: String?): List<String>? {
return if (userId?.isNotBlank() == true && map.containsKey(userId)) { return if (!userId.isNullOrBlank() && map.containsKey(userId)) {
map[userId]!!.keys.toList() map[userId]!!.keys.toList()
} else null } else null
} }
@ -52,7 +52,7 @@ class MXUsersDevicesMap<E> {
* @return the object * @return the object
*/ */
fun getObject(userId: String?, deviceId: String?): E? { 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) map[userId]?.get(deviceId)
} else null } else null
} }
@ -66,11 +66,8 @@ class MXUsersDevicesMap<E> {
*/ */
fun setObject(userId: String?, deviceId: String?, o: E?) { fun setObject(userId: String?, deviceId: String?, o: E?) {
if (null != o && userId?.isNotBlank() == true && deviceId?.isNotBlank() == true) { if (null != o && userId?.isNotBlank() == true && deviceId?.isNotBlank() == true) {
if (map[userId] == null) { val devices = map.getOrPut(userId) { HashMap() }
map[userId] = HashMap() devices[deviceId] = o
}

map[userId]?.put(deviceId, o)
} }
} }


@ -81,7 +78,7 @@ class MXUsersDevicesMap<E> {
* @param userId the user id * @param userId the user id
*/ */
fun setObjects(userId: String?, objectsPerDevices: Map<String, E>?) { fun setObjects(userId: String?, objectsPerDevices: Map<String, E>?) {
if (userId?.isNotBlank() == true) { if (!userId.isNullOrBlank()) {
if (null == objectsPerDevices) { if (null == objectsPerDevices) {
map.remove(userId) map.remove(userId)
} else { } else {
@ -96,7 +93,7 @@ class MXUsersDevicesMap<E> {
* @param userId the user id. * @param userId the user id.
*/ */
fun removeUserObjects(userId: String?) { fun removeUserObjects(userId: String?) {
if (userId?.isNotBlank() == true) { if (!userId.isNullOrBlank()) {
map.remove(userId) map.remove(userId)
} }
} }

View File

@ -161,7 +161,7 @@ internal class DefaultSasVerificationService @Inject constructor(private val cre
cancelTransaction( cancelTransaction(
startReq.transactionID!!, startReq.transactionID!!,
otherUserId!!, otherUserId!!,
startReq?.fromDevice ?: event.getSenderKey()!!, startReq.fromDevice ?: event.getSenderKey()!!,
CancelCode.UnknownMethod CancelCode.UnknownMethod
) )
} }
@ -388,14 +388,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 * 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 { private fun createUniqueIDForTransaction(userId: String, deviceID: String): String {
val buff = StringBuffer() return buildString {
buff append(credentials.userId).append("|")
.append(credentials.userId).append("|") append(credentials.deviceId).append("|")
.append(credentials.deviceId).append("|") append(userId).append("|")
.append(userId).append("|") append(deviceID).append("|")
.append(deviceID).append("|") append(UUID.randomUUID().toString())
.append(UUID.randomUUID().toString()) }
return buff.toString()
} }





View File

@ -100,25 +100,16 @@ constructor(trustPinned: Array<TrustManager>, acceptedTlsVersions: List<TlsVersi
} }


private fun enableTLSOnSocket(socket: Socket?): Socket? { private fun enableTLSOnSocket(socket: Socket?): Socket? {
if (socket != null && socket is SSLSocket) { if (socket is SSLSocket) {
val sslSocket = socket as SSLSocket? val supportedProtocols = socket.supportedProtocols.toSet()
val filteredEnabledProtocols = enabledProtocols.filter { it in supportedProtocols }


val supportedProtocols = Arrays.asList(*sslSocket!!.supportedProtocols) if (filteredEnabledProtocols.isNotEmpty()) {
val filteredEnabledProtocols = ArrayList<String>()

for (protocol in enabledProtocols) {
if (supportedProtocols.contains(protocol)) {
filteredEnabledProtocols.add(protocol)
}
}

if (!filteredEnabledProtocols.isEmpty()) {
try { try {
sslSocket.enabledProtocols = filteredEnabledProtocols.toTypedArray() socket.enabledProtocols = filteredEnabledProtocols.toTypedArray()
} catch (e: Exception) { } catch (e: Exception) {
Timber.e(e) Timber.e(e)
} }

} }
} }
return socket return socket

View File

@ -304,17 +304,22 @@ internal class LocalEchoEventFactory @Inject constructor(private val credentials
} }


private fun buildReplyFallback(body: TextContent, originalSenderId: String?, newBodyText: String): String { private fun buildReplyFallback(body: TextContent, originalSenderId: String?, newBodyText: String): String {
val lines = body.text.split("\n") return buildString {
val replyFallback = StringBuffer("> <$originalSenderId>") append("> <")
lines.forEachIndexed { index, s -> append(originalSenderId)
if (index == 0) { append(">")
replyFallback.append(" $s")
} else { val lines = body.text.split("\n")
replyFallback.append("\n> $s") 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()
} }


/** /**

View File

@ -29,16 +29,8 @@ internal class RoomTagHandler @Inject constructor() {
if (content == null) { if (content == null) {
return return
} }
val tags = ArrayList<RoomTagEntity>() val tags = content.tags.entries.map { (tagName, params) ->
for (tagName in content.tags.keys) { RoomTagEntity(tagName, params["order"] as? Double)
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 roomSummaryEntity = RoomSummaryEntity.where(realm, roomId).findFirst() val roomSummaryEntity = RoomSummaryEntity.where(realm, roomId).findFirst()
?: RoomSummaryEntity(roomId) ?: RoomSummaryEntity(roomId)

View File

@ -60,43 +60,33 @@ object JsonCanonicalizer {
when (any) { when (any) {
is JSONArray -> { is JSONArray -> {
// Canonicalize each element of the array // Canonicalize each element of the array
val result = StringBuilder("[") return (0 until any.length()).joinToString(separator = ",", prefix = "[", postfix = "]") {

canonicalizeRecursive(any.get(it))
for (i in 0 until any.length()) {
result.append(canonicalizeRecursive(any.get(i)))
if (i < any.length() - 1) {
result.append(",")
}
} }

result.append("]")

return result.toString()
} }
is JSONObject -> { is JSONObject -> {
// Sort the attributes by name, and the canonicalize each element of the JSONObject // Sort the attributes by name, and the canonicalize each element of the JSONObject
val result = StringBuilder("{")


val attributes = TreeSet<String>() val attributes = TreeSet<String>()
for (entry in any.keys()) { for (entry in any.keys()) {
attributes.add(entry) attributes.add(entry)
} }


for (attribute in attributes.withIndex()) { return buildString {
result.append("\"") append("{")
.append(attribute.value) for ((index, value) in attributes.withIndex()) {
.append("\"") append("\"")
.append(":") append(value)
.append(canonicalizeRecursive(any[attribute.value])) append("\"")
append(":")
append(canonicalizeRecursive(any[value]))


if (attribute.index < attributes.size - 1) { if (index < attributes.size - 1) {
result.append(",") append(",")
}
} }
append("}")
} }

result.append("}")

return result.toString()
} }
is String -> return JSONObject.quote(any) is String -> return JSONObject.quote(any)
else -> return any.toString() else -> return any.toString()