From 6c1719e365070a0d73c945461b801ba173f99a75 Mon Sep 17 00:00:00 2001 From: waylon531 Date: Thu, 16 Apr 2020 02:37:12 -0700 Subject: [PATCH 01/22] Use a bigger thread pool This patch makes RiotX use an unbounded thread pool to handle connections. The default thread pool for the android WorkManager has a fairly anemic number of threads and I suspect this was causing performance issues especially because of all the long-running jobs that happen whenever you sync. I tested this out on my phone and all of the sluggishness appears to have gone away. I tested both the debug and release builds to make sure it wasn't just some release optimization. RiotX is so much snappier now! This fixes #1221 Signed-off-by: Waylon Cude --- .../src/main/java/im/vector/matrix/android/api/Matrix.kt | 3 ++- vector/src/main/java/im/vector/riotx/VectorApplication.kt | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/Matrix.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/Matrix.kt index 22ac0324cf..4c6e3ea3bd 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/Matrix.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/Matrix.kt @@ -33,6 +33,7 @@ import im.vector.matrix.android.internal.util.BackgroundDetectionObserver import org.matrix.olm.OlmManager import java.io.InputStream import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.Executors import javax.inject.Inject data class MatrixConfiguration( @@ -61,7 +62,7 @@ class Matrix private constructor(context: Context, matrixConfiguration: MatrixCo Monarchy.init(context) DaggerMatrixComponent.factory().create(context, matrixConfiguration).inject(this) if (context.applicationContext !is Configuration.Provider) { - WorkManager.initialize(context, Configuration.Builder().build()) + WorkManager.initialize(context, Configuration.Builder().setExecutor(Executors.newCachedThreadPool()).build()) } ProcessLifecycleOwner.get().lifecycle.addObserver(backgroundDetectionObserver) } diff --git a/vector/src/main/java/im/vector/riotx/VectorApplication.kt b/vector/src/main/java/im/vector/riotx/VectorApplication.kt index 680550e818..2bceb38b75 100644 --- a/vector/src/main/java/im/vector/riotx/VectorApplication.kt +++ b/vector/src/main/java/im/vector/riotx/VectorApplication.kt @@ -56,6 +56,7 @@ import im.vector.riotx.features.version.VersionProvider import im.vector.riotx.push.fcm.FcmHelper import timber.log.Timber import java.text.SimpleDateFormat +import java.util.concurrent.Executors import java.util.Date import java.util.Locale import javax.inject.Inject @@ -146,7 +147,7 @@ class VectorApplication : Application(), HasVectorInjector, MatrixConfiguration. override fun providesMatrixConfiguration() = MatrixConfiguration(BuildConfig.FLAVOR_DESCRIPTION) - override fun getWorkManagerConfiguration() = androidx.work.Configuration.Builder().build() + override fun getWorkManagerConfiguration() = androidx.work.Configuration.Builder().setExecutor(Executors.newCachedThreadPool()).build() override fun injector(): VectorComponent { return vectorComponent From ec4458e84a8454a0afbd8ef1f8fec232fe70142c Mon Sep 17 00:00:00 2001 From: Waylon Cude Date: Thu, 16 Apr 2020 02:50:58 -0700 Subject: [PATCH 02/22] Updated CHANGES.md Signed-off-by: Waylon Cude --- CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.md b/CHANGES.md index 4ca393ab73..52f728d2c5 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -31,6 +31,7 @@ Bugfix 🐛: - Cross-Signing | web <-> riotX After QR code scan, gossiping fails (#1210) - Fix crash when trying to download file without internet connection (#1229) - Local echo are not updated in timeline (for failed & encrypted states) + - RiotX now uses as many threads as it needs to do work and send messages (#1221) Translations 🗣: - From 8a4f0a0c004aeae34675a916aace2e7c2b4a25ea Mon Sep 17 00:00:00 2001 From: Valere Date: Mon, 20 Apr 2020 16:53:14 +0200 Subject: [PATCH 03/22] KeyBackup / Use 4S if key in quadS --- CHANGES.md | 1 + .../keysbackup/DefaultKeysBackupService.kt | 3 +- .../restore/KeysBackupRestoreActivity.kt | 63 ++++- .../KeysBackupRestoreFromKeyFragment.kt | 2 +- .../KeysBackupRestoreFromKeyViewModel.kt | 86 ++----- ...KeysBackupRestoreFromPassphraseFragment.kt | 4 +- ...eysBackupRestoreFromPassphraseViewModel.kt | 90 ++----- .../KeysBackupRestoreSharedViewModel.kt | 223 ++++++++++++++++-- 8 files changed, 298 insertions(+), 174 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f61..b9f953b4cc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -455,6 +455,7 @@ Bugfix: - Fix messages with empty `in_reply_to` not rendering (#447) - Fix clear cache (#408) and Logout (#205) - Fix `(edited)` link can be copied to clipboard (#402) + - KeyBackup / SSSS | Should get the key from SSSS instead of asking recovery Key (#1163) Build: - Split APK: generate one APK per arch, to reduce APK size of about 30% diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/keysbackup/DefaultKeysBackupService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/keysbackup/DefaultKeysBackupService.kt index 9245f77317..ebef751925 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/keysbackup/DefaultKeysBackupService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/keysbackup/DefaultKeysBackupService.kt @@ -728,7 +728,8 @@ internal class DefaultKeysBackupService @Inject constructor( if (backUp) { maybeBackupKeys() } - + // Save for next time and for gossiping + saveBackupRecoveryKey(recoveryKey, keysVersionResult.version) result } }.foldToCallback(callback) diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt index e6d303b3aa..2b4e372166 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreActivity.kt @@ -20,16 +20,22 @@ import android.content.Context import android.content.Intent import androidx.appcompat.app.AlertDialog import androidx.lifecycle.Observer +import im.vector.matrix.android.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME import im.vector.riotx.R import im.vector.riotx.core.extensions.addFragmentToBackstack import im.vector.riotx.core.extensions.observeEvent import im.vector.riotx.core.extensions.replaceFragment import im.vector.riotx.core.platform.SimpleFragmentActivity +import im.vector.riotx.core.ui.views.KeysBackupBanner +import im.vector.riotx.features.crypto.quads.SharedSecureStorageActivity class KeysBackupRestoreActivity : SimpleFragmentActivity() { companion object { + private const val REQUEST_4S_SECRET = 100 + const val SECRET_ALIAS = SharedSecureStorageActivity.DEFAULT_RESULT_KEYSTORE_ALIAS + fun intent(context: Context): Intent { return Intent(context, KeysBackupRestoreActivity::class.java) } @@ -39,14 +45,20 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() { private lateinit var viewModel: KeysBackupRestoreSharedViewModel + override fun onBackPressed() { + hideWaitingView() + super.onBackPressed() + } + override fun initUiAndData() { super.initUiAndData() viewModel = viewModelProvider.get(KeysBackupRestoreSharedViewModel::class.java) viewModel.initSession(session) - viewModel.keyVersionResult.observe(this, Observer { keyVersion -> - if (keyVersion != null && supportFragmentManager.fragments.isEmpty()) { - val isBackupCreatedFromPassphrase = keyVersion.getAuthDataAsMegolmBackupAuthData()?.privateKeySalt != null + viewModel.keySourceModel.observe(this, Observer { keySource -> + if (keySource != null && !keySource.isInQuadS && supportFragmentManager.fragments.isEmpty()) { + val isBackupCreatedFromPassphrase = + viewModel.keyVersionResult.value?.getAuthDataAsMegolmBackupAuthData()?.privateKeySalt != null if (isBackupCreatedFromPassphrase) { replaceFragment(R.id.container, KeysBackupRestoreFromPassphraseFragment::class.java) } else { @@ -69,7 +81,7 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() { if (viewModel.keyVersionResult.value == null) { // We need to fetch from API - viewModel.getLatestVersion(this) + viewModel.getLatestVersion() } viewModel.navigateEvent.observeEvent(this) { uxStateEvent -> @@ -78,8 +90,25 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() { addFragmentToBackstack(R.id.container, KeysBackupRestoreFromKeyFragment::class.java) } KeysBackupRestoreSharedViewModel.NAVIGATE_TO_SUCCESS -> { + viewModel.keyVersionResult.value?.version?.let { + KeysBackupBanner.onRecoverDoneForVersion(this, it) + } replaceFragment(R.id.container, KeysBackupRestoreSuccessFragment::class.java) } + KeysBackupRestoreSharedViewModel.NAVIGATE_TO_4S -> { + launch4SActivity() + } + KeysBackupRestoreSharedViewModel.NAVIGATE_FAILED_TO_LOAD_4S -> { + AlertDialog.Builder(this) + .setTitle(R.string.unknown_error) + .setMessage(R.string.error_failed_to_import_keys) + .setCancelable(false) + .setPositiveButton(R.string.ok) { _, _ -> + // nop + launch4SActivity() + } + .show() + } } } @@ -93,4 +122,30 @@ class KeysBackupRestoreActivity : SimpleFragmentActivity() { finish() } } + + private fun launch4SActivity() { + SharedSecureStorageActivity.newIntent( + context = this, + keyId = null, // default key + requestedSecrets = listOf(KEYBACKUP_SECRET_SSSS_NAME), + resultKeyStoreAlias = SECRET_ALIAS + ).let { + startActivityForResult(it, REQUEST_4S_SECRET) + } + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (requestCode == REQUEST_4S_SECRET) { + val extraResult = data?.getStringExtra(SharedSecureStorageActivity.EXTRA_DATA_RESULT) + if (resultCode == Activity.RESULT_OK && extraResult != null) { + viewModel.handleGotSecretFromSSSS( + extraResult, + SECRET_ALIAS + ) + } else { + finish() + } + } + super.onActivityResult(requestCode, resultCode, data) + } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyFragment.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyFragment.kt index 730c92a319..9a6e65a885 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyFragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyFragment.kt @@ -82,7 +82,7 @@ class KeysBackupRestoreFromKeyFragment @Inject constructor() if (value.isNullOrBlank()) { viewModel.recoveryCodeErrorText.value = context?.getString(R.string.keys_backup_recovery_code_empty_error_message) } else { - viewModel.recoverKeys(requireContext(), sharedViewModel) + viewModel.recoverKeys(sharedViewModel) } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyViewModel.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyViewModel.kt index 0cf297f7f1..c8406570d3 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromKeyViewModel.kt @@ -15,21 +15,19 @@ */ package im.vector.riotx.features.crypto.keysbackup.restore -import android.content.Context import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel -import im.vector.matrix.android.api.MatrixCallback -import im.vector.matrix.android.api.listeners.StepProgressListener -import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService -import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersionResult -import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult +import androidx.lifecycle.viewModelScope import im.vector.riotx.R import im.vector.riotx.core.platform.WaitingViewData -import im.vector.riotx.core.ui.views.KeysBackupBanner -import timber.log.Timber +import im.vector.riotx.core.resources.StringProvider +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import javax.inject.Inject -class KeysBackupRestoreFromKeyViewModel @Inject constructor() : ViewModel() { +class KeysBackupRestoreFromKeyViewModel @Inject constructor( + private val stringProvider: StringProvider +) : ViewModel() { var recoveryCode: MutableLiveData = MutableLiveData() var recoveryCodeErrorText: MutableLiveData = MutableLiveData() @@ -45,66 +43,16 @@ class KeysBackupRestoreFromKeyViewModel @Inject constructor() : ViewModel() { recoveryCodeErrorText.value = null } - fun recoverKeys(context: Context, sharedViewModel: KeysBackupRestoreSharedViewModel) { - val session = sharedViewModel.session - val keysBackup = session.cryptoService().keysBackupService() - + fun recoverKeys(sharedViewModel: KeysBackupRestoreSharedViewModel) { + sharedViewModel.loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.loading))) recoveryCodeErrorText.value = null - val recoveryKey = recoveryCode.value!! - - val keysVersionResult = sharedViewModel.keyVersionResult.value!! - - keysBackup.restoreKeysWithRecoveryKey(keysVersionResult, - recoveryKey, - null, - session.myUserId, - object : StepProgressListener { - override fun onStepProgress(step: StepProgressListener.Step) { - when (step) { - is StepProgressListener.Step.DownloadingKey -> { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_downloading_backup_waiting_message), - isIndeterminate = true)) - } - is StepProgressListener.Step.ImportingKey -> { - // Progress 0 can take a while, display an indeterminate progress in this case - if (step.progress == 0) { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_importing_keys_waiting_message), - isIndeterminate = true)) - } else { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_importing_keys_waiting_message), - step.progress, - step.total)) - } - } - } - } - }, - object : MatrixCallback { - override fun onSuccess(data: ImportRoomKeysResult) { - sharedViewModel.loadingEvent.value = null - sharedViewModel.didRecoverSucceed(data) - - KeysBackupBanner.onRecoverDoneForVersion(context, keysVersionResult.version!!) - trustOnDecrypt(keysBackup, keysVersionResult) - } - - override fun onFailure(failure: Throwable) { - sharedViewModel.loadingEvent.value = null - recoveryCodeErrorText.value = context.getString(R.string.keys_backup_recovery_code_error_decrypt) - Timber.e(failure, "## onUnexpectedError") - } - }) - } - - private fun trustOnDecrypt(keysBackup: KeysBackupService, keysVersionResult: KeysVersionResult) { - keysBackup.trustKeysBackupVersion(keysVersionResult, true, - object : MatrixCallback { - override fun onSuccess(data: Unit) { - Timber.v("##### trustKeysBackupVersion onSuccess") - } - }) + viewModelScope.launch(Dispatchers.IO) { + val recoveryKey = recoveryCode.value!! + try { + sharedViewModel.recoverUsingBackupPass(recoveryKey) + } catch (failure: Throwable) { + recoveryCodeErrorText.value = stringProvider.getString(R.string.keys_backup_recovery_code_error_decrypt) + } + } } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseFragment.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseFragment.kt index 8dc8855583..0947c144d8 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseFragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseFragment.kt @@ -36,7 +36,7 @@ import im.vector.riotx.core.extensions.showPassword import im.vector.riotx.core.platform.VectorBaseFragment import javax.inject.Inject -class KeysBackupRestoreFromPassphraseFragment @Inject constructor(): VectorBaseFragment() { +class KeysBackupRestoreFromPassphraseFragment @Inject constructor() : VectorBaseFragment() { override fun getLayoutResId() = R.layout.fragment_keys_backup_restore_from_passphrase @@ -119,7 +119,7 @@ class KeysBackupRestoreFromPassphraseFragment @Inject constructor(): VectorBaseF if (value.isNullOrBlank()) { viewModel.passphraseErrorText.value = context?.getString(R.string.passphrase_empty_error_message) } else { - viewModel.recoverKeys(context!!, sharedViewModel) + viewModel.recoverKeys(sharedViewModel) } } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseViewModel.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseViewModel.kt index 69c5e70740..46e8d5fa18 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreFromPassphraseViewModel.kt @@ -15,21 +15,18 @@ */ package im.vector.riotx.features.crypto.keysbackup.restore -import android.content.Context import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel -import im.vector.matrix.android.api.MatrixCallback -import im.vector.matrix.android.api.listeners.StepProgressListener -import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService -import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersionResult -import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult +import androidx.lifecycle.viewModelScope import im.vector.riotx.R -import im.vector.riotx.core.platform.WaitingViewData -import im.vector.riotx.core.ui.views.KeysBackupBanner -import timber.log.Timber +import im.vector.riotx.core.resources.StringProvider +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch import javax.inject.Inject -class KeysBackupRestoreFromPassphraseViewModel @Inject constructor() : ViewModel() { +class KeysBackupRestoreFromPassphraseViewModel @Inject constructor( + private val stringProvider: StringProvider +) : ViewModel() { var passphrase: MutableLiveData = MutableLiveData() var passphraseErrorText: MutableLiveData = MutableLiveData() @@ -48,71 +45,14 @@ class KeysBackupRestoreFromPassphraseViewModel @Inject constructor() : ViewModel passphraseErrorText.value = null } - fun recoverKeys(context: Context, sharedViewModel: KeysBackupRestoreSharedViewModel) { - val keysBackup = sharedViewModel.session.cryptoService().keysBackupService() - + fun recoverKeys(sharedViewModel: KeysBackupRestoreSharedViewModel) { passphraseErrorText.value = null - - val keysVersionResult = sharedViewModel.keyVersionResult.value!! - - keysBackup.restoreKeyBackupWithPassword(keysVersionResult, - passphrase.value!!, - null, - sharedViewModel.session.myUserId, - object : StepProgressListener { - override fun onStepProgress(step: StepProgressListener.Step) { - when (step) { - is StepProgressListener.Step.ComputingKey -> { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_computing_key_waiting_message), - step.progress, - step.total)) - } - is StepProgressListener.Step.DownloadingKey -> { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_downloading_backup_waiting_message), - isIndeterminate = true)) - } - is StepProgressListener.Step.ImportingKey -> { - Timber.d("backupKeys.ImportingKey.progress: ${step.progress}") - // Progress 0 can take a while, display an indeterminate progress in this case - if (step.progress == 0) { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_importing_keys_waiting_message), - isIndeterminate = true)) - } else { - sharedViewModel.loadingEvent.postValue(WaitingViewData(context.getString(R.string.keys_backup_restoring_waiting_message) - + "\n" + context.getString(R.string.keys_backup_restoring_importing_keys_waiting_message), - step.progress, - step.total)) - } - } - } - } - }, - object : MatrixCallback { - override fun onSuccess(data: ImportRoomKeysResult) { - sharedViewModel.loadingEvent.value = null - sharedViewModel.didRecoverSucceed(data) - - KeysBackupBanner.onRecoverDoneForVersion(context, keysVersionResult.version!!) - trustOnDecrypt(keysBackup, keysVersionResult) - } - - override fun onFailure(failure: Throwable) { - sharedViewModel.loadingEvent.value = null - passphraseErrorText.value = context.getString(R.string.keys_backup_passphrase_error_decrypt) - Timber.e(failure, "## onUnexpectedError") - } - }) - } - - private fun trustOnDecrypt(keysBackup: KeysBackupService, keysVersionResult: KeysVersionResult) { - keysBackup.trustKeysBackupVersion(keysVersionResult, true, - object : MatrixCallback { - override fun onSuccess(data: Unit) { - Timber.v("##### trustKeysBackupVersion onSuccess") - } - }) + viewModelScope.launch(Dispatchers.IO) { + try { + sharedViewModel.recoverUsingBackupPass(passphrase.value!!) + } catch (failure: Throwable) { + passphraseErrorText.value = stringProvider.getString(R.string.keys_backup_passphrase_error_decrypt) + } + } } } diff --git a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt index 5586d0cf05..3852d1035f 100644 --- a/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt +++ b/vector/src/main/java/im/vector/riotx/features/crypto/keysbackup/restore/KeysBackupRestoreSharedViewModel.kt @@ -15,30 +15,52 @@ */ package im.vector.riotx.features.crypto.keysbackup.restore -import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope import im.vector.matrix.android.api.MatrixCallback +import im.vector.matrix.android.api.listeners.StepProgressListener import im.vector.matrix.android.api.session.Session +import im.vector.matrix.android.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME +import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupService +import im.vector.matrix.android.api.session.securestorage.KeyInfoResult +import im.vector.matrix.android.internal.crypto.crosssigning.fromBase64 import im.vector.matrix.android.internal.crypto.keysbackup.model.rest.KeysVersionResult +import im.vector.matrix.android.internal.crypto.keysbackup.util.computeRecoveryKey import im.vector.matrix.android.internal.crypto.model.ImportRoomKeysResult +import im.vector.matrix.android.internal.util.awaitCallback import im.vector.riotx.R import im.vector.riotx.core.platform.WaitingViewData +import im.vector.riotx.core.resources.StringProvider import im.vector.riotx.core.utils.LiveEvent +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import timber.log.Timber import javax.inject.Inject -class KeysBackupRestoreSharedViewModel @Inject constructor() : ViewModel() { +class KeysBackupRestoreSharedViewModel @Inject constructor( + private val stringProvider: StringProvider +) : ViewModel() { + + data class KeySource( + val isInMemory: Boolean, + val isInQuadS: Boolean + ) companion object { const val NAVIGATE_TO_RECOVER_WITH_KEY = "NAVIGATE_TO_RECOVER_WITH_KEY" const val NAVIGATE_TO_SUCCESS = "NAVIGATE_TO_SUCCESS" + const val NAVIGATE_TO_4S = "NAVIGATE_TO_4S" + const val NAVIGATE_FAILED_TO_LOAD_4S = "NAVIGATE_FAILED_TO_LOAD_4S" } lateinit var session: Session var keyVersionResult: MutableLiveData = MutableLiveData() + var keySourceModel: MutableLiveData = MutableLiveData() + private var _keyVersionResultError: MutableLiveData> = MutableLiveData() val keyVersionResultError: LiveData> get() = _keyVersionResultError @@ -62,30 +84,187 @@ class KeysBackupRestoreSharedViewModel @Inject constructor() : ViewModel() { this.session = session } - fun getLatestVersion(context: Context) { - val keysBackup = session.cryptoService().keysBackupService() - - loadingEvent.value = WaitingViewData(context.getString(R.string.keys_backup_restore_is_getting_backup_version)) - - keysBackup.getCurrentVersion(object : MatrixCallback { - override fun onSuccess(data: KeysVersionResult?) { - loadingEvent.value = null - if (data?.version.isNullOrBlank()) { - // should not happen - _keyVersionResultError.value = LiveEvent(context.getString(R.string.keys_backup_get_version_error, "")) - } else { - keyVersionResult.value = data + val progressObserver = object : StepProgressListener { + override fun onStepProgress(step: StepProgressListener.Step) { + when (step) { + is StepProgressListener.Step.ComputingKey -> { + loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) + + "\n" + stringProvider.getString(R.string.keys_backup_restoring_computing_key_waiting_message), + step.progress, + step.total)) + } + is StepProgressListener.Step.DownloadingKey -> { + loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) + + "\n" + stringProvider.getString(R.string.keys_backup_restoring_downloading_backup_waiting_message), + isIndeterminate = true)) + } + is StepProgressListener.Step.ImportingKey -> { + Timber.d("backupKeys.ImportingKey.progress: ${step.progress}") + // Progress 0 can take a while, display an indeterminate progress in this case + if (step.progress == 0) { + loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) + + "\n" + stringProvider.getString(R.string.keys_backup_restoring_importing_keys_waiting_message), + isIndeterminate = true)) + } else { + loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.keys_backup_restoring_waiting_message) + + "\n" + stringProvider.getString(R.string.keys_backup_restoring_importing_keys_waiting_message), + step.progress, + step.total)) + } } } + } + } - override fun onFailure(failure: Throwable) { - loadingEvent.value = null - _keyVersionResultError.value = LiveEvent(context.getString(R.string.keys_backup_get_version_error, failure.localizedMessage)) + fun getLatestVersion() { + val keysBackup = session.cryptoService().keysBackupService() - // TODO For network error - // _keyVersionResultError.value = LiveEvent(context.getString(R.string.network_error_please_check_and_retry)) + loadingEvent.value = WaitingViewData(stringProvider.getString(R.string.keys_backup_restore_is_getting_backup_version)) + + viewModelScope.launch(Dispatchers.IO) { + try { + val version = awaitCallback { + keysBackup.getCurrentVersion(it) + } + if (version?.version == null) { + loadingEvent.postValue(null) + _keyVersionResultError.postValue(LiveEvent(stringProvider.getString(R.string.keys_backup_get_version_error, ""))) + return@launch + } + + keyVersionResult.postValue(version) + // Let's check if there is quads + val isBackupKeyInQuadS = isBackupKeyInQuadS() + + val savedSecret = session.cryptoService().keysBackupService().getKeyBackupRecoveryKeyInfo() + if (savedSecret != null && savedSecret.version == version.version) { + // key is in memory! + keySourceModel.postValue( + KeySource(isInMemory = true, isInQuadS = true) + ) + // Go and use it!! + try { + recoverUsingBackupRecoveryKey(savedSecret.recoveryKey) + } catch (failure: Throwable) { + keySourceModel.postValue( + KeySource(isInMemory = false, isInQuadS = true) + ) + } + } else if (isBackupKeyInQuadS) { + // key is in QuadS! + keySourceModel.postValue( + KeySource(isInMemory = false, isInQuadS = true) + ) + _navigateEvent.postValue(LiveEvent(NAVIGATE_TO_4S)) + } else { + // we need to restore directly + keySourceModel.postValue( + KeySource(isInMemory = false, isInQuadS = false) + ) + } + + loadingEvent.postValue(null) + } catch (failure: Throwable) { + loadingEvent.postValue(null) + _keyVersionResultError.postValue(LiveEvent(stringProvider.getString(R.string.keys_backup_get_version_error, failure.localizedMessage))) } - }) + } + } + + fun handleGotSecretFromSSSS(cipherData: String, alias: String) { + try { + cipherData.fromBase64().inputStream().use { ins -> + val res = session.loadSecureSecret>(ins, alias) + val secret = res?.get(KEYBACKUP_SECRET_SSSS_NAME) + if (secret == null) { + _navigateEvent.postValue( + LiveEvent(NAVIGATE_FAILED_TO_LOAD_4S) + ) + return + } + loadingEvent.value = WaitingViewData(stringProvider.getString(R.string.keys_backup_restore_is_getting_backup_version)) + + viewModelScope.launch(Dispatchers.IO) { + try { + recoverUsingBackupRecoveryKey(computeRecoveryKey(secret.fromBase64())) + } catch (failure: Throwable) { + _navigateEvent.postValue( + LiveEvent(NAVIGATE_FAILED_TO_LOAD_4S) + ) + } + } + } + } catch (failure: Throwable) { + } + } + + suspend fun recoverUsingBackupPass(passphrase: String) { + val keysBackup = session.cryptoService().keysBackupService() + val keyVersion = keyVersionResult.value ?: return + + loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.loading))) + + try { + val result = awaitCallback { + keysBackup.restoreKeyBackupWithPassword(keyVersion, + passphrase, + null, + session.myUserId, + progressObserver, + it + ) + } + loadingEvent.postValue(null) + didRecoverSucceed(result) + trustOnDecrypt(keysBackup, keyVersion) + } catch (failure: Throwable) { + throw failure + } + } + + suspend fun recoverUsingBackupRecoveryKey(recoveryKey: String) { + val keysBackup = session.cryptoService().keysBackupService() + val keyVersion = keyVersionResult.value ?: return + + loadingEvent.postValue(WaitingViewData(stringProvider.getString(R.string.loading))) + + try { + val result = awaitCallback { + keysBackup.restoreKeysWithRecoveryKey(keyVersion, + recoveryKey, + null, + session.myUserId, + progressObserver, + it + ) + } + loadingEvent.postValue(null) + didRecoverSucceed(result) + trustOnDecrypt(keysBackup, keyVersion) + } catch (failure: Throwable) { + throw failure + } + } + + private fun isBackupKeyInQuadS(): Boolean { + val sssBackupSecret = session.getAccountDataEvent(KEYBACKUP_SECRET_SSSS_NAME) + ?: return false + + // Some sanity ? + val defaultKeyResult = session.sharedSecretStorageService.getDefaultKey() + val keyInfo = (defaultKeyResult as? KeyInfoResult.Success)?.keyInfo + ?: return false + + return (sssBackupSecret.content["encrypted"] as? Map<*, *>)?.containsKey(keyInfo.id) == true + } + + private fun trustOnDecrypt(keysBackup: KeysBackupService, keysVersionResult: KeysVersionResult) { + keysBackup.trustKeysBackupVersion(keysVersionResult, true, + object : MatrixCallback { + override fun onSuccess(data: Unit) { + Timber.v("##### trustKeysBackupVersion onSuccess") + } + }) } fun moveToRecoverWithKey() { @@ -94,6 +273,6 @@ class KeysBackupRestoreSharedViewModel @Inject constructor() : ViewModel() { fun didRecoverSucceed(result: ImportRoomKeysResult) { importKeyResult = result - _navigateEvent.value = LiveEvent(NAVIGATE_TO_SUCCESS) + _navigateEvent.postValue(LiveEvent(NAVIGATE_TO_SUCCESS)) } } From c1acb1af66e882dc1d7eabc691b62981a0369079 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 00:23:01 +0200 Subject: [PATCH 04/22] Add integration test for change password feature --- .../android/account/ChangePasswordTest.kt | 58 +++++++++++++++++++ .../matrix/android/common/CommonTestHelper.kt | 38 +++++++++++- 2 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt new file mode 100644 index 0000000000..981385f3c7 --- /dev/null +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/account/ChangePasswordTest.kt @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.matrix.android.account + +import im.vector.matrix.android.InstrumentedTest +import im.vector.matrix.android.common.CommonTestHelper +import im.vector.matrix.android.common.SessionTestParams +import im.vector.matrix.android.common.TestConstants +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import org.junit.runners.MethodSorters + +@RunWith(JUnit4::class) +@FixMethodOrder(MethodSorters.JVM) +class ChangePasswordTest : InstrumentedTest { + + private val commonTestHelper = CommonTestHelper(context()) + + companion object { + private const val NEW_PASSWORD = "this is a new password" + } + + @Test + fun changePasswordTest() { + val session = commonTestHelper.createAccount(TestConstants.USER_ALICE, SessionTestParams(withInitialSync = false)) + + // Change password + commonTestHelper.doSync { + session.changePassword(TestConstants.PASSWORD, NEW_PASSWORD, it) + } + + // Try to login with the previous password, it will fail + commonTestHelper.logAccountBadPassword(session.myUserId, TestConstants.PASSWORD) + + // Try to login with the new password, should work + val session2 = commonTestHelper.logIntoAccount(session.myUserId, NEW_PASSWORD, SessionTestParams(withInitialSync = false)) + + + commonTestHelper.signOutAndClose(session) + commonTestHelper.signOutAndClose(session2) + } +} diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt index 3cf03fff53..86378ee2fb 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt @@ -26,6 +26,7 @@ import im.vector.matrix.android.api.MatrixConfiguration import im.vector.matrix.android.api.auth.data.HomeServerConnectionConfig import im.vector.matrix.android.api.auth.data.LoginFlowResult import im.vector.matrix.android.api.auth.registration.RegistrationResult +import im.vector.matrix.android.api.failure.isInvalidPassword import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.events.model.EventType import im.vector.matrix.android.api.session.events.model.LocalEcho @@ -41,6 +42,7 @@ import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import org.amshove.kluent.shouldBeTrue import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue @@ -183,9 +185,9 @@ class CommonTestHelper(context: Context) { * @param testParams test params about the session * @return the session associated with the existing account */ - private fun logIntoAccount(userId: String, - password: String, - testParams: SessionTestParams): Session { + fun logIntoAccount(userId: String, + password: String, + testParams: SessionTestParams): Session { val session = logAccountAndSync(userId, password, testParams) assertNotNull(session) return session @@ -260,6 +262,36 @@ class CommonTestHelper(context: Context) { return session } + /** + * Log into the account using a wrong password + * + * @param userName the account username + * @param badPassword an incorrect password + */ + fun logAccountBadPassword(userName: String, + badPassword: String) { + val hs = createHomeServerConfig() + + doSync { + matrix.authenticationService + .getLoginFlow(hs, it) + } + + var requestFailure: Throwable? = null + val latch = CountDownLatch(1) + matrix.authenticationService + .getLoginWizard() + .login(userName, badPassword, "myDevice", object : TestMatrixCallback(latch, onlySuccessful = false) { + override fun onFailure(failure: Throwable) { + requestFailure = failure + super.onFailure(failure) + } + }) + await(latch) + + requestFailure!!.isInvalidPassword().shouldBeTrue() + } + /** * Await for a latch and ensure the result is true * From 59280ed18eede32ca994229e90435f8c6d8e4326 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 00:29:02 +0200 Subject: [PATCH 05/22] Small improvement in documentation --- docs/notifications.md | 4 ++-- docs/signin.md | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/notifications.md b/docs/notifications.md index 328eb86954..8efcb87bf3 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -38,10 +38,10 @@ When the client receives the new information, it immediately sends another reque This effectively emulates a server push feature. The HTTP long Polling can be fine tuned in the **SDK** using two parameters: -* timout (Sync request timeout) +* timeout (Sync request timeout) * delay (Delay between each sync) -**timeout** is a server paramter, defined by: +**timeout** is a server parameter, defined by: ``` The maximum time to wait, in milliseconds, before returning this request.` If no events (or other data) become available before this time elapses, the server will return a response with empty fields. diff --git a/docs/signin.md b/docs/signin.md index 245ea444f6..e7368137ae 100644 --- a/docs/signin.md +++ b/docs/signin.md @@ -57,7 +57,7 @@ We get credential (200) ```json { - "user_id": "@benoit0816:matrix.org", + "user_id": "@alice:matrix.org", "access_token": "MDAxOGxvY2F0aW9uIG1hdHREDACTEDb2l0MDgxNjptYXRyaXgub3JnCjAwMTZjaWQgdHlwZSA9IGFjY2VzcwowMDIxY2lkIG5vbmNlID0gfnYrSypfdTtkNXIuNWx1KgowMDJmc2lnbmF0dXJlIOsh1XqeAkXexh4qcofl_aR4kHJoSOWYGOhE7-ubX-DZCg", "home_server": "matrix.org", "device_id": "GTVREDALBF", @@ -128,6 +128,8 @@ We get the credentials (200) } ``` +It's worth noting that the response from the homeserver contains the userId of Alice. + ### Login with Msisdn Not supported yet in RiotX From c39a0e4fd51ae761cb97720c0375cfc7aab53893 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 00:29:44 +0200 Subject: [PATCH 06/22] timout -> timeout --- .../matrix/android/common/CommonTestHelper.kt | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt index 86378ee2fb..f5027ec7b1 100644 --- a/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt +++ b/matrix-sdk-android/src/androidTest/java/im/vector/matrix/android/common/CommonTestHelper.kt @@ -278,16 +278,16 @@ class CommonTestHelper(context: Context) { } var requestFailure: Throwable? = null - val latch = CountDownLatch(1) - matrix.authenticationService - .getLoginWizard() - .login(userName, badPassword, "myDevice", object : TestMatrixCallback(latch, onlySuccessful = false) { - override fun onFailure(failure: Throwable) { - requestFailure = failure - super.onFailure(failure) - } - }) - await(latch) + waitWithLatch { latch -> + matrix.authenticationService + .getLoginWizard() + .login(userName, badPassword, "myDevice", object : TestMatrixCallback(latch, onlySuccessful = false) { + override fun onFailure(failure: Throwable) { + requestFailure = failure + super.onFailure(failure) + } + }) + } requestFailure!!.isInvalidPassword().shouldBeTrue() } @@ -298,8 +298,8 @@ class CommonTestHelper(context: Context) { * @param latch * @throws InterruptedException */ - fun await(latch: CountDownLatch, timout: Long? = TestConstants.timeOutMillis) { - assertTrue(latch.await(timout ?: TestConstants.timeOutMillis, TimeUnit.MILLISECONDS)) + fun await(latch: CountDownLatch, timeout: Long? = TestConstants.timeOutMillis) { + assertTrue(latch.await(timeout ?: TestConstants.timeOutMillis, TimeUnit.MILLISECONDS)) } fun retryPeriodicallyWithLatch(latch: CountDownLatch, condition: (() -> Boolean)) { @@ -314,10 +314,10 @@ class CommonTestHelper(context: Context) { } } - fun waitWithLatch(timout: Long? = TestConstants.timeOutMillis, block: (CountDownLatch) -> Unit) { + fun waitWithLatch(timeout: Long? = TestConstants.timeOutMillis, block: (CountDownLatch) -> Unit) { val latch = CountDownLatch(1) block(latch) - await(latch, timout) + await(latch, timeout) } // Transform a method with a MatrixCallback to a synchronous method From eca3bf08172225f3c28ce14d68ce556f2fb44cf8 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 13:49:36 +0200 Subject: [PATCH 07/22] typo --- .../matrix/android/internal/session/signout/SignOutTask.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt index b14a7758c5..6945ac494e 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/signout/SignOutTask.kt @@ -44,7 +44,7 @@ import javax.inject.Inject internal interface SignOutTask : Task { data class Params( - val sigOutFromHomeserver: Boolean + val signOutFromHomeserver: Boolean ) } @@ -67,7 +67,7 @@ internal class DefaultSignOutTask @Inject constructor( override suspend fun execute(params: SignOutTask.Params) { // It should be done even after a soft logout, to be sure the deviceId is deleted on the - if (params.sigOutFromHomeserver) { + if (params.signOutFromHomeserver) { Timber.d("SignOut: send request...") try { executeRequest(eventBus) { From 3163bc8b8056d68ced9517db227ac79696e0fe59 Mon Sep 17 00:00:00 2001 From: onurays Date: Tue, 21 Apr 2020 15:25:48 +0300 Subject: [PATCH 08/22] Add user to direct chat by user id. Fixes #1065 --- CHANGES.md | 1 + .../createdirect/DirectoryUsersController.kt | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f61..91ebeecaa7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -35,6 +35,7 @@ Bugfix 🐛: - Local echo are not updated in timeline (for failed & encrypted states) - Render image event even if thumbnail_info does not have mimetype defined (#1209) - Fix issue with media path (#1227) + - Add user to direct chat by user id (#1065) Translations 🗣: - diff --git a/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt b/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt index 016806f319..fd943b6447 100644 --- a/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt +++ b/vector/src/main/java/im/vector/riotx/features/createdirect/DirectoryUsersController.kt @@ -23,6 +23,7 @@ import com.airbnb.mvrx.Fail import com.airbnb.mvrx.Loading import com.airbnb.mvrx.Success import com.airbnb.mvrx.Uninitialized +import im.vector.matrix.android.api.MatrixPatterns import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.user.model.User import im.vector.matrix.android.api.util.toMatrixItem @@ -56,15 +57,25 @@ class DirectoryUsersController @Inject constructor(private val session: Session, override fun buildModels() { val currentState = state ?: return val hasSearch = currentState.directorySearchTerm.isNotBlank() - val asyncUsers = currentState.directoryUsers - when (asyncUsers) { + when (val asyncUsers = currentState.directoryUsers) { is Uninitialized -> renderEmptyState(false) is Loading -> renderLoading() - is Success -> renderSuccess(asyncUsers(), currentState.selectedUsers.map { it.userId }, hasSearch) + is Success -> renderSuccess(getAsyncUsers(currentState), currentState.selectedUsers.map { it.userId }, hasSearch) is Fail -> renderFailure(asyncUsers.error) } } + private fun getAsyncUsers(currentState: CreateDirectRoomViewState): List { + return currentState + .directoryUsers() + ?.toMutableList() + ?.apply { + currentState.directorySearchTerm + .takeIf { MatrixPatterns.isUserId(it) } + ?.let { add(User(it)) } + } ?: emptyList() + } + private fun renderLoading() { loadingItem { id("loading") From 045e3d7bae1f6b6ce75791a0efe8d6dcc0366c95 Mon Sep 17 00:00:00 2001 From: Benoit Marty Date: Tue, 21 Apr 2020 20:31:54 +0200 Subject: [PATCH 09/22] Account deactivation (with password only) (#35) --- CHANGES.md | 1 + .../api/session/account/AccountService.kt | 19 ++- .../internal/session/account/AccountAPI.kt | 8 ++ .../internal/session/account/AccountModule.kt | 3 + .../account/DeactivateAccountParams.kt | 40 ++++++ .../session/account/DeactivateAccountTask.kt | 77 +++++++++++ .../session/account/DefaultAccountService.kt | 9 ++ .../im/vector/riotx/core/di/FragmentModule.kt | 7 + .../im/vector/riotx/features/MainActivity.kt | 16 ++- .../features/settings/VectorPreferences.kt | 1 - .../settings/VectorSettingsActivity.kt | 13 +- .../settings/VectorSettingsGeneralFragment.kt | 13 -- .../deactivation/DeactivateAccountFragment.kt | 124 ++++++++++++++++++ .../DeactivateAccountViewEvents.kt | 30 +++++ .../DeactivateAccountViewModel.kt | 93 +++++++++++++ .../layout/fragment_deactivate_account.xml | 116 ++++++++++++++++ .../main/res/xml/vector_settings_general.xml | 9 +- 17 files changed, 551 insertions(+), 28 deletions(-) create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt create mode 100644 matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt create mode 100644 vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt create mode 100644 vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt create mode 100644 vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt create mode 100644 vector/src/main/res/layout/fragment_deactivate_account.xml diff --git a/CHANGES.md b/CHANGES.md index 0c1d209f61..f43294ca9f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -7,6 +7,7 @@ Features ✨: - Cross-Signing | Verify new session from existing session (#1134) - Cross-Signing | Bootstraping cross signing with 4S from mobile (#985) - Save media files to Gallery (#973) + - Account deactivation (with password only) (#35) Improvements 🙌: - Verification DM / Handle concurrent .start after .ready (#794) diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt index 68643ff723..ddbaaea6ef 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/api/session/account/AccountService.kt @@ -23,11 +23,28 @@ import im.vector.matrix.android.api.util.Cancelable * This interface defines methods to manage the account. It's implemented at the session level. */ interface AccountService { - /** * Ask the homeserver to change the password. * @param password Current password. * @param newPassword New password */ fun changePassword(password: String, newPassword: String, callback: MatrixCallback): Cancelable + + /** + * Deactivate the account. + * + * This will make your account permanently unusable. You will not be able to log in, and no one will be able to re-register + * the same user ID. This will cause your account to leave all rooms it is participating in, and it will remove your account + * details from your identity server. This action is irreversible.\n\nDeactivating your account does not by default + * cause us to forget messages you have sent. If you would like us to forget your messages, please tick the box below. + * + * Message visibility in Matrix is similar to email. Our forgetting your messages means that messages you have sent will not + * be shared with any new or unregistered users, but registered users who already have access to these messages will still + * have access to their copy. + * + * @param password the account password + * @param eraseAllData set to true to forget all messages that have been sent. Warning: this will cause future users to see + * an incomplete view of conversations + */ + fun deactivateAccount(password: String, eraseAllData: Boolean, callback: MatrixCallback): Cancelable } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt index 23d8210e89..e7fbd3748c 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountAPI.kt @@ -30,4 +30,12 @@ internal interface AccountAPI { */ @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/password") fun changePassword(@Body params: ChangePasswordParams): Call + + /** + * Deactivate the user account + * + * @param params the deactivate account params + */ + @POST(NetworkConstants.URI_API_PREFIX_PATH_R0 + "account/deactivate") + fun deactivate(@Body params: DeactivateAccountParams): Call } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt index 87e003b0d3..032139ce5d 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/AccountModule.kt @@ -39,6 +39,9 @@ internal abstract class AccountModule { @Binds abstract fun bindChangePasswordTask(task: DefaultChangePasswordTask): ChangePasswordTask + @Binds + abstract fun bindDeactivateAccountTask(task: DefaultDeactivateAccountTask): DeactivateAccountTask + @Binds abstract fun bindAccountService(service: DefaultAccountService): AccountService } diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt new file mode 100644 index 0000000000..7a099ca03d --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountParams.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2020 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.matrix.android.internal.session.account; + +import com.squareup.moshi.Json; +import com.squareup.moshi.JsonClass; +import im.vector.matrix.android.internal.crypto.model.rest.UserPasswordAuth + +@JsonClass(generateAdapter = true) +internal data class DeactivateAccountParams( + @Json(name = "auth") + val auth: UserPasswordAuth? = null, + + // Set to true to erase all data of the account + @Json(name = "erase") + val erase: Boolean +) { + companion object { + fun create(userId: String, password: String, erase: Boolean): DeactivateAccountParams { + return DeactivateAccountParams( + auth = UserPasswordAuth(user = userId, password = password), + erase = erase + ) + } + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt new file mode 100644 index 0000000000..b8b57a24a4 --- /dev/null +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DeactivateAccountTask.kt @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2020 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.matrix.android.internal.session.account + +import im.vector.matrix.android.api.failure.Failure +import im.vector.matrix.android.internal.auth.registration.RegistrationFlowResponse +import im.vector.matrix.android.internal.di.MoshiProvider +import im.vector.matrix.android.internal.di.UserId +import im.vector.matrix.android.internal.network.executeRequest +import im.vector.matrix.android.internal.task.Task +import org.greenrobot.eventbus.EventBus +import javax.inject.Inject + +internal interface DeactivateAccountTask : Task { + data class Params( + val password: String, + val eraseAllData: Boolean + ) +} + +internal class DefaultDeactivateAccountTask @Inject constructor( + private val accountAPI: AccountAPI, + private val eventBus: EventBus, + @UserId private val userId: String +) : DeactivateAccountTask { + + override suspend fun execute(params: DeactivateAccountTask.Params) { + val deactivateAccountParams = DeactivateAccountParams.create(userId, params.password, params.eraseAllData) + try { + executeRequest(eventBus) { + apiCall = accountAPI.deactivate(deactivateAccountParams) + } + } catch (throwable: Throwable) { + if (throwable is Failure.OtherServerError + && throwable.httpCode == 401 + /* Avoid infinite loop */ + && deactivateAccountParams.auth?.session == null) { + try { + MoshiProvider.providesMoshi() + .adapter(RegistrationFlowResponse::class.java) + .fromJson(throwable.errorBody) + } catch (e: Exception) { + null + }?.let { + // Retry with authentication + try { + executeRequest(eventBus) { + apiCall = accountAPI.deactivate( + deactivateAccountParams.copy(auth = deactivateAccountParams.auth?.copy(session = it.session)) + ) + } + return + } catch (failure: Throwable) { + throw failure + } + } + } + throw throwable + } + + // TODO This task should also do the cleanup + } +} diff --git a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt index fce01994d3..f6db1dd3db 100644 --- a/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt +++ b/matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/account/DefaultAccountService.kt @@ -24,6 +24,7 @@ import im.vector.matrix.android.internal.task.configureWith import javax.inject.Inject internal class DefaultAccountService @Inject constructor(private val changePasswordTask: ChangePasswordTask, + private val deactivateAccountTask: DeactivateAccountTask, private val taskExecutor: TaskExecutor) : AccountService { override fun changePassword(password: String, newPassword: String, callback: MatrixCallback): Cancelable { @@ -33,4 +34,12 @@ internal class DefaultAccountService @Inject constructor(private val changePassw } .executeBy(taskExecutor) } + + override fun deactivateAccount(password: String, eraseAllData: Boolean, callback: MatrixCallback): Cancelable { + return deactivateAccountTask + .configureWith(DeactivateAccountTask.Params(password, eraseAllData)) { + this.callback = callback + } + .executeBy(taskExecutor) + } } diff --git a/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt b/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt index c2f2959bd7..d22d80c4b3 100644 --- a/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt +++ b/vector/src/main/java/im/vector/riotx/core/di/FragmentModule.kt @@ -81,6 +81,7 @@ import im.vector.riotx.features.settings.VectorSettingsNotificationPreferenceFra import im.vector.riotx.features.settings.VectorSettingsNotificationsTroubleshootFragment import im.vector.riotx.features.settings.VectorSettingsPreferencesFragment import im.vector.riotx.features.settings.VectorSettingsSecurityPrivacyFragment +import im.vector.riotx.features.settings.account.deactivation.DeactivateAccountFragment import im.vector.riotx.features.settings.crosssigning.CrossSigningSettingsFragment import im.vector.riotx.features.settings.devices.VectorSettingsDevicesFragment import im.vector.riotx.features.settings.devtools.AccountDataFragment @@ -445,8 +446,14 @@ interface FragmentModule { @IntoMap @FragmentKey(BootstrapAccountPasswordFragment::class) fun bindBootstrapAccountPasswordFragment(fragment: BootstrapAccountPasswordFragment): Fragment + @Binds @IntoMap @FragmentKey(BootstrapMigrateBackupFragment::class) fun bindBootstrapMigrateBackupFragment(fragment: BootstrapMigrateBackupFragment): Fragment + + @Binds + @IntoMap + @FragmentKey(DeactivateAccountFragment::class) + fun bindDeactivateAccountFragment(fragment: DeactivateAccountFragment): Fragment } diff --git a/vector/src/main/java/im/vector/riotx/features/MainActivity.kt b/vector/src/main/java/im/vector/riotx/features/MainActivity.kt index bc5a1aff95..9c5569f66d 100644 --- a/vector/src/main/java/im/vector/riotx/features/MainActivity.kt +++ b/vector/src/main/java/im/vector/riotx/features/MainActivity.kt @@ -49,6 +49,7 @@ data class MainActivityArgs( val clearCache: Boolean = false, val clearCredentials: Boolean = false, val isUserLoggedOut: Boolean = false, + val isAccountDeactivated: Boolean = false, val isSoftLogout: Boolean = false ) : Parcelable @@ -110,6 +111,7 @@ class MainActivity : VectorBaseActivity() { clearCache = argsFromIntent?.clearCache ?: false, clearCredentials = argsFromIntent?.clearCredentials ?: false, isUserLoggedOut = argsFromIntent?.isUserLoggedOut ?: false, + isAccountDeactivated = argsFromIntent?.isAccountDeactivated ?: false, isSoftLogout = argsFromIntent?.isSoftLogout ?: false ) } @@ -122,7 +124,7 @@ class MainActivity : VectorBaseActivity() { } when { args.clearCredentials -> session.signOut( - !args.isUserLoggedOut, + !args.isUserLoggedOut && !args.isAccountDeactivated, object : MatrixCallback { override fun onSuccess(data: Unit) { Timber.w("SIGN_OUT: success, start app") @@ -182,16 +184,16 @@ class MainActivity : VectorBaseActivity() { private fun startNextActivityAndFinish() { val intent = when { args.clearCredentials - && !args.isUserLoggedOut -> - // User has explicitly asked to log out + && (!args.isUserLoggedOut || args.isAccountDeactivated) -> + // User has explicitly asked to log out or deactivated his account LoginActivity.newIntent(this, null) - args.isSoftLogout -> + args.isSoftLogout -> // The homeserver has invalidated the token, with a soft logout SoftLogoutActivity.newIntent(this) - args.isUserLoggedOut -> + args.isUserLoggedOut -> // the homeserver has invalidated the token (password changed, device deleted, other security reasons) SignedOutActivity.newIntent(this) - sessionHolder.hasActiveSession() -> + sessionHolder.hasActiveSession() -> // We have a session. // Check it can be opened if (sessionHolder.getActiveSession().isOpenable) { @@ -200,7 +202,7 @@ class MainActivity : VectorBaseActivity() { // The token is still invalid SoftLogoutActivity.newIntent(this) } - else -> + else -> // First start, or no active session LoginActivity.newIntent(this, null) } diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt index f0a5a8ace8..e765f961dd 100755 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorPreferences.kt @@ -159,7 +159,6 @@ class VectorPreferences @Inject constructor(private val context: Context) { private const val DID_ASK_TO_IGNORE_BATTERY_OPTIMIZATIONS_KEY = "DID_ASK_TO_IGNORE_BATTERY_OPTIMIZATIONS_KEY" private const val DID_MIGRATE_TO_NOTIFICATION_REWORK = "DID_MIGRATE_TO_NOTIFICATION_REWORK" private const val DID_ASK_TO_USE_ANALYTICS_TRACKING_KEY = "DID_ASK_TO_USE_ANALYTICS_TRACKING_KEY" - const val SETTINGS_DEACTIVATE_ACCOUNT_KEY = "SETTINGS_DEACTIVATE_ACCOUNT_KEY" private const val SETTINGS_DISPLAY_ALL_EVENTS_KEY = "SETTINGS_DISPLAY_ALL_EVENTS_KEY" private const val MEDIA_SAVING_3_DAYS = 0 diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt index 5db14fdbd2..6d00f02c97 100755 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsActivity.kt @@ -20,6 +20,7 @@ import android.content.Intent import androidx.fragment.app.FragmentManager import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat +import im.vector.matrix.android.api.failure.GlobalError import im.vector.matrix.android.api.session.Session import im.vector.riotx.R import im.vector.riotx.core.di.ScreenComponent @@ -43,6 +44,8 @@ class VectorSettingsActivity : VectorBaseActivity(), private var keyToHighlight: String? = null + var ignoreInvalidTokenError = false + @Inject lateinit var session: Session override fun injectWith(injector: ScreenComponent) { @@ -57,7 +60,7 @@ class VectorSettingsActivity : VectorBaseActivity(), when (intent.getIntExtra(EXTRA_DIRECT_ACCESS, EXTRA_DIRECT_ACCESS_ROOT)) { EXTRA_DIRECT_ACCESS_ADVANCED_SETTINGS -> replaceFragment(R.id.vector_settings_page, VectorSettingsAdvancedSettingsFragment::class.java, null, FRAGMENT_TAG) - EXTRA_DIRECT_ACCESS_SECURITY_PRIVACY -> + EXTRA_DIRECT_ACCESS_SECURITY_PRIVACY -> replaceFragment(R.id.vector_settings_page, VectorSettingsSecurityPrivacyFragment::class.java, null, FRAGMENT_TAG) else -> replaceFragment(R.id.vector_settings_page, VectorSettingsRootFragment::class.java, null, FRAGMENT_TAG) @@ -110,6 +113,14 @@ class VectorSettingsActivity : VectorBaseActivity(), return keyToHighlight } + override fun handleInvalidToken(globalError: GlobalError.InvalidToken) { + if (ignoreInvalidTokenError) { + Timber.w("Ignoring invalid token global error") + } else { + super.handleInvalidToken(globalError) + } + } + companion object { fun getIntent(context: Context, directAccess: Int) = Intent(context, VectorSettingsActivity::class.java) .apply { putExtra(EXTRA_DIRECT_ACCESS, directAccess) } diff --git a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt index f754064fbc..802cf7b33f 100644 --- a/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt +++ b/vector/src/main/java/im/vector/riotx/features/settings/VectorSettingsGeneralFragment.kt @@ -234,19 +234,6 @@ class VectorSettingsGeneralFragment : VectorSettingsBaseFragment() { false } - - // Deactivate account section - - // deactivate account - findPreference(VectorPreferences.SETTINGS_DEACTIVATE_ACCOUNT_KEY)!! - .onPreferenceClickListener = Preference.OnPreferenceClickListener { - activity?.let { - notImplemented() - // TODO startActivity(DeactivateAccountActivity.getIntent(it)) - } - - false - } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { diff --git a/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt new file mode 100644 index 0000000000..487d913b7e --- /dev/null +++ b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountFragment.kt @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2020 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.riotx.features.settings.account.deactivation + +import android.content.Context +import android.os.Bundle +import android.view.View +import com.airbnb.mvrx.fragmentViewModel +import com.airbnb.mvrx.withState +import com.jakewharton.rxbinding3.widget.textChanges +import im.vector.riotx.R +import im.vector.riotx.core.extensions.exhaustive +import im.vector.riotx.core.extensions.showPassword +import im.vector.riotx.core.platform.VectorBaseActivity +import im.vector.riotx.core.platform.VectorBaseFragment +import im.vector.riotx.features.MainActivity +import im.vector.riotx.features.MainActivityArgs +import im.vector.riotx.features.settings.VectorSettingsActivity +import kotlinx.android.synthetic.main.fragment_deactivate_account.* +import javax.inject.Inject + +class DeactivateAccountFragment @Inject constructor( + val viewModelFactory: DeactivateAccountViewModel.Factory +) : VectorBaseFragment() { + + private val viewModel: DeactivateAccountViewModel by fragmentViewModel() + + override fun getLayoutResId() = R.layout.fragment_deactivate_account + + override fun onResume() { + super.onResume() + (activity as? VectorBaseActivity)?.supportActionBar?.setTitle(R.string.deactivate_account_title) + } + + private var settingsActivity: VectorSettingsActivity? = null + + override fun onAttach(context: Context) { + super.onAttach(context) + settingsActivity = context as? VectorSettingsActivity + } + + override fun onDetach() { + super.onDetach() + settingsActivity = null + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + setupUi() + setupViewListeners() + observeViewEvents() + } + + private fun setupUi() { + deactivateAccountPassword.textChanges() + .subscribe { + deactivateAccountPasswordTil.error = null + deactivateAccountSubmit.isEnabled = it.isNotBlank() + } + .disposeOnDestroyView() + } + + private fun setupViewListeners() { + deactivateAccountPasswordReveal.setOnClickListener { + viewModel.handle(DeactivateAccountAction.TogglePassword) + } + + deactivateAccountCancel.setOnClickListener { + (activity as? VectorBaseActivity)?.onBackPressed() + } + + deactivateAccountSubmit.setOnClickListener { + viewModel.handle(DeactivateAccountAction.DeactivateAccount( + deactivateAccountPassword.text.toString(), + deactivateAccountEraseCheckbox.isChecked)) + } + } + + private fun observeViewEvents() { + viewModel.observeViewEvents { + when (it) { + is DeactivateAccountViewEvents.Loading -> { + settingsActivity?.ignoreInvalidTokenError = true + showLoadingDialog(it.message) + } + DeactivateAccountViewEvents.EmptyPassword -> { + settingsActivity?.ignoreInvalidTokenError = false + deactivateAccountPasswordTil.error = getString(R.string.error_empty_field_your_password) + } + DeactivateAccountViewEvents.InvalidPassword -> { + settingsActivity?.ignoreInvalidTokenError = false + deactivateAccountPasswordTil.error = getString(R.string.settings_fail_to_update_password_invalid_current_password) + } + is DeactivateAccountViewEvents.OtherFailure -> { + settingsActivity?.ignoreInvalidTokenError = false + displayErrorDialog(it.throwable) + } + DeactivateAccountViewEvents.Done -> + MainActivity.restartApp(activity!!, MainActivityArgs(clearCredentials = true, isAccountDeactivated = true)) + + }.exhaustive + } + } + + override fun invalidate() = withState(viewModel) { state -> + deactivateAccountPassword.showPassword(state.passwordShown) + deactivateAccountPasswordReveal.setImageResource(if (state.passwordShown) R.drawable.ic_eye_closed_black else R.drawable.ic_eye_black) + } +} diff --git a/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt new file mode 100644 index 0000000000..4e7f7252e2 --- /dev/null +++ b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewEvents.kt @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package im.vector.riotx.features.settings.account.deactivation + +import im.vector.riotx.core.platform.VectorViewEvents + +/** + * Transient events for deactivate account settings screen + */ +sealed class DeactivateAccountViewEvents : VectorViewEvents { + data class Loading(val message: CharSequence? = null) : DeactivateAccountViewEvents() + object EmptyPassword : DeactivateAccountViewEvents() + object InvalidPassword : DeactivateAccountViewEvents() + data class OtherFailure(val throwable: Throwable) : DeactivateAccountViewEvents() + object Done : DeactivateAccountViewEvents() +} diff --git a/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt new file mode 100644 index 0000000000..adfc9ff5ae --- /dev/null +++ b/vector/src/main/java/im/vector/riotx/features/settings/account/deactivation/DeactivateAccountViewModel.kt @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 New Vector Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package im.vector.riotx.features.settings.account.deactivation + +import com.airbnb.mvrx.FragmentViewModelContext +import com.airbnb.mvrx.MvRxState +import com.airbnb.mvrx.MvRxViewModelFactory +import com.airbnb.mvrx.ViewModelContext +import com.squareup.inject.assisted.Assisted +import com.squareup.inject.assisted.AssistedInject +import im.vector.matrix.android.api.MatrixCallback +import im.vector.matrix.android.api.failure.isInvalidPassword +import im.vector.matrix.android.api.session.Session +import im.vector.riotx.core.extensions.exhaustive +import im.vector.riotx.core.platform.VectorViewModel +import im.vector.riotx.core.platform.VectorViewModelAction + +data class DeactivateAccountViewState( + val passwordShown: Boolean = false +) : MvRxState + +sealed class DeactivateAccountAction : VectorViewModelAction { + object TogglePassword : DeactivateAccountAction() + data class DeactivateAccount(val password: String, val eraseAllData: Boolean) : DeactivateAccountAction() +} + +class DeactivateAccountViewModel @AssistedInject constructor(@Assisted private val initialState: DeactivateAccountViewState, + private val session: Session) + : VectorViewModel(initialState) { + + @AssistedInject.Factory + interface Factory { + fun create(initialState: DeactivateAccountViewState): DeactivateAccountViewModel + } + + override fun handle(action: DeactivateAccountAction) { + when (action) { + DeactivateAccountAction.TogglePassword -> handleTogglePassword() + is DeactivateAccountAction.DeactivateAccount -> handleDeactivateAccount(action) + }.exhaustive + } + + private fun handleTogglePassword() = withState { + setState { + copy(passwordShown = !passwordShown) + } + } + + private fun handleDeactivateAccount(action: DeactivateAccountAction.DeactivateAccount) { + if (action.password.isEmpty()) { + _viewEvents.post(DeactivateAccountViewEvents.EmptyPassword) + return + } + + _viewEvents.post(DeactivateAccountViewEvents.Loading()) + + session.deactivateAccount(action.password, action.eraseAllData, object : MatrixCallback { + override fun onSuccess(data: Unit) { + _viewEvents.post(DeactivateAccountViewEvents.Done) + } + + override fun onFailure(failure: Throwable) { + if (failure.isInvalidPassword()) { + _viewEvents.post(DeactivateAccountViewEvents.InvalidPassword) + } else { + _viewEvents.post(DeactivateAccountViewEvents.OtherFailure(failure)) + } + } + }) + } + + companion object : MvRxViewModelFactory { + + @JvmStatic + override fun create(viewModelContext: ViewModelContext, state: DeactivateAccountViewState): DeactivateAccountViewModel? { + val fragment: DeactivateAccountFragment = (viewModelContext as FragmentViewModelContext).fragment() + return fragment.viewModelFactory.create(state) + } + } +} diff --git a/vector/src/main/res/layout/fragment_deactivate_account.xml b/vector/src/main/res/layout/fragment_deactivate_account.xml new file mode 100644 index 0000000000..aca8adf12d --- /dev/null +++ b/vector/src/main/res/layout/fragment_deactivate_account.xml @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + +