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

Use PreferenceKeys file to manage SharedPreferences keys. #891

Merged
merged 8 commits into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions 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 All @@ -37,13 +39,13 @@ class Application : android.app.Application(), SharedPreferences.OnSharedPrefere
}

override fun onSharedPreferenceChanged(prefs: SharedPreferences, key: String) {
if (key == "app_theme") {
if (key == PreferenceKeys.APP_THEME) {
setNightMode()
}
}

private fun setNightMode() {
AppCompatDelegate.setDefaultNightMode(when (prefs?.getString("app_theme", getString(R.string.app_theme_def))) {
AppCompatDelegate.setDefaultNightMode(when (prefs?.getString(PreferenceKeys.APP_THEME, getString(R.string.app_theme_def))) {
"light" -> MODE_NIGHT_NO
"dark" -> MODE_NIGHT_YES
"follow_system" -> MODE_NIGHT_FOLLOW_SYSTEM
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
5 changes: 3 additions & 2 deletions app/src/main/java/com/zeapo/pwdstore/LaunchActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,21 @@ import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.zeapo.pwdstore.crypto.DecryptActivity
import com.zeapo.pwdstore.utils.BiometricAuthenticator
import com.zeapo.pwdstore.utils.PreferenceKeys

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 -> {
startTargetActivity(false)
}
is BiometricAuthenticator.Result.HardwareUnavailableOrDisabled -> {
prefs.edit { remove("biometric_auth") }
prefs.edit { remove(PreferenceKeys.BIOMETRIC_AUTH) }
startTargetActivity(false)
}
is BiometricAuthenticator.Result.Failure, BiometricAuthenticator.Result.Cancelled -> {
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 @@ -187,12 +188,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 @@ -211,7 +212,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 @@ -261,7 +262,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 @@ -346,7 +347,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 @@ -361,8 +362,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 @@ -375,7 +376,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 @@ -431,12 +432,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 @@ -535,7 +536,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 @@ -751,7 +752,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 @@ -770,9 +771,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 @@ -832,7 +833,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 @@ -843,8 +844,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
Loading