treewide: use edit extension and cleanup some deprecation

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Harsh Shandilya 2020-04-21 13:11:27 +05:30
parent e1921b26e0
commit d505151662
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
12 changed files with 141 additions and 140 deletions

View file

@ -29,6 +29,7 @@ import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.SearchView.OnQueryTextListener import androidx.appcompat.widget.SearchView.OnQueryTextListener
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe import androidx.lifecycle.observe
@ -325,7 +326,7 @@ class PasswordStore : AppCompatActivity() {
check(localDir.mkdir()) { "Failed to create directory!" } check(localDir.mkdir()) { "Failed to create directory!" }
createRepository(localDir) createRepository(localDir)
if (File(localDir.absolutePath + "/.gpg-id").createNewFile()) { if (File(localDir.absolutePath + "/.gpg-id").createNewFile()) {
settings.edit().putBoolean("repository_initialized", true).apply() settings.edit { putBoolean("repository_initialized", true) }
} else { } else {
throw IllegalStateException("Failed to initialize repository state.") throw IllegalStateException("Failed to initialize repository state.")
} }
@ -383,7 +384,7 @@ class PasswordStore : AppCompatActivity() {
// do not push the fragment if we already have it // do not push the fragment if we already have it
if (fragmentManager.findFragmentByTag("PasswordsList") == null || if (fragmentManager.findFragmentByTag("PasswordsList") == null ||
settings.getBoolean("repo_changed", false)) { settings.getBoolean("repo_changed", false)) {
settings.edit().putBoolean("repo_changed", false).apply() settings.edit { putBoolean("repo_changed", false) }
plist = PasswordFragment() plist = PasswordFragment()
val args = Bundle() val args = Bundle()
args.putString(REQUEST_ARG_PATH, getRepositoryDirectory(applicationContext).absolutePath) args.putString(REQUEST_ARG_PATH, getRepositoryDirectory(applicationContext).absolutePath)
@ -589,7 +590,7 @@ class PasswordStore : AppCompatActivity() {
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
when (requestCode) { when (requestCode) {
// if we get here with a RESULT_OK then it's probably OK :) // if we get here with a RESULT_OK then it's probably OK :)
BaseGitActivity.REQUEST_CLONE -> settings.edit().putBoolean("repository_initialized", true).apply() BaseGitActivity.REQUEST_CLONE -> settings.edit { putBoolean("repository_initialized", true) }
// if went from decrypt->edit and user saved changes or HOTP counter was // if went from decrypt->edit and user saved changes or HOTP counter was
// incremented, we need to commitChange // incremented, we need to commitChange
REQUEST_CODE_DECRYPT_AND_VERIFY -> { REQUEST_CODE_DECRYPT_AND_VERIFY -> {
@ -721,7 +722,7 @@ class PasswordStore : AppCompatActivity() {
.setTitle(this.resources.getString(R.string.location_dialog_title)) .setTitle(this.resources.getString(R.string.location_dialog_title))
.setMessage(this.resources.getString(R.string.location_dialog_text)) .setMessage(this.resources.getString(R.string.location_dialog_text))
.setPositiveButton(this.resources.getString(R.string.location_hidden)) { _, _ -> .setPositiveButton(this.resources.getString(R.string.location_hidden)) { _, _ ->
settings.edit().putBoolean("git_external", false).apply() settings.edit { putBoolean("git_external", false) }
when (operation) { when (operation) {
NEW_REPO_BUTTON -> initializeRepositoryInfo() NEW_REPO_BUTTON -> initializeRepositoryInfo()
CLONE_REPO_BUTTON -> { CLONE_REPO_BUTTON -> {
@ -732,7 +733,7 @@ class PasswordStore : AppCompatActivity() {
} }
} }
.setNegativeButton(this.resources.getString(R.string.location_sdcard)) { _, _ -> .setNegativeButton(this.resources.getString(R.string.location_sdcard)) { _, _ ->
settings.edit().putBoolean("git_external", true).apply() settings.edit { putBoolean("git_external", true) }
val externalRepo = settings.getString("git_external_repo", null) val externalRepo = settings.getString("git_external_repo", null)
if (externalRepo == null) { if (externalRepo == null) {
val intent = Intent(activity, UserPreference::class.java) val intent = Intent(activity, UserPreference::class.java)

View file

@ -33,6 +33,7 @@ import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import androidx.preference.SwitchPreferenceCompat import androidx.preference.SwitchPreferenceCompat
import com.github.ajalt.timberkt.d
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
import com.zeapo.pwdstore.autofill.AutofillPreferenceActivity import com.zeapo.pwdstore.autofill.AutofillPreferenceActivity
@ -173,7 +174,7 @@ class UserPreference : AppCompatActivity() {
viewSshKeyPreference?.onPreferenceClickListener = ClickListener { viewSshKeyPreference?.onPreferenceClickListener = ClickListener {
val df = ShowSshKeyFragment() val df = ShowSshKeyFragment()
df.show(requireFragmentManager(), "public_key") df.show(parentFragmentManager, "public_key")
true true
} }
@ -189,13 +190,13 @@ class UserPreference : AppCompatActivity() {
} }
clearHotpIncrementPreference?.onPreferenceClickListener = ClickListener { clearHotpIncrementPreference?.onPreferenceClickListener = ClickListener {
sharedPreferences.edit().putBoolean("hotp_remember_check", false).apply() sharedPreferences.edit { putBoolean("hotp_remember_check", false) }
it.isVisible = false it.isVisible = false
true true
} }
openkeystoreIdPreference?.onPreferenceClickListener = ClickListener { openkeystoreIdPreference?.onPreferenceClickListener = ClickListener {
sharedPreferences.edit().putString("ssh_openkeystore_keyid", null).apply() sharedPreferences.edit { putString("ssh_openkeystore_keyid", null) }
it.isVisible = false it.isVisible = false
true true
} }
@ -224,7 +225,7 @@ class UserPreference : AppCompatActivity() {
// TODO Handle the different cases of exceptions // TODO Handle the different cases of exceptions
} }
sharedPreferences.edit().putBoolean("repository_initialized", false).apply() sharedPreferences.edit { putBoolean("repository_initialized", false) }
dialogInterface.cancel() dialogInterface.cancel()
callingActivity.finish() callingActivity.finish()
} }
@ -244,7 +245,7 @@ class UserPreference : AppCompatActivity() {
val resetRepo = Preference.OnPreferenceChangeListener { _, o -> val resetRepo = Preference.OnPreferenceChangeListener { _, o ->
deleteRepoPreference?.isVisible = !(o as Boolean) deleteRepoPreference?.isVisible = !(o as Boolean)
PasswordRepository.closeRepository() PasswordRepository.closeRepository()
sharedPreferences.edit().putBoolean("repo_changed", true).apply() sharedPreferences.edit { putBoolean("repo_changed", true) }
true true
} }
@ -294,30 +295,30 @@ class UserPreference : AppCompatActivity() {
} else { } else {
setOnPreferenceClickListener { setOnPreferenceClickListener {
isEnabled = false isEnabled = false
val editor = sharedPreferences.edit() sharedPreferences.edit {
val checked = isChecked val checked = isChecked
Authenticator(requireActivity()) { result -> Authenticator(requireActivity()) { result ->
when (result) { when (result) {
is AuthenticationResult.Success -> { is AuthenticationResult.Success -> {
// Apply the changes // Apply the changes
editor.putBoolean("biometric_auth", checked) putBoolean("biometric_auth", checked)
isEnabled = true isEnabled = true
}
else -> {
// If any error occurs, revert back to the previous state. This
// catch-all clause includes the cancellation case.
putBoolean("biometric_auth", !checked)
isChecked = !checked
isEnabled = true
}
} }
else -> { }.authenticate()
// If any error occurs, revert back to the previous state. This if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
// catch-all clause includes the cancellation case. requireContext().getSystemService<ShortcutManager>()?.apply {
editor.putBoolean("biometric_auth", !checked) removeDynamicShortcuts(dynamicShortcuts.map { it.id }.toMutableList())
isChecked = !checked
isEnabled = true
} }
} }
}.authenticate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
requireContext().getSystemService<ShortcutManager>()?.apply {
removeDynamicShortcuts(dynamicShortcuts.map { it.id }.toMutableList())
}
} }
editor.apply()
true true
} }
} }
@ -622,7 +623,7 @@ class UserPreference : AppCompatActivity() {
).show() ).show()
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext) val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
prefs.edit().putBoolean("use_generated_key", false).apply() prefs.edit { putBoolean("use_generated_key", false) }
// Delete the public key from generation // Delete the public key from generation
File("""$filesDir/.ssh_key.pub""").delete() File("""$filesDir/.ssh_key.pub""").delete()
@ -642,33 +643,27 @@ class UserPreference : AppCompatActivity() {
SELECT_GIT_DIRECTORY -> { SELECT_GIT_DIRECTORY -> {
val uri = data.data val uri = data.data
Timber.tag(TAG).d("Selected repository URI is $uri") Timber.tag(TAG).d { "Selected repository URI is $uri" }
// TODO: This is fragile. Workaround until PasswordItem is backed by DocumentFile // TODO: This is fragile. Workaround until PasswordItem is backed by DocumentFile
val docId = DocumentsContract.getTreeDocumentId(uri) val docId = DocumentsContract.getTreeDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val path = if (split.isNotEmpty()) split[1] else split[0] val path = if (split.isNotEmpty()) split[1] else split[0]
val repoPath = "${Environment.getExternalStorageDirectory()}/$path" val repoPath = "${Environment.getExternalStorageDirectory()}/$path"
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
Timber.tag(TAG).d("Selected repository path is $repoPath") Timber.tag(TAG).d {"Selected repository path is $repoPath" }
if (Environment.getExternalStorageDirectory().path == repoPath) { if (Environment.getExternalStorageDirectory().path == repoPath) {
MaterialAlertDialogBuilder(this) MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.sdcard_root_warning_title)) .setTitle(getString(R.string.sdcard_root_warning_title))
.setMessage(getString(R.string.sdcard_root_warning_message)) .setMessage(getString(R.string.sdcard_root_warning_message))
.setPositiveButton("Remove everything") { _, _ -> .setPositiveButton("Remove everything") { _, _ ->
PreferenceManager.getDefaultSharedPreferences(applicationContext) prefs.edit { putString("git_external_repo", uri?.path) }
.edit()
.putString("git_external_repo", uri?.path)
.apply()
} }
.setNegativeButton(R.string.dialog_cancel, null) .setNegativeButton(R.string.dialog_cancel, null)
.show() .show()
} }
prefs.edit { putString("git_external_repo", repoPath) }
PreferenceManager.getDefaultSharedPreferences(applicationContext)
.edit()
.putString("git_external_repo", repoPath)
.apply()
} }
EXPORT_PASSWORDS -> { EXPORT_PASSWORDS -> {
val uri = data.data val uri = data.data
@ -691,7 +686,7 @@ class UserPreference : AppCompatActivity() {
).show() ).show()
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext) val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
prefs.edit().putString("pref_key_custom_dict", uri.toString()).apply() prefs.edit { putString("pref_key_custom_dict", uri.toString()) }
val customDictPref = prefsFragment.findPreference<Preference>("pref_key_custom_dict") val customDictPref = prefsFragment.findPreference<Preference>("pref_key_custom_dict")
setCustomDictSummary(customDictPref, uri) setCustomDictSummary(customDictPref, uri)
@ -719,7 +714,7 @@ class UserPreference : AppCompatActivity() {
val repositoryDirectory = requireNotNull(PasswordRepository.getRepositoryDirectory(applicationContext)) val repositoryDirectory = requireNotNull(PasswordRepository.getRepositoryDirectory(applicationContext))
val sourcePassDir = DocumentFile.fromFile(repositoryDirectory) val sourcePassDir = DocumentFile.fromFile(repositoryDirectory)
Timber.tag(TAG).d("Copying ${repositoryDirectory.path} to $targetDirectory") Timber.tag(TAG).d { "Copying ${repositoryDirectory.path} to $targetDirectory" }
val dateString = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val dateString = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LocalDateTime LocalDateTime

View file

@ -11,10 +11,9 @@ import android.content.IntentSender
import android.content.SharedPreferences import android.content.SharedPreferences
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.zeapo.pwdstore.PasswordStore import com.zeapo.pwdstore.PasswordStore
import com.zeapo.pwdstore.utils.splitLines import com.zeapo.pwdstore.utils.splitLines
import java.util.ArrayList
import java.util.Arrays
import org.eclipse.jgit.util.StringUtils import org.eclipse.jgit.util.StringUtils
import timber.log.Timber import timber.log.Timber
@ -71,17 +70,17 @@ class AutofillActivity : AppCompatActivity() {
} else { } else {
applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE) applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE)
} }
val editor = prefs.edit() prefs.edit {
when (val preference = prefs.getString(packageName, "")) { when (val preference = prefs.getString(packageName, "")) {
"", "/first", "/never" -> editor.putString(packageName, path) "", "/first", "/never" -> putString(packageName, path)
else -> { else -> {
val matches = ArrayList(Arrays.asList(*preference!!.trim { it <= ' ' }.splitLines())) val matches = arrayListOf(*preference!!.trim { it <= ' ' }.splitLines())
matches.add(path) matches.add(path)
val paths = StringUtils.join(matches, "\n") val paths = StringUtils.join(matches, "\n")
editor.putString(packageName, paths) putString(packageName, paths)
}
} }
} }
editor.apply()
} }
} }
super.onActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data)

View file

@ -23,6 +23,7 @@ import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.edit
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zeapo.pwdstore.PasswordStore import com.zeapo.pwdstore.PasswordStore
@ -118,14 +119,14 @@ class AutofillFragment : DialogFragment() {
// write to preferences when OK clicked // write to preferences when OK clicked
builder.setPositiveButton(R.string.dialog_ok) { _, _ -> } builder.setPositiveButton(R.string.dialog_ok) { _, _ -> }
builder.setNegativeButton(R.string.dialog_cancel, null) builder.setNegativeButton(R.string.dialog_cancel, null)
val editor = prefs.edit()
if (isWeb) { if (isWeb) {
builder.setNeutralButton(R.string.autofill_apps_delete) { _, _ -> builder.setNeutralButton(R.string.autofill_apps_delete) { _, _ ->
if (callingActivity.recyclerAdapter != null && if (callingActivity.recyclerAdapter != null &&
packageName != null && packageName != "") { packageName != null && packageName != "") {
editor.remove(packageName) prefs.edit {
callingActivity.recyclerAdapter?.removeWebsite(packageName) remove(packageName)
editor.apply() callingActivity.recyclerAdapter?.removeWebsite(packageName)
}
} }
} }
} }
@ -148,7 +149,6 @@ class AutofillFragment : DialogFragment() {
} else { } else {
callingActivity.applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE) callingActivity.applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE)
} }
val editor = prefs.edit()
var packageName = args.getString("packageName", "") var packageName = args.getString("packageName", "")
if (isWeb) { if (isWeb) {
@ -169,27 +169,28 @@ class AutofillFragment : DialogFragment() {
} }
// write to preferences accordingly // write to preferences accordingly
val radioGroup = dialog.findViewById<RadioGroup>(R.id.autofill_radiogroup) prefs.edit {
when (radioGroup.checkedRadioButtonId) { val radioGroup = dialog.findViewById<RadioGroup>(R.id.autofill_radiogroup)
R.id.use_default -> if (!isWeb) { when (radioGroup.checkedRadioButtonId) {
editor.remove(packageName) R.id.use_default -> if (!isWeb) {
} else { remove(packageName)
editor.putString(packageName, "") } else {
} putString(packageName, "")
R.id.first -> editor.putString(packageName, "/first") }
R.id.never -> editor.putString(packageName, "/never") R.id.first -> putString(packageName, "/first")
else -> { R.id.never -> putString(packageName, "/never")
val paths = StringBuilder() else -> {
for (i in 0 until adapter!!.count) { val paths = StringBuilder()
paths.append(adapter!!.getItem(i)) for (i in 0 until adapter!!.count) {
if (i != adapter!!.count) { paths.append(adapter!!.getItem(i))
paths.append("\n") if (i != adapter!!.count) {
} paths.append("\n")
}
}
putString(packageName, paths.toString())
} }
editor.putString(packageName, paths.toString())
} }
} }
editor.apply()
// notify the recycler adapter if it is loaded // notify the recycler adapter if it is loaded
callingActivity.recyclerAdapter?.apply { callingActivity.recyclerAdapter?.apply {
@ -204,7 +205,7 @@ class AutofillFragment : DialogFragment() {
packageName -> notifyItemChanged(position) packageName -> notifyItemChanged(position)
"" -> addWebsite(packageName) "" -> addWebsite(packageName)
else -> { else -> {
editor.remove(oldPackageName) prefs.edit { remove(oldPackageName) }
updateWebsite(oldPackageName, packageName) updateWebsite(oldPackageName, packageName)
} }
} }

View file

@ -32,6 +32,7 @@ import android.widget.CheckBox
import android.widget.TextView import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.edit
import androidx.core.widget.doOnTextChanged import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.localbroadcastmanager.content.LocalBroadcastManager
@ -228,7 +229,7 @@ class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound {
} }
} }
fun updateEncryptUsernameState() { private fun updateEncryptUsernameState() {
encrypt_username.apply { encrypt_username.apply {
if (visibility != View.VISIBLE) if (visibility != View.VISIBLE)
return return
@ -489,20 +490,20 @@ class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound {
run { run {
calculateAndCommitHotp(entry) calculateAndCommitHotp(entry)
if (rememberCheck.isChecked) { if (rememberCheck.isChecked) {
val editor = settings.edit() settings.edit {
editor.putBoolean("hotp_remember_check", true) putBoolean("hotp_remember_check", true)
editor.putBoolean("hotp_remember_choice", true) putBoolean("hotp_remember_choice", true)
editor.apply() }
} }
} }
} }
.setNegativeButton(R.string.dialog_update_negative) { _, _ -> .setNegativeButton(R.string.dialog_update_negative) { _, _ ->
run { run {
calculateHotp(entry) calculateHotp(entry)
val editor = settings.edit() settings.edit {
editor.putBoolean("hotp_remember_check", true) putBoolean("hotp_remember_check", true)
editor.putBoolean("hotp_remember_choice", false) putBoolean("hotp_remember_choice", false)
editor.apply() }
} }
} }
val updateDialog = dialogBuilder.create() val updateDialog = dialogBuilder.create()
@ -722,7 +723,7 @@ class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound {
val keys = ids.map { it.toString() }.toSet() val keys = ids.map { it.toString() }.toSet()
// use Long // use Long
settings.edit().putStringSet("openpgp_key_ids_set", keys).apply() settings.edit { putStringSet("openpgp_key_ids_set", keys) }
showSnackbar("PGP keys selected") showSnackbar("PGP keys selected")

View file

@ -6,6 +6,7 @@ package com.zeapo.pwdstore.git
import android.os.Bundle import android.os.Bundle
import android.util.Patterns import android.util.Patterns
import androidx.core.content.edit
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zeapo.pwdstore.R import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.databinding.ActivityGitConfigBinding import com.zeapo.pwdstore.databinding.ActivityGitConfigBinding
@ -50,12 +51,12 @@ class GitConfigActivity : BaseGitActivity() {
.setPositiveButton(getString(R.string.dialog_ok), null) .setPositiveButton(getString(R.string.dialog_ok), null)
.show() .show()
} else { } else {
val editor = settings.edit() settings.edit {
editor.putString("git_config_user_email", email) putString("git_config_user_email", email)
editor.putString("git_config_user_name", name) putString("git_config_user_name", name)
PasswordRepository.setUserName(name) }
PasswordRepository.setUserEmail(email) PasswordRepository.setUserName(name)
editor.apply() PasswordRepository.setUserEmail(email)
} }
} }
} }

