Skip to content
This repository has been archived by the owner on Oct 15, 2024. It is now read-only.

Commit

Permalink
Use PreferenceKeys in all files
Browse files Browse the repository at this point in the history
Signed-off-by: Aditya Wasan <adityawasan55@gmail.com>
  • Loading branch information
Skrilltrax committed Jun 27, 2020
1 parent c092aaa commit c3eda0c
Show file tree
Hide file tree
Showing 23 changed files with 114 additions and 82 deletions.
4 changes: 3 additions & 1 deletion app/src/main/java/com/zeapo/pwdstore/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import androidx.preference.PreferenceManager
import com.github.ajalt.timberkt.Timber.DebugTree
import com.github.ajalt.timberkt.Timber.plant
import com.zeapo.pwdstore.git.config.setUpBouncyCastleForSshj
import com.zeapo.pwdstore.utils.PreferenceKeys

@Suppress("Unused")
class Application : android.app.Application(), SharedPreferences.OnSharedPreferenceChangeListener {
Expand All @@ -23,7 +24,8 @@ class Application : android.app.Application(), SharedPreferences.OnSharedPrefere
override fun onCreate() {
super.onCreate()
prefs = PreferenceManager.getDefaultSharedPreferences(this)
if (BuildConfig.ENABLE_DEBUG_FEATURES || prefs?.getBoolean("enable_debug_logging", false) == true) {
if (BuildConfig.ENABLE_DEBUG_FEATURES || prefs?.getBoolean(PreferenceKeys.ENABLE_DEBUG_LOGGING, false) ==
true) {
plant(DebugTree())
}
prefs?.registerOnSharedPreferenceChangeListener(this)
Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/com/zeapo/pwdstore/ClipboardService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import androidx.preference.PreferenceManager
import com.github.ajalt.timberkt.d
import com.zeapo.pwdstore.utils.PreferenceKeys
import com.zeapo.pwdstore.utils.clipboard
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -44,7 +45,7 @@ class ClipboardService : Service() {

ACTION_START -> {
val time = try {
Integer.parseInt(settings.getString("general_show_time", "45") as String)
Integer.parseInt(settings.getString(PreferenceKeys.GENERAL_SHOW_TIME, "45") as String)
} catch (e: NumberFormatException) {
45
}
Expand Down Expand Up @@ -82,7 +83,7 @@ class ClipboardService : Service() {
}

private fun clearClipboard() {
val deepClear = settings.getBoolean("clear_clipboard_20x", false)
val deepClear = settings.getBoolean(PreferenceKeys.CLEAR_CLIPBOARD_20X, false)
val clipboard = clipboard

if (clipboard != null) {
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/com/zeapo/pwdstore/LaunchActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LaunchActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
if (prefs.getBoolean("biometric_auth", false)) {
if (prefs.getBoolean(PreferenceKeys.BIOMETRIC_AUTH, false)) {
BiometricAuthenticator.authenticate(this) {
when (it) {
is BiometricAuthenticator.Result.Success -> {
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/com/zeapo/pwdstore/PasswordFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import com.zeapo.pwdstore.ui.adapters.PasswordItemRecyclerAdapter
import com.zeapo.pwdstore.ui.dialogs.ItemCreationBottomSheet
import com.zeapo.pwdstore.utils.PasswordItem
import com.zeapo.pwdstore.utils.PasswordRepository
import com.zeapo.pwdstore.utils.PreferenceKeys
import com.zeapo.pwdstore.utils.viewBinding
import me.zhanghai.android.fastscroll.FastScrollerBuilder
import java.io.File
Expand Down Expand Up @@ -78,7 +79,8 @@ class PasswordFragment : Fragment(R.layout.password_recycler_view) {
} else {
// When authentication is set to ConnectionMode.None then the only git operation we
// can run is a pull, so automatically fallback to that.
val operationId = when (ConnectionMode.fromString(settings.getString("git_remote_auth", null))) {
val operationId = when (ConnectionMode.fromString(settings.getString
(PreferenceKeys.GIT_REMOTE_AUTH, null))) {
ConnectionMode.None -> BaseGitActivity.REQUEST_PULL
else -> BaseGitActivity.REQUEST_SYNC
}
Expand Down
41 changes: 21 additions & 20 deletions app/src/main/java/com/zeapo/pwdstore/PasswordStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import com.zeapo.pwdstore.utils.PasswordRepository.Companion.getRepositoryDirect
import com.zeapo.pwdstore.utils.PasswordRepository.Companion.initialize
import com.zeapo.pwdstore.utils.PasswordRepository.Companion.isInitialized
import com.zeapo.pwdstore.utils.PasswordRepository.PasswordSortOrder.Companion.getSortOrder
import com.zeapo.pwdstore.utils.PreferenceKeys
import com.zeapo.pwdstore.utils.commitChange
import com.zeapo.pwdstore.utils.isInsideRepository
import com.zeapo.pwdstore.utils.listFilesRecursively
Expand Down Expand Up @@ -121,7 +122,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
// If user opens app with permission granted then revokes and returns,
// prevent attempt to create password list fragment
var savedInstance = savedInstanceState
if (savedInstanceState != null && (!settings.getBoolean("git_external", false) ||
if (savedInstanceState != null && (!settings.getBoolean(PreferenceKeys.GIT_EXTERNAL, false) ||
ContextCompat.checkSelfPermission(
activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)) {
Expand Down Expand Up @@ -182,12 +183,12 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
public override fun onResume() {
super.onResume()
// do not attempt to checkLocalRepository() if no storage permission: immediate crash
if (settings.getBoolean("git_external", false)) {
if (settings.getBoolean(PreferenceKeys.GIT_EXTERNAL, false)) {
hasRequiredStoragePermissions(true)
} else {
checkLocalRepository()
}
if (settings.getBoolean("search_on_start", false) && ::searchItem.isInitialized) {
if (settings.getBoolean(PreferenceKeys.SEARCH_ON_START, false) && ::searchItem.isInitialized) {
if (!searchItem.isActionViewExpanded) {
searchItem.expandActionView()
}
Expand All @@ -206,7 +207,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val menuRes = when {
ConnectionMode.fromString(settings.getString("git_remote_auth", null))
ConnectionMode.fromString(settings.getString(PreferenceKeys.GIT_REMOTE_AUTH, null))
== ConnectionMode.None -> R.menu.main_menu_no_auth
PasswordRepository.isGitRepo() -> R.menu.main_menu_git
else -> R.menu.main_menu_non_git
Expand Down Expand Up @@ -256,7 +257,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
return true
}
})
if (settings.getBoolean("search_on_start", false)) {
if (settings.getBoolean(PreferenceKeys.SEARCH_ON_START, false)) {
searchItem.expandActionView()
}
return super.onPrepareOptionsMenu(menu)
Expand Down Expand Up @@ -341,7 +342,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
check(localDir.mkdir()) { "Failed to create directory!" }
createRepository(localDir)
if (File(localDir.absolutePath + "/.gpg-id").createNewFile()) {
settings.edit { putBoolean("repository_initialized", true) }
settings.edit { putBoolean(PreferenceKeys.REPOSITORY_INITIALIZED, true) }
} else {
throw IllegalStateException("Failed to initialize repository state.")
}
Expand All @@ -356,8 +357,8 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
}

private fun initializeRepositoryInfo() {
val externalRepo = settings.getBoolean("git_external", false)
val externalRepoPath = settings.getString("git_external_repo", null)
val externalRepo = settings.getBoolean(PreferenceKeys.GIT_EXTERNAL, false)
val externalRepoPath = settings.getString(PreferenceKeys.GIT_EXTERNAL_REPO, null)
if (externalRepo && !hasRequiredStoragePermissions()) {
return
}
Expand All @@ -370,7 +371,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
return // if not empty, just show me the passwords!
}
}
val keyIds = settings.getStringSet("openpgp_key_ids_set", HashSet())
val keyIds = settings.getStringSet(PreferenceKeys.OPENPGP_KEY_IDS_SET, HashSet())
if (keyIds != null && keyIds.isEmpty()) {
MaterialAlertDialogBuilder(this)
.setMessage(resources.getString(R.string.key_dialog_text))
Expand Down Expand Up @@ -426,12 +427,12 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
}

private fun checkLocalRepository(localDir: File?) {
if (localDir != null && settings.getBoolean("repository_initialized", false)) {
if (localDir != null && settings.getBoolean(PreferenceKeys.REPOSITORY_INITIALIZED, false)) {
d { "Check, dir: ${localDir.absolutePath}" }
// do not push the fragment if we already have it
if (supportFragmentManager.findFragmentByTag("PasswordsList") == null ||
settings.getBoolean("repo_changed", false)) {
settings.edit { putBoolean("repo_changed", false) }
settings.getBoolean(PreferenceKeys.REPO_CHANGED, false)) {
settings.edit { putBoolean(PreferenceKeys.REPO_CHANGED, false) }
plist = PasswordFragment()
val args = Bundle()
args.putString(REQUEST_ARG_PATH, getRepositoryDirectory(applicationContext).absolutePath)
Expand Down Expand Up @@ -530,7 +531,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
.show()
return false
}
if (settings.getStringSet("openpgp_key_ids_set", HashSet()).isNullOrEmpty()) {
if (settings.getStringSet(PreferenceKeys.OPENPGP_KEY_IDS_SET, HashSet()).isNullOrEmpty()) {
MaterialAlertDialogBuilder(this)
.setTitle(resources.getString(R.string.no_key_selected_dialog_title))
.setMessage(resources.getString(R.string.no_key_selected_dialog_text))
Expand Down Expand Up @@ -754,7 +755,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
// if we get here with a RESULT_OK then it's probably OK :)
BaseGitActivity.REQUEST_CLONE -> settings.edit { putBoolean("repository_initialized", true) }
BaseGitActivity.REQUEST_CLONE -> settings.edit { putBoolean(PreferenceKeys.REPOSITORY_INITIALIZED, true) }
// if went from decrypt->edit and user saved changes, we need to commitChange
REQUEST_CODE_DECRYPT_AND_VERIFY -> {
if (data != null && data.getBooleanExtra("needCommit", false)) {
Expand All @@ -775,9 +776,9 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
HOME -> checkLocalRepository()
// duplicate code
CLONE_REPO_BUTTON -> {
if (settings.getBoolean("git_external", false) &&
settings.getString("git_external_repo", null) != null) {
val externalRepoPath = settings.getString("git_external_repo", null)
if (settings.getBoolean(PreferenceKeys.GIT_EXTERNAL, false) &&
settings.getString(PreferenceKeys.GIT_EXTERNAL_REPO, null) != null) {
val externalRepoPath = settings.getString(PreferenceKeys.GIT_EXTERNAL_REPO, null)
val dir = externalRepoPath?.let { File(it) }
if (dir != null &&
dir.exists() &&
Expand Down Expand Up @@ -829,7 +830,7 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
.setTitle(resources.getString(R.string.location_dialog_title))
.setMessage(resources.getString(R.string.location_dialog_text))
.setPositiveButton(resources.getString(R.string.location_hidden)) { _, _ ->
settings.edit { putBoolean("git_external", false) }
settings.edit { putBoolean(PreferenceKeys.GIT_EXTERNAL, false) }
when (operation) {
NEW_REPO_BUTTON -> initializeRepositoryInfo()
CLONE_REPO_BUTTON -> {
Expand All @@ -840,8 +841,8 @@ class PasswordStore : AppCompatActivity(R.layout.activity_pwdstore) {
}
}
.setNegativeButton(resources.getString(R.string.location_sdcard)) { _, _ ->
settings.edit { putBoolean("git_external", true) }
val externalRepo = settings.getString("git_external_repo", null)
settings.edit { putBoolean(PreferenceKeys.GIT_EXTERNAL, true) }
val externalRepo = settings.getString(PreferenceKeys.GIT_EXTERNAL_REPO, null)
if (externalRepo == null) {
val intent = Intent(activity, UserPreference::class.java)
intent.putExtra("operation", "git_external")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import com.zeapo.pwdstore.autofill.oreo.AutofillPreferences
import com.zeapo.pwdstore.autofill.oreo.DirectoryStructure
import com.zeapo.pwdstore.utils.PasswordItem
import com.zeapo.pwdstore.utils.PasswordRepository
import com.zeapo.pwdstore.utils.PreferenceKeys
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
Expand Down Expand Up @@ -140,9 +141,9 @@ class SearchableRepositoryViewModel(application: Application) : AndroidViewModel
get() = PasswordRepository.getRepositoryDirectory(getApplication())
private val settings = PreferenceManager.getDefaultSharedPreferences(getApplication())
private val showHiddenDirs
get() = settings.getBoolean("show_hidden_folders", false)
get() = settings.getBoolean(PreferenceKeys.SHOW_HIDDEN_FOLDERS, false)
private val defaultSearchMode
get() = if (settings.getBoolean("filter_recursively", true)) {
get() = if (settings.getBoolean(PreferenceKeys.FILTER_RECURSIVELY, true)) {
SearchMode.RecursivelyInSubdirectories
} else {
SearchMode.InCurrentDirectoryOnly
Expand Down
7 changes: 4 additions & 3 deletions app/src/main/java/com/zeapo/pwdstore/UserPreference.kt
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class UserPreference : AppCompatActivity() {
viewSshKeyPreference?.isVisible = sharedPreferences.getBoolean(PreferenceKeys.USE_GENERATED_KEY, false)
deleteRepoPreference?.isVisible = !sharedPreferences.getBoolean(PreferenceKeys.GIT_EXTERNAL, false)
clearClipboard20xPreference?.isVisible = sharedPreferences.getString(PreferenceKeys.GENERAL_SHOW_TIME, "45")?.toInt() != 0
openkeystoreIdPreference?.isVisible = sharedPreferences.getString(PreferenceKeys.SSH_OPENKEYSTORE_ID, null)?.isNotEmpty()
openkeystoreIdPreference?.isVisible = sharedPreferences.getString(PreferenceKeys.SSH_OPENKEYSTORE_KEYID, null)?.isNotEmpty()
?: false

updateAutofillSettings()
Expand All @@ -161,7 +161,7 @@ class UserPreference : AppCompatActivity() {
keyPreference?.let { pref ->
updateKeyIDsSummary(pref)
pref.onPreferenceClickListener = ClickListener {
val providerPackageName = requireNotNull(sharedPreferences.getString(PreferenceKeys.OPENPGP_LIST_PROVIDER, ""))
val providerPackageName = requireNotNull(sharedPreferences.getString(PreferenceKeys.OPENPGP_PROVIDER_LIST, ""))
if (providerPackageName.isEmpty()) {
Snackbar.make(requireView(), resources.getString(R.string.provider_toast_text), Snackbar.LENGTH_LONG).show()
false
Expand Down Expand Up @@ -295,7 +295,8 @@ class UserPreference : AppCompatActivity() {
}

showTimePreference?.summaryProvider = Preference.SummaryProvider<Preference> {
getString(R.string.pref_clipboard_timeout_summary, sharedPreferences.getString("general_show_time", "45"))
getString(R.string.pref_clipboard_timeout_summary, sharedPreferences.getString
(PreferenceKeys.GENERAL_SHOW_TIME, "45"))
}

findPreference<CheckBoxPreference>(PreferenceKeys.ENABLE_DEBUG_LOGGING)?.isVisible = !BuildConfig.ENABLE_DEBUG_FEATURES
Expand Down
14 changes: 8 additions & 6 deletions app/src/main/java/com/zeapo/pwdstore/autofill/AutofillService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zeapo.pwdstore.PasswordEntry
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.utils.PasswordRepository
import com.zeapo.pwdstore.utils.PreferenceKeys
import com.zeapo.pwdstore.utils.splitLines
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -228,7 +229,7 @@ class AutofillService : AccessibilityService(), CoroutineScope by CoroutineScope

// if autofill_always checked, show dialog even if no matches (automatic
// or otherwise)
if (items.isEmpty() && !settings!!.getBoolean("autofill_always", false)) {
if (items.isEmpty() && !settings!!.getBoolean(PreferenceKeys.AUTOFILL_ALWAYS, false)) {
return
}
showSelectPasswordDialog(packageName, appName, isWeb)
Expand Down Expand Up @@ -268,7 +269,7 @@ class AutofillService : AccessibilityService(), CoroutineScope by CoroutineScope
var settingsURL = webViewURL

// if autofill_default is checked and prefs.getString DNE, 'Automatically match with password'/"first" otherwise "never"
val defValue = if (settings!!.getBoolean("autofill_default", true)) "/first" else "/never"
val defValue = if (settings!!.getBoolean(PreferenceKeys.AUTOFILL_DEFAULT, true)) "/first" else "/never"
val prefs: SharedPreferences = getSharedPreferences("autofill_web", Context.MODE_PRIVATE)
var preference: String

Expand Down Expand Up @@ -414,7 +415,7 @@ class AutofillService : AccessibilityService(), CoroutineScope by CoroutineScope
// make it optional (or make height a setting for the same effect)
val itemNames = arrayOfNulls<CharSequence>(items.size + 2)
val passwordDirectory = PasswordRepository.getRepositoryDirectory(applicationContext).toString()
val autofillFullPath = settings!!.getBoolean("autofill_full_path", false)
val autofillFullPath = settings!!.getBoolean(PreferenceKeys.AUTOFILL_FULL_PATH, false)
for (i in items.indices) {
if (autofillFullPath) {
itemNames[i] = items[i].path.replace(".gpg", "")
Expand Down Expand Up @@ -518,9 +519,10 @@ class AutofillService : AccessibilityService(), CoroutineScope by CoroutineScope
// save password entry for pasting the username as well
if (entry?.hasUsername() == true) {
lastPassword = entry
val ttl = Integer.parseInt(settings!!.getString("general_show_time", "45")!!)
withContext(Dispatchers.Main) { Toast.makeText(applicationContext, getString(R.string.autofill_toast_username, ttl), Toast.LENGTH_LONG).show() }
lastPasswordMaxDate = System.currentTimeMillis() + ttl * 1000L
val ttl = Integer.parseInt(settings!!.getString(PreferenceKeys.GENERAL_SHOW_TIME, " +
""45")!!)
withContext (Dispatchers.Main) { Toast.makeText(applicationContext, getString(R.string.autofill_toast_username, ttl), Toast.LENGTH_LONG).show() }
lastPasswordMaxDate = System . currentTimeMillis () + ttl * 1000L
}
} catch (e: UnsupportedEncodingException) {
tag(Constants.TAG).e(e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.github.ajalt.timberkt.e
import com.zeapo.pwdstore.PasswordEntry
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.utils.PasswordRepository
import com.zeapo.pwdstore.utils.PreferenceKeys
import java.io.File
import java.security.MessageDigest

Expand All @@ -39,7 +40,7 @@ private fun ByteArray.base64(): String {
private fun Context.getDefaultUsername(): String? {
return PreferenceManager
.getDefaultSharedPreferences(this)
.getString("oreo_autofill_default_username", null)
.getString(PreferenceKeys.OREO_AUTOFILL_DEFAULT_USERNAME, null)
}

private fun stableHash(array: Collection<ByteArray>): String {
Expand Down
Loading

0 comments on commit c3eda0c

Please sign in to comment.