Remove all async thread

This commit is contained in:
Benoit Marty 2019-05-17 15:05:07 +02:00
parent c66e82c4ae
commit de4662b9d5
12 changed files with 558 additions and 902 deletions

View File

@ -43,11 +43,11 @@ interface CryptoService {

fun getKeysBackupService(): KeysBackupService

fun isRoomBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Boolean>?)
fun isRoomBlacklistUnverifiedDevices(roomId: String?): Boolean

fun setWarnOnUnknownDevices(warn: Boolean)

fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String, callback: MatrixCallback<Unit>)
fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String)

fun getUserDevices(userId: String): MutableList<MXDeviceInfo>

@ -57,11 +57,11 @@ interface CryptoService {

fun getMyDevice(): MXDeviceInfo

fun getGlobalBlacklistUnverifiedDevices(callback: MatrixCallback<Boolean>?)
fun getGlobalBlacklistUnverifiedDevices() : Boolean

fun setGlobalBlacklistUnverifiedDevices(block: Boolean, callback: MatrixCallback<Unit>?)
fun setGlobalBlacklistUnverifiedDevices(block: Boolean)

fun setRoomUnBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Unit>)
fun setRoomUnBlacklistUnverifiedDevices(roomId: String)

fun getDeviceTrackingStatus(userId: String): Int

@ -69,9 +69,9 @@ interface CryptoService {

fun exportRoomKeys(password: String, callback: MatrixCallback<ByteArray>)

fun setRoomBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Unit>)
fun setRoomBlacklistUnverifiedDevices(roomId: String)

fun getDeviceInfo(userId: String, deviceId: String?, callback: MatrixCallback<MXDeviceInfo?>)
fun getDeviceInfo(userId: String, deviceId: String?): MXDeviceInfo?

fun reRequestRoomKeyForEvent(event: Event)


View File

@ -25,6 +25,7 @@ import android.os.Looper
private const val THREAD_ENCRYPT_NAME = "Crypto_Encrypt_Thread"
private const val THREAD_DECRYPT_NAME = "Crypto_Decrypt_Thread"

