diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentSingleKeyWeakPassphraseTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentSingleKeyWeakPassphraseTest.kt index 297c062a1a..d0e6fea67f 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentSingleKeyWeakPassphraseTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentSingleKeyWeakPassphraseTest.kt @@ -5,15 +5,9 @@ package com.flowcrypt.email.ui.activity -import android.app.Activity -import android.app.Instrumentation -import android.content.ComponentName -import androidx.lifecycle.Lifecycle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.intent.Intents.intending -import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText @@ -29,7 +23,6 @@ import com.flowcrypt.email.rules.ClearAppSettingsRule import com.flowcrypt.email.rules.RetryRule import com.flowcrypt.email.rules.ScreenshotTestRule import com.flowcrypt.email.ui.activity.base.BaseBackupKeysFragmentTest -import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -76,34 +69,6 @@ class BackupKeysFragmentSingleKeyWeakPassphraseTest : BaseBackupKeysFragmentTest .check(matches(isDisplayed())) } - @Test - @DependsOnMailServer - @NotReadyForCI - fun testFixWeakPasswordForEmailOption() { - onView(withId(R.id.btBackup)) - .check(matches(isDisplayed())) - .perform(click()) - intending(hasComponent(ComponentName(getTargetContext(), ChangePassPhraseActivity::class.java))) - .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null)) - checkIsSnackbarDisplayedAndClick(getResString(R.string.pass_phrase_is_too_weak)) - assertTrue(activityScenarioRule.scenario.state == Lifecycle.State.RESUMED) - } - - @Test - fun testFixWeakPasswordForDownloadOption() { - onView(withId(R.id.rBDownloadOption)) - .check(matches(isDisplayed())) - .perform(click()) - intendingFileChoose(File("")) - onView(withId(R.id.btBackup)) - .check(matches(isDisplayed())) - .perform(click()) - intending(hasComponent(ComponentName(getTargetContext(), ChangePassPhraseActivity::class.java))) - .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null)) - checkIsSnackbarDisplayedAndClick(getResString(R.string.pass_phrase_is_too_weak)) - assertTrue(activityScenarioRule.scenario.state == Lifecycle.State.RESUMED) - } - @Test @DependsOnMailServer @NotReadyForCI diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentTwoKeysDiffPassphrasesTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentTwoKeysDiffPassphrasesTest.kt index 0b5e849752..fe05926579 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentTwoKeysDiffPassphrasesTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/BackupKeysFragmentTwoKeysDiffPassphrasesTest.kt @@ -5,15 +5,10 @@ package com.flowcrypt.email.ui.activity -import android.app.Activity -import android.app.Instrumentation -import android.content.ComponentName import androidx.lifecycle.Lifecycle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches -import androidx.test.espresso.intent.Intents.intending -import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -70,8 +65,8 @@ class BackupKeysFragmentTwoKeysDiffPassphrasesTest : BaseBackupKeysFragmentTest( onView(withId(R.id.btBackup)) .check(matches(isDisplayed())) .perform(click()) - intending(hasComponent(ComponentName(getTargetContext(), ChangePassPhraseActivity::class.java))) - .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null)) + /*intending(hasComponent(ComponentName(getTargetContext(), ChangePassPhraseActivity::class.java))) + .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))*/ checkIsSnackbarDisplayedAndClick(getResString(R.string.different_pass_phrases)) assertTrue(activityScenarioRule.scenario.state == Lifecycle.State.RESUMED) } @@ -85,8 +80,8 @@ class BackupKeysFragmentTwoKeysDiffPassphrasesTest : BaseBackupKeysFragmentTest( onView(withId(R.id.btBackup)) .check(matches(isDisplayed())) .perform(click()) - intending(hasComponent(ComponentName(getTargetContext(), ChangePassPhraseActivity::class.java))) - .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null)) + /*intending(hasComponent(ComponentName(getTargetContext(), ChangePassPhraseActivity::class.java))) + .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))*/ checkIsSnackbarDisplayedAndClick(getResString(R.string.different_pass_phrases)) assertTrue(activityScenarioRule.scenario.state == Lifecycle.State.RESUMED) } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/ChangePassPhraseActivityTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/ChangePassphraseOfImportedKeysFragmentTest.kt similarity index 52% rename from FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/ChangePassPhraseActivityTest.kt rename to FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/ChangePassphraseOfImportedKeysFragmentTest.kt index 02ed4b6e20..354fc123c6 100644 --- a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/ChangePassPhraseActivityTest.kt +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/ChangePassphraseOfImportedKeysFragmentTest.kt @@ -5,26 +5,23 @@ package com.flowcrypt.email.ui.activity -import android.app.Activity +import android.os.Bundle import androidx.test.espresso.Espresso.onView -import androidx.test.espresso.action.ViewActions.click -import androidx.test.espresso.action.ViewActions.closeSoftKeyboard -import androidx.test.espresso.action.ViewActions.replaceText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed -import androidx.test.espresso.matcher.ViewMatchers.withId +import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.rules.activityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.flowcrypt.email.R +import com.flowcrypt.email.base.BaseTest import com.flowcrypt.email.junit.annotations.DependsOnMailServer import com.flowcrypt.email.rules.AddAccountToDatabaseRule import com.flowcrypt.email.rules.AddPrivateKeyToDatabaseRule import com.flowcrypt.email.rules.ClearAppSettingsRule -import com.flowcrypt.email.rules.RetryRule import com.flowcrypt.email.rules.ScreenshotTestRule -import com.flowcrypt.email.ui.activity.base.BasePassphraseActivityTest -import org.junit.Assert +import com.flowcrypt.email.ui.activity.settings.SettingsActivity +import com.flowcrypt.email.util.TestGeneralUtil import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -33,43 +30,47 @@ import org.junit.runner.RunWith /** * @author Denis Bondarenko - * Date: 3/13/19 - * Time: 12:15 PM - * E-mail: DenBond7@gmail.com + * Date: 6/29/21 + * Time: 6:09 PM + * E-mail: DenBond7@gmail.com */ @MediumTest @RunWith(AndroidJUnit4::class) -class ChangePassPhraseActivityTest : BasePassphraseActivityTest() { +class ChangePassphraseOfImportedKeysFragmentTest : BaseTest() { private val addAccountToDatabaseRule = AddAccountToDatabaseRule() - override val useIntents: Boolean = true - override val activityScenarioRule = activityScenarioRule() + override val activityScenarioRule = activityScenarioRule( + TestGeneralUtil.genIntentForNavigationComponent( + uri = "flowcrypt://email.flowcrypt.com/settings/security/change_passphrase", + extras = Bundle().apply { + putInt("popBackStackIdIfSuccess", R.id.securitySettingsFragment) + putString("title", getResString(R.string.pass_phrase_changed)) + putString("subTitle", getResString(R.string.passphrase_was_changed)) + putString("passphrase", PERFECT_PASSWORD) + putParcelable("accountEntity", addAccountToDatabaseRule.account) + } + ) + ) @get:Rule var ruleChain: TestRule = RuleChain .outerRule(ClearAppSettingsRule()) .around(addAccountToDatabaseRule) .around(AddPrivateKeyToDatabaseRule()) - .around(RetryRule.DEFAULT) + //.around(RetryRule.DEFAULT) .around(activityScenarioRule) .around(ScreenshotTestRule()) @Test @DependsOnMailServer - fun testUseCorrectPassPhrase() { - onView(withId(R.id.editTextKeyPassword)) + fun testShowSuccess() { + onView(withText(getResString(R.string.pass_phrase_changed))) .check(matches(isDisplayed())) - .perform(replaceText(PERFECT_PASSWORD), closeSoftKeyboard()) - onView(withId(R.id.buttonSetPassPhrase)) + onView(withText(getResString(R.string.passphrase_was_changed))) .check(matches(isDisplayed())) - .perform(click()) - onView(withId(R.id.editTextKeyPasswordSecond)) - .check(matches(isDisplayed())) - .perform(replaceText(PERFECT_PASSWORD), closeSoftKeyboard()) - onView(withId(R.id.buttonConfirmPassPhrases)) - .check(matches(isDisplayed())) - .perform(click()) + } - Assert.assertTrue(activityScenarioRule.scenario.result.resultCode == Activity.RESULT_OK) + companion object { + internal const val PERFECT_PASSWORD = "unconventional blueberry unlike any other" } } diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/CheckPassphraseStrengthFragmentTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/CheckPassphraseStrengthFragmentTest.kt new file mode 100644 index 0000000000..a67da573e9 --- /dev/null +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/CheckPassphraseStrengthFragmentTest.kt @@ -0,0 +1,153 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: DenBond7 + */ + +package com.flowcrypt.email.ui.activity + +import android.os.Bundle +import androidx.test.espresso.Espresso.onView +import androidx.test.espresso.action.ViewActions.clearText +import androidx.test.espresso.action.ViewActions.click +import androidx.test.espresso.action.ViewActions.closeSoftKeyboard +import androidx.test.espresso.action.ViewActions.replaceText +import androidx.test.espresso.assertion.ViewAssertions.matches +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import androidx.test.espresso.matcher.ViewMatchers.withId +import androidx.test.espresso.matcher.ViewMatchers.withText +import androidx.test.ext.junit.rules.activityScenarioRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.MediumTest +import com.flowcrypt.email.R +import com.flowcrypt.email.base.BaseTest +import com.flowcrypt.email.rules.AddAccountToDatabaseRule +import com.flowcrypt.email.rules.AddPrivateKeyToDatabaseRule +import com.flowcrypt.email.rules.ClearAppSettingsRule +import com.flowcrypt.email.rules.RetryRule +import com.flowcrypt.email.rules.ScreenshotTestRule +import com.flowcrypt.email.ui.activity.settings.SettingsActivity +import com.flowcrypt.email.util.TestGeneralUtil +import org.hamcrest.Matchers.startsWith +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.rules.TestRule +import org.junit.runner.RunWith +import java.util.Locale + +/** + * @author Denis Bondarenko + * Date: 3/13/19 + * Time: 12:15 PM + * E-mail: DenBond7@gmail.com + */ +@MediumTest +@RunWith(AndroidJUnit4::class) +class CheckPassphraseStrengthFragmentTest : BaseTest() { + private val addAccountToDatabaseRule = AddAccountToDatabaseRule() + + override val activityScenarioRule = activityScenarioRule( + TestGeneralUtil.genIntentForNavigationComponent( + uri = "flowcrypt://email.flowcrypt.com/settings/security/check_passphrase", + extras = Bundle().apply { + putInt("popBackStackIdIfSuccess", R.id.securitySettingsFragment) + putString("title", getResString(R.string.change_pass_phrase)) + } + ) + ) + + @get:Rule + var ruleChain: TestRule = RuleChain + .outerRule(ClearAppSettingsRule()) + .around(addAccountToDatabaseRule) + .around(AddPrivateKeyToDatabaseRule()) + .around(RetryRule.DEFAULT) + .around(activityScenarioRule) + .around(ScreenshotTestRule()) + + @Test + fun testShowDialogWithPasswordRecommendation() { + onView(withId(R.id.iBShowPasswordHint)) + .check(matches(isDisplayed())) + .perform(click()) + onView(withId(R.id.webView)) + .check(matches(isDisplayed())) + } + + @Test + fun testEmptyPassPhrase() { + closeSoftKeyboard() + onView(withId(R.id.btSetPassphrase)) + .check(matches(isDisplayed())) + .perform(click()) + + checkIsNonEmptyHintShown() + } + + @Test + fun testChangingQualityOfPassPhrase() { + val passPhrases = arrayOf( + WEAK_PASSWORD, POOR_PASSWORD, REASONABLE_PASSWORD, GOOD_PASSWORD, + GREAT_PASSWORD, PERFECT_PASSWORD + ) + + val degreeOfReliabilityOfPassPhrase = arrayOf( + getResString(R.string.password_quality_weak), + getResString(R.string.password_quality_poor), + getResString(R.string.password_quality_reasonable), + getResString(R.string.password_quality_good), + getResString(R.string.password_quality_great), + getResString(R.string.password_quality_perfect) + ) + + for (i in passPhrases.indices) { + onView(withId(R.id.eTPassphrase)) + .check(matches(isDisplayed())) + .perform(replaceText(passPhrases[i])) + onView(withId(R.id.tVPassphraseQuality)) + .check(matches(withText(startsWith(degreeOfReliabilityOfPassPhrase[i].toUpperCase(Locale.getDefault()))))) + onView(withId(R.id.eTPassphrase)) + .check(matches(isDisplayed())) + .perform(clearText()) + } + } + + @Test + fun testShowDialogAboutBadPassPhrase() { + val badPassPhrases = arrayOf(WEAK_PASSWORD, POOR_PASSWORD) + + for (passPhrase in badPassPhrases) { + onView(withId(R.id.eTPassphrase)) + .check(matches(isDisplayed())) + .perform(replaceText(passPhrase), closeSoftKeyboard()) + onView(withId(R.id.btSetPassphrase)) + .check(matches(isDisplayed())) + .perform(click()) + onView(withText(getResString(R.string.select_stronger_pass_phrase))) + .check(matches(isDisplayed())) + onView(withId(android.R.id.button1)) + .check(matches(isDisplayed())) + .perform(click()) + onView(withId(R.id.eTPassphrase)) + .check(matches(isDisplayed())) + .perform(clearText()) + } + } + + private fun checkIsNonEmptyHintShown() { + onView(withText(getResString(R.string.passphrase_must_be_non_empty))) + .check(matches(isDisplayed())) + onView(withId(com.google.android.material.R.id.snackbar_action)) + .check(matches(isDisplayed())) + .perform(click()) + } + + companion object { + internal const val WEAK_PASSWORD = "weak" + internal const val POOR_PASSWORD = "weak, perfect, great" + internal const val REASONABLE_PASSWORD = "weak, poor, reasonable" + internal const val GOOD_PASSWORD = "weak, poor, good," + internal const val GREAT_PASSWORD = "weak, poor, great, good" + internal const val PERFECT_PASSWORD = "unconventional blueberry unlike any other" + } +} diff --git a/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/RecheckProvidedPassphraseFragmentTest.kt b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/RecheckProvidedPassphraseFragmentTest.kt new file mode 100644 index 0000000000..62e809ccd3 --- /dev/null +++ b/FlowCrypt/src/androidTest/java/com/flowcrypt/email/ui/activity/RecheckProvidedPassphraseFragmentTest.kt @@ -0,0 +1,94 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: DenBond7 + */ + +package com.flowcrypt.email.ui.activity + +import android.os.Bundle +import androidx.test.espresso.Espresso.onView +import androidx.test.espresso.action.ViewActions.click +import androidx.test.espresso.action.ViewActions.closeSoftKeyboard +import androidx.test.espresso.action.ViewActions.replaceText +import androidx.test.espresso.assertion.ViewAssertions.matches +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import androidx.test.espresso.matcher.ViewMatchers.withId +import androidx.test.espresso.matcher.ViewMatchers.withText +import androidx.test.ext.junit.rules.activityScenarioRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.MediumTest +import com.flowcrypt.email.R +import com.flowcrypt.email.base.BaseTest +import com.flowcrypt.email.rules.AddAccountToDatabaseRule +import com.flowcrypt.email.rules.AddPrivateKeyToDatabaseRule +import com.flowcrypt.email.rules.ClearAppSettingsRule +import com.flowcrypt.email.rules.RetryRule +import com.flowcrypt.email.rules.ScreenshotTestRule +import com.flowcrypt.email.ui.activity.settings.SettingsActivity +import com.flowcrypt.email.util.TestGeneralUtil +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.rules.TestRule +import org.junit.runner.RunWith + +/** + * @author Denis Bondarenko + * Date: 6/29/21 + * Time: 3:54 PM + * E-mail: DenBond7@gmail.com + */ +@MediumTest +@RunWith(AndroidJUnit4::class) +class RecheckProvidedPassphraseFragmentTest : BaseTest() { + private val addAccountToDatabaseRule = AddAccountToDatabaseRule() + + override val activityScenarioRule = activityScenarioRule( + TestGeneralUtil.genIntentForNavigationComponent( + uri = "flowcrypt://email.flowcrypt.com/settings/security/recheck_passphrase", + extras = Bundle().apply { + putInt("popBackStackIdIfSuccess", R.id.securitySettingsFragment) + putString("title", getResString(R.string.change_pass_phrase)) + putString("passphrase", PERFECT_PASSWORD) + } + ) + ) + + @get:Rule + var ruleChain: TestRule = RuleChain + .outerRule(ClearAppSettingsRule()) + .around(addAccountToDatabaseRule) + .around(AddPrivateKeyToDatabaseRule()) + .around(RetryRule.DEFAULT) + .around(activityScenarioRule) + .around(ScreenshotTestRule()) + + @Test + fun testEmptyPassphrase() { + onView(withId(R.id.btConfirmPassphrase)) + .perform(click()) + onView(withText(getResString(R.string.passphrase_must_be_non_empty))) + .check(matches(isDisplayed())) + onView(withId(com.google.android.material.R.id.snackbar_action)) + .check(matches(isDisplayed())) + .perform(click()) + } + + @Test + fun testShowMsgMismatchOfPassphrase() { + onView(withId(R.id.eTRepeatedPassphrase)) + .check(matches(isDisplayed())) + .perform(replaceText("some text"), closeSoftKeyboard()) + onView(withId(R.id.btConfirmPassphrase)) + .perform(click()) + onView(withText(getResString(R.string.pass_phrases_do_not_match))) + .check(matches(isDisplayed())) + onView(withId(com.google.android.material.R.id.snackbar_action)) + .check(matches(isDisplayed())).perform(click()) + } + + companion object { + internal const val GREAT_PASSWORD = "weak, poor, great, good" + internal const val PERFECT_PASSWORD = "unconventional blueberry unlike any other" + } +} diff --git a/FlowCrypt/src/main/AndroidManifest.xml b/FlowCrypt/src/main/AndroidManifest.xml index 4f912dbff3..2fba9ff57e 100644 --- a/FlowCrypt/src/main/AndroidManifest.xml +++ b/FlowCrypt/src/main/AndroidManifest.xml @@ -175,10 +175,6 @@ android:label="@string/add_contact" android:screenOrientation="portrait" /> - - diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/LoadPrivateKeysViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/LoadPrivateKeysViewModel.kt index 49b08db33b..b679fcf71f 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/LoadPrivateKeysViewModel.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/LoadPrivateKeysViewModel.kt @@ -49,12 +49,12 @@ class LoadPrivateKeysViewModel(application: Application) : BaseAndroidViewModel( fun fetchAvailableKeys(accountEntity: AccountEntity?) { viewModelScope.launch { val context: Context = getApplication() - privateKeysLiveData.postValue(Result.loading(progressMsg = context.getString(R.string.searching_backups))) + privateKeysLiveData.value = + Result.loading(progressMsg = context.getString(R.string.searching_backups)) if (accountEntity != null) { - val result = fetchKeys(accountEntity) - privateKeysLiveData.postValue(result) + privateKeysLiveData.value = fetchKeys(accountEntity) } else { - privateKeysLiveData.postValue(Result.exception(NullPointerException("AccountEntity is null!"))) + privateKeysLiveData.value = Result.exception(NullPointerException("AccountEntity is null!")) } } } @@ -109,7 +109,8 @@ class LoadPrivateKeysViewModel(application: Application) : BaseAndroidViewModel( privateKeysLiveData.postValue( Result.loading( progressMsg = context.resources - .getQuantityString(R.plurals.found_folder, folders.size, folders.size) + .getQuantityString(R.plurals.found_folder, folders.size, folders.size), + progress = 100.0 ) ) @@ -144,7 +145,8 @@ class LoadPrivateKeysViewModel(application: Application) : BaseAndroidViewModel( R.string.searching_in_folders, index, folders.size - ) + ), + progress = (index / folders.size).toDouble() ) ) } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt index 37ed3da37b..71c7708cb5 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/PrivateKeysViewModel.kt @@ -86,16 +86,13 @@ class PrivateKeysViewModel(application: Application) : BaseNodeApiViewModel(appl fun changePassphrase(newPassphrase: Passphrase) { viewModelScope.launch { + changePassphraseLiveData.value = Result.loading() try { - changePassphraseLiveData.value = Result.loading() - if (newPassphrase.isEmpty) { throw IllegalStateException("new Passphrase can't be empty") } - val account = roomDatabase.accountDao().getActiveAccountSuspend() - requireNotNull(account) - + val account = requireNotNull(roomDatabase.accountDao().getActiveAccountSuspend()) val rawKeys = keysStorage.getRawKeys() if (rawKeys.isEmpty()) { @@ -152,22 +149,13 @@ class PrivateKeysViewModel(application: Application) : BaseNodeApiViewModel(appl fun saveBackupsToInbox() { viewModelScope.launch { saveBackupToInboxLiveData.value = Result.loading() - withContext(Dispatchers.IO) { - try { - val account = - getAccountEntityWithDecryptedInfo(roomDatabase.accountDao().getActiveAccountSuspend()) - requireNotNull(account) - - val sess = OpenStoreHelper.getAccountSess(getApplication(), account) - val transport = SmtpProtocolUtil.prepareSmtpTransport(getApplication(), sess, account) - val msg = EmailUtil.genMsgWithAllPrivateKeys(getApplication(), account, sess) - transport.sendMessage(msg, msg.allRecipients) - saveBackupToInboxLiveData.postValue(Result.success(true)) - } catch (e: Exception) { - e.printStackTrace() - ExceptionUtil.handleError(e) - saveBackupToInboxLiveData.postValue(Result.exception(e)) - } + try { + saveBackupsToInboxInternal() + saveBackupToInboxLiveData.value = Result.success(true) + } catch (e: Exception) { + e.printStackTrace() + ExceptionUtil.handleError(e) + saveBackupToInboxLiveData.value = Result.exception(e) } } } @@ -175,21 +163,13 @@ class PrivateKeysViewModel(application: Application) : BaseNodeApiViewModel(appl fun saveBackupsAsFile(destinationUri: Uri) { viewModelScope.launch { saveBackupAsFileLiveData.value = Result.loading() - withContext(Dispatchers.IO) { - try { - val account = roomDatabase.accountDao().getActiveAccountSuspend() - requireNotNull(account) - - val backup = SecurityUtils.genPrivateKeysBackup(getApplication(), account) - val result = - GeneralUtil.writeFileFromStringToUri(getApplication(), destinationUri, backup) > 0 - - saveBackupAsFileLiveData.postValue(Result.success(result)) - } catch (e: Exception) { - e.printStackTrace() - ExceptionUtil.handleError(e) - saveBackupAsFileLiveData.postValue(Result.exception(e)) - } + try { + val result = saveBackupsAsFileInternal(destinationUri) + saveBackupAsFileLiveData.value = Result.success(result) + } catch (e: Exception) { + e.printStackTrace() + ExceptionUtil.handleError(e) + saveBackupAsFileLiveData.value = Result.exception(e) } } } @@ -628,6 +608,32 @@ class PrivateKeysViewModel(application: Application) : BaseNodeApiViewModel(appl } } + private suspend fun saveBackupsToInboxInternal() = withContext(Dispatchers.IO) { + val account = requireNotNull( + getAccountEntityWithDecryptedInfo( + roomDatabase.accountDao().getActiveAccountSuspend() + ) + ) + + val sess = OpenStoreHelper.getAccountSess(getApplication(), account) + val transport = SmtpProtocolUtil.prepareSmtpTransport(getApplication(), sess, account) + val msg = EmailUtil.genMsgWithAllPrivateKeys(getApplication(), account, sess) + transport.sendMessage(msg, msg.allRecipients) + } + + private suspend fun saveBackupsAsFileInternal(destinationUri: Uri) = + withContext(Dispatchers.IO) { + val account = roomDatabase.accountDao().getActiveAccountSuspend() + requireNotNull(account) + + val backup = SecurityUtils.genPrivateKeysBackup(getApplication(), account) + return@withContext GeneralUtil.writeFileFromStringToUri( + getApplication(), + destinationUri, + backup + ) > 0 + } + companion object { /** * Max size of a key is 256k. diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/ChangePassPhraseActivity.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/ChangePassPhraseActivity.kt deleted file mode 100644 index 2a4f348688..0000000000 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/ChangePassPhraseActivity.kt +++ /dev/null @@ -1,198 +0,0 @@ -/* - * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com - * Contributors: DenBond7 - */ - -package com.flowcrypt.email.ui.activity - -import android.app.Activity -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.os.Bundle -import android.view.View -import android.widget.Toast -import androidx.activity.viewModels -import com.flowcrypt.email.R -import com.flowcrypt.email.api.retrofit.response.base.Result -import com.flowcrypt.email.database.entity.AccountEntity -import com.flowcrypt.email.extensions.decrementSafely -import com.flowcrypt.email.extensions.incrementSafely -import com.flowcrypt.email.jetpack.viewmodel.LoadPrivateKeysViewModel -import com.flowcrypt.email.jetpack.viewmodel.PrivateKeysViewModel -import com.flowcrypt.email.ui.activity.base.BasePassPhraseManagerActivity -import com.flowcrypt.email.ui.notifications.SystemNotificationManager -import com.flowcrypt.email.util.UIUtil -import org.pgpainless.util.Passphrase - -/** - * This activity describes a logic of changing the pass phrase of all imported private keys of an active account. - * - * @author Denis Bondarenko - * Date: 05.08.2018 - * Time: 20:15 - * E-mail: DenBond7@gmail.com - */ -class ChangePassPhraseActivity : BasePassPhraseManagerActivity() { - private val loadPrivateKeysViewModel: LoadPrivateKeysViewModel by viewModels() - private val privateKeysViewModel: PrivateKeysViewModel by viewModels() - - override fun onConfirmPassPhraseSuccess() { - privateKeysViewModel.changePassphrase( - Passphrase.fromPassword(editTextKeyPassword.text.toString()) - ) - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - SystemNotificationManager(this).cancel(SystemNotificationManager.NOTIFICATION_ID_PASSPHRASE_TOO_WEAK) - setupLoadPrivateKeysViewModel() - setupPrivateKeysViewModel() - } - - override fun onBackPressed() { - if (isBackEnabled) { - super.onBackPressed() - } else { - Toast.makeText( - this, - R.string.please_wait_while_pass_phrase_will_be_changed, - Toast.LENGTH_SHORT - ).show() - } - } - - override fun onClick(v: View) { - when (v.id) { - R.id.buttonSuccess -> { - setResult(Activity.RESULT_OK) - finish() - } - - else -> super.onClick(v) - } - } - - override fun initViews() { - super.initViews() - - textViewFirstPasswordCheckTitle.setText(R.string.change_pass_phrase) - textViewSecondPasswordCheckTitle.setText(R.string.change_pass_phrase) - - textViewSuccessTitle.setText(R.string.done) - textViewSuccessSubTitle.setText(R.string.pass_phrase_changed) - btnSuccess.setText(R.string.back) - } - - private fun runBackupKeysActivity() { - isBackEnabled = true - Toast.makeText(this, R.string.back_up_updated_key, Toast.LENGTH_LONG).show() - val intent = - Intent(Intent.ACTION_VIEW, Uri.parse("flowcrypt://email.flowcrypt.com/settings/make_backup")) - startActivity(intent) - } - - private fun setupLoadPrivateKeysViewModel() { - loadPrivateKeysViewModel.privateKeysLiveData.observe(this, { - it?.let { - when (it.status) { - Result.Status.LOADING -> { - countingIdlingResource.incrementSafely() - } - - Result.Status.SUCCESS -> { - val keyDetailsList = it.data - if (keyDetailsList?.isEmpty() == true) { - runBackupKeysActivity() - } else { - privateKeysViewModel.saveBackupsToInbox() - } - countingIdlingResource.decrementSafely() - } - - Result.Status.ERROR, Result.Status.EXCEPTION -> { - runBackupKeysActivity() - countingIdlingResource.decrementSafely() - } - - else -> countingIdlingResource.decrementSafely() - } - } - }) - } - - private fun setupPrivateKeysViewModel() { - privateKeysViewModel.changePassphraseLiveData.observe(this, { - it?.let { - when (it.status) { - Result.Status.LOADING -> { - countingIdlingResource.incrementSafely() - isBackEnabled = false - UIUtil.exchangeViewVisibility(true, layoutProgress, layoutContentView) - } - - Result.Status.SUCCESS -> { - if (it.data == true) { - if (activeAccount?.isRuleExist(AccountEntity.DomainRule.NO_PRV_BACKUP) == true) { - isBackEnabled = true - Toast.makeText(this, R.string.pass_phrase_changed, Toast.LENGTH_SHORT).show() - setResult(Activity.RESULT_OK) - finish() - } else { - activeAccount?.let { accountEntity -> - loadPrivateKeysViewModel.fetchAvailableKeys(accountEntity) - } - } - } - - countingIdlingResource.decrementSafely() - } - - Result.Status.ERROR, Result.Status.EXCEPTION -> { - isBackEnabled = true - editTextKeyPasswordSecond.text = null - UIUtil.exchangeViewVisibility(false, layoutProgress, layoutContentView) - showInfoSnackbar(rootView, it.exception?.message ?: getString(R.string.unknown_error)) - - countingIdlingResource.decrementSafely() - } - - else -> countingIdlingResource.decrementSafely() - } - } - }) - - privateKeysViewModel.saveBackupToInboxLiveData.observe(this, { - it?.let { - when (it.status) { - Result.Status.LOADING -> { - countingIdlingResource.incrementSafely() - } - - Result.Status.SUCCESS -> { - isBackEnabled = true - - Toast.makeText(this, R.string.pass_phrase_changed, Toast.LENGTH_SHORT).show() - setResult(Activity.RESULT_OK) - countingIdlingResource.decrementSafely() - finish() - } - - Result.Status.ERROR, Result.Status.EXCEPTION -> { - isBackEnabled = true - runBackupKeysActivity() - countingIdlingResource.decrementSafely() - } - - else -> countingIdlingResource.decrementSafely() - } - } - }) - } - - companion object { - fun newIntent(context: Context?): Intent { - return Intent(context, ChangePassPhraseActivity::class.java) - } - } -} diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/BackupKeysFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/BackupKeysFragment.kt index 23af0fec2a..21cf7af944 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/BackupKeysFragment.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/BackupKeysFragment.kt @@ -27,7 +27,6 @@ import com.flowcrypt.email.jetpack.viewmodel.BackupsViewModel import com.flowcrypt.email.jetpack.viewmodel.PrivateKeysViewModel import com.flowcrypt.email.security.KeysStorageImpl import com.flowcrypt.email.security.SecurityUtils -import com.flowcrypt.email.ui.activity.ChangePassPhraseActivity import com.flowcrypt.email.ui.activity.fragment.base.BaseFragment import com.flowcrypt.email.ui.activity.fragment.base.ProgressBehaviour import com.flowcrypt.email.ui.activity.fragment.dialog.FixNeedPassphraseIssueDialogFragment @@ -201,7 +200,7 @@ class BackupKeysFragment : BaseFragment(), ProgressBehaviour { ) ) } - + privateKeysViewModel.saveBackupAsFileLiveData.value = Result.none() baseActivity.countingIdlingResource.decrementSafely() } @@ -236,6 +235,7 @@ class BackupKeysFragment : BaseFragment(), ProgressBehaviour { showBackupingErrorHint() } + backupsViewModel.postBackupLiveData.value = Result.none() baseActivity.countingIdlingResource.decrementSafely() } @@ -300,7 +300,13 @@ class BackupKeysFragment : BaseFragment(), ProgressBehaviour { btnName = btnName, duration = Snackbar.LENGTH_LONG ) { - startActivityForResult(ChangePassPhraseActivity.newIntent(requireContext()), 0) + navController?.navigate( + BackupKeysFragmentDirections + .actionBackupKeysFragmentToCheckPassphraseStrengthFragment( + popBackStackIdIfSuccess = navController?.currentDestination?.id ?: 0, + title = getString(R.string.change_pass_phrase) + ) + ) } } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/ChangePassphraseOfImportedKeysFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/ChangePassphraseOfImportedKeysFragment.kt new file mode 100644 index 0000000000..bfb01bd5ab --- /dev/null +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/ChangePassphraseOfImportedKeysFragment.kt @@ -0,0 +1,212 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: DenBond7 + */ + +package com.flowcrypt.email.ui.activity.fragment + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.addCallback +import androidx.fragment.app.viewModels +import androidx.navigation.fragment.navArgs +import com.flowcrypt.email.R +import com.flowcrypt.email.api.retrofit.response.base.Result +import com.flowcrypt.email.database.entity.AccountEntity +import com.flowcrypt.email.databinding.FragmentChangePassphraseOfImportedKeysBinding +import com.flowcrypt.email.extensions.decrementSafely +import com.flowcrypt.email.extensions.exceptionMsg +import com.flowcrypt.email.extensions.incrementSafely +import com.flowcrypt.email.extensions.navController +import com.flowcrypt.email.extensions.toast +import com.flowcrypt.email.jetpack.viewmodel.LoadPrivateKeysViewModel +import com.flowcrypt.email.jetpack.viewmodel.PrivateKeysViewModel +import com.flowcrypt.email.ui.activity.fragment.base.BaseFragment +import com.flowcrypt.email.ui.activity.fragment.base.ProgressBehaviour +import com.google.android.material.snackbar.Snackbar +import org.pgpainless.util.Passphrase + +/** + * @author Denis Bondarenko + * Date: 6/29/21 + * Time: 9:42 AM + * E-mail: DenBond7@gmail.com + */ +class ChangePassphraseOfImportedKeysFragment : BaseFragment(), ProgressBehaviour { + private val args by navArgs() + private var binding: FragmentChangePassphraseOfImportedKeysBinding? = null + private val loadPrivateKeysViewModel: LoadPrivateKeysViewModel by viewModels() + private val privateKeysViewModel: PrivateKeysViewModel by viewModels() + + override val progressView: View? + get() = binding?.iProgress?.root + override val contentView: View? + get() = binding?.gContent + override val statusView: View? + get() = binding?.iStatus?.root + + private var isBackEnabled = false + private var isPassphraseChanged = false + + override val contentResourceId: Int = R.layout.fragment_change_passphrase_of_imported_keys + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + requireActivity().onBackPressedDispatcher.addCallback(this) { + when { + isBackEnabled -> navigateUp() + else -> toast(R.string.processing_please_wait) + } + } + + privateKeysViewModel.changePassphrase( + Passphrase.fromPassword(args.passphrase) + ) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? + ): View? { + binding = FragmentChangePassphraseOfImportedKeysBinding.inflate(inflater, container, false) + return binding?.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + supportActionBar?.title = getString(R.string.security) + initViews() + setupPrivateKeysViewModel() + setupLoadPrivateKeysViewModel() + } + + private fun initViews() { + binding?.tVTitle?.text = args.title + binding?.tVSubTitle?.text = args.subTitle + binding?.btContinue?.setOnClickListener { + navigateUp() + } + } + + private fun navigateUp() { + if (isPassphraseChanged) { + if (navController?.popBackStack(args.popBackStackIdIfSuccess, false) == false) { + navController?.popBackStack(R.id.mainSettingsFragment, true) + } + } else { + navController?.navigateUp() + } + } + + private fun setupPrivateKeysViewModel() { + privateKeysViewModel.changePassphraseLiveData.observe(viewLifecycleOwner, { + it?.let { + when (it.status) { + Result.Status.LOADING -> { + baseActivity.countingIdlingResource.incrementSafely() + isBackEnabled = false + showProgress(getString(R.string.please_wait_while_pass_phrase_will_be_changed)) + } + + Result.Status.SUCCESS -> { + isPassphraseChanged = true + if (args.accountEntity.isRuleExist(AccountEntity.DomainRule.NO_PRV_BACKUP)) { + //making backups is not allowed by OrgRules. + isBackEnabled = true + showContent() + baseActivity.countingIdlingResource.decrementSafely() + } else { + baseActivity.countingIdlingResource.decrementSafely() + loadPrivateKeysViewModel.fetchAvailableKeys(args.accountEntity) + } + } + + Result.Status.ERROR, Result.Status.EXCEPTION -> { + isBackEnabled = true + showStatus(it.exceptionMsg) + showSnackbar( + view = binding?.root, + msgText = getString(R.string.could_not_change_pass_phrase), + btnName = getString(R.string.retry), + duration = Snackbar.LENGTH_INDEFINITE + ) { + privateKeysViewModel.changePassphrase( + Passphrase.fromPassword(args.passphrase) + ) + } + baseActivity.countingIdlingResource.decrementSafely() + } + + else -> { + } + } + } + }) + + privateKeysViewModel.saveBackupToInboxLiveData.observe(viewLifecycleOwner, { + it?.let { + when (it.status) { + Result.Status.LOADING -> { + baseActivity.countingIdlingResource.incrementSafely() + showProgress(getString(R.string.please_wait_while_backup_will_be_saved)) + } + + Result.Status.SUCCESS -> { + isBackEnabled = true + showContent() + baseActivity.countingIdlingResource.decrementSafely() + } + + Result.Status.ERROR, Result.Status.EXCEPTION -> { + navigateToMakeBackupFragment() + baseActivity.countingIdlingResource.decrementSafely() + } + + else -> { + } + } + } + }) + } + + private fun setupLoadPrivateKeysViewModel() { + loadPrivateKeysViewModel.privateKeysLiveData.observe(viewLifecycleOwner, { + it?.let { + when (it.status) { + Result.Status.LOADING -> { + if (it.progress == null) { + baseActivity.countingIdlingResource.incrementSafely() + } + showProgress(getString(R.string.searching_backups)) + } + + Result.Status.SUCCESS -> { + val keyDetailsList = it.data + baseActivity.countingIdlingResource.decrementSafely() + if (keyDetailsList?.isEmpty() == true) { + navigateToMakeBackupFragment() + } else { + privateKeysViewModel.saveBackupsToInbox() + } + } + + Result.Status.ERROR, Result.Status.EXCEPTION -> { + navigateToMakeBackupFragment() + baseActivity.countingIdlingResource.decrementSafely() + } + + else -> { + } + } + } + }) + } + + private fun navigateToMakeBackupFragment() { + navController?.navigate( + ChangePassphraseOfImportedKeysFragmentDirections + .actionChangePassphraseOfImportedKeysFragmentToBackupKeysFragment() + ) + } +} diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CheckPassphraseStrengthFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CheckPassphraseStrengthFragment.kt new file mode 100644 index 0000000000..8eb222ab75 --- /dev/null +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/CheckPassphraseStrengthFragment.kt @@ -0,0 +1,259 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: DenBond7 + */ + +package com.flowcrypt.email.ui.activity.fragment + +import android.content.Context +import android.graphics.Color +import android.graphics.Typeface +import android.os.Bundle +import android.text.Spannable +import android.text.SpannableString +import android.text.TextUtils +import android.text.style.ForegroundColorSpan +import android.text.style.StyleSpan +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.widget.Toast +import androidx.core.content.ContextCompat +import androidx.core.graphics.BlendModeColorFilterCompat +import androidx.core.graphics.BlendModeCompat +import androidx.core.widget.addTextChangedListener +import androidx.fragment.app.viewModels +import androidx.navigation.fragment.navArgs +import com.flowcrypt.email.Constants +import com.flowcrypt.email.NavGraphDirections +import com.flowcrypt.email.R +import com.flowcrypt.email.api.retrofit.response.base.Result +import com.flowcrypt.email.databinding.FragmentCheckPassphraseStrengthBinding +import com.flowcrypt.email.extensions.navController +import com.flowcrypt.email.extensions.toast +import com.flowcrypt.email.jetpack.viewmodel.PasswordStrengthViewModel +import com.flowcrypt.email.security.pgp.PgpPwd +import com.flowcrypt.email.ui.activity.fragment.base.BaseFragment +import com.flowcrypt.email.ui.notifications.SystemNotificationManager +import com.google.android.material.snackbar.Snackbar +import org.apache.commons.io.IOUtils +import java.nio.charset.StandardCharsets +import java.util.Locale + +/** + * This fragment does a reliability check of a provided passphrase. + * + * @author Denis Bondarenko + * Date: 05.08.2018 + * Time: 20:15 + * E-mail: DenBond7@gmail.com + */ +class CheckPassphraseStrengthFragment : BaseFragment() { + private val args by navArgs() + private var binding: FragmentCheckPassphraseStrengthBinding? = null + private val passwordStrengthViewModel: PasswordStrengthViewModel by viewModels() + private var pwdStrengthResult: PgpPwd.PwdStrengthResult? = null + + override val contentResourceId: Int = R.layout.fragment_check_passphrase_strength + + override fun onAttach(context: Context) { + super.onAttach(context) + SystemNotificationManager(context) + .cancel(SystemNotificationManager.NOTIFICATION_ID_PASSPHRASE_TOO_WEAK) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? + ): View? { + binding = FragmentCheckPassphraseStrengthBinding.inflate(inflater, container, false) + return binding?.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + supportActionBar?.title = getString(R.string.security) + initViews() + initPasswordStrengthViewModel() + } + + private fun initViews() { + binding?.tVTitle?.text = args.title + binding?.iBShowPasswordHint?.setOnClickListener { + navController?.navigate( + NavGraphDirections.actionGlobalInfoDialogFragment( + requestCode = 0, + dialogTitle = "", + dialogMsg = IOUtils.toString( + requireContext().assets.open("html/pass_phrase_hint.htm"), + StandardCharsets.UTF_8 + ), + useWebViewToRender = true + ) + ) + } + + binding?.eTPassphrase?.addTextChangedListener { editable -> + val passphrase = editable.toString() + passwordStrengthViewModel.check(passphrase) + if (TextUtils.isEmpty(editable)) { + binding?.tVPassphraseQuality?.setText(R.string.passphrase_must_be_non_empty) + } + } + + binding?.eTPassphrase?.setOnEditorActionListener { _, actionId, _ -> + return@setOnEditorActionListener when (actionId) { + EditorInfo.IME_ACTION_DONE -> { + checkAndMoveOn() + true + } + else -> false + } + } + + binding?.btSetPassphrase?.setOnClickListener { + checkAndMoveOn() + } + } + + private fun checkAndMoveOn() { + if (binding?.eTPassphrase?.text?.isEmpty() == true) { + showInfoSnackbar( + view = binding?.root, + msgText = getString(R.string.passphrase_must_be_non_empty), + duration = Snackbar.LENGTH_LONG + ) + } else { + snackBar?.dismiss() + pwdStrengthResult?.word?.let { word -> + when (word.word) { + Constants.PASSWORD_QUALITY_WEAK, Constants.PASSWORD_QUALITY_POOR -> { + navController?.navigate( + NavGraphDirections.actionGlobalInfoDialogFragment( + dialogTitle = "", + dialogMsg = getString(R.string.select_stronger_pass_phrase) + ) + ) + } + + else -> { + navController?.navigate( + CheckPassphraseStrengthFragmentDirections + .actionCheckPassphraseStrengthFragmentToRecheckProvidedPassphraseFragment( + popBackStackIdIfSuccess = args.popBackStackIdIfSuccess, + title = args.title, + passphrase = binding?.eTPassphrase?.text.toString() + ) + ) + } + } + } + } + } + + private fun initPasswordStrengthViewModel() { + passwordStrengthViewModel.pwdStrengthResultLiveData.observe(viewLifecycleOwner) { + when (it.status) { + Result.Status.SUCCESS -> { + pwdStrengthResult = it.data + updateStrengthViews() + } + + Result.Status.EXCEPTION -> { + toast( + it.exception?.message ?: it.exception?.javaClass?.simpleName + ?: getString(R.string.unknown_error), Toast.LENGTH_LONG + ) + } + else -> { + } + } + } + } + + private fun updateStrengthViews() { + if (pwdStrengthResult == null) { + return + } + + val word = pwdStrengthResult?.word + + when (word?.word) { + Constants.PASSWORD_QUALITY_WEAK, + Constants.PASSWORD_QUALITY_POOR -> { + val colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat( + ContextCompat.getColor(requireContext(), R.color.silver), BlendModeCompat.MODULATE + ) + binding?.btSetPassphrase?.background?.colorFilter = colorFilter + } + + else -> { + val colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat( + ContextCompat.getColor(requireContext(), R.color.colorPrimary), BlendModeCompat.MODULATE + ) + binding?.btSetPassphrase?.background?.colorFilter = colorFilter + } + } + + val color = parseColor() + + binding?.pBarPassphraseQuality?.progress = word?.bar?.toInt() ?: 0 + val colorFilter = + BlendModeColorFilterCompat.createBlendModeColorFilterCompat(color, BlendModeCompat.SRC_IN) + binding?.pBarPassphraseQuality?.progressDrawable?.colorFilter = colorFilter + + val qualityValue = getLocalizedPasswordQualityValue(word) + + val qualityValueSpannable = SpannableString(qualityValue) + qualityValueSpannable.setSpan( + ForegroundColorSpan(color), 0, qualityValueSpannable.length, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE + ) + qualityValueSpannable.setSpan( + StyleSpan(Typeface.BOLD), 0, + qualityValueSpannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE + ) + binding?.tVPassphraseQuality?.text = qualityValueSpannable + binding?.tVPassphraseQuality?.append(" ") + binding?.tVPassphraseQuality?.append(getString(R.string.password_quality_subtext)) + + val timeSpannable = SpannableString(pwdStrengthResult?.time ?: "") + timeSpannable.setSpan( + ForegroundColorSpan(color), 0, timeSpannable.length, + Spannable.SPAN_EXCLUSIVE_EXCLUSIVE + ) + binding?.tVPassphraseQuality?.append(" ") + binding?.tVPassphraseQuality?.append(timeSpannable) + binding?.tVPassphraseQuality?.append(")") + } + + private fun parseColor(): Int { + return try { + Color.parseColor(pwdStrengthResult?.word?.color) + } catch (e: IllegalArgumentException) { + e.printStackTrace() + + when (pwdStrengthResult?.word?.color) { + "orange" -> Color.parseColor("#FFA500") + + "darkorange" -> Color.parseColor("#FF8C00") + + "darkred" -> Color.parseColor("#8B0000") + + else -> Color.DKGRAY + } + } + } + + private fun getLocalizedPasswordQualityValue(word: PgpPwd.Word?): String? { + return when (word?.word) { + Constants.PASSWORD_QUALITY_PERFECT -> getString(R.string.password_quality_perfect) + Constants.PASSWORD_QUALITY_GREAT -> getString(R.string.password_quality_great) + Constants.PASSWORD_QUALITY_GOOD -> getString(R.string.password_quality_good) + Constants.PASSWORD_QUALITY_REASONABLE -> getString(R.string.password_quality_reasonable) + Constants.PASSWORD_QUALITY_POOR -> getString(R.string.password_quality_poor) + Constants.PASSWORD_QUALITY_WEAK -> getString(R.string.password_quality_weak) + else -> word?.word + }?.toUpperCase(Locale.getDefault()) + } +} diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/RecheckProvidedPassphraseFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/RecheckProvidedPassphraseFragment.kt new file mode 100644 index 0000000000..8cf86f86ef --- /dev/null +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/RecheckProvidedPassphraseFragment.kt @@ -0,0 +1,104 @@ +/* + * © 2016-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com + * Contributors: DenBond7 + */ + +package com.flowcrypt.email.ui.activity.fragment + +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import androidx.navigation.fragment.navArgs +import com.flowcrypt.email.R +import com.flowcrypt.email.databinding.FragmentRecheckProvidedPassphraseBinding +import com.flowcrypt.email.extensions.navController +import com.flowcrypt.email.ui.activity.fragment.base.BaseFragment +import com.flowcrypt.email.ui.notifications.SystemNotificationManager +import com.google.android.material.snackbar.Snackbar + +/** + * @author Denis Bondarenko + * Date: 6/28/21 + * Time: 6:10 PM + * E-mail: DenBond7@gmail.com + */ +class RecheckProvidedPassphraseFragment : BaseFragment() { + private val args by navArgs() + private var binding: FragmentRecheckProvidedPassphraseBinding? = null + + override val contentResourceId: Int = R.layout.fragment_recheck_provided_passphrase + + override fun onAttach(context: Context) { + super.onAttach(context) + SystemNotificationManager(context) + .cancel(SystemNotificationManager.NOTIFICATION_ID_PASSPHRASE_TOO_WEAK) + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? + ): View? { + binding = FragmentRecheckProvidedPassphraseBinding.inflate(inflater, container, false) + return binding?.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + supportActionBar?.title = getString(R.string.security) + initViews() + } + + private fun initViews() { + binding?.tVTitle?.text = args.title + binding?.eTRepeatedPassphrase?.setOnEditorActionListener { _, actionId, _ -> + return@setOnEditorActionListener when (actionId) { + EditorInfo.IME_ACTION_DONE -> { + checkAndMoveOn() + true + } + else -> false + } + } + binding?.btConfirmPassphrase?.setOnClickListener { + checkAndMoveOn() + } + binding?.btUseAnotherPassphrase?.setOnClickListener { + navController?.navigateUp() + } + } + + private fun checkAndMoveOn() { + if (binding?.eTRepeatedPassphrase?.text?.isEmpty() == true) { + showInfoSnackbar( + view = binding?.root, + msgText = getString(R.string.passphrase_must_be_non_empty), + duration = Snackbar.LENGTH_LONG + ) + } else { + snackBar?.dismiss() + if (binding?.eTRepeatedPassphrase?.text.toString() == args.passphrase) { + account?.let { accountEntity -> + navController?.navigate( + RecheckProvidedPassphraseFragmentDirections + .actionRecheckProvidedPassphraseFragmentToChangePassphraseOfImportedKeysFragment( + popBackStackIdIfSuccess = args.popBackStackIdIfSuccess, + title = getString(R.string.pass_phrase_changed), + subTitle = getString(R.string.passphrase_was_changed), + passphrase = args.passphrase, + accountEntity = accountEntity + ) + ) + } + } else { + showInfoSnackbar( + view = binding?.root, + msgText = getString(R.string.pass_phrases_do_not_match), + duration = Snackbar.LENGTH_LONG + ) + } + } + } +} + diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/base/BaseSyncFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/base/BaseSyncFragment.kt index 6e14d8e74d..d73607d201 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/base/BaseSyncFragment.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/base/BaseSyncFragment.kt @@ -23,7 +23,7 @@ abstract class BaseSyncFragment : BaseFragment() { protected var progressView: View? = null protected var statusView: View? = null - protected var textViewStatusInfo: TextView? = null + protected var tVStatusMsg: TextView? = null protected val baseSyncActivity: BaseSyncActivity get() { @@ -43,8 +43,8 @@ abstract class BaseSyncFragment : BaseFragment() { super.onViewCreated(view, savedInstanceState) progressView = view.findViewById(R.id.viewIdProgressView) statusView = view.findViewById(R.id.viewIdStatusView) - textViewStatusInfo = view.findViewById(R.id.viewIdTextViewStatusInfo) - if (progressView == null || statusView == null || textViewStatusInfo == null) { + tVStatusMsg = view.findViewById(R.id.tVStatusMsg) + if (progressView == null || statusView == null || tVStatusMsg == null) { throw IllegalArgumentException("The layout file of this fragment not contains " + "some needed views") } } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/InfoDialogFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/InfoDialogFragment.kt index 4e41b381f1..afd8898ab5 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/InfoDialogFragment.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/InfoDialogFragment.kt @@ -8,6 +8,7 @@ package com.flowcrypt.email.ui.activity.fragment.dialog import android.app.Dialog import android.content.Context import android.os.Bundle +import android.webkit.WebView import androidx.appcompat.app.AlertDialog import androidx.navigation.fragment.navArgs import com.flowcrypt.email.R @@ -15,6 +16,7 @@ import com.flowcrypt.email.extensions.navController import com.flowcrypt.email.extensions.setNavigationResult import com.flowcrypt.email.util.GeneralUtil import com.flowcrypt.email.util.UIUtil +import java.nio.charset.StandardCharsets /** * This class can be used to show an info dialog to the user. @@ -59,21 +61,41 @@ class InfoDialogFragment : BaseDialogFragment() { } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { - val dialog = AlertDialog.Builder(requireActivity()) - dialog.setTitle(dialogTitle) - dialog.setMessage(if (hasHtml) UIUtil.getHtmlSpannedFromText(dialogMsg) else dialogMsg) - dialog.setPositiveButton(buttonTitle) { _, _ -> - targetFragment?.onActivityResult(targetRequestCode, RESULT_OK, null) - onInfoDialogButtonClickListener?.onInfoDialogButtonClick(targetRequestCode) - setNavigationResult(KEY_RESULT, RESULT_OK) - - if (isPopBackStack) { - val fragmentManager = requireActivity().supportFragmentManager - fragmentManager.popBackStackImmediate() - navController?.navigateUp() + val builder = AlertDialog.Builder(requireActivity()).apply { + setTitle(dialogTitle) + if (!args.useWebViewToRender) { + setMessage(if (hasHtml) UIUtil.getHtmlSpannedFromText(dialogMsg) else dialogMsg) } + setPositiveButton(buttonTitle) { _, _ -> + targetFragment?.onActivityResult(targetRequestCode, RESULT_OK, null) + onInfoDialogButtonClickListener?.onInfoDialogButtonClick(targetRequestCode) + setNavigationResult(KEY_RESULT, RESULT_OK) + + if (isPopBackStack) { + val fragmentManager = requireActivity().supportFragmentManager + fragmentManager.popBackStackImmediate() + navController?.navigateUp() + } + } + } + + val dialog = builder.create() + if (args.useWebViewToRender) { + val webView = WebView(requireContext()) + webView.id = R.id.webView + dialogMsg?.let { + webView.loadDataWithBaseURL( + null, + it, + "text/html", + StandardCharsets.UTF_8.displayName(), + null + ) + } + val padding = requireContext().resources.getDimensionPixelSize(R.dimen.default_margin_content) + dialog.setView(webView, padding, padding, padding, padding) } - return dialog.create() + return dialog } interface OnInfoDialogButtonClickListener { @@ -111,6 +133,12 @@ class InfoDialogFragment : BaseDialogFragment() { InfoDialogFragment::class.java ) + private val KEY_USE_WEB_VIEW_TO_RENDER = + GeneralUtil.generateUniqueExtraKey( + "KEY_USE_WEB_VIEW_TO_RENDER", + InfoDialogFragment::class.java + ) + fun newInstance( dialogTitle: String? = null, dialogMsg: String? = null, @@ -118,6 +146,7 @@ class InfoDialogFragment : BaseDialogFragment() { isPopBackStack: Boolean = false, isCancelable: Boolean = false, hasHtml: Boolean = false, + useWebViewToRender: Boolean = false, useLinkify: Boolean = false ): InfoDialogFragment { val dialogFragment = InfoDialogFragment() @@ -129,6 +158,7 @@ class InfoDialogFragment : BaseDialogFragment() { args.putBoolean(KEY_INFO_IS_POP_BACK_STACK, isPopBackStack) args.putBoolean(KEY_INFO_IS_CANCELABLE, isCancelable) args.putBoolean(KEY_INFO_HAS_HTML, hasHtml) + args.putBoolean(KEY_USE_WEB_VIEW_TO_RENDER, useWebViewToRender) args.putBoolean(KEY_INFO_USE_LINKIFY, useLinkify) dialogFragment.arguments = args diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/WebViewInfoDialogFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/WebViewInfoDialogFragment.kt index 9af902fb01..5fb0acc025 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/WebViewInfoDialogFragment.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/dialog/WebViewInfoDialogFragment.kt @@ -25,6 +25,7 @@ import java.nio.charset.StandardCharsets * Time: 15:56 * E-mail: DenBond7@gmail.com */ +//todo-denbond7 remove this after migrating #1193 will be completed class WebViewInfoDialogFragment : DialogFragment(), View.OnClickListener { protected var dialogTitle: String? = null diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/preferences/SecuritySettingsFragment.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/preferences/SecuritySettingsFragment.kt index eba829f60d..af498ccc13 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/preferences/SecuritySettingsFragment.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/activity/fragment/preferences/SecuritySettingsFragment.kt @@ -12,9 +12,9 @@ import androidx.appcompat.app.AppCompatActivity import androidx.preference.Preference import com.flowcrypt.email.Constants import com.flowcrypt.email.R +import com.flowcrypt.email.extensions.navController import com.flowcrypt.email.extensions.showNeedPassphraseDialog import com.flowcrypt.email.security.KeysStorageImpl -import com.flowcrypt.email.ui.activity.ChangePassPhraseActivity import com.flowcrypt.email.ui.activity.fragment.base.BasePreferenceFragment import com.flowcrypt.email.ui.activity.fragment.dialog.FixNeedPassphraseIssueDialogFragment import com.flowcrypt.email.util.UIUtil @@ -44,7 +44,7 @@ class SecuritySettingsFragment : BasePreferenceFragment(), Preference.OnPreferen when (requestCode) { REQUEST_CODE_SHOW_FIX_EMPTY_PASSPHRASE_DIALOG -> when (resultCode) { FixNeedPassphraseIssueDialogFragment.RESULT_OK -> { - startActivity(ChangePassPhraseActivity.newIntent(context)) + navigateToCheckPassphraseStrengthFragment() } } @@ -72,7 +72,7 @@ class SecuritySettingsFragment : BasePreferenceFragment(), Preference.OnPreferen logicType = FixNeedPassphraseIssueDialogFragment.LogicType.ALL ) } else { - startActivity(ChangePassPhraseActivity.newIntent(context)) + navigateToCheckPassphraseStrengthFragment() } } true @@ -82,6 +82,16 @@ class SecuritySettingsFragment : BasePreferenceFragment(), Preference.OnPreferen } } + private fun navigateToCheckPassphraseStrengthFragment() { + navController?.navigate( + SecuritySettingsFragmentDirections + .actionSecuritySettingsFragmentToCheckPassphraseStrengthFragment( + popBackStackIdIfSuccess = navController?.currentDestination?.id ?: 0, + title = getString(R.string.change_pass_phrase) + ) + ) + } + companion object { private const val REQUEST_CODE_SHOW_FIX_EMPTY_PASSPHRASE_DIALOG = 100 } diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/notifications/SystemNotificationManager.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/notifications/SystemNotificationManager.kt index 11d50a6d1c..b89b80717d 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/ui/notifications/SystemNotificationManager.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/ui/notifications/SystemNotificationManager.kt @@ -10,11 +10,11 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory +import android.net.Uri import androidx.core.app.NotificationCompat import com.flowcrypt.email.BuildConfig import com.flowcrypt.email.R import com.flowcrypt.email.database.entity.AccountEntity -import com.flowcrypt.email.ui.activity.ChangePassPhraseActivity import com.flowcrypt.email.ui.activity.EmailManagerActivity /** @@ -42,7 +42,10 @@ class SystemNotificationManager(context: Context) : CustomNotificationManager(co val intent = if (account?.isRuleExist(AccountEntity.DomainRule.NO_PRV_BACKUP) == true) { Intent(context, EmailManagerActivity::class.java) } else { - ChangePassPhraseActivity.newIntent(context) + Intent( + Intent.ACTION_VIEW, + Uri.parse("flowcrypt://email.flowcrypt.com/settings/security") + ) } val pendingIntent = diff --git a/FlowCrypt/src/main/res/layout/fragment_change_passphrase_of_imported_keys.xml b/FlowCrypt/src/main/res/layout/fragment_change_passphrase_of_imported_keys.xml new file mode 100644 index 0000000000..9cb8e62b73 --- /dev/null +++ b/FlowCrypt/src/main/res/layout/fragment_change_passphrase_of_imported_keys.xml @@ -0,0 +1,105 @@ + + + + + + + +