aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/dev/msfjarvis/aps/util/settings/GitSettings.kt
blob: 3a508e453c93dbcc43fbf8ae1f74e4256c4a43e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/*
 * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved.
 * SPDX-License-Identifier: GPL-3.0-only
 */
package dev.msfjarvis.aps.util.settings

import androidx.core.content.edit
import com.github.michaelbull.result.getOrElse
import com.github.michaelbull.result.runCatching
import dev.msfjarvis.aps.Application
import dev.msfjarvis.aps.data.repo.PasswordRepository
import dev.msfjarvis.aps.util.extensions.getEncryptedGitPrefs
import dev.msfjarvis.aps.util.extensions.getEncryptedProxyPrefs
import dev.msfjarvis.aps.util.extensions.getString
import dev.msfjarvis.aps.util.extensions.sharedPrefs
import java.io.File
import org.eclipse.jgit.transport.URIish

enum class Protocol(val pref: String) {
  Ssh("ssh://"),
  Https("https://"),
  ;

  companion object {

    private val map = values().associateBy(Protocol::pref)
    fun fromString(type: String?): Protocol {
      return map[type ?: return Ssh] ?: throw IllegalArgumentException("$type is not a valid Protocol")
    }
  }
}

enum class AuthMode(val pref: String) {
  SshKey("ssh-key"),
  Password("username/password"),
  OpenKeychain("OpenKeychain"),
  None("None"),
  ;

  companion object {

    private val map = values().associateBy(AuthMode::pref)
    fun fromString(type: String?): AuthMode {
      return map[type ?: return SshKey] ?: throw IllegalArgumentException("$type is not a valid AuthMode")
    }
  }
}

object GitSettings {

  private const val DEFAULT_BRANCH = "master"

  private val settings by lazy(LazyThreadSafetyMode.PUBLICATION) { Application.instance.sharedPrefs }
  private val encryptedSettings by lazy(LazyThreadSafetyMode.PUBLICATION) {
    Application.instance.getEncryptedGitPrefs()
  }
  private val proxySettings by lazy(LazyThreadSafetyMode.PUBLICATION) { Application.instance.getEncryptedProxyPrefs() }
  private val hostKeyPath by lazy(LazyThreadSafetyMode.NONE) { "${Application.instance.filesDir}/.host_key" }

  var authMode
    get() = AuthMode.fromString(settings.getString(PreferenceKeys.GIT_REMOTE_AUTH))
    private set(value) {
      settings.edit { putString(PreferenceKeys.GIT_REMOTE_AUTH, value.pref) }
    }

  var url
    get() = settings.getString(PreferenceKeys.GIT_REMOTE_URL)
    private set(value) {
      require(value != null)
      if (value == url) return
      settings.edit { putString(PreferenceKeys.GIT_REMOTE_URL, value) }
      if (PasswordRepository.isInitialized) PasswordRepository.addRemote("origin", value, true)
      // When the server changes, remote password, multiplexing support and host key file
      // should be deleted/reset.
      useMultiplexing = true
      encryptedSettings.edit { remove(PreferenceKeys.HTTPS_PASSWORD) }
      clearSavedHostKey()
    }

  var authorName
    get() = settings.getString(PreferenceKeys.GIT_CONFIG_AUTHOR_NAME) ?: ""
    set(value) {
      settings.edit { putString(PreferenceKeys.GIT_CONFIG_AUTHOR_NAME, value) }
    }

  var authorEmail
    get() = settings.getString(PreferenceKeys.GIT_CONFIG_AUTHOR_EMAIL) ?: ""
    set(value) {
      settings.edit { putString(PreferenceKeys.GIT_CONFIG_AUTHOR_EMAIL, value) }
    }

  var branch
    get() = settings.getString(PreferenceKeys.GIT_BRANCH_NAME) ?: DEFAULT_BRANCH
    private set(value) {
      settings.edit { putString(PreferenceKeys.GIT_BRANCH_NAME, value) }
    }

  var useMultiplexing
    get() = settings.getBoolean(PreferenceKeys.GIT_REMOTE_USE_MULTIPLEXING, true)
    set(value) {
      settings.edit { putBoolean(PreferenceKeys.GIT_REMOTE_USE_MULTIPLEXING, value) }
    }

  var proxyHost
    get() = proxySettings.getString(PreferenceKeys.PROXY_HOST)
    set(value) {
      proxySettings.edit { putString(PreferenceKeys.PROXY_HOST, value) }
    }

  var proxyPort
    get() = proxySettings.getInt(PreferenceKeys.PROXY_PORT, -1)
    set(value) {
      proxySettings.edit { putInt(PreferenceKeys.PROXY_PORT, value) }
    }

  var proxyUsername
    get() = settings.getString(PreferenceKeys.PROXY_USERNAME)
    set(value) {
      proxySettings.edit { putString(PreferenceKeys.PROXY_USERNAME, value) }
    }

  var proxyPassword
    get() = proxySettings.getString(PreferenceKeys.PROXY_PASSWORD)
    set(value) {
      proxySettings.edit { putString(PreferenceKeys.PROXY_PASSWORD, value) }
    }

  var rebaseOnPull
    get() = settings.getBoolean(PreferenceKeys.REBASE_ON_PULL, true)
    set(value) {
      settings.edit { putBoolean(PreferenceKeys.REBASE_ON_PULL, value) }
    }

  sealed class UpdateConnectionSettingsResult {
    class MissingUsername(val newProtocol: Protocol) : UpdateConnectionSettingsResult()
    class AuthModeMismatch(val newProtocol: Protocol, val validModes: List<AuthMode>) :
      UpdateConnectionSettingsResult()
    object Valid : UpdateConnectionSettingsResult()
    object FailedToParseUrl : UpdateConnectionSettingsResult()
  }

  fun updateConnectionSettingsIfValid(
    newAuthMode: AuthMode,
    newUrl: String,
    newBranch: String
  ): UpdateConnectionSettingsResult {
    val parsedUrl =
      runCatching { URIish(newUrl) }.getOrElse {
        return UpdateConnectionSettingsResult.FailedToParseUrl
      }
    val newProtocol =
      when (parsedUrl.scheme) {
        in listOf("http", "https") -> Protocol.Https
        in listOf("ssh", null) -> Protocol.Ssh
        else -> return UpdateConnectionSettingsResult.FailedToParseUrl
      }
    if (newAuthMode != AuthMode.None && parsedUrl.user.isNullOrBlank())
      return UpdateConnectionSettingsResult.MissingUsername(newProtocol)

    val validHttpsAuth = listOf(AuthMode.None, AuthMode.Password)
    val validSshAuth = listOf(AuthMode.OpenKeychain, AuthMode.Password, AuthMode.SshKey)
    when {
      newProtocol == Protocol.Https && newAuthMode !in validHttpsAuth -> {
        return UpdateConnectionSettingsResult.AuthModeMismatch(newProtocol, validHttpsAuth)
      }
      newProtocol == Protocol.Ssh && newAuthMode !in validSshAuth -> {
        return UpdateConnectionSettingsResult.AuthModeMismatch(newProtocol, validSshAuth)
      }
    }

    url = newUrl
    authMode = newAuthMode
    branch = newBranch
    return UpdateConnectionSettingsResult.Valid
  }

  /** Deletes a previously saved SSH host key */
  fun clearSavedHostKey() {
    File(hostKeyPath).delete()
  }

  /** Returns true if a host key was previously saved */
  fun hasSavedHostKey(): Boolean = File(hostKeyPath).exists()
}