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
|
/*
* Copyright © 2014-2020 The Android Password Store Authors. All Rights Reserved.
* SPDX-License-Identifier: GPL-3.0-only
*/
package com.zeapo.pwdstore
import android.app.Application
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asFlow
import androidx.lifecycle.asLiveData
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
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 java.io.File
import java.text.Collator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.yield
private fun File.toPasswordItem(root: File) = if (isFile)
PasswordItem.newPassword(name, this, root)
else
PasswordItem.newCategory(name, this, root)
private fun PasswordItem.fuzzyMatch(filter: String): Int {
var i = 0
var j = 0
var score = 0
var bonus = 0
var bonusIncrement = 0
val toMatch = longName
while (i < filter.length && j < toMatch.length) {
when {
filter[i].isWhitespace() -> i++
filter[i].toLowerCase() == toMatch[j].toLowerCase() -> {
i++
bonusIncrement += 1
bonus += bonusIncrement
score += bonus
}
else -> {
bonus = 0
bonusIncrement = 0
}
}
j++
}
return if (i == filter.length) score else 0
}
private val CaseInsensitiveComparator = Collator.getInstance().apply {
strength = Collator.PRIMARY
}
private fun PasswordItem.Companion.makeComparator(
typeSortOrder: PasswordRepository.PasswordSortOrder,
directoryStructure: DirectoryStructure
): Comparator<PasswordItem> {
return when (typeSortOrder) {
PasswordRepository.PasswordSortOrder.FOLDER_FIRST -> compareBy { it.type }
PasswordRepository.PasswordSortOrder.INDEPENDENT -> compareBy<PasswordItem>()
PasswordRepository.PasswordSortOrder.FILE_FIRST -> compareByDescending { it.type }
}
.then(compareBy(nullsLast(CaseInsensitiveComparator)) {
directoryStructure.getIdentifierFor(
it.file
)
})
.then(compareBy(CaseInsensitiveComparator) { directoryStructure.getUsernameFor(it.file) })
}
enum class FilterMode {
ListOnly,
StrictDomain,
Fuzzy
}
enum class SearchMode {
RecursivelyInSubdirectories,
InCurrentDirectoryOnly
}
private data class SearchAction(
val currentDir: File,
val filter: String,
val filterMode: FilterMode,
val searchMode: SearchMode,
val listFilesOnly: Boolean
)
@ExperimentalCoroutinesApi
@FlowPreview
class SearchableRepositoryViewModel(application: Application) : AndroidViewModel(application) {
private val root = PasswordRepository.getRepositoryDirectory(application)
private val settings = PreferenceManager.getDefaultSharedPreferences(getApplication())
private val showHiddenDirs = settings.getBoolean("show_hidden_folders", false)
private val searchFromRoot = settings.getBoolean("search_from_root", false)
private val defaultSearchMode = if (settings.getBoolean("filter_recursively", true)) {
SearchMode.RecursivelyInSubdirectories
} else {
SearchMode.InCurrentDirectoryOnly
}
private val typeSortOrder = PasswordRepository.PasswordSortOrder.getSortOrder(settings)
private val directoryStructure = AutofillPreferences.directoryStructure(application)
private val itemComparator = PasswordItem.makeComparator(typeSortOrder, directoryStructure)
private val searchAction = MutableLiveData(
SearchAction(
currentDir = root,
filter = "",
filterMode = FilterMode.ListOnly,
searchMode = SearchMode.InCurrentDirectoryOnly,
listFilesOnly = true
)
)
private val searchActionFlow = searchAction.asFlow()
.map { it.copy(filter = it.filter.trim()) }
.distinctUntilChanged()
private val passwordItemsFlow = searchActionFlow
.mapLatest { searchAction ->
val dirToSearch =
if (searchFromRoot && searchAction.filterMode != FilterMode.ListOnly) root else searchAction.currentDir
val listResultFlow = when (searchAction.searchMode) {
SearchMode.RecursivelyInSubdirectories -> listFilesRecursively(dirToSearch)
SearchMode.InCurrentDirectoryOnly -> listFiles(dirToSearch)
}
val prefilteredResultFlow =
if (searchAction.listFilesOnly) listResultFlow.filter { it.isFile } else listResultFlow
val filterModeToUse =
if (searchAction.filter == "") FilterMode.ListOnly else searchAction.filterMode
when (filterModeToUse) {
FilterMode.ListOnly -> {
prefilteredResultFlow
.map { it.toPasswordItem(root) }
.toList()
.sortedWith(itemComparator)
}
FilterMode.StrictDomain -> {
check(searchAction.listFilesOnly) { "Searches with StrictDomain search mode can only list files" }
prefilteredResultFlow
.filter { file ->
val toMatch =
directoryStructure.getIdentifierFor(file) ?: return@filter false
// In strict domain mode, we match
// * the search term exactly,
// * subdomains of the search term,
// * or the search term plus an arbitrary protocol.
toMatch == searchAction.filter ||
toMatch.endsWith(".${searchAction.filter}") ||
toMatch.endsWith("://${searchAction.filter}")
}
.map { it.toPasswordItem(root) }
.toList()
.sortedWith(itemComparator)
}
FilterMode.Fuzzy -> {
prefilteredResultFlow
.map {
val item = it.toPasswordItem(root)
Pair(item.fuzzyMatch(searchAction.filter), item)
}
.filter { it.first > 0 }
.toList()
.sortedWith(
compareByDescending<Pair<Int, PasswordItem>> { it.first }.thenBy(
itemComparator
) { it.second })
.map { it.second }
}
}
}
val passwordItemsList = passwordItemsFlow.asLiveData(Dispatchers.IO)
fun list(currentDir: File) {
require(currentDir.isDirectory) { "Can only list files in a directory" }
searchAction.postValue(
SearchAction(
filter = "",
currentDir = currentDir,
filterMode = FilterMode.ListOnly,
searchMode = SearchMode.InCurrentDirectoryOnly,
listFilesOnly = false
)
)
}
fun search(
filter: String,
currentDir: File? = null,
filterMode: FilterMode = FilterMode.Fuzzy,
searchMode: SearchMode? = null,
listFilesOnly: Boolean = false
) {
require(currentDir?.isDirectory != false) { "Can only search in a directory" }
val action = SearchAction(
filter = filter.trim(),
currentDir = currentDir ?: searchAction.value!!.currentDir,
filterMode = filterMode,
searchMode = searchMode ?: defaultSearchMode,
listFilesOnly = listFilesOnly
)
searchAction.postValue(action)
}
private fun shouldTake(file: File) = with(file) {
if (isDirectory) {
!isHidden || showHiddenDirs
} else {
!isHidden && file.extension == "gpg"
}
}
private fun listFiles(dir: File): Flow<File> {
return dir.listFiles { file -> shouldTake(file) }?.asFlow() ?: emptyFlow()
}
private fun listFilesRecursively(dir: File): Flow<File> {
return dir
.walkTopDown().onEnter { file -> shouldTake(file) }
.asFlow()
.map {
yield()
it
}
.filter { file -> shouldTake(file) }
}
}
private object PasswordItemDiffCallback : DiffUtil.ItemCallback<PasswordItem>() {
override fun areItemsTheSame(oldItem: PasswordItem, newItem: PasswordItem) =
oldItem.file.absolutePath == newItem.file.absolutePath
override fun areContentsTheSame(oldItem: PasswordItem, newItem: PasswordItem) = oldItem == newItem
}
class DelegatedSearchableRepositoryAdapter<T : RecyclerView.ViewHolder>(
private val layoutRes: Int,
private val viewHolderCreator: (view: View) -> T,
private val viewHolderBinder: T.(item: PasswordItem) -> Unit
) : ListAdapter<PasswordItem, T>(PasswordItemDiffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): T {
val view = LayoutInflater.from(parent.context)
.inflate(layoutRes, parent, false)
return viewHolderCreator(view)
}
override fun onBindViewHolder(holder: T, position: Int) {
viewHolderBinder.invoke(holder, getItem(position))
}
}
|