forked from android-password-store/Android-Password-Store
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PasswordRepository.kt
289 lines (251 loc) · 10 KB
/
PasswordRepository.kt
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
* Copyright © 2014-2020 The Android Password Store Authors. All Rights Reserved.
* SPDX-License-Identifier: GPL-3.0-only
*/
package com.zeapo.pwdstore.utils
import android.content.SharedPreferences
import androidx.core.content.edit
import com.zeapo.pwdstore.Application
import java.io.File
import java.io.FileFilter
import java.util.Comparator
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.transport.RefSpec
import org.eclipse.jgit.transport.RemoteConfig
import org.eclipse.jgit.transport.URIish
open class PasswordRepository protected constructor() {
@Suppress("Unused")
enum class PasswordSortOrder(val comparator: Comparator<PasswordItem>) {
FOLDER_FIRST(Comparator { p1: PasswordItem, p2: PasswordItem ->
(p1.type + p1.name)
.compareTo(p2.type + p2.name, ignoreCase = true)
}),
INDEPENDENT(Comparator { p1: PasswordItem, p2: PasswordItem ->
p1.name.compareTo(p2.name, ignoreCase = true)
}),
RECENTLY_USED(Comparator { p1: PasswordItem, p2: PasswordItem ->
val recentHistory = Application.instance.getSharedPreferences("recent_password_history", android.content.Context.MODE_PRIVATE)
val timeP1 = recentHistory.getString(p1.file.absolutePath)
val timeP2 = recentHistory.getString(p2.file.absolutePath)
when {
timeP1 != null && timeP2 != null -> timeP2.compareTo(timeP1)
timeP1 != null && timeP2 == null -> return@Comparator -1
timeP1 == null && timeP2 != null -> return@Comparator 1
else -> p1.name.compareTo(p2.name, ignoreCase = true)
}
}),
FILE_FIRST(Comparator { p1: PasswordItem, p2: PasswordItem ->
(p2.type + p1.name).compareTo(p1.type + p2.name, ignoreCase = true)
});
companion object {
@JvmStatic
fun getSortOrder(settings: SharedPreferences): PasswordSortOrder {
return valueOf(settings.getString(PreferenceKeys.SORT_ORDER) ?: FOLDER_FIRST.name)
}
}
}
companion object {
private var repository: Repository? = null
private val settings by lazy { Application.instance.sharedPrefs }
private val filesDir
get() = Application.instance.filesDir
/**
* Returns the git repository
*
* @param localDir needed only on the creation
* @return the git repository
*/
@JvmStatic
fun getRepository(localDir: File?): Repository? {
if (repository == null && localDir != null) {
val builder = FileRepositoryBuilder()
try {
repository = builder.setGitDir(localDir)
.readEnvironment()
.build()
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
return repository
}
@JvmStatic
val isInitialized: Boolean
get() = repository != null
@JvmStatic
fun isGitRepo(): Boolean {
if (repository != null) {
// Check if remote exists
return repository!!.config.getSubsections("remote").isNotEmpty() &&
repository!!.objectDatabase.exists() &&
repository!!.allRefs.isNotEmpty()
}
return false
}
@JvmStatic
@Throws(Exception::class)
fun createRepository(localDir: File) {
localDir.delete()
Git.init().setDirectory(localDir).call()
getRepository(localDir)
}
// TODO add multiple remotes support for pull/push
@JvmStatic
fun addRemote(name: String, url: String, replace: Boolean = false) {
val storedConfig = repository!!.config
val remotes = storedConfig.getSubsections("remote")
if (!remotes.contains(name)) {
try {
val uri = URIish(url)
val refSpec = RefSpec("+refs/head/*:refs/remotes/$name/*")
val remoteConfig = RemoteConfig(storedConfig, name)
remoteConfig.addFetchRefSpec(refSpec)
remoteConfig.addPushRefSpec(refSpec)
remoteConfig.addURI(uri)
remoteConfig.addPushURI(uri)
remoteConfig.update(storedConfig)
storedConfig.save()
} catch (e: Exception) {
e.printStackTrace()
}
} else if (replace) {
try {
val uri = URIish(url)
val remoteConfig = RemoteConfig(storedConfig, name)
// remove the first and eventually the only uri
if (remoteConfig.urIs.size > 0) {
remoteConfig.removeURI(remoteConfig.urIs[0])
}
if (remoteConfig.pushURIs.size > 0) {
remoteConfig.removePushURI(remoteConfig.pushURIs[0])
}
remoteConfig.addURI(uri)
remoteConfig.addPushURI(uri)
remoteConfig.update(storedConfig)
storedConfig.save()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@JvmStatic
fun closeRepository() {
if (repository != null) repository!!.close()
repository = null
}
@JvmStatic
fun getRepositoryDirectory(): File {
return if (settings.getBoolean(PreferenceKeys.GIT_EXTERNAL, false)) {
val externalRepo = settings.getString(PreferenceKeys.GIT_EXTERNAL_REPO)
if (externalRepo != null)
File(externalRepo)
else
File(filesDir.toString(), "/store")
} else {
File(filesDir.toString(), "/store")
}
}
@JvmStatic
fun initialize(): Repository? {
val dir = getRepositoryDirectory()
// uninitialize the repo if the dir does not exist or is absolutely empty
settings.edit {
if (!dir.exists() || !dir.isDirectory || dir.listFiles()?.isEmpty() == true) {
putBoolean(PreferenceKeys.REPOSITORY_INITIALIZED, false)
} else {
putBoolean(PreferenceKeys.REPOSITORY_INITIALIZED, true)
}
}
// create the repository static variable in PasswordRepository
return getRepository(File(dir.absolutePath + "/.git"))
}
/**
* Gets the .gpg files in a directory
*
* @param path the directory path
* @return the list of gpg files in that directory
*/
@JvmStatic
fun getFilesList(path: File?): ArrayList<File> {
if (path == null || !path.exists()) return ArrayList()
val directories = (path.listFiles(FileFilter { pathname -> pathname.isDirectory })
?: emptyArray()).toList()
val files = (path.listFiles(FileFilter { pathname -> pathname.extension == "gpg" })
?: emptyArray()).toList()
val items = ArrayList<File>()
items.addAll(directories)
items.addAll(files)
return items
}
/**
* Gets the passwords (PasswordItem) in a directory
*
* @param path the directory path
* @return a list of password items
*/
@JvmStatic
fun getPasswords(path: File, rootDir: File, sortOrder: PasswordSortOrder): ArrayList<PasswordItem> {
// We need to recover the passwords then parse the files
val passList = getFilesList(path).also { it.sortBy { f -> f.name } }
val passwordList = ArrayList<PasswordItem>()
val showHiddenDirs = settings.getBoolean(PreferenceKeys.SHOW_HIDDEN_FOLDERS, false)
if (passList.size == 0) return passwordList
if (showHiddenDirs) {
passList.filter { !(it.isFile && it.isHidden) }.toCollection(passList.apply { clear() })
} else {
passList.filter { !it.isHidden }.toCollection(passList.apply { clear() })
}
passList.forEach { file ->
passwordList.add(if (file.isFile) {
PasswordItem.newPassword(file.name, file, rootDir)
} else {
PasswordItem.newCategory(file.name, file, rootDir)
})
}
passwordList.sortWith(sortOrder.comparator)
return passwordList
}
/**
* Sets the git user name
*
* @param username username
*/
@JvmStatic
fun setGitAuthorName(username: String) {
setStringConfig("user", null, "name", username)
}
/**
* Sets the git user email
*
* @param email email
*/
@JvmStatic
fun setGitAuthorEmail(email: String) {
setStringConfig("user", null, "email", email)
}
/**
* Sets a git config value
*
* @param section config section name
* @param subsection config subsection name
* @param name config name
* @param value the value to be set
*/
@JvmStatic
@Suppress("SameParameterValue")
private fun setStringConfig(section: String, subsection: String?, name: String, value: String) {
if (isInitialized) {
val config = repository!!.config
config.setString(section, subsection, name, value)
try {
config.save()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}