// TODO Remove and replace by Task
internal object CryptoAsyncHelper {

private var uiHandler: Handler? = null

View File

@ -20,8 +20,6 @@ package im.vector.matrix.android.internal.crypto

import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.text.TextUtils
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.auth.data.Credentials
@ -58,7 +56,6 @@ import im.vector.matrix.android.internal.util.convertToUTF8
import org.matrix.olm.OlmManager
import timber.log.Timber
import java.util.*
import java.util.concurrent.CountDownLatch

/**
* A `MXCrypto` class instance manages the end-to-end crypto for a MXSession instance.
@ -110,11 +107,10 @@ internal class CryptoManager(
private val mTaskExecutor: TaskExecutor
) : KeysBackup.KeysBackupCryptoListener,
DefaultSasVerificationService.SasCryptoListener,
DeviceListManager.DeviceListCryptoListener,
CryptoService {

// MXEncrypting instance for each room.
private val mRoomEncryptors: MutableMap<String, IMXEncrypting>
private val mRoomEncryptors: MutableMap<String, IMXEncrypting> = HashMap()

// Our device keys
/**
@ -128,16 +124,6 @@ internal class CryptoManager(
// tell if the crypto is started
private var mIsStarted: Boolean = false

// the crypto background threads
private var mEncryptingHandlerThread: HandlerThread? = null
private var mEncryptingHandler: Handler? = null

private var mDecryptingHandlerThread: HandlerThread? = null
private var mDecryptingHandler: Handler? = null

// the UI thread
private val mUIHandler: Handler

// TODO
//private val mNetworkListener = object : IMXNetworkEventListener {
// override fun onNetworkConnectionUpdate(isConnected: Boolean) {
@ -165,32 +151,6 @@ internal class CryptoManager(
// Set of parameters used to configure/customize the end-to-end crypto.
private var mCryptoConfig: MXCryptoConfig? = null

/**
* @return the encrypting thread handler
*/
// mEncryptingHandlerThread was not yet ready
// fail to get the handler
// might happen if the thread is not yet ready
val encryptingThreadHandler: Handler
get() {
if (null == mEncryptingHandler) {
mEncryptingHandler = Handler(mEncryptingHandlerThread!!.looper)
}
return if (null == mEncryptingHandler) {
mUIHandler
} else mEncryptingHandler!!
}

/**
* Tells whether the client should ever send encrypted messages to unverified devices.
* The default value is false.
* This function must be called in the getEncryptingThreadHandler() thread.
*
* @return true to unilaterally blacklist all unverified devices.
*/
val globalBlacklistUnverifiedDevices: Boolean
get() = mCryptoStore.getGlobalBlacklistUnverifiedDevices()

init {
if (null != cryptoConfig) {
mCryptoConfig = cryptoConfig
@ -199,8 +159,6 @@ internal class CryptoManager(
mCryptoConfig = MXCryptoConfig()
}

mRoomEncryptors = HashMap() // TODO Merge with declaration

var deviceId = mCredentials.deviceId
// deviceId should always be defined
val refreshDevicesList = !TextUtils.isEmpty(deviceId)
@ -255,26 +213,14 @@ internal class CryptoManager(

this.mCryptoStore.storeUserDevices(mCredentials.userId, myDevices)

mEncryptingHandlerThread = HandlerThread("MXCrypto_encrypting_" + mCredentials.userId, Thread.MIN_PRIORITY)
mEncryptingHandlerThread!!.start()

mDecryptingHandlerThread = HandlerThread("MXCrypto_decrypting_" + mCredentials.userId, Thread.MIN_PRIORITY)
mDecryptingHandlerThread!!.start()

mUIHandler = Handler(Looper.getMainLooper())

if (refreshDevicesList) {
// ensure to have the up-to-date devices list
// got some issues when upgrading from Riot < 0.6.4
deviceListManager.handleDeviceListsChanges(listOf(mCredentials.userId), null)
}

mOutgoingRoomKeyRequestManager.setWorkingHandler(encryptingThreadHandler)
mIncomingRoomKeyRequestManager.setEncryptingThreadHandler(encryptingThreadHandler)

mKeysBackup.setCryptoInternalListener(this)
mSasVerificationService.setCryptoInternalListener(this)
deviceListManager.setCryptoInternalListener(this)
}

override fun setDeviceName(deviceId: String, deviceName: String, callback: MatrixCallback<Unit>) {
@ -306,33 +252,10 @@ internal class CryptoManager(
.executeBy(mTaskExecutor)
}

/**
* @return the decrypting thread handler
*/
fun getDecryptingThreadHandler(): Handler {
// mDecryptingHandlerThread was not yet ready
if (null == mDecryptingHandler) {
mDecryptingHandler = Handler(mDecryptingHandlerThread!!.looper)
}

// fail to get the handler
// might happen if the thread is not yet ready
return if (null == mDecryptingHandler) {
mUIHandler
} else mDecryptingHandler!!
}

override fun inboundGroupSessionsCount(onlyBackedUp: Boolean): Int {
return mCryptoStore.inboundGroupSessionsCount(onlyBackedUp)
}

/**
* @return true if this instance has been released
*/
override fun hasBeenReleased(): Boolean {
return null == mOlmDevice
}

/**
* Provides the tracking status
*
@ -395,10 +318,9 @@ internal class CryptoManager(
// Open the store
mCryptoStore.open()

encryptingThreadHandler.post {
uploadDeviceKeys(object : MatrixCallback<KeysUploadResponse> {
private fun onError() {
mUIHandler.postDelayed({
Handler().postDelayed({
if (!isStarted()) {
mIsStarting = false
start(isInitialSync, null)
@ -407,8 +329,6 @@ internal class CryptoManager(
}

override fun onSuccess(data: KeysUploadResponse) {
encryptingThreadHandler.post {
if (!hasBeenReleased()) {
Timber.d("###########################################################")
Timber.d("uploadDeviceKeys done for " + mCredentials.userId)
Timber.d(" - device id : " + mCredentials.deviceId)
@ -417,10 +337,8 @@ internal class CryptoManager(
Timber.d(" - oneTimeKeys: " + mOneTimeKeysManager.mLastPublishedOneTimeKeys)
Timber.d("")

encryptingThreadHandler.post {
mOneTimeKeysManager.maybeUploadOneTimeKeys(object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) {
encryptingThreadHandler.post {
// TODO
//if (null != mNetworkConnectivityReceiver) {
// mNetworkConnectivityReceiver!!.removeEventListener(mNetworkListener)
@ -435,23 +353,17 @@ internal class CryptoManager(

synchronized(mInitializationCallbacks) {
for (callback in mInitializationCallbacks) {
mUIHandler.post { callback.onSuccess(Unit) }
callback.onSuccess(Unit)
}
mInitializationCallbacks.clear()
}

if (isInitialSync) {
encryptingThreadHandler.post {
// refresh the devices list for each known room members
deviceListManager.invalidateAllDeviceLists()
deviceListManager.refreshOutdatedDeviceLists()
}
} else {
encryptingThreadHandler.post {
mIncomingRoomKeyRequestManager.processReceivedRoomKeyRequests()

}
}
}
}

@ -461,9 +373,6 @@ internal class CryptoManager(
}
})
}
}
}
}

override fun onFailure(failure: Throwable) {
Timber.e(failure, "## start failed")
@ -471,40 +380,18 @@ internal class CryptoManager(
}
})
}
}

/**
* Close the crypto
*/
fun close() {
if (null != mEncryptingHandlerThread) {
encryptingThreadHandler.post {
mOlmDevice.release()

// Do not reset My Device
// mMyDevice = null;

mCryptoStore.close()
// Do not reset Crypto store
// mCryptoStore = null;

if (null != mEncryptingHandlerThread) {
mEncryptingHandlerThread!!.quit()
mEncryptingHandlerThread = null
}

mOutgoingRoomKeyRequestManager.stop()
}

getDecryptingThreadHandler().post {
if (null != mDecryptingHandlerThread) {
mDecryptingHandlerThread!!.quit()
mDecryptingHandlerThread = null
}
}
}
}

override fun isCryptoEnabled(): Boolean {
// TODO Check that this test is correct
return mOlmDevice != null
@ -532,7 +419,6 @@ internal class CryptoManager(
* @param isCatchingUp true if there is a catch-up in progress.
*/
fun onSyncCompleted(syncResponse: SyncResponse, fromToken: String?, isCatchingUp: Boolean) {
encryptingThreadHandler.post {
if (null != syncResponse.deviceLists) {
deviceListManager.handleDeviceListsChanges(syncResponse.deviceLists.changed, syncResponse.deviceLists.left)
}
@ -553,23 +439,6 @@ internal class CryptoManager(
mIncomingRoomKeyRequestManager.processReceivedRoomKeyRequests()
}
}
}

/**
* Get the stored device keys for a user.
*
* @param userId the user to list keys for.
* @param callback the asynchronous callback
*/
fun getUserDevices(userId: String, callback: MatrixCallback<List<MXDeviceInfo>>?) {
encryptingThreadHandler.post {
val list = getUserDevices(userId)

if (null != callback) {
mUIHandler.post { callback.onSuccess(list) }
}
}
}

/**
* Find a device by curve25519 identity key
@ -579,16 +448,10 @@ internal class CryptoManager(
* @return the device info, or null if not found / unsupported algorithm / crypto released
*/
override fun deviceWithIdentityKey(senderKey: String, algorithm: String): MXDeviceInfo? {
return if (!hasBeenReleased()) {
if (!TextUtils.equals(algorithm, MXCRYPTO_ALGORITHM_MEGOLM) && !TextUtils.equals(algorithm, MXCRYPTO_ALGORITHM_OLM)) {
return if (!TextUtils.equals(algorithm, MXCRYPTO_ALGORITHM_MEGOLM) && !TextUtils.equals(algorithm, MXCRYPTO_ALGORITHM_OLM)) {
// We only deal in olm keys
null
} else mCryptoStore.deviceWithIdentityKey(senderKey)

// Find in the crypto store
} else null

// The store is released
}

/**
@ -598,17 +461,11 @@ internal class CryptoManager(
* @param deviceId the device id
* @param callback the asynchronous callback
*/
override fun getDeviceInfo(userId: String, deviceId: String?, callback: MatrixCallback<MXDeviceInfo?>) {
getDecryptingThreadHandler().post {
val di: MXDeviceInfo?

if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(deviceId)) {
di = mCryptoStore.getUserDevice(deviceId!!, userId)
override fun getDeviceInfo(userId: String, deviceId: String?): MXDeviceInfo? {
return if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(deviceId)) {
mCryptoStore.getUserDevice(deviceId!!, userId)
} else {
di = null
}

mUIHandler.post { callback.onSuccess(di) }
null
}
}

@ -619,10 +476,6 @@ internal class CryptoManager(
* @param callback the asynchronous callback
*/
override fun setDevicesKnown(devices: List<MXDeviceInfo>, callback: MatrixCallback<Unit>?) {
if (hasBeenReleased()) {
return
}
encryptingThreadHandler.post {
// build a devices map
val devicesIdListByUserId = HashMap<String, List<String>>()

@ -663,10 +516,8 @@ internal class CryptoManager(
}
}

if (null != callback) {
mUIHandler.post { callback.onSuccess(Unit) }
}
}

callback?.onSuccess(Unit)
}

/**
@ -677,19 +528,13 @@ internal class CryptoManager(
* @param userId the owner of the device
* @param callback the asynchronous callback
*/
override fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String, callback: MatrixCallback<Unit>) {
if (hasBeenReleased()) {
return
}

encryptingThreadHandler.post(Runnable {
override fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String) {
val device = mCryptoStore.getUserDevice(deviceId, userId)

// Sanity check
if (null == device) {
Timber.e("## setDeviceVerification() : Unknown device $userId:$deviceId")
mUIHandler.post { callback.onSuccess(Unit) }
return@Runnable
Timber.w("## setDeviceVerification() : Unknown device $userId:$deviceId")
return
}

if (device.mVerified != verificationStatus) {
@ -703,9 +548,6 @@ internal class CryptoManager(
mKeysBackup.checkAndStartKeysBackup()
}
}

mUIHandler.post { callback.onSuccess(Unit) }
})
}

/**
@ -719,10 +561,6 @@ internal class CryptoManager(
* @return true if the operation succeeds.
*/
private fun setEncryptionInRoom(roomId: String, algorithm: String?, inhibitDeviceQuery: Boolean, membersId: List<String>): Boolean {
if (hasBeenReleased()) {
return false
}

// If we already have encryption in this room, we should ignore this event
// (for now at least. Maybe we should alert the user somehow?)
val existingAlgorithm = mCryptoStore.getRoomAlgorithm(roomId)
@ -891,9 +729,7 @@ internal class CryptoManager(
}

if (devicesWithoutSession.size == 0) {
if (null != callback) {
mUIHandler.post { callback.onSuccess(results) }
}
callback?.onSuccess(results)
return
}

@ -918,7 +754,6 @@ internal class CryptoManager(
.configureWith(ClaimOneTimeKeysForUsersDeviceTask.Params(usersDevicesToClaim))
.dispatchTo(object : MatrixCallback<MXUsersDevicesMap<MXKey>> {
override fun onSuccess(data: MXUsersDevicesMap<MXKey>) {
encryptingThreadHandler.post {
try {
Timber.d("## claimOneTimeKeysForUsersDevices() : keysClaimResponse.oneTimeKeys: $data")

@ -962,12 +797,7 @@ internal class CryptoManager(
Timber.e(e, "## ensureOlmSessionsForDevices() " + e.message)
}

if (!hasBeenReleased()) {
if (null != callback) {
mUIHandler.post { callback.onSuccess(results) }
}
}
}
callback?.onSuccess(results)
}

override fun onFailure(failure: Throwable) {
@ -1060,7 +890,6 @@ internal class CryptoManager(

// just as you are sending a secret message?

encryptingThreadHandler.post {
var alg: IMXEncrypting?

synchronized(mRoomEncryptors) {
@ -1100,13 +929,10 @@ internal class CryptoManager(
algorithm ?: MXCryptoError.NO_MORE_ALGORITHM_REASON)
Timber.e("## encryptEventContent() : $reason")

mUIHandler.post {
callback.onFailure(Failure.CryptoError(MXCryptoError(MXCryptoError.UNABLE_TO_ENCRYPT_ERROR_CODE,
MXCryptoError.UNABLE_TO_ENCRYPT, reason)))
}
}
}
}

/**
* Decrypt an event
@ -1125,10 +951,8 @@ internal class CryptoManager(
}

val results = ArrayList<MXEventDecryptionResult>()
val lock = CountDownLatch(1)
val exceptions = ArrayList<MXDecryptionException>()

getDecryptingThreadHandler().post {
var result: MXEventDecryptionResult? = null
val alg = roomDecryptorProvider.getOrCreateRoomDecryptor(this, event.roomId, eventContent["algorithm"] as String)

@ -1148,14 +972,6 @@ internal class CryptoManager(
results.add(result)
}
}
lock.countDown()
}

try {
lock.await()
} catch (e: Exception) {
Timber.e(e, "## decryptEvent() : failed")
}

if (!exceptions.isEmpty()) {
throw exceptions[0]
@ -1164,7 +980,6 @@ internal class CryptoManager(
return if (!results.isEmpty()) {
results[0]
} else null

}

/**
@ -1173,7 +988,7 @@ internal class CryptoManager(
* @param timelineId the timeline id
*/
fun resetReplayAttackCheckInTimeline(timelineId: String) {
getDecryptingThreadHandler().post { mOlmDevice.resetReplayAttackCheckInTimeline(timelineId) }
mOlmDevice.resetReplayAttackCheckInTimeline(timelineId)
}

/**
@ -1185,11 +1000,6 @@ internal class CryptoManager(
* @return the content for an m.room.encrypted event.
*/
fun encryptMessage(payloadFields: Map<String, Any>, deviceInfos: List<MXDeviceInfo>): EncryptedMessage {
if (hasBeenReleased()) {
// Empty object
return EncryptedMessage()
}

val deviceInfoParticipantKey = HashMap<String, MXDeviceInfo>()
val participantKeys = ArrayList<String>()

@ -1254,15 +1064,11 @@ internal class CryptoManager(
*/
fun onToDeviceEvent(event: Event) {
if (event.type == EventType.ROOM_KEY || event.type == EventType.FORWARDED_ROOM_KEY) {
getDecryptingThreadHandler().post {
onRoomKeyEvent(event)
}
} else if (event.type == EventType.ROOM_KEY_REQUEST) {
encryptingThreadHandler.post {
mIncomingRoomKeyRequestManager.onRoomKeyRequestEvent(event)
}
}
}

/**
* Handle a key event.
@ -1314,7 +1120,7 @@ internal class CryptoManager(
room.getJoinedRoomMemberIds()
}

encryptingThreadHandler.post { setEncryptionInRoom(roomId, eventContent!!["algorithm"] as String, true, userIds) }
setEncryptionInRoom(roomId, eventContent!!["algorithm"] as String, true, userIds)
}

/**
@ -1342,7 +1148,6 @@ internal class CryptoManager(
if (null != roomMember) {
val membership = roomMember.membership

encryptingThreadHandler.post {
if (membership == Membership.JOIN) {
// make sure we are tracking the deviceList for this user.
deviceListManager.startTrackingDeviceList(Arrays.asList(userId))
@ -1358,7 +1163,6 @@ internal class CryptoManager(
}
}
}
}

/**
* Upload my user's device keys.
@ -1402,7 +1206,6 @@ internal class CryptoManager(
fun exportRoomKeys(password: String, anIterationCount: Int, callback: MatrixCallback<ByteArray>) {
val iterationCount = Math.max(0, anIterationCount)

getDecryptingThreadHandler().post(Runnable {
val exportedSessions = ArrayList<MegolmSessionData>()

val inboundGroupSessions = mCryptoStore.getInboundGroupSessions()
@ -1425,11 +1228,10 @@ internal class CryptoManager(
.encryptMegolmKeyFile(adapter.toJson(exportedSessions), password, iterationCount)
} catch (e: Exception) {
callback.onFailure(e)
return@Runnable
return
}

mUIHandler.post { callback.onSuccess(encryptedRoomKeys) }
})
callback.onSuccess(encryptedRoomKeys)
}

/**
@ -1444,7 +1246,6 @@ internal class CryptoManager(
password: String,
progressListener: ProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) {
getDecryptingThreadHandler().post(Runnable {
Timber.d("## importRoomKeys starts")

val t0 = System.currentTimeMillis()
@ -1453,8 +1254,8 @@ internal class CryptoManager(
try {
roomKeys = MXMegolmExportEncryption.decryptMegolmKeyFile(roomKeysAsArray, password)
} catch (e: Exception) {
mUIHandler.post { callback.onFailure(e) }
return@Runnable
callback.onFailure(e)
return
}

val importedSessions: List<MegolmSessionData>
@ -1470,8 +1271,8 @@ internal class CryptoManager(
importedSessions = list as List<MegolmSessionData>
} catch (e: Exception) {
Timber.e(e, "## importRoomKeys failed")
mUIHandler.post { callback.onFailure(e) }
return@Runnable
callback.onFailure(e)
return
}

val t2 = System.currentTimeMillis()
@ -1479,7 +1280,6 @@ internal class CryptoManager(
Timber.d("## importRoomKeys : JSON parsing " + (t2 - t1) + " ms")

importMegolmSessionsData(importedSessions, true, progressListener, callback)
})
}

/**
@ -1494,7 +1294,6 @@ internal class CryptoManager(
backUpKeys: Boolean,
progressListener: ProgressListener?,
callback: MatrixCallback<ImportRoomKeysResult>) {
getDecryptingThreadHandler().post {
val t0 = System.currentTimeMillis()

val totalNumbersOfKeys = megolmSessionsData.size
@ -1503,7 +1302,7 @@ internal class CryptoManager(
var totalNumbersOfImportedKeys = 0

if (progressListener != null) {
mUIHandler.post { progressListener.onProgress(0, 100) }
progressListener.onProgress(0, 100)
}

val sessions = mOlmDevice.importInboundGroupSessions(megolmSessionsData)
@ -1544,7 +1343,7 @@ internal class CryptoManager(
if (lastProgress != progress) {
lastProgress = progress

mUIHandler.post { progressListener.onProgress(progress, 100) }
progressListener.onProgress(progress, 100)
}
}
}
@ -1562,8 +1361,7 @@ internal class CryptoManager(

val finalTotalNumbersOfImportedKeys = totalNumbersOfImportedKeys

mUIHandler.post { callback.onSuccess(ImportRoomKeysResult(totalNumbersOfKeys, finalTotalNumbersOfImportedKeys)) }
}
callback.onSuccess(ImportRoomKeysResult(totalNumbersOfKeys, finalTotalNumbersOfImportedKeys))
}

/**
@ -1621,44 +1419,31 @@ internal class CryptoManager(
* If true, it overrides the per-room settings.
*
* @param block true to unilaterally blacklist all
* @param callback the asynchronous callback.
*/
override fun setGlobalBlacklistUnverifiedDevices(block: Boolean, callback: MatrixCallback<Unit>?) {
encryptingThreadHandler.post {
override fun setGlobalBlacklistUnverifiedDevices(block: Boolean) {
mCryptoStore.setGlobalBlacklistUnverifiedDevices(block)
mUIHandler.post {
callback?.onSuccess(Unit)
}
}
}

/**
* Tells whether the client should ever send encrypted messages to unverified devices.
* The default value is false.
* messages to unverified devices.
* This function must be called in the getEncryptingThreadHandler() thread.
*
* @param callback the asynchronous callback
* @return true to unilaterally blacklist all unverified devices.
*/
override fun getGlobalBlacklistUnverifiedDevices(callback: MatrixCallback<Boolean>?) {
encryptingThreadHandler.post {
if (null != callback) {
val status = globalBlacklistUnverifiedDevices

mUIHandler.post { callback.onSuccess(status) }
}
}
override fun getGlobalBlacklistUnverifiedDevices(): Boolean {
return mCryptoStore.getGlobalBlacklistUnverifiedDevices()
}

/**
* Tells whether the client should encrypt messages only for the verified devices
* in this room.
* The default value is false.
* This function must be called in the getEncryptingThreadHandler() thread.
*
* @param roomId the room id
* @return true if the client should encrypt messages only for the verified devices.
*/
fun isRoomBlacklistUnverifiedDevices(roomId: String?): Boolean {
override fun isRoomBlacklistUnverifiedDevices(roomId: String?): Boolean {
return if (null != roomId) {
mCryptoStore.getRoomsListBlacklistUnverifiedDevices().contains(roomId)
} else {
@ -1666,43 +1451,20 @@ internal class CryptoManager(
}
}

/**
* Tells whether the client should encrypt messages only for the verified devices
* in this room.
* The default value is false.
* This function must be called in the getEncryptingThreadHandler() thread.
*
* @param roomId the room id
* @param callback the asynchronous callback
*/
override fun isRoomBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Boolean>?) {
encryptingThreadHandler.post {
val status = isRoomBlacklistUnverifiedDevices(roomId)

mUIHandler.post {
callback?.onSuccess(status)
}
}
}

/**
* Manages the room black-listing for unverified devices.
*
* @param roomId the room id
* @param add true to add the room id to the list, false to remove it.
* @param callback the asynchronous callback
*/
private fun setRoomBlacklistUnverifiedDevices(roomId: String, add: Boolean, callback: MatrixCallback<Unit>?) {
private fun setRoomBlacklistUnverifiedDevices(roomId: String, add: Boolean) {
val room = mRoomService.getRoom(roomId)

// sanity check
if (null == room) {
mUIHandler.post { callback!!.onSuccess(Unit) }

return
}

encryptingThreadHandler.post {
val roomIds = mCryptoStore.getRoomsListBlacklistUnverifiedDevices().toMutableList()

if (add) {
@ -1714,11 +1476,6 @@ internal class CryptoManager(
}

mCryptoStore.setRoomsListBlacklistUnverifiedDevices(roomIds)

mUIHandler.post {
callback?.onSuccess(Unit)
}
}
}


@ -1728,8 +1485,8 @@ internal class CryptoManager(
* @param roomId the room id
* @param callback the asynchronous callback
*/
override fun setRoomBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Unit>) {
setRoomBlacklistUnverifiedDevices(roomId, true, callback)
override fun setRoomBlacklistUnverifiedDevices(roomId: String) {
setRoomBlacklistUnverifiedDevices(roomId, true)
}

/**
@ -1738,8 +1495,8 @@ internal class CryptoManager(
* @param roomId the room id
* @param callback the asynchronous callback
*/
override fun setRoomUnBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Unit>) {
setRoomBlacklistUnverifiedDevices(roomId, false, callback)
override fun setRoomUnBlacklistUnverifiedDevices(roomId: String) {
setRoomBlacklistUnverifiedDevices(roomId, false)
}

/**
@ -1749,7 +1506,7 @@ internal class CryptoManager(
* @param recipients recipients
*/
fun requestRoomKey(requestBody: RoomKeyRequestBody, recipients: List<Map<String, String>>) {
encryptingThreadHandler.post { mOutgoingRoomKeyRequestManager.sendRoomKeyRequest(requestBody, recipients) }
mOutgoingRoomKeyRequestManager.sendRoomKeyRequest(requestBody, recipients)
}

/**
@ -1758,7 +1515,7 @@ internal class CryptoManager(
* @param requestBody requestBody
*/
override fun cancelRoomKeyRequest(requestBody: RoomKeyRequestBody) {
encryptingThreadHandler.post { mOutgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody) }
mOutgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody)
}

/**
@ -1773,7 +1530,6 @@ internal class CryptoManager(
val senderKey = wireContent["sender_key"].toString()
val sessionId = wireContent["session_id"].toString()

encryptingThreadHandler.post {
val requestBody = RoomKeyRequestBody()

requestBody.roomId = event.roomId
@ -1783,7 +1539,6 @@ internal class CryptoManager(

mOutgoingRoomKeyRequestManager.resendRoomKeyRequest(requestBody)
}
}

/**
* Add a RoomKeysRequestListener listener.

View File

@ -55,9 +55,6 @@ internal class DeviceListManager(private val mCryptoStore: IMXCryptoStore,
// tells if there is a download keys request in progress
private var mIsDownloadingKeys = false

// Internal listener
private lateinit var mCryptoListener: DeviceListCryptoListener

/**
* Creator
*
@ -330,13 +327,12 @@ internal class DeviceListManager(private val mCryptoStore: IMXCryptoStore,
}
}

if (!mCryptoListener.hasBeenReleased()) {
val callback = promise.mCallback

if (null != callback) {
CryptoAsyncHelper.getUiHandler().post { callback.onSuccess(usersDevicesInfoMap) }
}
}

promisesToRemove.add(promise)
}
}
@ -703,15 +699,6 @@ internal class DeviceListManager(private val mCryptoStore: IMXCryptoStore,
})
}

fun setCryptoInternalListener(listener: DeviceListCryptoListener) {
mCryptoListener = listener
}


interface DeviceListCryptoListener {
fun hasBeenReleased(): Boolean
}

companion object {

/**

View File

@ -16,21 +16,20 @@

package im.vector.matrix.android.internal.crypto

import android.os.Handler
import android.text.TextUtils
import im.vector.matrix.android.api.auth.data.Credentials
import im.vector.matrix.android.api.session.crypto.keyshare.RoomKeysRequestListener
import im.vector.matrix.android.api.session.events.model.Event
import im.vector.matrix.android.api.session.events.model.toModel
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyShare
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import timber.log.Timber
import java.util.*

internal class IncomingRoomKeyRequestManager(
val mCredentials: Credentials,
val mCryptoStore: IMXCryptoStore,
val mRoomDecryptorProvider: RoomDecryptorProvider) {
private val mCredentials: Credentials,
private val mCryptoStore: IMXCryptoStore,
private val mRoomDecryptorProvider: RoomDecryptorProvider) {


// list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations
@ -39,7 +38,7 @@ internal class IncomingRoomKeyRequestManager(
private val mReceivedRoomKeyRequestCancellations = ArrayList<IncomingRoomKeyRequestCancellation>()

// the listeners
val mRoomKeysRequestListeners: MutableSet<RoomKeysRequestListener> = HashSet<RoomKeysRequestListener>()
val mRoomKeysRequestListeners: MutableSet<RoomKeysRequestListener> = HashSet()

init {
mReceivedRoomKeyRequests.addAll(mCryptoStore.getPendingIncomingRoomKeyRequests())
@ -52,26 +51,18 @@ internal class IncomingRoomKeyRequestManager(
* @param event the announcement event.
*/
fun onRoomKeyRequestEvent(event: Event) {
val roomKeyShare = event.content.toModel<RoomKeyShare>()!!
val roomKeyShare = event.content.toModel<RoomKeyShare>()

if (null != roomKeyShare.action) {
when (roomKeyShare.action) {
when (roomKeyShare?.action) {
RoomKeyShare.ACTION_SHARE_REQUEST -> synchronized(mReceivedRoomKeyRequests) {
mReceivedRoomKeyRequests.add(IncomingRoomKeyRequest(event))
}
RoomKeyShare.ACTION_SHARE_CANCELLATION -> synchronized(mReceivedRoomKeyRequestCancellations) {
mReceivedRoomKeyRequestCancellations.add(IncomingRoomKeyRequestCancellation(event))
}
else -> Timber.e("## onRoomKeyRequestEvent() : unsupported action " + roomKeyShare.action!!)
else -> Timber.e("## onRoomKeyRequestEvent() : unsupported action " + roomKeyShare?.action)
}
}
}

private lateinit var encryptingThreadHandler: Handler

fun setEncryptingThreadHandler(encryptingThreadHandler: Handler) {
this.encryptingThreadHandler = encryptingThreadHandler
}

/**
* Process any m.room_key_request events which were queued up during the
@ -129,13 +120,11 @@ internal class IncomingRoomKeyRequestManager(
}

request.mShare = Runnable {
encryptingThreadHandler.post {
decryptor.shareKeysWithDevice(request)
mCryptoStore.deleteIncomingRoomKeyRequest(request)
}
}

request.mIgnore = Runnable { encryptingThreadHandler.post { mCryptoStore.deleteIncomingRoomKeyRequest(request) } }
request.mIgnore = Runnable { mCryptoStore.deleteIncomingRoomKeyRequest(request) }

// if the device is verified already, share the keys
val device = mCryptoStore.getUserDevice(deviceId!!, userId)

View File

@ -20,11 +20,11 @@ package im.vector.matrix.android.internal.crypto
import android.os.Handler
import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.session.events.model.EventType
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap
import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyRequestBody
import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyShareCancellation
import im.vector.matrix.android.internal.crypto.model.rest.RoomKeyShareRequest
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask
import im.vector.matrix.android.internal.task.TaskExecutor
import im.vector.matrix.android.internal.task.configureWith
@ -36,9 +36,6 @@ internal class MXOutgoingRoomKeyRequestManager(
private val mSendToDeviceTask: SendToDeviceTask,
private val mTaskExecutor: TaskExecutor) {

// working handler (should not be the UI thread)
private lateinit var mWorkingHandler: Handler

// running
var mClientRunning: Boolean = false

@ -49,10 +46,6 @@ internal class MXOutgoingRoomKeyRequestManager(
// of mSendOutgoingRoomKeyRequestsTimer
private var mSendOutgoingRoomKeyRequestsRunning: Boolean = false

fun setWorkingHandler(encryptingThreadHandler: Handler) {
mWorkingHandler = encryptingThreadHandler
}

/**
* Called when the client is started. Sets background processes running.
*/
@ -90,7 +83,6 @@ internal class MXOutgoingRoomKeyRequestManager(
* @param recipients recipients
*/
fun sendRoomKeyRequest(requestBody: RoomKeyRequestBody?, recipients: List<Map<String, String>>) {
mWorkingHandler.post {
val req = mCryptoStore.getOrAddOutgoingRoomKeyRequest(
OutgoingRoomKeyRequest(requestBody, recipients, makeTxnId(), OutgoingRoomKeyRequest.RequestState.UNSENT))

@ -99,7 +91,6 @@ internal class MXOutgoingRoomKeyRequestManager(
startTimer()
}
}
}

/**
* Cancel room key requests, if any match the given details
@ -154,12 +145,11 @@ internal class MXOutgoingRoomKeyRequestManager(
* Start the background timer to send queued requests, if the timer isn't already running.
*/
private fun startTimer() {
mWorkingHandler.post(Runnable {
if (mSendOutgoingRoomKeyRequestsRunning) {
return@Runnable
return
}

mWorkingHandler.postDelayed(Runnable {
Handler().postDelayed(Runnable {
if (mSendOutgoingRoomKeyRequestsRunning) {
Timber.d("## startTimer() : RoomKeyRequestSend already in progress!")
return@Runnable
@ -168,7 +158,6 @@ internal class MXOutgoingRoomKeyRequestManager(
mSendOutgoingRoomKeyRequestsRunning = true
sendOutgoingRoomKeyRequests()
}, SEND_KEY_REQUESTS_DELAY_MS.toLong())
})
}

// look for and send any queued requests. Runs itself recursively until
@ -215,7 +204,6 @@ internal class MXOutgoingRoomKeyRequestManager(

sendMessageToDevices(requestMessage, request.mRecipients, request.mRequestId, object : MatrixCallback<Unit> {
private fun onDone(state: OutgoingRoomKeyRequest.RequestState) {
mWorkingHandler.post {
if (request.mState !== OutgoingRoomKeyRequest.RequestState.UNSENT) {
Timber.d("## sendOutgoingRoomKeyRequest() : Cannot update room key request from UNSENT as it was already updated to " + request.mState)
} else {
@ -226,7 +214,6 @@ internal class MXOutgoingRoomKeyRequestManager(
mSendOutgoingRoomKeyRequestsRunning = false
startTimer()
}
}

override fun onSuccess(data: Unit) {
Timber.d("## sendOutgoingRoomKeyRequest succeed")
@ -256,12 +243,10 @@ internal class MXOutgoingRoomKeyRequestManager(

sendMessageToDevices(roomKeyShareCancellation, request.mRecipients, request.mCancellationTxnId, object : MatrixCallback<Unit> {
private fun onDone() {
mWorkingHandler.post {
mCryptoStore.deleteOutgoingRoomKeyRequest(request.mRequestId)
mSendOutgoingRoomKeyRequestsRunning = false
startTimer()
}
}


override fun onSuccess(data: Unit) {

View File

@ -154,11 +154,9 @@ internal class MXMegolmEncryption : IMXEncrypting {
override fun onSuccess(devicesInRoom: MXUsersDevicesMap<MXDeviceInfo>) {
ensureOutboundSession(devicesInRoom, object : MatrixCallback<MXOutboundSessionInfo> {
override fun onSuccess(data: MXOutboundSessionInfo) {
mCrypto!!.encryptingThreadHandler.post {
Timber.d("## encryptEventContent () processPendingEncryptions after " + (System.currentTimeMillis() - t0) + "ms")
processPendingEncryptions(data)
}
}

override fun onFailure(failure: Throwable) {
dispatchFailure(failure)
@ -178,12 +176,12 @@ internal class MXMegolmEncryption : IMXEncrypting {
* @return the session description
*/
private fun prepareNewSessionInRoom(): MXOutboundSessionInfo {
val sessionId = olmDevice!!.createOutboundGroupSession()
val sessionId = olmDevice.createOutboundGroupSession()

val keysClaimedMap = HashMap<String, String>()
keysClaimedMap["ed25519"] = olmDevice.deviceEd25519Key!!

olmDevice.addInboundGroupSession(sessionId!!, olmDevice.getSessionKey(sessionId)!!, mRoomId!!, olmDevice.deviceCurve25519Key!!,
olmDevice.addInboundGroupSession(sessionId!!, olmDevice.getSessionKey(sessionId)!!, mRoomId, olmDevice.deviceCurve25519Key!!,
ArrayList(), keysClaimedMap, false)

mKeysBackup.maybeBackupKeys()
@ -296,13 +294,11 @@ internal class MXMegolmEncryption : IMXEncrypting {
Timber.d("## shareKey() ; userId $userIds")
shareUserDevicesKey(session, subMap, object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) {
mCrypto!!.encryptingThreadHandler.post {
for (userId in userIds) {
devicesByUsers.remove(userId)
}
shareKey(session, devicesByUsers, callback)
}
}

override fun onFailure(failure: Throwable) {
Timber.e(failure, "## shareKey() ; userIds " + userIds + " failed")
@ -326,7 +322,7 @@ internal class MXMegolmEncryption : IMXEncrypting {

val submap = HashMap<String, Any>()
submap["algorithm"] = MXCRYPTO_ALGORITHM_MEGOLM
submap["room_id"] = mRoomId!!
submap["room_id"] = mRoomId
submap["session_id"] = session.mSessionId
submap["session_key"] = sessionKey!!
submap["chain_index"] = chainIndex
@ -338,22 +334,21 @@ internal class MXMegolmEncryption : IMXEncrypting {
val t0 = System.currentTimeMillis()
Timber.d("## shareUserDevicesKey() : starts")

mCrypto!!.ensureOlmSessionsForDevices(devicesByUser, object : MatrixCallback<MXUsersDevicesMap<MXOlmSessionResult>> {
override fun onSuccess(results: MXUsersDevicesMap<MXOlmSessionResult>) {
mCrypto!!.encryptingThreadHandler.post {
mCrypto.ensureOlmSessionsForDevices(devicesByUser, object : MatrixCallback<MXUsersDevicesMap<MXOlmSessionResult>> {
override fun onSuccess(data: MXUsersDevicesMap<MXOlmSessionResult>) {
Timber.d("## shareUserDevicesKey() : ensureOlmSessionsForDevices succeeds after "
+ (System.currentTimeMillis() - t0) + " ms")
val contentMap = MXUsersDevicesMap<Any>()

var haveTargets = false
val userIds = results.userIds
val userIds = data.userIds

for (userId in userIds) {
val devicesToShareWith = devicesByUser[userId]

for ((deviceID) in devicesToShareWith!!) {

val sessionResult = results.getObject(deviceID, userId)
val sessionResult = data.getObject(deviceID, userId)

if (null == sessionResult || null == sessionResult.mSessionId) {
// no session with this device, probably because there
@ -372,19 +367,18 @@ internal class MXMegolmEncryption : IMXEncrypting {

Timber.d("## shareUserDevicesKey() : Sharing keys with device $userId:$deviceID")
//noinspection ArraysAsListWithZeroOrOneArgument,ArraysAsListWithZeroOrOneArgument
contentMap.setObject(mCrypto!!.encryptMessage(payload, Arrays.asList(sessionResult.mDevice)), userId, deviceID)
contentMap.setObject(mCrypto.encryptMessage(payload, Arrays.asList(sessionResult.mDevice)), userId, deviceID)
haveTargets = true
}
}

if (haveTargets && !mCrypto!!.hasBeenReleased()) {
if (haveTargets) {
val t0 = System.currentTimeMillis()
Timber.d("## shareUserDevicesKey() : has target")

mSendToDeviceTask.configureWith(SendToDeviceTask.Params(EventType.ENCRYPTED, contentMap))
.dispatchTo(object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) {
mCrypto!!.encryptingThreadHandler.post {
Timber.d("## shareUserDevicesKey() : sendToDevice succeeds after "
+ (System.currentTimeMillis() - t0) + " ms")

@ -405,7 +399,6 @@ internal class MXMegolmEncryption : IMXEncrypting {
callback?.onSuccess(Unit)
}
}
}

override fun onFailure(failure: Throwable) {
Timber.e(failure, "## shareUserDevicesKey() : sendToDevice")
@ -422,7 +415,6 @@ internal class MXMegolmEncryption : IMXEncrypting {
}
}
}
}

override fun onFailure(failure: Throwable) {
Timber.e(failure, "## shareUserDevicesKey() : ensureOlmSessionsForDevices failed")
@ -443,7 +435,7 @@ internal class MXMegolmEncryption : IMXEncrypting {
for (queuedEncryption in queuedEncryptions) {
val payloadJson = HashMap<String, Any>()

payloadJson["room_id"] = mRoomId!!
payloadJson["room_id"] = mRoomId
payloadJson["type"] = queuedEncryption.mEventType!!
payloadJson["content"] = queuedEncryption.mEventContent!!

@ -487,22 +479,19 @@ internal class MXMegolmEncryption : IMXEncrypting {
// with them, which means that they will have announced any new devices via
// an m.new_device.
mDeviceListManager.downloadKeys(userIds, false, object : MatrixCallback<MXUsersDevicesMap<MXDeviceInfo>> {
override fun onSuccess(devices: MXUsersDevicesMap<MXDeviceInfo>) {
mCrypto!!.encryptingThreadHandler.post {
val encryptToVerifiedDevicesOnly = mCrypto!!.globalBlacklistUnverifiedDevices || mCrypto!!.isRoomBlacklistUnverifiedDevices(mRoomId)
override fun onSuccess(data: MXUsersDevicesMap<MXDeviceInfo>) {
val encryptToVerifiedDevicesOnly = mCrypto.getGlobalBlacklistUnverifiedDevices() || mCrypto.isRoomBlacklistUnverifiedDevices(mRoomId)

val devicesInRoom = MXUsersDevicesMap<MXDeviceInfo>()
val unknownDevices = MXUsersDevicesMap<MXDeviceInfo>()

val userIds = devices.userIds

for (userId in userIds) {
val deviceIds = devices.getUserDeviceIds(userId)
for (userId in data.userIds) {
val deviceIds = data.getUserDeviceIds(userId)

for (deviceId in deviceIds!!) {
val deviceInfo = devices.getObject(deviceId, userId)
val deviceInfo = data.getObject(deviceId, userId)

if (mCrypto!!.warnOnUnknownDevices() && deviceInfo!!.isUnknown) {
if (mCrypto.warnOnUnknownDevices() && deviceInfo!!.isUnknown) {
// The device is not yet known by the user
unknownDevices.setObject(deviceInfo, userId, deviceId)
continue
@ -537,7 +526,6 @@ internal class MXMegolmEncryption : IMXEncrypting {
}
}
}
}

override fun onFailure(failure: Throwable) {
callback.onFailure(failure)

View File

@ -701,8 +701,4 @@ internal class RealmCryptoStore(private val enableFileEncryption: Boolean = fals
}
.toMutableList()
}

companion object {
private const val LOG_TAG = "RealmCryptoStore"
}
}

View File

@ -29,10 +29,10 @@ import im.vector.matrix.android.api.session.events.model.EventType
import im.vector.matrix.android.api.session.events.model.toModel
import im.vector.matrix.android.internal.crypto.CryptoAsyncHelper
import im.vector.matrix.android.internal.crypto.DeviceListManager
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.MXUsersDevicesMap
import im.vector.matrix.android.internal.crypto.model.rest.*
import im.vector.matrix.android.internal.crypto.store.IMXCryptoStore
import im.vector.matrix.android.internal.crypto.tasks.SendToDeviceTask
import im.vector.matrix.android.internal.task.TaskExecutor
import im.vector.matrix.android.internal.task.configureWith
@ -59,7 +59,8 @@ internal class DefaultSasVerificationService(private val mCredentials: Credentia

// Event received from the sync
fun onToDeviceEvent(event: Event) {
CryptoAsyncHelper.getDecryptBackgroundHandler().post { // TODO We are already in a BG thread
CryptoAsyncHelper.getDecryptBackgroundHandler().post {
// TODO We are already in a BG thread
when (event.type) {
EventType.KEY_VERIFICATION_START -> {
onStartRequestReceived(event)
@ -131,10 +132,8 @@ internal class DefaultSasVerificationService(private val mCredentials: Credentia
override fun markedLocallyAsManuallyVerified(userId: String, deviceID: String) {
mCryptoListener.setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED,
deviceID,
userId,
object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) {
uiHandler.post {
userId)

listeners.forEach {
try {
it.markedAsManuallyVerified(userId, deviceID)
@ -143,13 +142,6 @@ internal class DefaultSasVerificationService(private val mCredentials: Credentia
}
}
}
}

override fun onFailure(failure: Throwable) {
Timber.e(failure, "## Manual verification failed in state")
}
})
}

private fun onStartRequestReceived(event: Event) {
val startReq = event.content.toModel<KeyVerificationStart>()!!
@ -435,12 +427,12 @@ internal class DefaultSasVerificationService(private val mCredentials: Credentia
mCryptoListener = listener
}

fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String, callback: MatrixCallback<Unit>) {
mCryptoListener.setDeviceVerification(verificationStatus, deviceId, userId, callback)
fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String) {
mCryptoListener.setDeviceVerification(verificationStatus, deviceId, userId)
}

interface SasCryptoListener {
fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String, callback: MatrixCallback<Unit>)
fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String)
fun getMyDevice(): MXDeviceInfo
}
}

View File

@ -239,33 +239,15 @@ internal abstract class SASVerificationTransaction(

setDeviceVerified(
otherDeviceId ?: "",
otherUserId,
success = {
otherUserId)

state = SasVerificationTxState.Verified
},
error = {
//mmm what to do?, looks like this is never called
}
)
}

private fun setDeviceVerified(deviceId: String, userId: String, success: () -> Unit, error: () -> Unit) {
private fun setDeviceVerified(deviceId: String, userId: String) {
mSasVerificationService.setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED,
deviceId,
userId,
object : MatrixCallback<Unit> {

override fun onSuccess(data: Unit) {
//We good
Timber.d("## SAS verification complete and device status updated for id:$transactionId")
success()
}

override fun onFailure(failure: Throwable) {
Timber.e(failure, "## SAS verification [$transactionId] failed in state : $state")
error()
}
})
userId)
}

override fun cancel() {

View File

@ -257,16 +257,16 @@ internal class DefaultSession(override val sessionParams: SessionParams) : Sessi
return cryptoService.getKeysBackupService()
}

override fun isRoomBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Boolean>?) {
cryptoService.isRoomBlacklistUnverifiedDevices(roomId, callback)
override fun isRoomBlacklistUnverifiedDevices(roomId: String?): Boolean {
return cryptoService.isRoomBlacklistUnverifiedDevices(roomId)
}

override fun setWarnOnUnknownDevices(warn: Boolean) {
cryptoService.setWarnOnUnknownDevices(warn)
}

override fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String, callback: MatrixCallback<Unit>) {
cryptoService.setDeviceVerification(verificationStatus, deviceId, userId, callback)
override fun setDeviceVerification(verificationStatus: Int, deviceId: String, userId: String) {
cryptoService.setDeviceVerification(verificationStatus, deviceId, userId)
}

override fun getUserDevices(userId: String): MutableList<MXDeviceInfo> {
@ -293,16 +293,16 @@ internal class DefaultSession(override val sessionParams: SessionParams) : Sessi
return cryptoService.inboundGroupSessionsCount(onlyBackedUp)
}

override fun getGlobalBlacklistUnverifiedDevices(callback: MatrixCallback<Boolean>?) {
cryptoService.getGlobalBlacklistUnverifiedDevices(callback)
override fun getGlobalBlacklistUnverifiedDevices(): Boolean {
return cryptoService.getGlobalBlacklistUnverifiedDevices()
}

override fun setGlobalBlacklistUnverifiedDevices(block: Boolean, callback: MatrixCallback<Unit>?) {
cryptoService.setGlobalBlacklistUnverifiedDevices(block, callback)
override fun setGlobalBlacklistUnverifiedDevices(block: Boolean) {
cryptoService.setGlobalBlacklistUnverifiedDevices(block)
}

override fun setRoomUnBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Unit>) {
cryptoService.setRoomUnBlacklistUnverifiedDevices(roomId, callback)
override fun setRoomUnBlacklistUnverifiedDevices(roomId: String) {
cryptoService.setRoomUnBlacklistUnverifiedDevices(roomId)
}

override fun getDeviceTrackingStatus(userId: String): Int {
@ -317,12 +317,12 @@ internal class DefaultSession(override val sessionParams: SessionParams) : Sessi
cryptoService.exportRoomKeys(password, callback)
}

override fun setRoomBlacklistUnverifiedDevices(roomId: String, callback: MatrixCallback<Unit>) {
cryptoService.setRoomBlacklistUnverifiedDevices(roomId, callback)
override fun setRoomBlacklistUnverifiedDevices(roomId: String) {
cryptoService.setRoomBlacklistUnverifiedDevices(roomId)
}

override fun getDeviceInfo(userId: String, deviceId: String?, callback: MatrixCallback<MXDeviceInfo?>) {
cryptoService.getDeviceInfo(userId, deviceId, callback)
override fun getDeviceInfo(userId: String, deviceId: String?): MXDeviceInfo? {
return cryptoService.getDeviceInfo(userId, deviceId)
}

override fun reRequestRoomKeyForEvent(event: Event) {

View File

@ -47,7 +47,6 @@ import im.vector.matrix.android.api.MatrixCallback
import im.vector.matrix.android.api.extensions.getFingerprintHumanReadable
import im.vector.matrix.android.api.extensions.sortByLastSeen
import im.vector.matrix.android.api.session.Session
import im.vector.matrix.android.internal.crypto.model.MXDeviceInfo
import im.vector.matrix.android.internal.crypto.model.rest.DeviceInfo
import im.vector.matrix.android.internal.crypto.model.rest.DevicesListResponse
import im.vector.riotredesign.R
@ -2210,42 +2209,26 @@ class VectorSettingsPreferencesFragment : VectorPreferenceFragment(), SharedPref

// crypto section: device key (fingerprint)
if (!TextUtils.isEmpty(deviceId) && !TextUtils.isEmpty(userId)) {
mSession.getDeviceInfo(userId, deviceId, object : MatrixCallback<MXDeviceInfo?> {
override fun onSuccess(data: MXDeviceInfo?) {
if (null != data && !TextUtils.isEmpty(data.fingerprint()) && null != activity) {
cryptoInfoTextPreference.summary = data.getFingerprintHumanReadable()
val deviceInfo = mSession.getDeviceInfo(userId, deviceId)

if (null != deviceInfo && !TextUtils.isEmpty(deviceInfo.fingerprint())) {
cryptoInfoTextPreference.summary = deviceInfo.getFingerprintHumanReadable()

cryptoInfoTextPreference.setOnPreferenceClickListener {
data.fingerprint()?.let {
deviceInfo.fingerprint()?.let {
copyToClipboard(requireActivity(), it)
}
true
}
}
}
})
}

sendToUnverifiedDevicesPref.isChecked = false

mSession.getGlobalBlacklistUnverifiedDevices(object : MatrixCallback<Boolean> {
override fun onSuccess(data: Boolean) {
sendToUnverifiedDevicesPref.isChecked = data
}
})
sendToUnverifiedDevicesPref.isChecked = mSession.getGlobalBlacklistUnverifiedDevices()

sendToUnverifiedDevicesPref.onPreferenceClickListener = Preference.OnPreferenceClickListener {
mSession.getGlobalBlacklistUnverifiedDevices(object : MatrixCallback<Boolean> {
override fun onSuccess(data: Boolean) {
if (sendToUnverifiedDevicesPref.isChecked != data) {
mSession.setGlobalBlacklistUnverifiedDevices(sendToUnverifiedDevicesPref.isChecked, object : MatrixCallback<Unit> {
override fun onSuccess(data: Unit) {

}
})
}
}
})
mSession.setGlobalBlacklistUnverifiedDevices(sendToUnverifiedDevicesPref.isChecked)

true
}
@ -2871,8 +2854,6 @@ if (sharedDataItems.isNotEmpty() && thisActivity != null) {
* ========================================================================================== */

companion object {
private val LOG_TAG = VectorSettingsPreferencesFragment::class.java.simpleName

// arguments indexes
private const val ARG_MATRIX_ID = "VectorSettingsPreferencesFragment.ARG_MATRIX_ID"