@amrshbib/react-native-pushbib 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +475 -0
- package/android/build.gradle +51 -0
- package/android/src/main/AndroidManifest.xml +15 -0
- package/android/src/main/java/com/amrshbib/pushbib/FirebaseBootstrap.kt +37 -0
- package/android/src/main/java/com/amrshbib/pushbib/LiveUpdatePayload.kt +102 -0
- package/android/src/main/java/com/amrshbib/pushbib/LiveUpdateRenderer.kt +294 -0
- package/android/src/main/java/com/amrshbib/pushbib/NotificationPayload.kt +130 -0
- package/android/src/main/java/com/amrshbib/pushbib/NotificationRenderer.kt +181 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibChannels.kt +281 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibEmitter.kt +133 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibMessagingService.kt +87 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibModule.kt +286 -0
- package/android/src/main/java/com/amrshbib/pushbib/PushbibPackage.kt +14 -0
- package/index.d.ts +224 -0
- package/ios/PushbibCenterDelegate.h +16 -0
- package/ios/PushbibCenterDelegate.m +138 -0
- package/ios/PushbibEventBus.h +34 -0
- package/ios/PushbibEventBus.m +88 -0
- package/ios/PushbibLiveActivities.h +18 -0
- package/ios/PushbibLiveActivities.m +46 -0
- package/ios/PushbibModule.h +5 -0
- package/ios/PushbibModule.m +260 -0
- package/ios/PushbibSwizzler.m +135 -0
- package/package.json +40 -0
- package/react-native-pushbib.podspec +19 -0
- package/src/EventManager.js +55 -0
- package/src/Logger.js +18 -0
- package/src/NativePushbib.js +36 -0
- package/src/api.js +108 -0
- package/src/index.js +753 -0
- package/src/version.js +2 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
package com.amrshbib.pushbib
|
|
2
|
+
|
|
3
|
+
import android.app.NotificationChannel
|
|
4
|
+
import android.app.NotificationManager
|
|
5
|
+
import android.app.PendingIntent
|
|
6
|
+
import android.content.Context
|
|
7
|
+
import android.content.Intent
|
|
8
|
+
import android.os.Build
|
|
9
|
+
import androidx.core.app.NotificationCompat
|
|
10
|
+
import androidx.core.app.NotificationManagerCompat
|
|
11
|
+
import org.json.JSONObject
|
|
12
|
+
import java.util.concurrent.Executors
|
|
13
|
+
|
|
14
|
+
object LiveUpdateRenderer {
|
|
15
|
+
const val CHANNEL_ID = "pushbib_live_updates"
|
|
16
|
+
|
|
17
|
+
private const val META_CHANNEL_NAME = "com.amrshbib.pushbib.live_update_channel_name"
|
|
18
|
+
private const val PREFS = "pushbib_sdk"
|
|
19
|
+
private const val SEQ_PREFIX = "live_seq_"
|
|
20
|
+
private const val STREAM_PREFIX = "live_stream_"
|
|
21
|
+
|
|
22
|
+
private const val DEFAULT_ACCENT = 0xFF1A73E8.toInt()
|
|
23
|
+
|
|
24
|
+
private const val DISMISSAL_GRACE_SECONDS = 5L
|
|
25
|
+
|
|
26
|
+
private const val CANCEL_SETTLE_MS = 400L
|
|
27
|
+
|
|
28
|
+
private val executor = Executors.newSingleThreadExecutor()
|
|
29
|
+
|
|
30
|
+
const val OUTCOME_SHOWN = "shown"
|
|
31
|
+
const val OUTCOME_ENDED = "ended"
|
|
32
|
+
const val OUTCOME_STALE = "stale-sequence"
|
|
33
|
+
const val OUTCOME_NOTIFICATIONS_DISABLED = "notifications-disabled"
|
|
34
|
+
const val OUTCOME_BLOCKED = "notify-blocked"
|
|
35
|
+
const val OUTCOME_ERROR = "render-error"
|
|
36
|
+
const val OUTCOME_OPTED_OUT = "opted-out"
|
|
37
|
+
const val OUTCOME_LOCAL_DISPLAY_OFF = "local-display-off"
|
|
38
|
+
|
|
39
|
+
fun render(context: Context, payload: LiveUpdatePayload, onOutcome: ((String) -> Unit)? = null) {
|
|
40
|
+
val appContext = context.applicationContext
|
|
41
|
+
executor.execute {
|
|
42
|
+
var outcome = OUTCOME_ERROR
|
|
43
|
+
try {
|
|
44
|
+
outcome = renderBlocking(appContext, payload)
|
|
45
|
+
} catch (e: Exception) {
|
|
46
|
+
android.util.Log.w("Pushbib", "live update render failed: ${e.message}")
|
|
47
|
+
} finally {
|
|
48
|
+
runCatching { onOutcome?.invoke(outcome) }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private fun renderBlocking(context: Context, p: LiveUpdatePayload): String {
|
|
54
|
+
if (!claimSequence(context, p)) {
|
|
55
|
+
android.util.Log.i(
|
|
56
|
+
"Pushbib",
|
|
57
|
+
"live update ${p.activityId} seq=${p.sequenceNumber} stream=${p.streamId} is stale — ignoring",
|
|
58
|
+
)
|
|
59
|
+
return OUTCOME_STALE
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
val nm = NotificationManagerCompat.from(context)
|
|
63
|
+
|
|
64
|
+
if (p.isEnd) {
|
|
65
|
+
endActivity(context, nm, p)
|
|
66
|
+
return OUTCOME_ENDED
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!nm.areNotificationsEnabled()) {
|
|
70
|
+
android.util.Log.w(
|
|
71
|
+
"Pushbib",
|
|
72
|
+
"live update ${p.activityId} dropped: notifications are disabled for this app — " +
|
|
73
|
+
"grant POST_NOTIFICATIONS (Pushbib.Notifications.requestPermission())",
|
|
74
|
+
)
|
|
75
|
+
return OUTCOME_NOTIFICATIONS_DISABLED
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
ensureChannel(context)
|
|
79
|
+
|
|
80
|
+
if (Build.VERSION.SDK_INT >= 36) {
|
|
81
|
+
return if (notifyPromoted(context, nm, p)) OUTCOME_SHOWN else OUTCOME_BLOCKED
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
val builder = baseBuilder(context, p)
|
|
85
|
+
.setOngoing(true)
|
|
86
|
+
.setAutoCancel(false)
|
|
87
|
+
.setOnlyAlertOnce(!p.alerting)
|
|
88
|
+
|
|
89
|
+
p.progress?.let { builder.setProgress(100, it, false) }
|
|
90
|
+
if (p.progress == null && p.indeterminate) builder.setProgress(0, 0, true)
|
|
91
|
+
|
|
92
|
+
return if (notify(context, nm, p, builder)) OUTCOME_SHOWN else OUTCOME_BLOCKED
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
@androidx.annotation.RequiresApi(36)
|
|
96
|
+
private fun notifyPromoted(context: Context, nm: NotificationManagerCompat, p: LiveUpdatePayload): Boolean {
|
|
97
|
+
val style = android.app.Notification.ProgressStyle()
|
|
98
|
+
if (p.progress != null) {
|
|
99
|
+
style.setProgressSegments(listOf(android.app.Notification.ProgressStyle.Segment(100)))
|
|
100
|
+
style.setProgress(p.progress)
|
|
101
|
+
} else {
|
|
102
|
+
style.setProgressIndeterminate(true)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
val title = p.title ?: p.body ?: NotificationRenderer.appName(context)
|
|
106
|
+
val builder = android.app.Notification.Builder(context, CHANNEL_ID)
|
|
107
|
+
.setSmallIcon(NotificationRenderer.resolveSmallIcon(context, null))
|
|
108
|
+
.setContentTitle(title)
|
|
109
|
+
.setStyle(style)
|
|
110
|
+
.setOngoing(true)
|
|
111
|
+
.setAutoCancel(false)
|
|
112
|
+
.setOnlyAlertOnce(!p.alerting)
|
|
113
|
+
.setCategory(android.app.Notification.CATEGORY_PROGRESS)
|
|
114
|
+
.setContentIntent(clickIntent(context, p))
|
|
115
|
+
.setShortCriticalText(chipText(p))
|
|
116
|
+
.setColorized(true)
|
|
117
|
+
.setFlag(android.app.Notification.FLAG_PROMOTED_ONGOING, true)
|
|
118
|
+
|
|
119
|
+
if (p.body != null && p.body != title) builder.setContentText(p.body)
|
|
120
|
+
builder.setColor(NotificationRenderer.resolveColor(context, null) ?: DEFAULT_ACCENT)
|
|
121
|
+
p.staleDate?.let { stale ->
|
|
122
|
+
if (System.currentTimeMillis() / 1000 > stale) builder.setSubText("Updating…")
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
val notification = builder.build()
|
|
126
|
+
|
|
127
|
+
if (!notification.hasPromotableCharacteristics()) {
|
|
128
|
+
android.util.Log.i("Pushbib", "live update ${p.activityId}: not promotable — showing as an ordinary ongoing card")
|
|
129
|
+
} else if (!canPostPromoted(context)) {
|
|
130
|
+
android.util.Log.i(
|
|
131
|
+
"Pushbib",
|
|
132
|
+
"live update ${p.activityId}: promotion not allowed for this app " +
|
|
133
|
+
"(Settings ▸ Notifications ▸ Live Updates) — showing as an ordinary ongoing card",
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return try {
|
|
138
|
+
nm.notify(p.activityId, p.notificationId, notification)
|
|
139
|
+
true
|
|
140
|
+
} catch (e: SecurityException) {
|
|
141
|
+
android.util.Log.w("Pushbib", "live update notify blocked: ${e.message}")
|
|
142
|
+
false
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
@androidx.annotation.RequiresApi(36)
|
|
147
|
+
private fun canPostPromoted(context: Context): Boolean =
|
|
148
|
+
runCatching {
|
|
149
|
+
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
|
|
150
|
+
.canPostPromotedNotifications()
|
|
151
|
+
}.getOrDefault(false)
|
|
152
|
+
|
|
153
|
+
private fun chipText(p: LiveUpdatePayload): String {
|
|
154
|
+
p.progress?.let { return "$it%" }
|
|
155
|
+
val text = p.title ?: p.body ?: return "Live"
|
|
156
|
+
return if (text.length <= 12) text else text.take(12).trimEnd()
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private fun endActivity(context: Context, nm: NotificationManagerCompat, p: LiveUpdatePayload) {
|
|
160
|
+
val nowSeconds = System.currentTimeMillis() / 1000
|
|
161
|
+
val keepVisible = p.dismissalDate != null && p.dismissalDate > nowSeconds + DISMISSAL_GRACE_SECONDS
|
|
162
|
+
|
|
163
|
+
if (!keepVisible || (p.title == null && p.body == null)) {
|
|
164
|
+
nm.cancel(p.activityId, p.notificationId)
|
|
165
|
+
val stranded = runCatching {
|
|
166
|
+
Thread.sleep(CANCEL_SETTLE_MS)
|
|
167
|
+
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
|
|
168
|
+
.activeNotifications.any { it.id == p.notificationId && it.tag == p.activityId }
|
|
169
|
+
}.getOrDefault(false)
|
|
170
|
+
if (stranded) {
|
|
171
|
+
android.util.Log.w(
|
|
172
|
+
"Pushbib",
|
|
173
|
+
"live update ${p.activityId}: END cancel(tag=${p.activityId}, id=${p.notificationId}) " +
|
|
174
|
+
"did not remove the card — it is still active",
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
clearSequence(context, p.activityId)
|
|
178
|
+
return
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (!nm.areNotificationsEnabled()) {
|
|
182
|
+
clearSequence(context, p.activityId)
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
ensureChannel(context)
|
|
187
|
+
val builder = baseBuilder(context, p)
|
|
188
|
+
.setOngoing(false)
|
|
189
|
+
.setAutoCancel(true)
|
|
190
|
+
.setOnlyAlertOnce(!p.alerting)
|
|
191
|
+
notify(context, nm, p, builder)
|
|
192
|
+
clearSequence(context, p.activityId)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private fun baseBuilder(context: Context, p: LiveUpdatePayload): NotificationCompat.Builder {
|
|
196
|
+
val title = p.title ?: NotificationRenderer.appName(context)
|
|
197
|
+
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
|
|
198
|
+
.setSmallIcon(NotificationRenderer.resolveSmallIcon(context, null))
|
|
199
|
+
.setContentTitle(title)
|
|
200
|
+
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
|
|
201
|
+
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
|
202
|
+
.setWhen(System.currentTimeMillis())
|
|
203
|
+
.setShowWhen(false)
|
|
204
|
+
.setContentIntent(clickIntent(context, p))
|
|
205
|
+
|
|
206
|
+
p.body?.let {
|
|
207
|
+
builder.setContentText(it)
|
|
208
|
+
builder.setStyle(NotificationCompat.BigTextStyle().bigText(it))
|
|
209
|
+
}
|
|
210
|
+
NotificationRenderer.resolveColor(context, null)?.let { builder.setColor(it) }
|
|
211
|
+
|
|
212
|
+
p.staleDate?.let { stale ->
|
|
213
|
+
if (System.currentTimeMillis() / 1000 > stale) builder.setSubText("Updating…")
|
|
214
|
+
}
|
|
215
|
+
return builder
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private fun notify(
|
|
219
|
+
context: Context,
|
|
220
|
+
nm: NotificationManagerCompat,
|
|
221
|
+
p: LiveUpdatePayload,
|
|
222
|
+
builder: NotificationCompat.Builder,
|
|
223
|
+
): Boolean {
|
|
224
|
+
return try {
|
|
225
|
+
nm.notify(p.activityId, p.notificationId, builder.build())
|
|
226
|
+
true
|
|
227
|
+
} catch (e: SecurityException) {
|
|
228
|
+
android.util.Log.w("Pushbib", "live update notify blocked: ${e.message}")
|
|
229
|
+
false
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private fun clickIntent(context: Context, p: LiveUpdatePayload): PendingIntent {
|
|
234
|
+
val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)
|
|
235
|
+
?: Intent().setPackage(context.packageName)
|
|
236
|
+
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
237
|
+
val event = JSONObject()
|
|
238
|
+
.put("notification", p.toJson())
|
|
239
|
+
.put("liveUpdate", p.toJson())
|
|
240
|
+
.put("notificationId", p.notificationId)
|
|
241
|
+
launch.putExtra(NotificationRenderer.EXTRA_EVENT, event.toString())
|
|
242
|
+
return PendingIntent.getActivity(
|
|
243
|
+
context,
|
|
244
|
+
p.notificationId,
|
|
245
|
+
launch,
|
|
246
|
+
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private fun ensureChannel(context: Context) {
|
|
251
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
|
252
|
+
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
253
|
+
if (manager.getNotificationChannel(CHANNEL_ID) != null) return
|
|
254
|
+
val name = NotificationRenderer.metaString(context, META_CHANNEL_NAME) ?: "Live updates"
|
|
255
|
+
manager.createNotificationChannel(
|
|
256
|
+
NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT).apply {
|
|
257
|
+
setShowBadge(false)
|
|
258
|
+
},
|
|
259
|
+
)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private fun claimSequence(context: Context, p: LiveUpdatePayload): Boolean {
|
|
263
|
+
if (p.sequenceNumber <= 0L) return true
|
|
264
|
+
|
|
265
|
+
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
266
|
+
val seqKey = SEQ_PREFIX + p.activityId
|
|
267
|
+
val streamKey = STREAM_PREFIX + p.activityId
|
|
268
|
+
|
|
269
|
+
val knownStream = prefs.getString(streamKey, null)
|
|
270
|
+
val streamChanged = p.streamId != null && p.streamId != knownStream
|
|
271
|
+
if (streamChanged) {
|
|
272
|
+
prefs.edit().putString(streamKey, p.streamId).putLong(seqKey, p.sequenceNumber).apply()
|
|
273
|
+
return true
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
val last = prefs.getLong(seqKey, 0L)
|
|
277
|
+
if (!p.isEnd && p.sequenceNumber <= last) return false
|
|
278
|
+
|
|
279
|
+
prefs.edit().apply {
|
|
280
|
+
putLong(seqKey, p.sequenceNumber)
|
|
281
|
+
if (p.streamId != null) putString(streamKey, p.streamId)
|
|
282
|
+
apply()
|
|
283
|
+
}
|
|
284
|
+
return true
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private fun clearSequence(context: Context, activityId: String) {
|
|
288
|
+
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
289
|
+
.edit()
|
|
290
|
+
.remove(SEQ_PREFIX + activityId)
|
|
291
|
+
.remove(STREAM_PREFIX + activityId)
|
|
292
|
+
.apply()
|
|
293
|
+
}
|
|
294
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
package com.amrshbib.pushbib
|
|
2
|
+
|
|
3
|
+
import com.google.firebase.messaging.RemoteMessage
|
|
4
|
+
import org.json.JSONArray
|
|
5
|
+
import org.json.JSONObject
|
|
6
|
+
|
|
7
|
+
class NotificationPayload private constructor(
|
|
8
|
+
val title: String?,
|
|
9
|
+
val subtitle: String?,
|
|
10
|
+
val body: String?,
|
|
11
|
+
val imageUrl: String?,
|
|
12
|
+
val largeIcon: String?,
|
|
13
|
+
val channelId: String?,
|
|
14
|
+
val channel: JSONObject?,
|
|
15
|
+
val sound: String?,
|
|
16
|
+
val smallIcon: String?,
|
|
17
|
+
val color: String?,
|
|
18
|
+
val collapseId: String?,
|
|
19
|
+
val url: String?,
|
|
20
|
+
val buttons: List<Button>,
|
|
21
|
+
val data: Map<String, String>,
|
|
22
|
+
val notificationId: Int,
|
|
23
|
+
val showForeground: Boolean,
|
|
24
|
+
val showBackground: Boolean,
|
|
25
|
+
) {
|
|
26
|
+
class Button(val id: String, val text: String)
|
|
27
|
+
|
|
28
|
+
fun toJson(): JSONObject = JSONObject().apply {
|
|
29
|
+
put("notificationId", notificationId)
|
|
30
|
+
put("showForeground", showForeground)
|
|
31
|
+
put("showBackground", showBackground)
|
|
32
|
+
putOpt("title", title)
|
|
33
|
+
putOpt("subtitle", subtitle)
|
|
34
|
+
putOpt("body", body)
|
|
35
|
+
putOpt("imageUrl", imageUrl)
|
|
36
|
+
putOpt("largeIcon", largeIcon)
|
|
37
|
+
putOpt("channelId", channelId)
|
|
38
|
+
putOpt("channel", channel)
|
|
39
|
+
putOpt("sound", sound)
|
|
40
|
+
putOpt("smallIcon", smallIcon)
|
|
41
|
+
putOpt("color", color)
|
|
42
|
+
putOpt("collapseId", collapseId)
|
|
43
|
+
putOpt("url", url)
|
|
44
|
+
put("buttons", JSONArray().apply { buttons.forEach { put(JSONObject().put("id", it.id).put("text", it.text)) } })
|
|
45
|
+
put("data", JSONObject(data as Map<*, *>))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
companion object {
|
|
49
|
+
private val CONTROL_KEYS =
|
|
50
|
+
setOf("pushbib_payload", "url", "buttons", "largeIcon", "showForeground", "showBackground")
|
|
51
|
+
|
|
52
|
+
private fun flag(raw: String?, default: Boolean = true): Boolean =
|
|
53
|
+
when (raw?.trim()?.lowercase()) {
|
|
54
|
+
null, "" -> default
|
|
55
|
+
"false", "0", "no" -> false
|
|
56
|
+
else -> true
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
fun fromRemoteMessage(message: RemoteMessage): NotificationPayload? {
|
|
60
|
+
val data = message.data
|
|
61
|
+
val display = data["pushbib_payload"]?.let { runCatching { JSONObject(it) }.getOrNull() }
|
|
62
|
+
val notif = message.notification
|
|
63
|
+
if (display == null && notif == null) return null
|
|
64
|
+
|
|
65
|
+
val custom = HashMap<String, String>()
|
|
66
|
+
for ((k, v) in data) if (k !in CONTROL_KEYS) custom[k] = v
|
|
67
|
+
|
|
68
|
+
return NotificationPayload(
|
|
69
|
+
title = display?.optNonEmpty("title") ?: notif?.title,
|
|
70
|
+
subtitle = display?.optNonEmpty("subtitle"),
|
|
71
|
+
body = display?.optNonEmpty("body") ?: notif?.body,
|
|
72
|
+
imageUrl = display?.optNonEmpty("imageUrl") ?: notif?.imageUrl?.toString(),
|
|
73
|
+
largeIcon = data["largeIcon"],
|
|
74
|
+
channelId = display?.optNonEmpty("channelId") ?: notif?.channelId,
|
|
75
|
+
channel = display?.optJSONObject("channel"),
|
|
76
|
+
sound = display?.optNonEmpty("sound") ?: notif?.sound,
|
|
77
|
+
smallIcon = display?.optNonEmpty("smallIcon") ?: notif?.icon,
|
|
78
|
+
color = display?.optNonEmpty("color") ?: notif?.color,
|
|
79
|
+
collapseId = display?.optNonEmpty("collapseId") ?: message.collapseKey,
|
|
80
|
+
url = data["url"],
|
|
81
|
+
buttons = parseButtons(data["buttons"]),
|
|
82
|
+
data = custom,
|
|
83
|
+
notificationId = (System.currentTimeMillis() and 0x7FFFFFFF).toInt(),
|
|
84
|
+
showForeground = flag(data["showForeground"]),
|
|
85
|
+
showBackground = flag(data["showBackground"]),
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
fun fromJson(json: JSONObject): NotificationPayload = NotificationPayload(
|
|
90
|
+
title = json.optNonEmpty("title"),
|
|
91
|
+
subtitle = json.optNonEmpty("subtitle"),
|
|
92
|
+
body = json.optNonEmpty("body"),
|
|
93
|
+
imageUrl = json.optNonEmpty("imageUrl"),
|
|
94
|
+
largeIcon = json.optNonEmpty("largeIcon"),
|
|
95
|
+
channelId = json.optNonEmpty("channelId"),
|
|
96
|
+
channel = json.optJSONObject("channel"),
|
|
97
|
+
sound = json.optNonEmpty("sound"),
|
|
98
|
+
smallIcon = json.optNonEmpty("smallIcon"),
|
|
99
|
+
color = json.optNonEmpty("color"),
|
|
100
|
+
collapseId = json.optNonEmpty("collapseId"),
|
|
101
|
+
url = json.optNonEmpty("url"),
|
|
102
|
+
buttons = parseButtons(json.optJSONArray("buttons")),
|
|
103
|
+
data = json.optJSONObject("data")?.let { obj ->
|
|
104
|
+
val out = HashMap<String, String>()
|
|
105
|
+
obj.keys().forEach { k -> out[k] = obj.optString(k) }
|
|
106
|
+
out
|
|
107
|
+
} ?: emptyMap(),
|
|
108
|
+
notificationId = json.optInt("notificationId", (System.currentTimeMillis() and 0x7FFFFFFF).toInt()),
|
|
109
|
+
showForeground = json.optBoolean("showForeground", true),
|
|
110
|
+
showBackground = json.optBoolean("showBackground", true),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
private fun parseButtons(raw: String?): List<Button> =
|
|
114
|
+
raw?.let { runCatching { parseButtons(JSONArray(it)) }.getOrDefault(emptyList()) } ?: emptyList()
|
|
115
|
+
|
|
116
|
+
private fun parseButtons(arr: JSONArray?): List<Button> {
|
|
117
|
+
if (arr == null) return emptyList()
|
|
118
|
+
val out = ArrayList<Button>(arr.length())
|
|
119
|
+
for (i in 0 until arr.length()) {
|
|
120
|
+
val o = arr.optJSONObject(i) ?: continue
|
|
121
|
+
val text = o.optString("text", o.optString("id"))
|
|
122
|
+
if (text.isNotEmpty()) out.add(Button(o.optString("id", i.toString()), text))
|
|
123
|
+
}
|
|
124
|
+
return out
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private fun JSONObject.optNonEmpty(key: String): String? =
|
|
128
|
+
optString(key, "").takeIf { it.isNotEmpty() }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
package com.amrshbib.pushbib
|
|
2
|
+
|
|
3
|
+
import android.app.NotificationChannel
|
|
4
|
+
import android.app.NotificationManager
|
|
5
|
+
import android.app.PendingIntent
|
|
6
|
+
import android.content.Context
|
|
7
|
+
import android.content.Intent
|
|
8
|
+
import android.content.pm.PackageManager
|
|
9
|
+
import android.graphics.Bitmap
|
|
10
|
+
import android.graphics.BitmapFactory
|
|
11
|
+
import android.graphics.Color
|
|
12
|
+
import android.media.RingtoneManager
|
|
13
|
+
import android.os.Build
|
|
14
|
+
import androidx.core.app.NotificationCompat
|
|
15
|
+
import androidx.core.app.NotificationManagerCompat
|
|
16
|
+
import org.json.JSONObject
|
|
17
|
+
import java.net.HttpURLConnection
|
|
18
|
+
import java.net.URL
|
|
19
|
+
import java.util.concurrent.Executors
|
|
20
|
+
|
|
21
|
+
object NotificationRenderer {
|
|
22
|
+
const val EXTRA_EVENT = "pushbib_event"
|
|
23
|
+
const val DEFAULT_CHANNEL_ID = "pushbib_default"
|
|
24
|
+
|
|
25
|
+
private const val META_DEFAULT_ICON = "com.amrshbib.pushbib.default_notification_icon"
|
|
26
|
+
private const val META_DEFAULT_COLOR = "com.amrshbib.pushbib.default_notification_color"
|
|
27
|
+
private const val META_DEFAULT_CHANNEL_NAME = "com.amrshbib.pushbib.default_channel_name"
|
|
28
|
+
private const val IMAGE_TIMEOUT_MS = 8000
|
|
29
|
+
|
|
30
|
+
private val executor = Executors.newSingleThreadExecutor()
|
|
31
|
+
|
|
32
|
+
fun render(context: Context, payload: NotificationPayload) {
|
|
33
|
+
val appContext = context.applicationContext
|
|
34
|
+
executor.execute {
|
|
35
|
+
try {
|
|
36
|
+
renderBlocking(appContext, payload)
|
|
37
|
+
} catch (e: Exception) {
|
|
38
|
+
android.util.Log.w("Pushbib", "render failed: ${e.message}")
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private fun renderBlocking(context: Context, p: NotificationPayload) {
|
|
44
|
+
val nm = NotificationManagerCompat.from(context)
|
|
45
|
+
if (!nm.areNotificationsEnabled()) {
|
|
46
|
+
android.util.Log.i("Pushbib", "notifications disabled — dropping display")
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
ensureDefaultChannel(context)
|
|
51
|
+
val channelId = resolveChannel(context, p)
|
|
52
|
+
|
|
53
|
+
val builder = NotificationCompat.Builder(context, channelId)
|
|
54
|
+
.setSmallIcon(resolveSmallIcon(context, p.smallIcon))
|
|
55
|
+
.setAutoCancel(true)
|
|
56
|
+
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
|
57
|
+
|
|
58
|
+
(p.title ?: appName(context)).let { builder.setContentTitle(it) }
|
|
59
|
+
p.body?.let {
|
|
60
|
+
builder.setContentText(it)
|
|
61
|
+
builder.setStyle(NotificationCompat.BigTextStyle().bigText(it))
|
|
62
|
+
}
|
|
63
|
+
p.subtitle?.let { builder.setSubText(it) }
|
|
64
|
+
resolveColor(context, p.color)?.let { builder.setColor(it) }
|
|
65
|
+
|
|
66
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
|
67
|
+
builder.setSound(resolveSound(context, p.sound))
|
|
68
|
+
builder.setDefaults(NotificationCompat.DEFAULT_VIBRATE or NotificationCompat.DEFAULT_LIGHTS)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
fetchBitmap(p.largeIcon)?.let { builder.setLargeIcon(it) }
|
|
72
|
+
fetchBitmap(p.imageUrl)?.let { image ->
|
|
73
|
+
builder.setStyle(
|
|
74
|
+
NotificationCompat.BigPictureStyle().bigPicture(image).setSummaryText(p.body),
|
|
75
|
+
)
|
|
76
|
+
if (p.largeIcon == null) builder.setLargeIcon(image)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
builder.setContentIntent(clickIntent(context, p, null, p.notificationId))
|
|
80
|
+
p.buttons.forEachIndexed { index, button ->
|
|
81
|
+
builder.addAction(0, button.text, clickIntent(context, p, button.id, p.notificationId + index + 1))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
nm.notify(p.collapseId, p.notificationId, builder.build())
|
|
86
|
+
} catch (e: SecurityException) {
|
|
87
|
+
android.util.Log.w("Pushbib", "notify blocked: ${e.message}")
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private fun clickIntent(context: Context, p: NotificationPayload, actionId: String?, requestCode: Int): PendingIntent {
|
|
92
|
+
val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)
|
|
93
|
+
?: Intent().setPackage(context.packageName)
|
|
94
|
+
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
95
|
+
val event = JSONObject()
|
|
96
|
+
.put("notification", p.toJson())
|
|
97
|
+
.putOpt("actionId", actionId)
|
|
98
|
+
.put("notificationId", p.notificationId)
|
|
99
|
+
launch.putExtra(EXTRA_EVENT, event.toString())
|
|
100
|
+
return PendingIntent.getActivity(
|
|
101
|
+
context,
|
|
102
|
+
requestCode,
|
|
103
|
+
launch,
|
|
104
|
+
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private fun ensureDefaultChannel(context: Context) {
|
|
109
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
|
110
|
+
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
111
|
+
if (manager.getNotificationChannel(DEFAULT_CHANNEL_ID) != null) return
|
|
112
|
+
val name = metaString(context, META_DEFAULT_CHANNEL_NAME) ?: "Notifications"
|
|
113
|
+
manager.createNotificationChannel(
|
|
114
|
+
NotificationChannel(DEFAULT_CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH),
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private fun resolveChannel(context: Context, p: NotificationPayload): String {
|
|
119
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return DEFAULT_CHANNEL_ID
|
|
120
|
+
|
|
121
|
+
PushbibChannels.ensureChannel(context, p.channel)?.let { return it }
|
|
122
|
+
|
|
123
|
+
val requested = p.channelId
|
|
124
|
+
if (requested.isNullOrEmpty()) return DEFAULT_CHANNEL_ID
|
|
125
|
+
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
126
|
+
return if (manager.getNotificationChannel(requested) != null) requested else DEFAULT_CHANNEL_ID
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
internal fun resolveSmallIcon(context: Context, name: String?): Int {
|
|
130
|
+
val res = context.resources
|
|
131
|
+
val pkg = context.packageName
|
|
132
|
+
name?.let {
|
|
133
|
+
res.getIdentifier(it, "drawable", pkg).takeIf { id -> id != 0 }?.let { id -> return id }
|
|
134
|
+
res.getIdentifier(it, "mipmap", pkg).takeIf { id -> id != 0 }?.let { id -> return id }
|
|
135
|
+
}
|
|
136
|
+
metaResource(context, META_DEFAULT_ICON)?.let { return it }
|
|
137
|
+
context.applicationInfo.icon.takeIf { it != 0 }?.let { return it }
|
|
138
|
+
return android.R.drawable.ic_dialog_info
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
internal fun resolveColor(context: Context, hex: String?): Int? {
|
|
142
|
+
hex?.let { runCatching { return Color.parseColor(it) } }
|
|
143
|
+
metaString(context, META_DEFAULT_COLOR)?.let { runCatching { return Color.parseColor(it) } }
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private fun resolveSound(context: Context, name: String?) =
|
|
148
|
+
name?.let {
|
|
149
|
+
val id = context.resources.getIdentifier(it, "raw", context.packageName)
|
|
150
|
+
if (id != 0) android.net.Uri.parse("android.resource://${context.packageName}/$id") else null
|
|
151
|
+
} ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
|
|
152
|
+
|
|
153
|
+
private fun fetchBitmap(url: String?): Bitmap? {
|
|
154
|
+
if (url.isNullOrEmpty()) return null
|
|
155
|
+
return try {
|
|
156
|
+
val conn = URL(url).openConnection() as HttpURLConnection
|
|
157
|
+
conn.connectTimeout = IMAGE_TIMEOUT_MS
|
|
158
|
+
conn.readTimeout = IMAGE_TIMEOUT_MS
|
|
159
|
+
conn.inputStream.use { BitmapFactory.decodeStream(it) }
|
|
160
|
+
} catch (e: Exception) {
|
|
161
|
+
android.util.Log.w("Pushbib", "image fetch failed ($url): ${e.message}")
|
|
162
|
+
null
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
internal fun appName(context: Context): String =
|
|
167
|
+
context.applicationInfo.loadLabel(context.packageManager).toString()
|
|
168
|
+
|
|
169
|
+
internal fun metaString(context: Context, key: String): String? = metaData(context)?.getString(key)
|
|
170
|
+
|
|
171
|
+
private fun metaResource(context: Context, key: String): Int? =
|
|
172
|
+
metaData(context)?.getInt(key, 0)?.takeIf { it != 0 }
|
|
173
|
+
|
|
174
|
+
private fun metaData(context: Context) = try {
|
|
175
|
+
context.packageManager
|
|
176
|
+
.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
|
|
177
|
+
.metaData
|
|
178
|
+
} catch (e: Exception) {
|
|
179
|
+
null
|
|
180
|
+
}
|
|
181
|
+
}
|