-
Notifications
You must be signed in to change notification settings - Fork 524
Expand file tree
/
Copy pathNotificationPlugin.kt
More file actions
484 lines (426 loc) · 14.7 KB
/
NotificationPlugin.kt
File metadata and controls
484 lines (426 loc) · 14.7 KB
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
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
package app.tauri.notification
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.webkit.WebView
import app.tauri.Logger
import app.tauri.PermissionState
import app.tauri.annotation.Command
import app.tauri.annotation.InvokeArg
import app.tauri.annotation.Permission
import app.tauri.annotation.PermissionCallback
import app.tauri.annotation.TauriPlugin
import app.tauri.plugin.Invoke
import app.tauri.plugin.JSArray
import app.tauri.plugin.JSObject
import app.tauri.plugin.Plugin
import org.json.JSONArray
import org.json.JSONObject
const val LOCAL_NOTIFICATIONS = "permissionState"
private const val PREFS_NAME = "tauri_notification_plugin"
private const val PREF_KEY_PENDING_ACTION_EVENTS = "pending_action_events"
private const val PENDING_ACTION_EVENT_TTL_MS = 24 * 60 * 60 * 1000L
@InvokeArg
class PluginConfig {
var icon: String? = null
var sound: String? = null
var iconColor: String? = null
}
@InvokeArg
class BatchArgs {
lateinit var notifications: List<Notification>
}
@InvokeArg
class CancelArgs {
lateinit var notifications: List<Int>
}
@InvokeArg
class NotificationAction {
lateinit var id: String
var title: String? = null
var input: Boolean? = null
}
@InvokeArg
class ActionType {
lateinit var id: String
lateinit var actions: List<NotificationAction>
}
@InvokeArg
class RegisterActionTypesArgs {
lateinit var types: List<ActionType>
}
@InvokeArg
class ActiveNotification {
var id: Int = 0
var tag: String? = null
}
@InvokeArg
class RemoveActiveArgs {
var notifications: List<ActiveNotification> = listOf()
}
@TauriPlugin(
permissions = [
Permission(strings = [Manifest.permission.POST_NOTIFICATIONS], alias = "permissionState")
]
)
class NotificationPlugin(private val activity: Activity): Plugin(activity) {
private var webView: WebView? = null
private lateinit var manager: TauriNotificationManager
private lateinit var notificationManager: NotificationManager
private lateinit var notificationStorage: NotificationStorage
private var channelManager = ChannelManager(activity)
private data class PendingActionEvent(
val key: String,
val payload: JSObject,
val timestampMs: Long
)
private val pendingActionEvents = mutableListOf<PendingActionEvent>()
private val pendingActionEventKeys = mutableSetOf<String>()
private var isActionListenerReady = false
private fun nowMs(): Long = System.currentTimeMillis()
private fun isEventExpired(timestampMs: Long): Boolean {
return nowMs() - timestampMs > PENDING_ACTION_EVENT_TTL_MS
}
private fun buildActionEventKey(payload: JSObject): String {
val notification = payload.optJSONObject("notification")
val notificationId = notification?.opt("id") ?: payload.opt("id")
val actionId = payload.optString("actionId")
val inputValue = payload.optString("inputValue")
if (notificationId != null && actionId.isNotEmpty()) {
return "$notificationId|$actionId|$inputValue"
}
// Fallback for malformed payloads so we can still dedupe identical events.
return "payload:${payload.toString()}"
}
private fun rebuildPendingActionEventKeysLocked() {
pendingActionEventKeys.clear()
for (event in pendingActionEvents) {
pendingActionEventKeys.add(event.key)
}
}
private fun persistPendingActionEventsLocked() {
val iterator = pendingActionEvents.iterator()
var droppedExpired = 0
while (iterator.hasNext()) {
val event = iterator.next()
if (isEventExpired(event.timestampMs)) {
iterator.remove()
droppedExpired += 1
}
}
if (droppedExpired > 0) {
rebuildPendingActionEventKeysLocked()
Logger.debug(
NOTIFICATION_LOG_TAGS,
"Dropped expired pending actionPerformed events=$droppedExpired"
)
}
val events = JSONArray()
for (event in pendingActionEvents) {
try {
val wrappedEvent = JSONObject()
wrappedEvent.put("key", event.key)
wrappedEvent.put("timestampMs", event.timestampMs)
wrappedEvent.put("payload", JSONObject(event.payload.toString()))
events.put(wrappedEvent)
} catch (_: Throwable) {
events.put(event.payload)
}
}
activity
.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.edit()
.putString(PREF_KEY_PENDING_ACTION_EVENTS, events.toString())
.apply()
}
private fun restorePendingActionEventsLocked() {
val prefs = activity.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val serializedEvents = prefs.getString(PREF_KEY_PENDING_ACTION_EVENTS, null) ?: return
try {
val events = JSONArray(serializedEvents)
for (index in 0 until events.length()) {
val event = events.optJSONObject(index) ?: continue
val wrappedPayload = event.optJSONObject("payload")
val payloadObject = wrappedPayload ?: event
val payload = JSObject(payloadObject.toString())
val timestampMs =
if (wrappedPayload != null) event.optLong("timestampMs", nowMs()) else nowMs()
if (isEventExpired(timestampMs)) {
continue
}
val key = event.optString("key").ifEmpty { buildActionEventKey(payload) }
if (pendingActionEventKeys.contains(key)) {
Logger.debug(
NOTIFICATION_LOG_TAGS,
"Skipping duplicate restored actionPerformed event key=$key"
)
continue
}
pendingActionEvents.add(PendingActionEvent(key, payload, timestampMs))
pendingActionEventKeys.add(key)
}
Logger.debug(
NOTIFICATION_LOG_TAGS,
"Restored pending actionPerformed events=${pendingActionEvents.size}"
)
} catch (error: Throwable) {
Logger.error(
NOTIFICATION_LOG_TAGS,
"Failed to restore pending actionPerformed events",
error
)
pendingActionEvents.clear()
pendingActionEventKeys.clear()
persistPendingActionEventsLocked()
}
}
companion object {
var instance: NotificationPlugin? = null
fun triggerNotification(notification: Notification) {
instance?.triggerObject("notification", notification)
}
}
override fun load(webView: WebView) {
instance = this
super.load(webView)
this.webView = webView
Logger.debug(NOTIFICATION_LOG_TAGS, "Plugin load started")
synchronized(this) {
pendingActionEvents.clear()
pendingActionEventKeys.clear()
isActionListenerReady = false
restorePendingActionEventsLocked()
}
notificationStorage = NotificationStorage(activity, jsonMapper())
val manager = TauriNotificationManager(
notificationStorage,
activity,
activity,
getConfig(PluginConfig::class.java)
)
manager.createNotificationChannel()
this.manager = manager
notificationManager = activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
Logger.debug(NOTIFICATION_LOG_TAGS, "Plugin load complete; awaiting notification intents")
val intent = activity.intent
intent?.let {
onIntent(it)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
Logger.debug(NOTIFICATION_LOG_TAGS, "onNewIntent received action=${intent.action}")
onIntent(intent)
}
fun onIntent(intent: Intent) {
if (Intent.ACTION_MAIN != intent.action) {
Logger.debug(NOTIFICATION_LOG_TAGS, "Ignoring intent action=${intent.action}")
return
}
Logger.debug(NOTIFICATION_LOG_TAGS, "Processing ACTION_MAIN intent for notification action")
val dataJson = manager.handleNotificationActionPerformed(intent, notificationStorage)
if (dataJson != null) {
dispatchActionPerformed(dataJson)
} else {
Logger.debug(NOTIFICATION_LOG_TAGS, "No action payload extracted from intent")
}
}
private fun dispatchActionPerformed(payload: JSObject) {
synchronized(this) {
if (!isActionListenerReady) {
val key = buildActionEventKey(payload)
// `load()` restores persisted pending events before processing the current activity intent.
// Without this key check, the same action can be enqueued twice across reload boundaries.
if (pendingActionEventKeys.contains(key)) {
Logger.debug(
NOTIFICATION_LOG_TAGS,
"Skipping duplicate queued actionPerformed event key=$key"
)
return
}
pendingActionEvents.add(PendingActionEvent(key, payload, nowMs()))
pendingActionEventKeys.add(key)
persistPendingActionEventsLocked()
Logger.debug(
NOTIFICATION_LOG_TAGS,
"Queued actionPerformed event; listener not ready (pending=${pendingActionEvents.size})"
)
return
}
}
Logger.debug(NOTIFICATION_LOG_TAGS, "Dispatching actionPerformed event immediately")
trigger("actionPerformed", payload)
}
@Command
fun show(invoke: Invoke) {
val notification = invoke.parseArgs(Notification::class.java)
Logger.debug(
NOTIFICATION_LOG_TAGS,
"show called id=${notification.id} title=${notification.title} actionTypeId=${notification.actionTypeId} hasSchedule=${notification.schedule != null}"
)
val id = manager.schedule(notification)
invoke.resolveObject(id)
}
@Command
fun batch(invoke: Invoke) {
val args = invoke.parseArgs(BatchArgs::class.java)
Logger.debug(
NOTIFICATION_LOG_TAGS,
"batch called notifications=${args.notifications.size}"
)
val ids = manager.schedule(args.notifications)
notificationStorage.appendNotifications(args.notifications)
Logger.debug(NOTIFICATION_LOG_TAGS, "batch scheduled ids=$ids")
invoke.resolveObject(ids)
}
@Command
fun cancel(invoke: Invoke) {
val args = invoke.parseArgs(CancelArgs::class.java)
Logger.debug(NOTIFICATION_LOG_TAGS, "cancel called notifications=${args.notifications}")
manager.cancel(args.notifications)
invoke.resolve()
}
@Command
fun removeActive(invoke: Invoke) {
val args = invoke.parseArgs(RemoveActiveArgs::class.java)
Logger.debug(NOTIFICATION_LOG_TAGS, "removeActive called notifications=${args.notifications.size}")
if (args.notifications.isEmpty()) {
notificationManager.cancelAll()
invoke.resolve()
} else {
for (notification in args.notifications) {
if (notification.tag == null) {
notificationManager.cancel(notification.id)
} else {
notificationManager.cancel(notification.tag, notification.id)
}
}
invoke.resolve()
}
}
@Command
fun getPending(invoke: Invoke) {
val notifications= notificationStorage.getSavedNotifications()
Logger.debug(NOTIFICATION_LOG_TAGS, "getPending returning count=${notifications.size}")
val result = Notification.buildNotificationPendingList(notifications)
invoke.resolveObject(result)
}
@Command
fun registerActionTypes(invoke: Invoke) {
val args = invoke.parseArgs(RegisterActionTypesArgs::class.java)
Logger.debug(
NOTIFICATION_LOG_TAGS,
"registerActionTypes called types=${args.types.size}"
)
notificationStorage.writeActionGroup(args.types)
invoke.resolve()
}
@Command
fun registerActionListenerReady(invoke: Invoke) {
val pending = JSArray()
var drainedCount = 0
synchronized(this) {
isActionListenerReady = true
for (event in pendingActionEvents) {
pending.put(event.payload)
}
drainedCount = pendingActionEvents.size
pendingActionEvents.clear()
pendingActionEventKeys.clear()
persistPendingActionEventsLocked()
}
Logger.debug(
NOTIFICATION_LOG_TAGS,
"Action listener marked ready; drained pending actionPerformed events=$drainedCount"
)
invoke.resolveObject(pending)
}
@SuppressLint("ObsoleteSdkInt")
@Command
fun getActive(invoke: Invoke) {
val notifications = JSArray()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val activeNotifications = notificationManager.activeNotifications
for (activeNotification in activeNotifications) {
val jsNotification = JSObject()
jsNotification.put("id", activeNotification.id)
jsNotification.put("tag", activeNotification.tag)
val notification = activeNotification.notification
if (notification != null) {
jsNotification.put("title", notification.extras.getCharSequence(android.app.Notification.EXTRA_TITLE))
jsNotification.put("body", notification.extras.getCharSequence(android.app.Notification.EXTRA_TEXT))
jsNotification.put("group", notification.group)
jsNotification.put(
"groupSummary",
0 != notification.flags and android.app.Notification.FLAG_GROUP_SUMMARY
)
val extras = JSObject()
for (key in notification.extras.keySet()) {
extras.put(key!!, notification.extras.getString(key))
}
jsNotification.put("data", extras)
}
notifications.put(jsNotification)
}
}
invoke.resolveObject(notifications)
}
@Command
fun createChannel(invoke: Invoke) {
channelManager.createChannel(invoke)
}
@Command
fun deleteChannel(invoke: Invoke) {
channelManager.deleteChannel(invoke)
}
@Command
fun listChannels(invoke: Invoke) {
channelManager.listChannels(invoke)
}
@Command
override fun checkPermissions(invoke: Invoke) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
val permissionsResultJSON = JSObject()
permissionsResultJSON.put("permissionState", getPermissionState())
invoke.resolve(permissionsResultJSON)
} else {
super.checkPermissions(invoke)
}
}
@Command
override fun requestPermissions(invoke: Invoke) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
permissionState(invoke)
} else {
if (getPermissionState(LOCAL_NOTIFICATIONS) !== PermissionState.GRANTED) {
requestPermissionForAlias(LOCAL_NOTIFICATIONS, invoke, "permissionsCallback")
}
}
}
@Command
fun permissionState(invoke: Invoke) {
val permissionsResultJSON = JSObject()
permissionsResultJSON.put("permissionState", getPermissionState())
invoke.resolve(permissionsResultJSON)
}
@PermissionCallback
private fun permissionsCallback(invoke: Invoke) {
val permissionsResultJSON = JSObject()
permissionsResultJSON.put("permissionState", getPermissionState())
invoke.resolve(permissionsResultJSON)
}
private fun getPermissionState(): String {
return if (manager.areNotificationsEnabled()) {
"granted"
} else {
"denied"
}
}
}