-
Notifications
You must be signed in to change notification settings - Fork 599
/
MessagingManager.kt
1978 lines (1844 loc) · 86.7 KB
/
MessagingManager.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.notifications
import android.Manifest
import android.app.ActivityManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.bluetooth.BluetoothManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.media.AudioManager
import android.media.MediaMetadataRetriever
import android.media.RingtoneManager
import android.media.session.MediaController
import android.media.session.MediaSessionManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.widget.RemoteViews
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.biometric.BiometricManager
import androidx.car.app.notification.CarAppExtender
import androidx.car.app.notification.CarNotificationManager
import androidx.car.app.notification.CarPendingIntent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.RemoteInput
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.getSystemService
import androidx.core.text.isDigitsOnly
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import dagger.hilt.android.qualifiers.ApplicationContext
import io.homeassistant.companion.android.R
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.prefs.PrefsRepository
import io.homeassistant.companion.android.common.data.servers.ServerManager
import io.homeassistant.companion.android.common.notifications.DeviceCommandData
import io.homeassistant.companion.android.common.notifications.NotificationData
import io.homeassistant.companion.android.common.notifications.clearNotification
import io.homeassistant.companion.android.common.notifications.commandBeaconMonitor
import io.homeassistant.companion.android.common.notifications.commandBleTransmitter
import io.homeassistant.companion.android.common.notifications.createChannelID
import io.homeassistant.companion.android.common.notifications.getGroupNotificationBuilder
import io.homeassistant.companion.android.common.notifications.handleChannel
import io.homeassistant.companion.android.common.notifications.handleColor
import io.homeassistant.companion.android.common.notifications.handleDeleteIntent
import io.homeassistant.companion.android.common.notifications.handleSmallIcon
import io.homeassistant.companion.android.common.notifications.handleText
import io.homeassistant.companion.android.common.notifications.parseColor
import io.homeassistant.companion.android.common.notifications.parseVibrationPattern
import io.homeassistant.companion.android.common.notifications.prepareText
import io.homeassistant.companion.android.common.util.TextToSpeechData
import io.homeassistant.companion.android.common.util.cancelGroupIfNeeded
import io.homeassistant.companion.android.common.util.getActiveNotification
import io.homeassistant.companion.android.common.util.speakText
import io.homeassistant.companion.android.common.util.stopTTS
import io.homeassistant.companion.android.database.notification.NotificationDao
import io.homeassistant.companion.android.database.notification.NotificationItem
import io.homeassistant.companion.android.database.sensor.SensorDao
import io.homeassistant.companion.android.database.settings.SettingsDao
import io.homeassistant.companion.android.database.settings.WebsocketSetting
import io.homeassistant.companion.android.sensors.LocationSensorManager
import io.homeassistant.companion.android.sensors.NotificationSensorManager
import io.homeassistant.companion.android.sensors.SensorReceiver
import io.homeassistant.companion.android.settings.SettingsActivity
import io.homeassistant.companion.android.util.UrlUtil
import io.homeassistant.companion.android.vehicle.HaCarAppService
import io.homeassistant.companion.android.websocket.WebsocketManager
import io.homeassistant.companion.android.webview.WebViewActivity
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLDecoder
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
class MessagingManager @Inject constructor(
@ApplicationContext val context: Context,
private val okHttpClient: OkHttpClient,
private val serverManager: ServerManager,
private val prefsRepository: PrefsRepository,
private val notificationDao: NotificationDao,
private val sensorDao: SensorDao,
private val settingsDao: SettingsDao
) {
companion object {
const val TAG = "MessagingService"
const val APP_PREFIX = "app://"
const val DEEP_LINK_PREFIX = "deep-link://"
const val INTENT_PREFIX = "intent:"
const val MARKET_PREFIX = "https://play.google.com/store/apps/details?id="
const val SETTINGS_PREFIX = "settings://"
const val NOTIFICATION_HISTORY = "notification_history"
const val NO_ACTION = "noAction"
const val SUBJECT = "subject"
const val TIMEOUT = "timeout"
const val IMAGE_URL = "image"
const val ICON_URL = "icon_url"
const val VIDEO_URL = "video"
const val VISIBILITY = "visibility"
const val PERSISTENT = "persistent"
const val CHRONOMETER = "chronometer"
const val WHEN = "when"
const val WHEN_RELATIVE = "when_relative"
const val CAR_UI = "car_ui"
const val KEY_TEXT_REPLY = "key_text_reply"
const val INTENT_CLASS_NAME = "intent_class_name"
const val URI = "URI"
const val REPLY = "REPLY"
const val HIGH_ACCURACY_UPDATE_INTERVAL = "high_accuracy_update_interval"
const val PACKAGE_NAME = "package_name"
const val CONFIRMATION = "confirmation"
// special intent constants
const val INTENT_PACKAGE_NAME = "intent_package_name"
const val INTENT_ACTION = "intent_action"
const val INTENT_EXTRAS = "intent_extras"
const val INTENT_URI = "intent_uri"
const val INTENT_TYPE = "intent_type"
// special action constants
const val REQUEST_LOCATION_UPDATE = "request_location_update"
const val REMOVE_CHANNEL = "remove_channel"
const val COMMAND_DND = "command_dnd"
const val COMMAND_RINGER_MODE = "command_ringer_mode"
const val COMMAND_BROADCAST_INTENT = "command_broadcast_intent"
const val COMMAND_VOLUME_LEVEL = "command_volume_level"
const val COMMAND_BLUETOOTH = "command_bluetooth"
const val COMMAND_SCREEN_ON = "command_screen_on"
const val COMMAND_MEDIA = "command_media"
const val COMMAND_HIGH_ACCURACY_MODE = "command_high_accuracy_mode"
const val COMMAND_ACTIVITY = "command_activity"
const val COMMAND_WEBVIEW = "command_webview"
const val COMMAND_KEEP_SCREEN_ON = "keep_screen_on"
const val COMMAND_LAUNCH_APP = "command_launch_app"
const val COMMAND_APP_LOCK = "command_app_lock"
const val COMMAND_PERSISTENT_CONNECTION = "command_persistent_connection"
const val COMMAND_AUTO_SCREEN_BRIGHTNESS = "command_auto_screen_brightness"
const val COMMAND_SCREEN_BRIGHTNESS_LEVEL = "command_screen_brightness_level"
const val COMMAND_SCREEN_OFF_TIMEOUT = "command_screen_off_timeout"
// DND commands
const val DND_PRIORITY_ONLY = "priority_only"
const val DND_ALARMS_ONLY = "alarms_only"
const val DND_ALL = "off"
const val DND_NONE = "total_silence"
// Ringer mode commands
const val RM_NORMAL = "normal"
const val RM_SILENT = "silent"
const val RM_VIBRATE = "vibrate"
// Media Commands
const val MEDIA_FAST_FORWARD = "fast_forward"
const val MEDIA_NEXT = "next"
const val MEDIA_PAUSE = "pause"
const val MEDIA_PLAY = "play"
const val MEDIA_PLAY_PAUSE = "play_pause"
const val MEDIA_PREVIOUS = "previous"
const val MEDIA_REWIND = "rewind"
const val MEDIA_STOP = "stop"
const val MEDIA_PACKAGE_NAME = "media_package_name"
const val MEDIA_COMMAND = "media_command"
// App-lock command parameters:
const val APP_LOCK_ENABLED = "app_lock_enabled"
const val APP_LOCK_TIMEOUT = "app_lock_timeout"
const val HOME_BYPASS_ENABLED = "home_bypass_enabled"
// High accuracy commands
const val HIGH_ACCURACY_SET_UPDATE_INTERVAL = "high_accuracy_set_update_interval"
const val FORCE_ON = "force_on"
const val FORCE_OFF = "force_off"
// Command groups
val DEVICE_COMMANDS = listOf(
COMMAND_DND,
COMMAND_RINGER_MODE,
COMMAND_BROADCAST_INTENT,
COMMAND_VOLUME_LEVEL,
COMMAND_BLUETOOTH,
DeviceCommandData.COMMAND_BLE_TRANSMITTER,
DeviceCommandData.COMMAND_BEACON_MONITOR,
COMMAND_HIGH_ACCURACY_MODE,
COMMAND_ACTIVITY,
COMMAND_WEBVIEW,
COMMAND_SCREEN_ON,
COMMAND_MEDIA,
DeviceCommandData.COMMAND_UPDATE_SENSORS,
COMMAND_LAUNCH_APP,
COMMAND_APP_LOCK,
COMMAND_PERSISTENT_CONNECTION,
COMMAND_AUTO_SCREEN_BRIGHTNESS,
COMMAND_SCREEN_BRIGHTNESS_LEVEL,
COMMAND_SCREEN_OFF_TIMEOUT
)
val DND_COMMANDS = listOf(DND_ALARMS_ONLY, DND_ALL, DND_NONE, DND_PRIORITY_ONLY)
val RM_COMMANDS = listOf(RM_NORMAL, RM_SILENT, RM_VIBRATE)
val CHANNEL_VOLUME_STREAM = listOf(
NotificationData.ALARM_STREAM,
NotificationData.MUSIC_STREAM,
NotificationData.NOTIFICATION_STREAM,
NotificationData.RING_STREAM,
NotificationData.CALL_STREAM,
NotificationData.SYSTEM_STREAM,
NotificationData.DTMF_STREAM
)
val FORCE_COMMANDS = listOf(FORCE_OFF, FORCE_ON)
val MEDIA_COMMANDS = listOf(
MEDIA_FAST_FORWARD,
MEDIA_NEXT,
MEDIA_PAUSE,
MEDIA_PLAY,
MEDIA_PLAY_PAUSE,
MEDIA_PREVIOUS,
MEDIA_REWIND,
MEDIA_STOP
)
// Video Values
const val VIDEO_START_MICROSECONDS = 100000L
const val VIDEO_INCREMENT_MICROSECONDS = 750000L
const val VIDEO_GUESS_MILLISECONDS = 7000L
// Values for a notification that has been replied to
const val SOURCE_REPLY = "REPLY_"
const val SOURCE_REPLY_HISTORY = "reply_history_"
// Values for temporarily added keys
const val THIS_SERVER_ID = "server_id"
}
private val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job())
fun handleMessage(notificationData: Map<String, String>, source: String) {
var now = System.currentTimeMillis()
var jsonData = notificationData
val notificationId: Long
if (source.startsWith(SOURCE_REPLY)) {
notificationId = source.substringAfter(SOURCE_REPLY).toLong()
notificationDao.get(notificationId.toInt())?.let {
val dbData: Map<String, String> = jacksonObjectMapper().readValue(it.data)
now = it.received // Allow for updating the existing notification without a tag
jsonData = jsonData + dbData // Add the notificationData, this contains the reply text
} ?: return
} else {
val jsonObject = JSONObject(jsonData)
val receivedServer = jsonData[NotificationData.WEBHOOK_ID]?.let {
serverManager.getServer(webhookId = it)?.id
}
val notificationRow =
NotificationItem(0, now, jsonData[NotificationData.MESSAGE].toString(), jsonObject.toString(), source, receivedServer)
notificationId = notificationDao.add(notificationRow)
val confirmation = jsonData[CONFIRMATION]?.toBoolean() ?: false
if (confirmation) {
mainScope.launch {
try {
serverManager.integrationRepository(receivedServer ?: ServerManager.SERVER_ID_ACTIVE)
.fireEvent("mobile_app_notification_received", jsonData)
} catch (e: Exception) {
Log.e(TAG, "Unable to send notification received event", e)
}
}
}
}
val serverId = jsonData[NotificationData.WEBHOOK_ID]?.let { webhookId ->
serverManager.getServer(webhookId = webhookId)?.id
} ?: ServerManager.SERVER_ID_ACTIVE
if (serverManager.getServer(serverId) == null) {
Log.w(TAG, "Received notification but no server for it, discarding")
return
}
jsonData = jsonData + mutableMapOf<String, String>().apply { put(THIS_SERVER_ID, serverId.toString()) }
mainScope.launch {
val allowCommands = serverManager.integrationRepository(serverId).isTrusted()
when {
jsonData[NotificationData.MESSAGE] == REQUEST_LOCATION_UPDATE && allowCommands -> {
Log.d(TAG, "Request location update")
requestAccurateLocationUpdate()
}
jsonData[NotificationData.MESSAGE] == NotificationData.CLEAR_NOTIFICATION && !jsonData["tag"].isNullOrBlank() -> {
clearNotification(context, jsonData["tag"]!!)
}
jsonData[NotificationData.MESSAGE] == REMOVE_CHANNEL && !jsonData[NotificationData.CHANNEL].isNullOrBlank() -> {
Log.d(TAG, "Removing Notification channel ${jsonData[NotificationData.CHANNEL]}")
removeNotificationChannel(jsonData[NotificationData.CHANNEL]!!)
}
jsonData[NotificationData.MESSAGE] == TextToSpeechData.TTS -> {
speakText(context, jsonData)
}
jsonData[NotificationData.MESSAGE] == TextToSpeechData.COMMAND_STOP_TTS -> stopTTS()
jsonData[NotificationData.MESSAGE] in DEVICE_COMMANDS && allowCommands -> {
Log.d(TAG, "Processing device command")
when (jsonData[NotificationData.MESSAGE]) {
COMMAND_DND -> {
if (jsonData[NotificationData.COMMAND] in DND_COMMANDS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Posting notification to device as it does not support DND commands"
)
sendNotification(jsonData)
}
} else {
Log.d(
TAG,
"Invalid DND command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_RINGER_MODE -> {
if (jsonData[NotificationData.COMMAND] in RM_COMMANDS) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid ringer mode command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_BROADCAST_INTENT -> {
if (!jsonData[INTENT_ACTION].isNullOrEmpty() && !jsonData[INTENT_PACKAGE_NAME].isNullOrEmpty()) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid broadcast command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_VOLUME_LEVEL -> {
if (!jsonData[NotificationData.MEDIA_STREAM].isNullOrEmpty() && jsonData[NotificationData.MEDIA_STREAM] in CHANNEL_VOLUME_STREAM &&
!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null
) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid volume command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_BLUETOOTH -> {
if (
!jsonData[NotificationData.COMMAND].isNullOrEmpty() &&
jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS &&
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid bluetooth command received, posting notification to device"
)
sendNotification(jsonData)
}
}
DeviceCommandData.COMMAND_BLE_TRANSMITTER -> {
if (!commandBleTransmitter(context, jsonData, sensorDao, mainScope)) {
sendNotification(jsonData)
}
}
DeviceCommandData.COMMAND_BEACON_MONITOR -> {
if (!commandBeaconMonitor(context, jsonData)) {
sendNotification(jsonData)
}
}
COMMAND_HIGH_ACCURACY_MODE -> {
if ((!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS) ||
(!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in FORCE_COMMANDS) ||
(
!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] == HIGH_ACCURACY_SET_UPDATE_INTERVAL &&
jsonData[HIGH_ACCURACY_UPDATE_INTERVAL]?.toIntOrNull() != null && jsonData[HIGH_ACCURACY_UPDATE_INTERVAL]?.toInt()!! >= 5
)
) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid high accuracy mode command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_ACTIVITY -> {
if (!jsonData[INTENT_ACTION].isNullOrEmpty()) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid activity command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_APP_LOCK -> {
val appLockEnablePresent = jsonData[APP_LOCK_ENABLED] != null
val appLockTimeoutPresent = jsonData[APP_LOCK_TIMEOUT] != null
val homeBypassEnablePresent = jsonData[HOME_BYPASS_ENABLED] != null
val appLockEnableValue = jsonData[APP_LOCK_ENABLED]?.lowercase()?.toBooleanStrictOrNull()
val appLockTimeoutValue = jsonData[APP_LOCK_TIMEOUT]?.toIntOrNull()
val homeBypassEnableValue = jsonData[HOME_BYPASS_ENABLED]?.lowercase()?.toBooleanStrictOrNull()
val invalid = (!appLockEnablePresent && !appLockTimeoutPresent && !homeBypassEnablePresent) ||
(appLockEnablePresent && appLockEnableValue == null) ||
(appLockTimeoutPresent && (appLockTimeoutValue == null || appLockTimeoutValue < 0)) ||
(homeBypassEnablePresent && homeBypassEnableValue == null)
if (!invalid) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Invalid app lock command received, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_WEBVIEW -> {
handleDeviceCommands(jsonData)
}
COMMAND_SCREEN_ON -> {
handleDeviceCommands(jsonData)
}
COMMAND_MEDIA -> {
if (!jsonData[MEDIA_COMMAND].isNullOrEmpty() && jsonData[MEDIA_COMMAND] in MEDIA_COMMANDS && !jsonData[MEDIA_PACKAGE_NAME].isNullOrEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Posting notification to device as it does not support media commands"
)
sendNotification(jsonData)
}
} else {
Log.d(
TAG,
"Invalid media command received, posting notification to device"
)
sendNotification(jsonData)
}
}
DeviceCommandData.COMMAND_UPDATE_SENSORS -> SensorReceiver.updateAllSensors(context)
COMMAND_LAUNCH_APP -> {
if (!jsonData[PACKAGE_NAME].isNullOrEmpty()) {
handleDeviceCommands(jsonData)
} else {
Log.d(
TAG,
"Missing package name for app to launch, posting notification to device"
)
sendNotification(jsonData)
}
}
COMMAND_PERSISTENT_CONNECTION -> {
val validPersistentTypes = WebsocketSetting.values().map { setting -> setting.name }
when {
jsonData[PERSISTENT].isNullOrEmpty() -> {
Log.d(
TAG,
"Missing persistent modifier, posting notification to device"
)
sendNotification(jsonData)
}
jsonData[PERSISTENT]!!.uppercase() !in validPersistentTypes -> {
Log.d(
TAG,
"Persistent modifier is not one of $validPersistentTypes"
)
sendNotification(jsonData)
}
else -> handleDeviceCommands(jsonData)
}
}
COMMAND_AUTO_SCREEN_BRIGHTNESS -> {
if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND] in DeviceCommandData.ENABLE_COMMANDS) {
handleDeviceCommands(jsonData)
} else {
sendNotification(jsonData)
}
}
COMMAND_SCREEN_BRIGHTNESS_LEVEL, COMMAND_SCREEN_OFF_TIMEOUT -> {
if (!jsonData[NotificationData.COMMAND].isNullOrEmpty() && jsonData[NotificationData.COMMAND]?.toIntOrNull() != null) {
handleDeviceCommands(jsonData)
} else {
sendNotification(jsonData)
}
}
else -> Log.d(TAG, "No command received")
}
}
else -> {
Log.d(TAG, "Creating notification with following data: $jsonData")
sendNotification(jsonData, notificationId, now)
}
}
}
}
private fun requestAccurateLocationUpdate() {
val intent = Intent(context, LocationSensorManager::class.java)
intent.action = LocationSensorManager.ACTION_REQUEST_ACCURATE_LOCATION_UPDATE
context.sendBroadcast(intent)
}
private fun removeNotificationChannel(channelName: String) {
val notificationManagerCompat = NotificationManagerCompat.from(context)
val channelID: String = createChannelID(channelName)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && channelID != NotificationChannel.DEFAULT_CHANNEL_ID) {
notificationManagerCompat.deleteNotificationChannel(channelID)
}
}
private fun handleDeviceCommands(data: Map<String, String>) {
val message = data[NotificationData.MESSAGE]
val command = data[NotificationData.COMMAND]
val serverId = data[THIS_SERVER_ID]!!
when (message) {
COMMAND_DND -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val notificationManager =
context.getSystemService<NotificationManager>()
if (notificationManager?.isNotificationPolicyAccessGranted == false) {
notifyMissingPermission(message.toString(), serverId)
} else {
when (command) {
DND_ALARMS_ONLY -> notificationManager?.setInterruptionFilter(
NotificationManager.INTERRUPTION_FILTER_ALARMS
)
DND_ALL -> notificationManager?.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL)
DND_NONE -> notificationManager?.setInterruptionFilter(
NotificationManager.INTERRUPTION_FILTER_NONE
)
DND_PRIORITY_ONLY -> notificationManager?.setInterruptionFilter(
NotificationManager.INTERRUPTION_FILTER_PRIORITY
)
else -> Log.d(TAG, "Skipping invalid command")
}
}
}
}
COMMAND_RINGER_MODE -> {
val audioManager = context.getSystemService<AudioManager>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val notificationManager =
context.getSystemService<NotificationManager>()
if (notificationManager?.isNotificationPolicyAccessGranted == false) {
notifyMissingPermission(message.toString(), serverId)
} else {
processRingerMode(audioManager!!, command)
}
} else {
processRingerMode(audioManager!!, command)
}
}
COMMAND_BROADCAST_INTENT -> {
try {
val packageName = data[INTENT_PACKAGE_NAME]
val intent = Intent(data[INTENT_ACTION])
val extras = data[INTENT_EXTRAS]
val className = data[INTENT_CLASS_NAME]
if (!extras.isNullOrEmpty()) {
addExtrasToIntent(intent, extras)
}
intent.`package` = packageName
if (!packageName.isNullOrEmpty() && !className.isNullOrEmpty()) {
intent.setClassName(packageName, className)
}
Log.d(TAG, "Sending broadcast intent")
context.sendBroadcast(intent)
} catch (e: Exception) {
Log.e(TAG, "Unable to send broadcast intent please check command format", e)
Handler(Looper.getMainLooper()).post {
Toast.makeText(
context,
commonR.string.broadcast_intent_error,
Toast.LENGTH_LONG
).show()
}
}
}
COMMAND_VOLUME_LEVEL -> {
val audioManager =
context.getSystemService<AudioManager>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val notificationManager = context.getSystemService<NotificationManager>()
if (notificationManager?.isNotificationPolicyAccessGranted == false) {
notifyMissingPermission(message.toString(), serverId)
} else {
processStreamVolume(
audioManager!!,
data[NotificationData.MEDIA_STREAM].toString(),
command!!.toInt()
)
}
} else {
processStreamVolume(
audioManager!!,
data[NotificationData.MEDIA_STREAM].toString(),
command!!.toInt()
)
}
}
COMMAND_BLUETOOTH -> {
val bluetoothAdapter = context.getSystemService<BluetoothManager>()?.adapter
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
when (PackageManager.PERMISSION_GRANTED) {
ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) -> {
Log.d(TAG, "We have proper bluetooth permissions proceeding with command")
}
else -> {
Log.e(TAG, "Missing Bluetooth permissions, notifying user to grant permissions")
notifyMissingPermission(message.toString(), serverId)
}
}
}
@Suppress("DEPRECATION")
if (command == DeviceCommandData.TURN_OFF) {
bluetoothAdapter?.disable()
} else if (command == DeviceCommandData.TURN_ON) {
bluetoothAdapter?.enable()
}
}
COMMAND_HIGH_ACCURACY_MODE -> {
when (command) {
DeviceCommandData.TURN_OFF -> LocationSensorManager.setHighAccuracyModeSetting(context, false)
DeviceCommandData.TURN_ON -> LocationSensorManager.setHighAccuracyModeSetting(context, true)
FORCE_ON -> LocationSensorManager.setHighAccuracyModeSetting(context, true)
HIGH_ACCURACY_SET_UPDATE_INTERVAL -> LocationSensorManager.setHighAccuracyModeIntervalSetting(context, data[HIGH_ACCURACY_UPDATE_INTERVAL]!!.toInt())
}
val intent = Intent(context, LocationSensorManager::class.java)
intent.action = LocationSensorManager.ACTION_FORCE_HIGH_ACCURACY
intent.putExtra("command", command)
context.sendBroadcast(intent)
}
COMMAND_ACTIVITY -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(context)) {
notifyMissingPermission(message.toString(), serverId)
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED && data["tag"] == Intent.ACTION_CALL) {
Handler(Looper.getMainLooper()).post {
Toast.makeText(
context,
context.getString(commonR.string.missing_phone_permission),
Toast.LENGTH_LONG
).show()
}
navigateAppDetails()
} else {
processActivityCommand(data)
}
} else {
processActivityCommand(data)
}
}
COMMAND_APP_LOCK -> {
mainScope.launch {
setAppLock(data)
}
}
COMMAND_WEBVIEW -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(context)) {
notifyMissingPermission(message.toString(), serverId)
} else {
openWebview(command, data)
}
} else {
openWebview(command, data)
}
}
COMMAND_SCREEN_ON -> {
if (!command.isNullOrEmpty()) {
mainScope.launch {
prefsRepository.setKeepScreenOnEnabled(
command == COMMAND_KEEP_SCREEN_ON
)
}
}
val powerManager = context.getSystemService<PowerManager>()
val wakeLock = powerManager?.newWakeLock(
PowerManager.FULL_WAKE_LOCK or
PowerManager.ACQUIRE_CAUSES_WAKEUP or
PowerManager.ON_AFTER_RELEASE,
"HomeAssistant::NotificationScreenOnWakeLock"
)
wakeLock?.acquire(1 * 30 * 1000L) // 30 seconds
wakeLock?.release()
}
COMMAND_MEDIA -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
if (!NotificationManagerCompat.getEnabledListenerPackages(context)
.contains(context.packageName)
) {
notifyMissingPermission(message.toString(), serverId)
} else {
processMediaCommand(data)
}
}
}
COMMAND_LAUNCH_APP -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(context)) {
notifyMissingPermission(message.toString(), serverId)
} else {
launchApp(data)
}
} else {
launchApp(data)
}
}
COMMAND_PERSISTENT_CONNECTION -> {
togglePersistentConnection(data[PERSISTENT].toString(), serverId.toIntOrNull() ?: ServerManager.SERVER_ID_ACTIVE)
}
COMMAND_AUTO_SCREEN_BRIGHTNESS, COMMAND_SCREEN_BRIGHTNESS_LEVEL, COMMAND_SCREEN_OFF_TIMEOUT -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(context)) {
if (!processScreenCommands(data)) {
mainScope.launch { sendNotification(data) }
}
} else {
notifyMissingPermission(message.toString(), serverId)
}
} else if (!processScreenCommands(data)) {
mainScope.launch { sendNotification(data) }
}
}
else -> Log.d(TAG, "No command received")
}
}
/**
* Add Extra values to Intent.
* Extra value might include type information based on type
* given by the user. If a known type is given, the initial string value
* will be converted to this type.
*/
private fun addExtrasToIntent(intent: Intent, extras: String) {
val items = extras.split(',')
for (item in items) {
val chunks = item.split(":")
val name = chunks[0]
var value = chunks[1]
val hasTypeInfo = chunks.size > 2
// Intent item has included type info, convert to this type
if (hasTypeInfo) {
value = chunks.subList(1, chunks.lastIndex).joinToString(":")
when (chunks.last()) {
"int" -> intent.putExtra(name, value.toInt())
"int[]" -> intent.putExtra(
name,
value.split(";").map { it.toInt() }.toIntArray()
)
"ArrayList<Integer>" -> intent.putIntegerArrayListExtra(
name,
value.split(";").map { it.toInt() }.toCollection(ArrayList())
)
"double" -> intent.putExtra(name, value.toDouble())
"double[]" -> intent.putExtra(
name,
value.split(";").map { it.toDouble() }.toDoubleArray()
)
"float" -> intent.putExtra(name, value.toFloat())
"float[]" -> intent.putExtra(
name,
value.split(";").map { it.toFloat() }.toFloatArray()
)
"long" -> intent.putExtra(name, value.toLong())
"long[]" -> intent.putExtra(
name,
value.split(";").map { it.toLong() }.toLongArray()
)
"short" -> intent.putExtra(name, value.toShort())
"short[]" -> intent.putExtra(
name,
value.split(";").map { it.toShort() }.toShortArray()
)
"byte" -> intent.putExtra(name, value.toByte())
"byte[]" -> intent.putExtra(
name,
value.split(";").map { it.toByte() }.toByteArray()
)
"boolean" -> intent.putExtra(name, value.toBoolean())
"boolean[]" -> intent.putExtra(
name,
value.split(";").map { it.toBoolean() }.toBooleanArray()
)
"char" -> intent.putExtra(name, value[0])
"char[]" -> intent.putExtra(
name,
value.split(";").map { it[0] }.toCharArray()
)
"String" -> intent.putExtra(name, value)
"String.urlencoded", "urlencoded" -> intent.putExtra(
name,
URLDecoder.decode(value, "UTF-8")
)
"String[]" -> intent.putExtra(
name,
value.split(";").toTypedArray()
)
"ArrayList<String>" -> intent.putStringArrayListExtra(
name,
value.split(";").toCollection(ArrayList())
)
"String[].urlencoded" -> intent.putExtra(
name,
value.split(";").map { URLDecoder.decode(value, "UTF-8") }.toTypedArray()
)
"ArrayList<String>.urlencoded" -> intent.putStringArrayListExtra(
name,
value.split(";").map { URLDecoder.decode(value, "UTF-8") }.toCollection(ArrayList())
)
else -> {
intent.putExtra(name, value)
}
}
} else {
// Try to guess the correct type
if (value.isDigitsOnly()) {
intent.putExtra(name, value.toInt())
} else if ((value.lowercase() == "true") || (value.lowercase() == "false")) {
intent.putExtra(name, value.toBoolean())
} else {
intent.putExtra(name, value)
}
}
}
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private suspend fun sendNotification(data: Map<String, String>, id: Long? = null, received: Long? = null) {
val notificationManagerCompat = NotificationManagerCompat.from(context)
val tag = data["tag"]
val messageId = tag?.hashCode() ?: received?.toInt() ?: System.currentTimeMillis().toInt()
var group = data["group"]
var groupId = 0
var previousGroup = ""
var previousGroupId = 0
if (!group.isNullOrBlank()) {
group = NotificationData.GROUP_PREFIX + group
groupId = group.hashCode()
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val notification = notificationManagerCompat.getActiveNotification(tag, messageId)
if (notification != null && notification.isGroup) {
previousGroup = NotificationData.GROUP_PREFIX + notification.tag
previousGroupId = previousGroup.hashCode()
}
}
}
val channelId = handleChannel(context, notificationManagerCompat, data)
val notificationBuilder = NotificationCompat.Builder(context, channelId)
handleSmallIcon(context, notificationBuilder, data)
handleSound(notificationBuilder, data)
handlePersistent(notificationBuilder, tag, data)
handleLargeIcon(notificationBuilder, data)
handleGroup(notificationBuilder, group, data[NotificationData.ALERT_ONCE].toBoolean())
handleTimeout(notificationBuilder, data)
handleColor(context, notificationBuilder, data)
handleSticky(notificationBuilder, data)
handleText(notificationBuilder, data)
handleSubject(notificationBuilder, data)
handleServer(notificationBuilder, data)
handleImage(notificationBuilder, data)
handleVideo(notificationBuilder, data)
handleVisibility(notificationBuilder, data)
handleActions(notificationBuilder, tag, messageId, id, data)
handleReplyHistory(notificationBuilder, data)
handleDeleteIntent(context, notificationBuilder, data, messageId, group, groupId, id)
handleContentIntent(notificationBuilder, data)
handleChronometer(notificationBuilder, data)
val useCarNotification = handleCarUiVisible(context, notificationBuilder, data)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
handleLegacyPriority(notificationBuilder, data)
handleLegacyLedColor(notificationBuilder, data)
handleLegacyVibrationPattern(notificationBuilder, data)
}
Log.d(TAG, "Show notification with tag \"$tag\" and id \"$messageId\"")
if (useCarNotification) {
CarNotificationManager.from(context).apply {
notify(tag, messageId, notificationBuilder)
}
} else {
notificationManagerCompat.apply {
notify(tag, messageId, notificationBuilder.build())
}
}
notificationManagerCompat.apply {
if (!group.isNullOrBlank()) {
Log.d(TAG, "Show group notification with tag \"$group\" and id \"$groupId\"")
notify(group, groupId, getGroupNotificationBuilder(context, channelId, group, data).build())
} else if (previousGroup.isNotBlank()) {
Log.d(
TAG,
"Remove group notification with tag \"$previousGroup\" and id \"$previousGroupId\""
)
cancelGroupIfNeeded(previousGroup, previousGroupId)
}
}
}
private fun handleChronometer(
builder: NotificationCompat.Builder,
data: Map<String, String>
) {
try { // Without this, a non-numeric when value will crash the app
var notificationWhen = data[WHEN]?.toLongOrNull()?.times(1000) ?: 0
val isRelative = data[WHEN_RELATIVE]?.toBoolean() ?: false
val usesChronometer = data[CHRONOMETER]?.toBoolean() ?: false
if (notificationWhen != 0L) {
if (isRelative) {
notificationWhen += System.currentTimeMillis()
}
builder.setWhen(notificationWhen)