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)
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<ByteArray, ByteArray> {
@ -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)
}
}

View File

@ -157,33 +157,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<String>

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

View File

@ -113,7 +113,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")
@ -204,13 +204,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 {
@ -226,34 +226,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("=", "")
}
}

View File

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

map["key"] = value

return map
return mapOf("key" to value)
}

/**

View File

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

val isEmpty: Boolean
get() = map.isEmpty()
@ -39,7 +39,7 @@ class MXUsersDevicesMap<E> {
* @return the device ids list
*/
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()
} else null
}
@ -52,7 +52,7 @@ class MXUsersDevicesMap<E> {
* @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
}
@ -66,11 +66,8 @@ class MXUsersDevicesMap<E> {
*/
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
}
}

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

View File

@ -161,7 +161,7 @@ internal class DefaultSasVerificationService @Inject constructor(private val cre
cancelTransaction(
startReq.transactionID!!,
otherUserId!!,
startReq?.fromDevice ?: event.getSenderKey()!!,
startReq.fromDevice ?: event.getSenderKey()!!,
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
*/
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())
}
}



View File

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

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

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

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

View File

@ -304,17 +304,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()
}

/**

View File

@ -29,16 +29,8 @@ internal class RoomTagHandler @Inject constructor() {
if (content == null) {
return
}
val tags = ArrayList<RoomTagEntity>()
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)

View File

@ -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<String>()
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()