forked from home-assistant/android
/
SettingsFragment.kt
513 lines (460 loc) · 22.5 KB
/
SettingsFragment.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package io.homeassistant.companion.android.settings
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.text.InputType
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.content.res.AppCompatResources
import androidx.biometric.BiometricManager
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import io.homeassistant.companion.android.BuildConfig
import io.homeassistant.companion.android.DaggerPresenterComponent
import io.homeassistant.companion.android.PresenterModule
import io.homeassistant.companion.android.R
import io.homeassistant.companion.android.authenticator.Authenticator
import io.homeassistant.companion.android.common.dagger.GraphComponentAccessor
import io.homeassistant.companion.android.nfc.NfcSetupActivity
import io.homeassistant.companion.android.sensors.SensorsSettingsFragment
import io.homeassistant.companion.android.settings.language.LanguagesProvider
import io.homeassistant.companion.android.settings.log.LogFragment
import io.homeassistant.companion.android.settings.notification.NotificationHistoryFragment
import io.homeassistant.companion.android.settings.qs.ManageTilesFragment
import io.homeassistant.companion.android.settings.shortcuts.ManageShortcutsSettingsFragment
import io.homeassistant.companion.android.settings.ssid.SsidDialogFragment
import io.homeassistant.companion.android.settings.ssid.SsidPreference
import io.homeassistant.companion.android.settings.widgets.ManageWidgetsSettingsFragment
import io.homeassistant.companion.android.util.DisabledLocationHandler
import io.homeassistant.companion.android.util.LocationPermissionInfoHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
class SettingsFragment : PreferenceFragmentCompat(), SettingsView {
companion object {
private const val TAG = "SettingsFragment"
private const val SSID_DIALOG_TAG = "${BuildConfig.APPLICATION_ID}.SSID_DIALOG_TAG"
private const val LOCATION_REQUEST_CODE = 0
private const val BACKGROUND_LOCATION_REQUEST_CODE = 1
fun newInstance() = SettingsFragment()
}
@Inject
lateinit var presenter: SettingsPresenter
@Inject
lateinit var langProvider: LanguagesProvider
private lateinit var authenticator: Authenticator
private var setLock = false
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
DaggerPresenterComponent
.builder()
.appComponent((activity?.application as GraphComponentAccessor).appComponent)
.presenterModule(PresenterModule(this))
.build()
.inject(this)
authenticator = Authenticator(requireContext(), requireActivity(), ::authenticationResult)
preferenceManager.preferenceDataStore = presenter.getPreferenceDataStore()
setPreferencesFromResource(R.xml.preferences, rootKey)
val onChangeUrlValidator = Preference.OnPreferenceChangeListener { _, newValue ->
val isValid = newValue.toString().isBlank() || newValue.toString().toHttpUrlOrNull() != null
if (!isValid) {
AlertDialog.Builder(requireActivity())
.setTitle(R.string.url_invalid)
.setMessage(R.string.url_parse_error)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.show()
}
isValid
}
findPreference<SwitchPreference>("app_lock")?.setOnPreferenceChangeListener { _, newValue ->
var isValid: Boolean
if (newValue == false) {
isValid = true
findPreference<EditTextPreference>("session_timeout")?.isVisible = false
} else {
isValid = true
if (BiometricManager.from(requireActivity()).canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) {
setLock = true
authenticator.authenticate(getString(R.string.biometric_set_title))
} else {
isValid = false
AlertDialog.Builder(requireActivity())
.setTitle(R.string.set_lock_title)
.setMessage(R.string.set_lock_message)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.show()
}
}
isValid
}
findPreference<EditTextPreference>("session_timeout")?.let { pref ->
pref.setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER
}
pref.isVisible = findPreference<SwitchPreference>("app_lock")?.isChecked == true
}
findPreference<Preference>("nfc_tags")?.let {
val pm: PackageManager = requireContext().packageManager
it.isVisible = pm.hasSystemFeature(PackageManager.FEATURE_NFC)
it.onPreferenceClickListener = Preference.OnPreferenceClickListener {
startActivity(NfcSetupActivity.newInstance(requireActivity()))
true
}
}
removeSystemFromThemesIfNeeded()
updateBackgroundAccessPref()
findPreference<EditTextPreference>("connection_internal")?.onPreferenceChangeListener =
onChangeUrlValidator
findPreference<EditTextPreference>("connection_external")?.onPreferenceChangeListener =
onChangeUrlValidator
findPreference<Preference>("sensors")?.setOnPreferenceClickListener {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, SensorsSettingsFragment.newInstance())
.addToBackStack(getString(R.string.sensors))
.commit()
return@setOnPreferenceClickListener true
}
findPreference<Preference>("manage_widgets")?.setOnPreferenceClickListener {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, ManageWidgetsSettingsFragment.newInstance())
.addToBackStack(getString(R.string.widgets))
.commit()
return@setOnPreferenceClickListener true
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
findPreference<PreferenceCategory>("shortcuts")?.let {
it.isVisible = true
}
findPreference<Preference>("manage_shortcuts")?.setOnPreferenceClickListener {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, ManageShortcutsSettingsFragment.newInstance())
.addToBackStack(getString(R.string.shortcuts))
.commit()
return@setOnPreferenceClickListener true
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
findPreference<PreferenceCategory>("quick_settings")?.let {
it.isVisible = true
}
findPreference<Preference>("manage_tiles")?.setOnPreferenceClickListener {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, ManageTilesFragment.newInstance())
.addToBackStack(getString(R.string.tiles))
.commit()
return@setOnPreferenceClickListener true
}
}
if (BuildConfig.FLAVOR == "full") {
findPreference<PreferenceCategory>("notifications")?.let {
it.isVisible = true
}
findPreference<Preference>("notification_history")?.let {
it.isVisible = true
it.setOnPreferenceClickListener {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, NotificationHistoryFragment.newInstance())
.addToBackStack(getString(R.string.notifications))
.commit()
return@setOnPreferenceClickListener true
}
}
findPreference<Preference>("notification_rate_limit")?.let {
lifecycleScope.launch(Dispatchers.Main) {
// Runs in IO Dispatcher
val rateLimits = presenter.getNotificationRateLimits()
if (rateLimits != null) {
var formattedDate = rateLimits?.resetsAt
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
val localDateTime = LocalDateTime.parse(rateLimits?.resetsAt, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
formattedDate = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault()).format(localDateTime)
} catch (e: Exception) {
Log.d(TAG, "Cannot parse notification rate limit date \"${rateLimits?.resetsAt}\"", e)
}
}
it.isVisible = true
it.summary = "\n${getString(R.string.successful)}: ${rateLimits?.successful} ${getString(R.string.errors)}: ${rateLimits?.errors}" +
"\n\n${getString(R.string.remaining)}/${getString(R.string.maximum)}: ${rateLimits?.remaining}/${rateLimits?.maximum}" +
"\n\n${getString(R.string.resets_at)}: $formattedDate"
}
}
}
findPreference<SwitchPreference>("crash_reporting")?.let {
it.isVisible = true
it.setOnPreferenceChangeListener { _, newValue ->
val checked = newValue as Boolean
true
}
}
val pm = requireContext().packageManager
val hasWearApp = pm.getLaunchIntentForPackage("com.google.android.wearable.app")
findPreference<PreferenceCategory>("wear_category")?.isVisible = hasWearApp != null
findPreference<Preference>("wear_settings")?.setOnPreferenceClickListener {
startActivity(SettingsWearActivity.newInstance(requireContext()))
return@setOnPreferenceClickListener true
}
}
findPreference<Preference>("changelog")?.let {
val link = if (BuildConfig.VERSION_NAME.startsWith("LOCAL"))
"https://github.com/home-assistant/android/releases"
else "https://github.com/home-assistant/android/releases/tag/${BuildConfig.VERSION_NAME.replace("-full", "").replace("-minimal", "")}"
it.summary = link
it.intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
}
findPreference<Preference>("version")?.let {
it.isCopyingEnabled = true
it.summary = BuildConfig.VERSION_NAME
}
findPreference<ListPreference>("languages")?.let {
val languages = langProvider.getSupportedLanguages(requireContext())
it.entries = languages.keys.toTypedArray()
it.entryValues = languages.values.toTypedArray()
}
findPreference<Preference>("privacy")?.let {
it.summary = "https://www.home-assistant.io/privacy/"
it.intent = Intent(Intent.ACTION_VIEW, Uri.parse(it.summary.toString()))
}
findPreference<Preference>("show_share_logs")?.setOnPreferenceClickListener {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, LogFragment.newInstance())
.addToBackStack(getString(R.string.log))
.commit()
return@setOnPreferenceClickListener true
}
presenter.onCreate()
}
override fun disableInternalConnection() {
findPreference<EditTextPreference>("connection_internal")?.let {
it.isEnabled = false
try {
val unwrappedDrawable =
AppCompatResources.getDrawable(requireContext(), R.drawable.ic_computer)
unwrappedDrawable?.setTint(Color.DKGRAY)
it.icon = unwrappedDrawable
} catch (e: Exception) {
Log.d("SettingsFragment", "Unable to set the icon tint", e)
}
}
findPreference<SwitchPreference>("prioritize_internal")?.let {
it.isEnabled = false
try {
val unwrappedDrawable =
AppCompatResources.getDrawable(requireContext(), R.drawable.ic_priority)
unwrappedDrawable?.setTint(Color.DKGRAY)
it.icon = unwrappedDrawable
} catch (e: Exception) {
Log.d("SettingsFragment", "Unable to set the icon tint", e)
}
}
}
override fun enableInternalConnection() {
findPreference<EditTextPreference>("connection_internal")?.let {
it.isEnabled = true
try {
val unwrappedDrawable =
AppCompatResources.getDrawable(requireContext(), R.drawable.ic_computer)
unwrappedDrawable?.setTint(resources.getColor(R.color.colorAccent))
it.icon = unwrappedDrawable
} catch (e: Exception) {
Log.d("SettingsFragment", "Unable to set the icon tint", e)
}
}
findPreference<SwitchPreference>("prioritize_internal")?.let {
it.isEnabled = true
try {
val unwrappedDrawable =
AppCompatResources.getDrawable(requireContext(), R.drawable.ic_priority)
unwrappedDrawable?.setTint(resources.getColor(R.color.colorAccent))
it.icon = unwrappedDrawable
} catch (e: Exception) {
Log.d("SettingsFragment", "Unable to set the icon tint", e)
}
}
}
override fun onLangSettingsChanged() {
requireActivity().recreate()
}
override fun onDisplayPreferenceDialog(preference: Preference) {
if (preference is SsidPreference) {
val permissionsToCheck: Array<String> = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} else {
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)
}
if (DisabledLocationHandler.isLocationEnabled(requireContext())) {
var permissionsToRequest: Array<String>? = null
if (!permissionsToCheck.isNullOrEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// For Android 11 we MUST NOT request Background Location permission with fine or coarse permissions
// as for Android 11 the background location request needs to be done separately
// See here: https://developer.android.com/about/versions/11/privacy/location#request-background-location-separately
permissionsToRequest = permissionsToCheck.toList().minus(Manifest.permission.ACCESS_BACKGROUND_LOCATION).toTypedArray()
}
val hasPermission = checkPermission(permissionsToCheck)
if (permissionsToCheck.isNotEmpty() && !hasPermission) {
LocationPermissionInfoHandler.showLocationPermInfoDialogIfNeeded(
requireContext(), permissionsToCheck,
continueYesCallback = {
checkAndRequestPermissions(permissionsToCheck, LOCATION_REQUEST_CODE, permissionsToRequest, true)
// openSsidDialog() will be called in onRequestPermissionsResult if permission is granted
}
)
} else openSsidDialog()
} else {
if (presenter.isSsidUsed()) {
DisabledLocationHandler.showLocationDisabledWarnDialog(requireActivity(), arrayOf(getString(R.string.pref_connection_wifi)), showAsNotification = false, withDisableOption = true) {
presenter.clearSsids()
preference.setSsids(emptySet())
}
} else {
DisabledLocationHandler.showLocationDisabledWarnDialog(requireActivity(), arrayOf(getString(R.string.pref_connection_wifi)))
}
}
} else {
super.onDisplayPreferenceDialog(preference)
}
}
private fun authenticationResult(result: Int) {
val success = result == Authenticator.SUCCESS
val switchLock = findPreference<SwitchPreference>("app_lock")
switchLock?.isChecked = success
findPreference<EditTextPreference>("session_timeout")?.isVisible = success
}
private fun removeSystemFromThemesIfNeeded() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
val pref = findPreference<ListPreference>("themes")
if (pref != null) {
val systemIndex = pref.findIndexOfValue("system")
if (systemIndex > 0) {
var entries = pref.entries?.toMutableList()
entries?.removeAt(systemIndex)
var entryValues = pref.entryValues?.toMutableList()
entryValues?.removeAt(systemIndex)
if (entries != null && entryValues != null) {
pref.entries = entries.toTypedArray()
pref.entryValues = entryValues.toTypedArray()
}
}
}
}
}
private fun updateBackgroundAccessPref() {
findPreference<Preference>("background")?.let {
if (isIgnoringBatteryOptimizations()) {
it.setSummary(R.string.background_access_enabled)
it.setOnPreferenceClickListener {
true
}
} else {
it.setSummary(R.string.background_access_disabled)
it.setOnPreferenceClickListener {
requestBackgroundAccess()
true
}
}
}
}
@SuppressLint("BatteryLife")
private fun requestBackgroundAccess() {
val intent: Intent
if (!isIgnoringBatteryOptimizations()) {
intent = Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:${activity?.packageName}")
)
startActivityForResult(intent, 0)
}
}
private fun checkAndRequestPermissions(permissions: Array<String>, requestCode: Int, requestPermissions: Array<String>? = null, forceRequest: Boolean = false): Boolean {
val permissionsNeeded = mutableListOf<String>()
for (permission in permissions) {
if (forceRequest || ContextCompat.checkSelfPermission(requireContext(), permission) === PackageManager.PERMISSION_DENIED) {
if (requestPermissions.isNullOrEmpty() || requestPermissions.contains(permission)) {
permissionsNeeded.add(permission)
}
}
}
return if (permissionsNeeded.isNotEmpty()) {
requestPermissions(permissionsNeeded.toTypedArray(), requestCode)
false
} else true
}
fun checkPermission(permissions: Array<String>?): Boolean {
if (!permissions.isNullOrEmpty()) {
for (permission in permissions) {
if (ContextCompat.checkSelfPermission(requireContext(), permission) === PackageManager.PERMISSION_DENIED) {
return false
}
}
}
return true
}
private fun openSsidDialog() {
// check if dialog is already showing
val fm = parentFragmentManager
if (fm.findFragmentByTag(SSID_DIALOG_TAG) != null) {
return
}
val ssidDialog = SsidDialogFragment.newInstance("connection_internal_ssids")
ssidDialog.setTargetFragment(this, 0)
ssidDialog.show(fm, SSID_DIALOG_TAG)
}
private fun isIgnoringBatteryOptimizations(): Boolean {
return Build.VERSION.SDK_INT <= Build.VERSION_CODES.M ||
context?.getSystemService(PowerManager::class.java)
?.isIgnoringBatteryOptimizations(requireActivity().packageName)
?: false
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
updateBackgroundAccessPref()
val isGreaterR = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
if (requestCode == LOCATION_REQUEST_CODE && grantResults.isNotEmpty()) {
if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
if (isGreaterR) {
// For Android 11 we MUST NOT request Background Location permission with fine or coarse permissions
// as for Android 11 the background location request needs to be done separately
// See here: https://developer.android.com/about/versions/11/privacy/location#request-background-location-separately
// The separate request of background location is done here
requestPermissions(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), BACKGROUND_LOCATION_REQUEST_CODE)
}
}
}
if ((requestCode == LOCATION_REQUEST_CODE && !isGreaterR || requestCode == BACKGROUND_LOCATION_REQUEST_CODE && isGreaterR) && grantResults.isNotEmpty()) {
if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
openSsidDialog()
}
}
}
override fun onResume() {
super.onResume()
activity?.title = getString(R.string.app_name)
}
}