forked from mozilla-mobile/focus-android
/
ManualAddSearchEngineSettingsFragment.kt
263 lines (222 loc) · 10.6 KB
/
ManualAddSearchEngineSettingsFragment.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.settings
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.ViewGroup
import android.widget.EditText
import androidx.annotation.WorkerThread
import com.google.android.material.snackbar.Snackbar
import mozilla.components.concept.fetch.Client
import mozilla.components.concept.fetch.Request
import mozilla.components.concept.fetch.Request.Redirect.FOLLOW
import org.mozilla.focus.R
import org.mozilla.focus.ext.requireComponents
import org.mozilla.focus.search.CustomSearchEngineStore
import org.mozilla.focus.search.ManualAddSearchEnginePreference
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.utils.Settings
import org.mozilla.focus.utils.SupportUtils
import org.mozilla.focus.utils.UrlUtils
import org.mozilla.focus.utils.ViewUtils
import java.io.IOException
import java.lang.ref.WeakReference
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.TimeUnit
class ManualAddSearchEngineSettingsFragment : BaseSettingsFragment() {
override fun onCreatePreferences(p0: Bundle?, p1: String?) {
setHasOptionsMenu(true)
addPreferencesFromResource(R.xml.manual_add_search_engine)
}
/**
* A reference to an active async task, if applicable, used to manage the task for lifecycle changes.
* See {@link #onPause()} for details.
*/
private var activeAsyncTask: AsyncTask<Void, Void, Boolean>? = null
private var menuItemForActiveAsyncTask: MenuItem? = null
private val handler = Handler()
override fun onResume() {
super.onResume()
// We've checked that this cast is legal in super.onAttach.
(activity as? ActionBarUpdater)?.updateIcon(R.drawable.ic_close)
val updater = getActionBarUpdater()
updater.updateTitle(R.string.action_option_add_search_engine)
updater.updateIcon(R.drawable.ic_close)
}
override fun onPause() {
super.onPause()
// This is a last minute change and we want to keep the async task management simple: onPause is the
// first required callback for various lifecycle changes: a dialog is shown, the user
// leaves the app, the app rotates, etc. To keep things simple, we do our AsyncTask management here,
// before it gets more complex (e.g. reattaching the AsyncTask to a new fragment).
//
// We cancel the AsyncTask also to keep things simple: if the task is cancelled, it will:
// - Likely end immediately and we don't need to handle it returning after the lifecycle changes
// - Get onPostExecute scheduled on the UI thread, which must run after onPause (since it also runs on
// the UI thread), and we check if the AsyncTask is cancelled there before we perform any other actions.
if (activeAsyncTask == null) return
activeAsyncTask?.cancel(true)
setUiIsValidatingAsync(false, menuItemForActiveAsyncTask)
activeAsyncTask = null
menuItemForActiveAsyncTask = null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_search_engine_manual_add, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val openLearnMore = {
requireComponents.tabsUseCases.addPrivateTab(
SupportUtils.getSumoURLForTopic(requireContext(), SupportUtils.SumoTopic.ADD_SEARCH_ENGINE),
selectTab = true
)
TelemetryWrapper.addSearchEngineLearnMoreEvent()
activity?.finish()
}
val saveSearchEngine = {
val engineName = requireView().findViewById<EditText>(R.id.edit_engine_name).text.toString()
val searchQuery = requireView().findViewById<EditText>(R.id.edit_search_string).text.toString()
val pref = findManualAddSearchEnginePreference(R.string.pref_key_manual_add_search_engine)
val engineValid = pref.validateEngineNameAndShowError(engineName)
val searchValid = pref.validateSearchQueryAndShowError(searchQuery)
val isPartialSuccess = engineValid && searchValid
if (isPartialSuccess) {
ViewUtils.hideKeyboard(view)
setUiIsValidatingAsync(true, item)
activeAsyncTask = ValidateSearchEngineAsyncTask(
this,
engineName,
searchQuery,
requireComponents.client
).execute()
menuItemForActiveAsyncTask = item
} else {
TelemetryWrapper.saveCustomSearchEngineEvent(false)
}
}
when (item.itemId) {
R.id.learn_more -> openLearnMore()
R.id.menu_save_search_engine -> saveSearchEngine()
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun onDestroyView() {
super.onDestroyView()
if (view != null) ViewUtils.hideKeyboard(view)
}
private fun setUiIsValidatingAsync(isValidating: Boolean, saveMenuItem: MenuItem?) {
val pref = findManualAddSearchEnginePreference(R.string.pref_key_manual_add_search_engine)
if (isValidating) {
view?.alpha = DISABLED_ALPHA
// Delay showing the loading indicator to prevent it flashing on the screen
handler.postDelayed({
pref.setProgressViewShown(isValidating)
}, LOADING_INDICATOR_DELAY)
} else {
view?.alpha = 1f
handler.removeCallbacksAndMessages(null)
pref.setProgressViewShown(isValidating)
}
// Disable text entry until done validating
val viewGroup = view as ViewGroup
enableAllSubviews(!isValidating, viewGroup)
saveMenuItem!!.isEnabled = !isValidating
}
private fun enableAllSubviews(shouldEnable: Boolean, viewGroup: ViewGroup) {
for (i in 0 until viewGroup.childCount) {
val child = viewGroup.getChildAt(i)
if (child is ViewGroup) {
enableAllSubviews(shouldEnable, child)
} else {
child.isEnabled = shouldEnable
}
}
}
private fun findManualAddSearchEnginePreference(id: Int): ManualAddSearchEnginePreference {
return findPreference(getString(id)) as ManualAddSearchEnginePreference
}
companion object {
private const val LOGTAG = "ManualAddSearchEngine"
private const val SEARCH_QUERY_VALIDATION_TIMEOUT_MILLIS = 4000
private const val VALID_RESPONSE_CODE_UPPER_BOUND = 300
private const val DISABLED_ALPHA = 0.5f
private const val LOADING_INDICATOR_DELAY: Long = 1000
@WorkerThread
@JvmStatic
fun isValidSearchQueryURL(client: Client, query: String): Boolean {
// we should share the code to substitute and normalize the search string (see SearchEngine.buildSearchUrl).
val encodedTestQuery = Uri.encode("testSearchEngineValidation")
val normalizedHttpsSearchURLStr = UrlUtils.normalize(query)
val searchURLStr = normalizedHttpsSearchURLStr.replace("%s".toRegex(), encodedTestQuery)
try { URL(searchURLStr) } catch (e: MalformedURLException) {
// Don't log exception to avoid leaking URL.
Log.d(LOGTAG, "Failure to get response code from server: returning invalid search query")
return false
}
val request = Request(
url = searchURLStr,
connectTimeout = SEARCH_QUERY_VALIDATION_TIMEOUT_MILLIS.toLong() to TimeUnit.MILLISECONDS,
readTimeout = SEARCH_QUERY_VALIDATION_TIMEOUT_MILLIS.toLong() to TimeUnit.MILLISECONDS,
redirect = FOLLOW,
private = true
)
return try {
client.fetch(request).status < VALID_RESPONSE_CODE_UPPER_BOUND
} catch (e: IOException) {
Log.d(LOGTAG, "Failure to get response code from server: returning invalid search query")
false
}
}
}
private class ValidateSearchEngineAsyncTask
constructor (
fragment: ManualAddSearchEngineSettingsFragment,
private val engineName: String,
private val query: String,
private val client: Client
) : AsyncTask<Void, Void, Boolean>() {
private val fragmentWeakReference = WeakReference(fragment)
override fun doInBackground(vararg p0: Void?): Boolean {
val isValidSearchQuery = isValidSearchQueryURL(client, query)
TelemetryWrapper.saveCustomSearchEngineEvent(isValidSearchQuery)
return isValidSearchQuery
}
override fun onPostExecute(isValidSearchQuery: Boolean) {
super.onPostExecute(isValidSearchQuery)
if (isCancelled) {
Log.d(LOGTAG, "ValidateSearchEngineAsyncTask has been cancelled")
return
}
val fragment = fragmentWeakReference.get()
if (fragment == null) {
Log.d(LOGTAG, "Fragment or menu item no longer exists when search query " +
"validation async task returned.")
return
}
if (isValidSearchQuery) {
CustomSearchEngineStore.addSearchEngine(fragment.requireActivity(), engineName, query)
Snackbar.make(fragment.requireView(), R.string.search_add_confirmation, Snackbar.LENGTH_SHORT).show()
Settings.getInstance(fragment.requireActivity()).setDefaultSearchEngineByName(engineName)
@Suppress("DEPRECATION")
fragment.requireFragmentManager().popBackStack()
} else {
showServerError(fragment)
}
fragment.setUiIsValidatingAsync(false, fragment.menuItemForActiveAsyncTask)
fragment.activeAsyncTask = null
fragment.menuItemForActiveAsyncTask = null
}
private fun showServerError(that: ManualAddSearchEngineSettingsFragment) {
val pref = that.findManualAddSearchEnginePreference(R.string.pref_key_manual_add_search_engine)
pref.setSearchQueryErrorText(that.getString(R.string.error_hostLookup_title))
}
}
}