View file

@ -189,7 +189,7 @@ abstract class GitOperation(fileDir: File, internal val callingActivity: Activit
// Authenticate using the ssh-key and then execute the command // Authenticate using the ssh-key and then execute the command
setAuthentication(sshKey, username, passphrase.text.toString()).execute() setAuthentication(sshKey, username, passphrase.text.toString()).execute()
} else { } else {
encryptedSettings.edit().putString("ssh_key_local_passphrase", null).apply() encryptedSettings.edit { putString("ssh_key_local_passphrase", null) }
// call back the method // call back the method
executeAfterAuthentication(connectionMode, username, sshKey, identity, true) executeAfterAuthentication(connectionMode, username, sshKey, identity, true)
} }

View file

@ -5,6 +5,7 @@
package com.zeapo.pwdstore.pwgen package com.zeapo.pwdstore.pwgen
import android.content.Context import android.content.Context
import androidx.core.content.edit
import com.zeapo.pwdstore.R import com.zeapo.pwdstore.R
import java.util.ArrayList import java.util.ArrayList
@ -50,28 +51,26 @@ object PasswordGenerator {
*/ */
@JvmStatic @JvmStatic
fun setPrefs(ctx: Context, argv: ArrayList<String>, vararg numArgv: Int): Boolean { fun setPrefs(ctx: Context, argv: ArrayList<String>, vararg numArgv: Int): Boolean {
val prefs = ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE) ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE).edit {
val editor = prefs.edit() for (option in pwOptions.toCharArray()) {
if (argv.contains(option.toString())) {
for (option in pwOptions.toCharArray()) { putBoolean(option.toString(), true)
if (argv.contains(option.toString())) { argv.remove(option.toString())
editor.putBoolean(option.toString(), true) } else {
argv.remove(option.toString()) putBoolean(option.toString(), false)
} else { }
editor.putBoolean(option.toString(), false) }
var i = 0
while (i < numArgv.size && i < 2) {
if (numArgv[i] <= 0) {
// Invalid password length or number of passwords
return false
}
val name = if (i == 0) "length" else "num"
putInt(name, numArgv[i])
i++
} }
} }
var i = 0
while (i < numArgv.size && i < 2) {
if (numArgv[i] <= 0) {
// Invalid password length or number of passwords
return false
}
val name = if (i == 0) "length" else "num"
editor.putInt(name, numArgv[i])
i++
}
editor.apply()
return true return true
} }
@ -84,7 +83,7 @@ object PasswordGenerator {
* @return list of generated passwords * @return list of generated passwords
*/ */
@JvmStatic @JvmStatic
@Throws(PasswordGenerator.PasswordGeneratorExeption::class) @Throws(PasswordGeneratorExeption::class)
fun generate(ctx: Context): ArrayList<String> { fun generate(ctx: Context): ArrayList<String> {
val prefs = ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE) val prefs = ctx.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE)

View file

@ -8,6 +8,7 @@ import android.app.ProgressDialog
import android.os.AsyncTask import android.os.AsyncTask
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
@ -60,9 +61,7 @@ class KeyGenerateTask(activity: AppCompatActivity) : AsyncTask<String?, Void?, E
val df: DialogFragment = ShowSshKeyFragment() val df: DialogFragment = ShowSshKeyFragment()
df.show(activity.supportFragmentManager, "public_key") df.show(activity.supportFragmentManager, "public_key")
val prefs = PreferenceManager.getDefaultSharedPreferences(weakReference.get()) val prefs = PreferenceManager.getDefaultSharedPreferences(weakReference.get())
val editor = prefs.edit() prefs.edit { putBoolean("use_generated_key", true) }
editor.putBoolean("use_generated_key", true)
editor.apply()
} else { } else {
MaterialAlertDialogBuilder(activity) MaterialAlertDialogBuilder(activity)
.setTitle(activity.getString(R.string.error_generate_ssh_key)) .setTitle(activity.getString(R.string.error_generate_ssh_key))

View file

@ -16,6 +16,7 @@ import android.widget.Toast
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatTextView import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.edit
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zeapo.pwdstore.R import com.zeapo.pwdstore.R
@ -48,17 +49,17 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() {
prefs = callingActivity.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE) prefs = callingActivity.getSharedPreferences("PasswordGenerator", Context.MODE_PRIVATE)
cbNumbers = view.findViewById<CheckBox>(R.id.xknumerals) cbNumbers = view.findViewById(R.id.xknumerals)
cbNumbers.isChecked = prefs.getBoolean(PREF_KEY_USE_NUMERALS, false) cbNumbers.isChecked = prefs.getBoolean(PREF_KEY_USE_NUMERALS, false)
spinnerNumbersCount = view.findViewById<Spinner>(R.id.xk_numbers_count) spinnerNumbersCount = view.findViewById(R.id.xk_numbers_count)
val storedNumbersCount = prefs.getInt(PREF_KEY_NUMBERS_COUNT, 0) val storedNumbersCount = prefs.getInt(PREF_KEY_NUMBERS_COUNT, 0)
spinnerNumbersCount.setSelection(storedNumbersCount) spinnerNumbersCount.setSelection(storedNumbersCount)
cbSymbols = view.findViewById<CheckBox>(R.id.xksymbols) cbSymbols = view.findViewById(R.id.xksymbols)
cbSymbols.isChecked = prefs.getBoolean(PREF_KEY_USE_SYMBOLS, false) != false cbSymbols.isChecked = prefs.getBoolean(PREF_KEY_USE_SYMBOLS, false) != false
spinnerSymbolsCount = view.findViewById<Spinner>(R.id.xk_symbols_count) spinnerSymbolsCount = view.findViewById(R.id.xk_symbols_count)
val symbolsCount = prefs.getInt(PREF_KEY_SYMBOLS_COUNT, 0) val symbolsCount = prefs.getInt(PREF_KEY_SYMBOLS_COUNT, 0)
spinnerSymbolsCount.setSelection(symbolsCount) spinnerSymbolsCount.setSelection(symbolsCount)
@ -68,7 +69,7 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() {
Timber.tag("xkpw").e(e) Timber.tag("xkpw").e(e)
DEFAULT_CAPS_STYLE DEFAULT_CAPS_STYLE
} }
spinnerCapsType = view.findViewById<Spinner>(R.id.xkCapType) spinnerCapsType = view.findViewById(R.id.xkCapType)
val lastCapitalsStyleIndex: Int val lastCapitalsStyleIndex: Int
@ -80,10 +81,10 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() {
} }
spinnerCapsType.setSelection(lastCapitalsStyleIndex) spinnerCapsType.setSelection(lastCapitalsStyleIndex)
editNumWords = view.findViewById<AppCompatEditText>(R.id.xk_num_words) editNumWords = view.findViewById(R.id.xk_num_words)
editNumWords.setText(prefs.getString(PREF_KEY_NUM_WORDS, DEFAULT_NUMBER_OF_WORDS)) editNumWords.setText(prefs.getString(PREF_KEY_NUM_WORDS, DEFAULT_NUMBER_OF_WORDS))
editSeparator = view.findViewById<AppCompatEditText>(R.id.xk_separator) editSeparator = view.findViewById(R.id.xk_separator)
editSeparator.setText(prefs.getString(PREF_KEY_SEPARATOR, DEFAULT_WORD_SEPARATOR)) editSeparator.setText(prefs.getString(PREF_KEY_SEPARATOR, DEFAULT_WORD_SEPARATOR))
val passwordText: AppCompatTextView = view.findViewById(R.id.xkPasswordText) val passwordText: AppCompatTextView = view.findViewById(R.id.xkPasswordText)
@ -131,14 +132,15 @@ class XkPasswordGeneratorDialogFragment : DialogFragment() {
} }
private fun setPreferences() { private fun setPreferences() {
prefs.edit().putBoolean(PREF_KEY_USE_NUMERALS, cbNumbers.isChecked) prefs.edit {
.putBoolean(PREF_KEY_USE_SYMBOLS, cbSymbols.isChecked) putBoolean(PREF_KEY_USE_NUMERALS, cbNumbers.isChecked)
.putString(PREF_KEY_CAPITALS_STYLE, spinnerCapsType.selectedItem.toString()) putBoolean(PREF_KEY_USE_SYMBOLS, cbSymbols.isChecked)
.putString(PREF_KEY_NUM_WORDS, editNumWords.text.toString()) putString(PREF_KEY_CAPITALS_STYLE, spinnerCapsType.selectedItem.toString())
.putString(PREF_KEY_SEPARATOR, editSeparator.text.toString()) putString(PREF_KEY_NUM_WORDS, editNumWords.text.toString())
.putInt(PREF_KEY_NUMBERS_COUNT, Integer.parseInt(spinnerNumbersCount.selectedItem as String) - 1) putString(PREF_KEY_SEPARATOR, editSeparator.text.toString())
.putInt(PREF_KEY_SYMBOLS_COUNT, Integer.parseInt(spinnerSymbolsCount.selectedItem as String) - 1) putInt(PREF_KEY_NUMBERS_COUNT, Integer.parseInt(spinnerNumbersCount.selectedItem as String) - 1)
.apply() putInt(PREF_KEY_SYMBOLS_COUNT, Integer.parseInt(spinnerSymbolsCount.selectedItem as String) - 1)
}
} }
companion object { companion object {

View file

@ -65,4 +65,4 @@ fun <T : View> AlertDialog.requestInputFocusOnView(@IdRes id: Int) {
val Context.autofillManager: AutofillManager? val Context.autofillManager: AutofillManager?
@RequiresApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O)
get() = getSystemService(AutofillManager::class.java) get() = getSystemService()

View file

@ -6,6 +6,7 @@ package com.zeapo.pwdstore.utils
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import java.io.File import java.io.File
import java.io.FileFilter import java.io.FileFilter
@ -170,10 +171,12 @@ open class PasswordRepository protected constructor() {
} }
val dir = getRepositoryDirectory(context) val dir = getRepositoryDirectory(context)
// uninitialize the repo if the dir does not exist or is absolutely empty // uninitialize the repo if the dir does not exist or is absolutely empty
if (!dir.exists() || !dir.isDirectory || dir.listFiles()!!.isEmpty()) { settings.edit {
settings.edit().putBoolean("repository_initialized", false).apply() if (!dir.exists() || !dir.isDirectory || dir.listFiles()!!.isEmpty()) {
} else { putBoolean("repository_initialized", false)
settings.edit().putBoolean("repository_initialized", true).apply() } else {
putBoolean("repository_initialized", true)
}
} }
// create the repository static variable in PasswordRepository // create the repository static variable in PasswordRepository