-
Notifications
You must be signed in to change notification settings - Fork 590
/
WebViewActivity.kt
1643 lines (1518 loc) · 71.8 KB
/
WebViewActivity.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package io.homeassistant.companion.android.webview
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.app.PictureInPictureParams
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Rect
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.os.VibrationEffect
import android.os.Vibrator
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Log
import android.util.Rational
import android.view.HapticFeedbackConstants
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.webkit.CookieManager
import android.webkit.HttpAuthHandler
import android.webkit.JavascriptInterface
import android.webkit.JsResult
import android.webkit.PermissionRequest
import android.webkit.RenderProcessGoneDetail
import android.webkit.SslErrorHandler
import android.webkit.URLUtil
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.OptIn
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.getSystemService
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.ColorUtils
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.VideoSize
import androidx.media3.datasource.cronet.CronetDataSource
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import dagger.hilt.android.AndroidEntryPoint
import io.homeassistant.companion.android.BaseActivity
import io.homeassistant.companion.android.BuildConfig
import io.homeassistant.companion.android.R
import io.homeassistant.companion.android.assist.AssistActivity
import io.homeassistant.companion.android.authenticator.Authenticator
import io.homeassistant.companion.android.common.R as commonR
import io.homeassistant.companion.android.common.data.HomeAssistantApis
import io.homeassistant.companion.android.common.data.keychain.KeyChainRepository
import io.homeassistant.companion.android.common.data.servers.ServerManager
import io.homeassistant.companion.android.common.util.DisabledLocationHandler
import io.homeassistant.companion.android.database.authentication.Authentication
import io.homeassistant.companion.android.database.authentication.AuthenticationDao
import io.homeassistant.companion.android.databinding.ActivityWebviewBinding
import io.homeassistant.companion.android.databinding.DialogAuthenticationBinding
import io.homeassistant.companion.android.launch.LaunchActivity
import io.homeassistant.companion.android.nfc.WriteNfcTag
import io.homeassistant.companion.android.sensors.SensorReceiver
import io.homeassistant.companion.android.sensors.SensorWorker
import io.homeassistant.companion.android.settings.SettingsActivity
import io.homeassistant.companion.android.settings.server.ServerChooserFragment
import io.homeassistant.companion.android.themes.ThemesManager
import io.homeassistant.companion.android.util.ChangeLog
import io.homeassistant.companion.android.util.DataUriDownloadManager
import io.homeassistant.companion.android.util.LifecycleHandler
import io.homeassistant.companion.android.util.OnSwipeListener
import io.homeassistant.companion.android.util.TLSWebViewClient
import io.homeassistant.companion.android.util.isStarted
import io.homeassistant.companion.android.websocket.WebsocketManager
import io.homeassistant.companion.android.webview.WebView.ErrorType
import io.homeassistant.companion.android.webview.externalbus.ExternalBusMessage
import java.util.concurrent.Executors
import javax.inject.Inject
import javax.inject.Named
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.chromium.net.CronetEngine
import org.json.JSONObject
@OptIn(androidx.media3.common.util.UnstableApi::class)
@AndroidEntryPoint
class WebViewActivity : BaseActivity(), io.homeassistant.companion.android.webview.WebView {
companion object {
const val EXTRA_PATH = "path"
const val EXTRA_SERVER = "server"
const val EXTRA_SHOW_WHEN_LOCKED = "show_when_locked"
private const val TAG = "WebviewActivity"
private const val APP_PREFIX = "app://"
private const val INTENT_PREFIX = "intent:"
private const val MARKET_PREFIX = "https://play.google.com/store/apps/details?id="
fun newInstance(context: Context, path: String? = null, serverId: Int? = null): Intent {
return Intent(context, WebViewActivity::class.java).apply {
putExtra(EXTRA_PATH, path)
putExtra(EXTRA_SERVER, serverId)
}
}
private const val CONNECTION_DELAY = 10000L
}
private val ioScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job())
private val requestPermissions =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
if (it.any { result -> result.value }) {
webView.reload()
}
}
private val requestStoragePermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
downloadFile(downloadFileUrl, downloadFileContentDisposition, downloadFileMimetype)
}
}
private val writeNfcTag = registerForActivityResult(WriteNfcTag()) { messageId ->
sendExternalBusMessage(
ExternalBusMessage(
id = messageId,
type = "result",
success = true,
result = emptyMap<String, String>(),
callback = {
Log.d(TAG, "NFC Write Complete $it")
}
)
)
}
private val showWebFileChooser = registerForActivityResult(ShowWebFileChooser()) { result ->
mFilePathCallback?.onReceiveValue(result)
mFilePathCallback = null
}
private val commissionMatterDevice = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
presenter.onMatterThreadIntentResult(this, result)
}
@Inject
lateinit var presenter: WebViewPresenter
@Inject
lateinit var themesManager: ThemesManager
@Inject
lateinit var changeLog: ChangeLog
@Inject
lateinit var serverManager: ServerManager
@Inject
lateinit var authenticationDao: AuthenticationDao
@Inject
@Named("keyChainRepository")
lateinit var keyChainRepository: KeyChainRepository
private lateinit var binding: ActivityWebviewBinding
private lateinit var webView: WebView
private lateinit var loadedUrl: String
private lateinit var decor: FrameLayout
private lateinit var myCustomView: View
private lateinit var authenticator: Authenticator
private lateinit var exoPlayerView: PlayerView
private lateinit var windowInsetsController: WindowInsetsControllerCompat
private var mFilePathCallback: ValueCallback<Array<Uri>>? = null
private var isConnected = false
private var isShowingError = false
private var alertDialog: AlertDialog? = null
private var isVideoFullScreen = false
private var videoHeight = 0
private var firstAuthTime: Long = 0
private var resourceURL: String = ""
private var appLocked = true
private var unlockingApp = false
private var exoPlayer: ExoPlayer? = null
private var isExoFullScreen = false
private var exoTop = 0 // These margins are from the DOM and scaled to screen
private var exoLeft = 0
private var exoRight = 0
private var exoBottom = 0
private var exoMute = true
private var failedConnection = "external"
private var clearHistory = false
private var moreInfoEntity = ""
private val moreInfoMutex = Mutex()
private var currentAutoplay: Boolean = false
private var downloadFileUrl = ""
private var downloadFileContentDisposition = ""
private var downloadFileMimetype = ""
private val javascriptInterface = "externalApp"
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
if (
intent.extras?.containsKey(EXTRA_SHOW_WHEN_LOCKED) == true &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1
) {
// Allow showing this on the lock screen when using device controls panel
setShowWhenLocked(intent.extras?.getBoolean(EXTRA_SHOW_WHEN_LOCKED) ?: false)
}
super.onCreate(savedInstanceState)
binding = ActivityWebviewBinding.inflate(layoutInflater)
setContentView(binding.root)
if (intent.extras?.containsKey(EXTRA_SERVER) == true) {
intent.extras?.getInt(EXTRA_SERVER)?.let {
presenter.setActiveServer(it)
intent.removeExtra(EXTRA_SERVER)
}
}
windowInsetsController = WindowInsetsControllerCompat(window, window.decorView)
// Initially set status and navigation bar color to colorLaunchScreenBackground to match the launch screen until the web frontend is loaded
val colorLaunchScreenBackground = ResourcesCompat.getColor(resources, commonR.color.colorLaunchScreenBackground, theme)
setStatusBarAndNavigationBarColor(colorLaunchScreenBackground, colorLaunchScreenBackground)
binding.blurView.setupWith(binding.root)
.setBlurRadius(8f)
exoPlayerView = binding.exoplayerView
exoPlayerView.visibility = View.GONE
exoPlayerView.setBackgroundColor(Color.BLACK)
exoPlayerView.alpha = 1f
exoPlayerView.controllerShowTimeoutMs = 2000
appLocked = presenter.isAppLocked()
binding.blurView.setBlurEnabled(appLocked)
authenticator = Authenticator(this, this, ::authenticationResult)
decor = window.decorView as FrameLayout
webView = binding.webview
val onBackPressed = object : OnBackPressedCallback(webView.canGoBack()) {
override fun handleOnBackPressed() {
if (webView.canGoBack()) webView.goBack()
}
}
onBackPressedDispatcher.addCallback(this, onBackPressed)
webView.apply {
setOnTouchListener(object : OnSwipeListener(this@WebViewActivity) {
override fun onSwipe(
e1: MotionEvent,
e2: MotionEvent,
velocity: Float,
direction: SwipeDirection,
pointerCount: Int
): Boolean {
if (pointerCount == 3 && velocity >= 75) {
when (direction) {
SwipeDirection.LEFT -> presenter.nextServer()
SwipeDirection.RIGHT -> presenter.previousServer()
SwipeDirection.UP -> {
val serverChooser = ServerChooserFragment()
supportFragmentManager.setFragmentResultListener(ServerChooserFragment.RESULT_KEY, this@WebViewActivity) { _, bundle ->
if (bundle.containsKey(ServerChooserFragment.RESULT_SERVER)) {
presenter.switchActiveServer(bundle.getInt(ServerChooserFragment.RESULT_SERVER))
}
supportFragmentManager.clearFragmentResultListener(ServerChooserFragment.RESULT_KEY)
}
serverChooser.show(supportFragmentManager, ServerChooserFragment.TAG)
}
SwipeDirection.DOWN -> {
dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E))
}
}
}
return appLocked
}
override fun onMotionEventHandled(v: View?, event: MotionEvent?): Boolean {
return appLocked
}
})
settings.minimumFontSize = 5
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.displayZoomControls = false
settings.mediaPlaybackRequiresUserGesture = !presenter.isAutoPlayVideoEnabled()
settings.userAgentString = settings.userAgentString + " ${HomeAssistantApis.USER_AGENT_STRING}"
webViewClient = object : TLSWebViewClient(keyChainRepository) {
@Deprecated("Deprecated in Java for SDK >= 23")
override fun onReceivedError(
view: WebView?,
errorCode: Int,
description: String?,
failingUrl: String?
) {
Log.e(TAG, "onReceivedError: errorCode: $errorCode url:$failingUrl")
if (failingUrl == loadedUrl) {
showError()
}
}
override fun onPageFinished(view: WebView?, url: String?) {
if (clearHistory) {
webView.clearHistory()
clearHistory = false
}
enablePinchToZoom()
if (moreInfoEntity != "" && view?.progress == 100 && isConnected) {
ioScope.launch {
val owner = "onPageFinished:$moreInfoEntity"
if (moreInfoMutex.tryLock(owner)) {
delay(2000L)
Log.d(TAG, "More info entity: $moreInfoEntity")
webView.evaluateJavascript(
"document.querySelector(\"home-assistant\").dispatchEvent(new CustomEvent(\"hass-more-info\", { detail: { entityId: \"$moreInfoEntity\" }}))"
) {
moreInfoMutex.unlock(owner)
moreInfoEntity = ""
}
}
}
}
}
override fun onReceivedHttpError(
view: WebView?,
request: WebResourceRequest?,
errorResponse: WebResourceResponse?
) {
Log.e(TAG, "onReceivedHttpError: ${errorResponse?.statusCode} : ${errorResponse?.reasonPhrase} for: ${request?.url}")
if (request?.url.toString() == loadedUrl) {
showError()
}
}
override fun onReceivedHttpAuthRequest(
view: WebView,
handler: HttpAuthHandler,
host: String,
realm: String
) {
var authError = false
if (System.currentTimeMillis() <= (firstAuthTime + 500)) {
authError = true
}
authenticationDialog(handler, host, realm, authError)
}
override fun onReceivedSslError(
view: WebView?,
handler: SslErrorHandler?,
error: SslError?
) {
Log.e(TAG, "onReceivedSslError: $error")
showError(
ErrorType.SSL,
error,
null
)
}
override fun onRenderProcessGone(
view: WebView?,
handler: RenderProcessGoneDetail?
): Boolean {
Log.e(TAG, "onRenderProcessGone: webView crashed")
view?.let {
reload()
webViewAddJavascriptInterface()
}
return true
}
override fun onLoadResource(
view: WebView?,
url: String?
) {
resourceURL = url!!
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
request?.url?.let {
try {
if (it.toString().startsWith(APP_PREFIX)) {
Log.d(TAG, "Launching the app")
val intent = packageManager.getLaunchIntentForPackage(
it.toString().substringAfter(APP_PREFIX)
)
if (intent != null) {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
} else {
Log.w(TAG, "No intent to launch app found, opening app store")
val marketIntent = Intent(Intent.ACTION_VIEW)
marketIntent.data = Uri.parse(
MARKET_PREFIX + it.toString().substringAfter(APP_PREFIX)
)
startActivity(marketIntent)
}
return true
} else if (it.toString().startsWith(INTENT_PREFIX)) {
Log.d(TAG, "Launching the intent")
val intent =
Intent.parseUri(it.toString(), Intent.URI_INTENT_SCHEME)
val intentPackage = intent.`package`?.let { it1 ->
packageManager.getLaunchIntentForPackage(
it1
)
}
if (intentPackage == null && !intent.`package`.isNullOrEmpty()) {
Log.w(TAG, "No app found for intent prefix, opening app store")
val marketIntent = Intent(Intent.ACTION_VIEW)
marketIntent.data =
Uri.parse(MARKET_PREFIX + intent.`package`.toString())
startActivity(marketIntent)
} else {
startActivity(intent)
}
return true
} else if (!webView.url.toString().contains(it.toString())) {
Log.d(TAG, "Launching browser")
val browserIntent = Intent(Intent.ACTION_VIEW, it)
startActivity(browserIntent)
return true
} else {
Log.d(TAG, "No unique cases found to override")
}
} catch (e: Exception) {
Log.e(TAG, "Unable to override the URL", e)
}
}
return false
}
override fun doUpdateVisitedHistory(
view: WebView?,
url: String?,
isReload: Boolean
) {
super.doUpdateVisitedHistory(view, url, isReload)
onBackPressed.isEnabled = canGoBack()
}
}
setDownloadListener { url, _, contentDisposition, mimetype, _ ->
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ||
ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
downloadFile(url, contentDisposition, mimetype)
} else {
downloadFileUrl = url
downloadFileContentDisposition = contentDisposition
downloadFileMimetype = mimetype
requestStoragePermission.launch(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}
webChromeClient = object : WebChromeClient() {
override fun onJsConfirm(
view: WebView,
url: String,
message: String,
result: JsResult
): Boolean {
AlertDialog
.Builder(this@WebViewActivity)
.setTitle(commonR.string.app_name)
.setMessage(message)
.setPositiveButton(android.R.string.ok) { _, _ -> result.confirm() }
.setNegativeButton(android.R.string.cancel) { _, _ -> result.cancel() }
.setOnDismissListener { result.cancel() }
.create()
.show()
return true
}
override fun onPermissionRequest(request: PermissionRequest?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val alreadyGranted = ArrayList<String>()
val toBeGranted = ArrayList<String>()
request?.resources?.forEach {
if (it == PermissionRequest.RESOURCE_VIDEO_CAPTURE) {
if (ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
alreadyGranted.add(it)
} else {
toBeGranted.add(android.Manifest.permission.CAMERA)
}
} else if (it == PermissionRequest.RESOURCE_AUDIO_CAPTURE) {
if (ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED
) {
alreadyGranted.add(it)
} else {
toBeGranted.add(android.Manifest.permission.RECORD_AUDIO)
}
}
}
if (alreadyGranted.size > 0) {
request?.grant(alreadyGranted.toTypedArray())
}
if (toBeGranted.size > 0) {
requestPermissions.launch(
toBeGranted.toTypedArray()
)
}
} else {
// If we are before M we already have permission, just grant it.
request?.grant(request.resources)
}
}
override fun onShowFileChooser(
view: WebView,
uploadMsg: ValueCallback<Array<Uri>>,
fileChooserParams: FileChooserParams
): Boolean {
mFilePathCallback = uploadMsg
showWebFileChooser.launch(fileChooserParams)
return true
}
override fun onShowCustomView(view: View, callback: CustomViewCallback) {
myCustomView = view
decor.addView(
view,
FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT
)
)
hideSystemUI()
isVideoFullScreen = true
}
override fun onHideCustomView() {
decor.removeView(myCustomView)
if (!presenter.isFullScreen()) {
showSystemUI()
}
isVideoFullScreen = false
super.onHideCustomView()
}
}
webViewAddJavascriptInterface()
}
// Set WebView background color to transparent, so that the theme of the android activity has control over it.
// This enables the ability to have the launch screen behind the WebView until the web frontend gets rendered
binding.webview.setBackgroundColor(Color.TRANSPARENT)
themesManager.setThemeForWebView(this, webView.settings)
val cookieManager = CookieManager.getInstance()
cookieManager.setAcceptCookie(true)
cookieManager.setAcceptThirdPartyCookies(webView, true)
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
if (presenter.isFullScreen()) {
hideSystemUI()
}
}
}
if (presenter.isKeepScreenOnEnabled()) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
currentAutoplay = presenter.isAutoPlayVideoEnabled()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val webviewPackage = WebViewCompat.getCurrentWebViewPackage(this)
Log.d(TAG, "Current webview package ${webviewPackage?.packageName} and version ${webviewPackage?.versionName}")
}
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
presenter.getMatterThreadStepFlow().collect {
Log.d(TAG, "Matter/Thread step changed to $it")
when (it) {
MatterThreadStep.THREAD_EXPORT_TO_SERVER_MATTER,
MatterThreadStep.THREAD_EXPORT_TO_SERVER_ONLY,
MatterThreadStep.MATTER_IN_PROGRESS -> {
presenter.getMatterThreadIntent()?.let { intentSender ->
commissionMatterDevice.launch(IntentSenderRequest.Builder(intentSender).build())
}
}
MatterThreadStep.THREAD_NONE -> {
alertDialog?.cancel()
AlertDialog.Builder(this@WebViewActivity)
.setMessage(commonR.string.thread_export_none)
.setPositiveButton(commonR.string.ok, null)
.show()
presenter.finishMatterThreadFlow()
}
MatterThreadStep.THREAD_SENT -> {
Toast.makeText(this@WebViewActivity, commonR.string.thread_export_success, Toast.LENGTH_SHORT).show()
alertDialog?.cancel()
presenter.finishMatterThreadFlow()
}
MatterThreadStep.ERROR_MATTER -> {
Toast.makeText(this@WebViewActivity, commonR.string.matter_commissioning_unavailable, Toast.LENGTH_SHORT).show()
presenter.finishMatterThreadFlow()
}
MatterThreadStep.ERROR_THREAD_LOCAL_NETWORK -> {
alertDialog?.cancel()
AlertDialog.Builder(this@WebViewActivity)
.setMessage(commonR.string.thread_export_not_connected)
.setPositiveButton(commonR.string.ok, null)
.show()
presenter.finishMatterThreadFlow()
}
MatterThreadStep.ERROR_THREAD_OTHER -> {
Toast.makeText(this@WebViewActivity, commonR.string.thread_export_unavailable, Toast.LENGTH_SHORT).show()
alertDialog?.cancel()
presenter.finishMatterThreadFlow()
}
else -> { } // Do nothing
}
}
}
}
}
private fun webViewAddJavascriptInterface() {
webView.removeJavascriptInterface(javascriptInterface)
webView.apply {
addJavascriptInterface(
object : Any() {
// TODO This feature is deprecated and should be removed after 2022.6
@JavascriptInterface
fun onHomeAssistantSetTheme() {
// We need to launch the getAndSetStatusBarNavigationBarColors in another thread, because otherwise the evaluateJavascript inside the method
// will not trigger it's callback method :/
GlobalScope.launch(Dispatchers.Main) {
getAndSetStatusBarNavigationBarColors()
}
}
@JavascriptInterface
fun getExternalAuth(payload: String) {
JSONObject(payload).let {
presenter.onGetExternalAuth(
this@WebViewActivity,
it.getString("callback"),
it.has("force") && it.getBoolean("force")
)
}
}
@JavascriptInterface
fun revokeExternalAuth(callback: String) {
presenter.onRevokeExternalAuth(JSONObject(callback).get("callback") as String)
relaunchApp()
finish()
}
@JavascriptInterface
fun externalBus(message: String) {
Log.d(TAG, "External bus $message")
webView.post {
val json = JSONObject(message)
when (json.get("type")) {
"connection-status" -> {
isConnected = json.getJSONObject("payload")
.getString("event") == "connected"
if (isConnected) {
alertDialog?.cancel()
presenter.checkSecurityVersion()
}
}
"config/get" -> {
val pm: PackageManager = context.packageManager
val hasNfc = pm.hasSystemFeature(PackageManager.FEATURE_NFC)
val canCommissionMatter = presenter.appCanCommissionMatterDevice()
val canExportThread = presenter.appCanExportThreadCredentials()
sendExternalBusMessage(
ExternalBusMessage(
id = JSONObject(message).get("id"),
type = "result",
success = true,
result = JSONObject(
mapOf(
"hasSettingsScreen" to true,
"canWriteTag" to hasNfc,
"hasExoPlayer" to true,
"canCommissionMatter" to canCommissionMatter,
"canImportThreadCredentials" to canExportThread,
"hasAssist" to true
)
),
callback = {
Log.d(TAG, "Callback $it")
}
)
)
// TODO This feature is deprecated and should be removed after 2022.6
getAndSetStatusBarNavigationBarColors()
// TODO This feature is deprecated and should be removed after 2022.6
// Set event lister for HA theme change
webView.evaluateJavascript(
"document.addEventListener('settheme', function ()" +
"{" +
"window.externalApp.onHomeAssistantSetTheme();" +
"});",
null
)
}
"assist/show" -> {
val payload = if (json.has("payload")) json.getJSONObject("payload") else null
startActivity(
AssistActivity.newInstance(
this@WebViewActivity,
serverId = presenter.getActiveServer(),
pipelineId = if (payload?.has("pipeline_id") == true) payload.getString("pipeline_id") else null,
startListening = if (payload?.has("start_listening") == true) payload.getBoolean("start_listening") else true
)
)
}
"config_screen/show" ->
startActivity(
SettingsActivity.newInstance(this@WebViewActivity)
)
"tag/write" ->
writeNfcTag.launch(
WriteNfcTag.Input(
tagId = json.getJSONObject("payload").getString("tag"),
messageId = JSONObject(message).getInt("id")
)
)
"matter/commission" -> presenter.startCommissioningMatterDevice(this@WebViewActivity)
"thread/import_credentials" -> {
presenter.exportThreadCredentials(this@WebViewActivity)
alertDialog = AlertDialog.Builder(this@WebViewActivity)
.setMessage(commonR.string.thread_debug_active)
.create()
alertDialog?.show()
}
"exoplayer/play_hls" -> exoPlayHls(json)
"exoplayer/stop" -> exoStopHls()
"exoplayer/resize" -> exoResizeHls(json)
"haptic" -> processHaptic(json.getJSONObject("payload").getString("hapticType"))
"theme-update" -> getAndSetStatusBarNavigationBarColors()
else -> presenter.onExternalBusMessage(json)
}
}
}
},
javascriptInterface
)
}
}
private fun getAndSetStatusBarNavigationBarColors() {
val htmlArraySpacer = "-SPACER-"
webView.evaluateJavascript(
"[" +
"document.getElementsByTagName('html')[0].computedStyleMap().get('--app-header-background-color')[0]," +
"document.getElementsByTagName('html')[0].computedStyleMap().get('--primary-background-color')[0]" +
"].join('" + htmlArraySpacer + "')"
) { webViewColors ->
GlobalScope.launch {
withContext(Dispatchers.Main) {
var statusBarColor = 0
var navigationBarColor = 0
if (!webViewColors.isNullOrEmpty() && webViewColors != "null") {
val trimmedColorString = webViewColors.substring(1, webViewColors.length - 1).trim()
val colors = trimmedColorString.split(htmlArraySpacer)
for (color in colors) {
Log.d(TAG, "Color from webview is \"$trimmedColorString\"")
}
statusBarColor = presenter.parseWebViewColor(colors[0].trim())
navigationBarColor = presenter.parseWebViewColor(colors[1].trim())
}
setStatusBarAndNavigationBarColor(statusBarColor, navigationBarColor)
}
}
}
}
override fun onStart() {
super.onStart()
presenter.onStart(this)
}
override fun onResume() {
super.onResume()
if (currentAutoplay != presenter.isAutoPlayVideoEnabled()) {
recreate()
}
presenter.updateActiveServer()
appLocked = presenter.isAppLocked()
binding.blurView.setBlurEnabled(appLocked)
enablePinchToZoom()
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG || presenter.isWebViewDebugEnabled())
requestedOrientation = when (presenter.getScreenOrientation()) {
getString(commonR.string.screen_orientation_option_value_portrait) -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
getString(commonR.string.screen_orientation_option_value_landscape) -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
else -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
if (presenter.isKeepScreenOnEnabled()) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
SensorWorker.start(this)
WebsocketManager.start(this)
lifecycleScope.launch {
checkAndWarnForDisabledLocation()
}
changeLog.showChangeLog(this, false)
}
override fun onStop() {
super.onStop()
openFirstViewOnDashboardIfNeeded()
}
override fun onPause() {
super.onPause()
presenter.setAppActive(false)
if (!isFinishing) SensorReceiver.updateAllSensors(this)
}
private suspend fun checkAndWarnForDisabledLocation() {
var showLocationDisabledWarning = false
val settingsWithLocationPermissions = mutableListOf<String>()
if (!DisabledLocationHandler.isLocationEnabled(this) && presenter.isSsidUsed()) {
showLocationDisabledWarning = true
settingsWithLocationPermissions.add(getString(commonR.string.pref_connection_wifi))
}
for (manager in SensorReceiver.MANAGERS) {
for (basicSensor in manager.getAvailableSensors(this)) {
if (manager.isEnabled(this, basicSensor)) {
val permissions = manager.requiredPermissions(basicSensor.id)
val fineLocation = DisabledLocationHandler.containsLocationPermission(permissions, true)
val coarseLocation = DisabledLocationHandler.containsLocationPermission(permissions, false)
if ((fineLocation || coarseLocation)) {
if (!DisabledLocationHandler.isLocationEnabled(this)) showLocationDisabledWarning = true
settingsWithLocationPermissions.add(getString(basicSensor.name))
}
}
}
}
if (showLocationDisabledWarning) {
DisabledLocationHandler.showLocationDisabledWarnDialog(this@WebViewActivity, settingsWithLocationPermissions.toTypedArray(), true)
} else {
DisabledLocationHandler.removeLocationDisabledWarning(this@WebViewActivity)
}
}
fun exoPlayHls(json: JSONObject) {
val payload = json.getJSONObject("payload")
val uri = Uri.parse(payload.getString("url"))
exoMute = payload.optBoolean("muted")
runOnUiThread {
exoPlayer = ExoPlayer.Builder(applicationContext).setMediaSourceFactory(
DefaultMediaSourceFactory(
CronetDataSource.Factory(
CronetEngine.Builder(applicationContext).enableQuic(true).build(),
Executors.newSingleThreadExecutor()
)
).setLiveMaxSpeed(8.0f)
).setLoadControl(
DefaultLoadControl.Builder().setBufferDurationsMs(
0,
30000,
0,
0
).build()
).build()
exoPlayer?.setMediaItem(MediaItem.fromUri(uri))
exoPlayer?.playWhenReady = true
exoPlayer?.addListener(object : Player.Listener {
override fun onVideoSizeChanged(videoSize: VideoSize) {
super.onVideoSizeChanged(videoSize)
if (videoSize.height == 0 || videoSize.width == 0) return
exoBottom =
exoTop + ((exoRight - exoLeft) * videoSize.height / videoSize.width)
runOnUiThread {
exoResizeLayout()
}
}
})
exoPlayer?.prepare()
exoMute = !exoMute // Invert because exoToggleMute() will invert again
exoToggleMute()
exoPlayerView.setFullscreenButtonClickListener { isFullScreen ->
isExoFullScreen = isFullScreen
exoResizeLayout()
}
exoPlayerView.player = exoPlayer
exoPlayerView.visibility = View.VISIBLE
findViewById<ImageButton>(R.id.exo_ha_mute)?.setOnClickListener { exoToggleMute() }
}
sendExternalBusMessage(
ExternalBusMessage(
id = json.get("id"),
type = "result",
success = true,
callback = {
Log.d(TAG, "Callback $it")
}
)
)
}
fun exoStopHls() {
runOnUiThread {
exoPlayerView.visibility = View.GONE
exoPlayerView.player = null
exoPlayer?.release()
exoPlayer = null
}
}
fun exoResizeHls(json: JSONObject) {
val rect = json.getJSONObject("payload")
val displayMetrics = applicationContext.resources.displayMetrics
exoLeft = (rect.getInt("left") * displayMetrics.density).toInt()
exoTop = (rect.getInt("top") * displayMetrics.density).toInt()
exoRight = (rect.getInt("right") * displayMetrics.density).toInt()
exoBottom = if ((exoPlayer == null) || (exoPlayer!!.videoFormat == null)) {
// only set exoBottom if we can't calculate it from the video
(rect.getInt("bottom") * displayMetrics.density).toInt()
} else {
exoTop + (exoRight - exoLeft) * exoPlayer!!.videoFormat!!.height /