@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.0

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.
Files changed (177) hide show
  1. package/CHANGELOG.md +465 -0
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +353 -31
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +353 -31
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +3 -1
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +3 -1
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +13 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +18 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +476 -67
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -0,0 +1,438 @@
1
+ package com.appswissknife.notifications
2
+
3
+ import android.Manifest
4
+ import android.app.Activity
5
+ import android.app.NotificationManager
6
+ import android.content.Context
7
+ import android.content.Intent
8
+ import android.content.pm.PackageManager
9
+ import android.os.Build
10
+ import android.util.Log
11
+ import com.appswissknife.context.AppLifecycle
12
+ import com.appswissknife.device.DeviceID
13
+ import com.appswissknife.identity.Identity
14
+ import com.appswissknife.net.BackendConfig
15
+ import com.appswissknife.net.BackendHttpClient
16
+ import com.appswissknife.net.ConfigBridge
17
+ import java.io.IOException
18
+ import java.util.Locale
19
+ import java.util.TimeZone
20
+ import java.util.concurrent.CopyOnWriteArrayList
21
+ import java.util.concurrent.Executor
22
+ import java.util.concurrent.Executors
23
+
24
+ /**
25
+ * Push notifications entry point: `SwissKnife.notifications`.
26
+ *
27
+ * Firebase is a `compileOnly` dependency of the SDK, so apps that do not use
28
+ * push never pull Firebase in. Everything FCM-specific lives in
29
+ * [FcmBridge] / [SwissKnifeMessagingService], which are only loaded when the
30
+ * app itself ships `firebase-messaging`.
31
+ */
32
+ object SwissKnifeNotifications {
33
+ private const val TAG = "SwissKnife.Push"
34
+ private const val PREFS = "swissknife_push"
35
+ const val DEFAULT_CHANNEL_ID = "swissknife_default"
36
+ internal const val DEVICES_PATH = "/api/sdk/push/devices"
37
+
38
+ @Volatile private var appContext: Context? = null
39
+ @Volatile private var attached = false
40
+ private val openedListeners = CopyOnWriteArrayList<(NotificationOpen) -> Unit>()
41
+ // Opens not yet delivered to a listener (cold start), oldest first. Each is delivered once.
42
+ private val pendingOpens = ArrayDeque<NotificationOpen>()
43
+ // Events from taps handled before configure; flushed on attach.
44
+ private val pendingTracks = ArrayList<PendingTrack>()
45
+ // deliveryId|action keys already handled in this process (idempotent across recreated intents).
46
+ private val handledKeys = LinkedHashSet<String>()
47
+ private var lifecycleCallbacks: android.app.Application.ActivityLifecycleCallbacks? = null
48
+
49
+ private class PendingTrack(val deliveryId: String, val messageId: String, val type: String, val actionId: String?)
50
+
51
+ // --- test seams --------------------------------------------------------
52
+ internal var executor: Executor = Executors.newSingleThreadExecutor { r ->
53
+ Thread(r, "swissknife-push").apply { isDaemon = true }
54
+ }
55
+ internal var httpProvider: () -> BackendHttpClient = { BackendHttpClient.shared }
56
+ internal var isConfigured: () -> Boolean = { ConfigBridge.snapshot().apiKey.isNotEmpty() }
57
+ internal var nowMs: () -> Long = System::currentTimeMillis
58
+ internal var eventQueueProvider: (Context) -> PushEventQueue = { PushEventQueue.forContext(it) }
59
+ internal var stateStoreProvider: (Context) -> PushStateStore = { PrefsPushStateStore(it) }
60
+ internal var fcmAvailable: () -> Boolean = { FcmBridge.isAvailable() }
61
+ internal var tokenFetcher: (onToken: (String) -> Unit, onError: (Throwable?) -> Unit) -> Unit =
62
+ { ok, err -> FcmBridge.fetchToken(ok, err) }
63
+
64
+ // --- lifecycle wiring --------------------------------------------------
65
+
66
+ /**
67
+ * Called from `SwissKnife.ensureObservabilityBackend`. Subscribes to identity
68
+ * changes and app-foreground so the device row follows the user and the
69
+ * permission state. Idempotent.
70
+ */
71
+ @JvmStatic
72
+ @Synchronized
73
+ internal fun attach(context: Context) {
74
+ appContext = context.applicationContext ?: context
75
+ if (attached) return
76
+ attached = true
77
+ runCatching { Identity.addObserver { upsertIfChanged("identity") } }
78
+ runCatching {
79
+ AppLifecycle.subscribe { ev ->
80
+ if (ev == AppLifecycle.Event.DidBecomeActive) {
81
+ upsertIfChanged("foreground")
82
+ eventQueueProvider(context).scheduleFlush(context)
83
+ }
84
+ }
85
+ }
86
+ registerLaunchIntentHandling(appContext!!)
87
+ // Taps handled before configure had nowhere to record their events.
88
+ val tracks = synchronized(pendingTracks) { pendingTracks.toList().also { pendingTracks.clear() } }
89
+ tracks.forEach { trackEvent(appContext!!, it.deliveryId, it.messageId, it.type, it.actionId) }
90
+ // Existing installs (permission already granted, never asked via the SDK): get a token.
91
+ autoFetchTokenIfNeeded(appContext!!)
92
+ // A token may have been stored by the messaging service before configure ran.
93
+ upsertIfChanged("attach")
94
+ }
95
+
96
+ /** Cold start / warm start: feed every activity's launch intent to [handleIntent] (idempotent). */
97
+ private fun registerLaunchIntentHandling(ctx: Context) {
98
+ val app = ctx as? android.app.Application ?: ctx.applicationContext as? android.app.Application ?: return
99
+ val cb = object : android.app.Application.ActivityLifecycleCallbacks {
100
+ override fun onActivityCreated(activity: Activity, savedInstanceState: android.os.Bundle?) { handleIntent(activity.intent) }
101
+ override fun onActivityResumed(activity: Activity) { handleIntent(activity.intent) }
102
+ override fun onActivityStarted(activity: Activity) {}
103
+ override fun onActivityPaused(activity: Activity) {}
104
+ override fun onActivityStopped(activity: Activity) {}
105
+ override fun onActivitySaveInstanceState(activity: Activity, outState: android.os.Bundle) {}
106
+ override fun onActivityDestroyed(activity: Activity) {}
107
+ }
108
+ lifecycleCallbacks = cb
109
+ app.registerActivityLifecycleCallbacks(cb)
110
+ }
111
+
112
+ private fun autoFetchTokenIfNeeded(ctx: Context) {
113
+ val store = stateStoreProvider(ctx)
114
+ if (store.unregistered || store.token != null) return
115
+ if (!fcmAvailable() || permissionStatus() != PermissionStatus.AUTHORIZED) return
116
+ fetchToken()
117
+ }
118
+
119
+ // --- public API --------------------------------------------------------
120
+
121
+ /**
122
+ * Shows the POST_NOTIFICATIONS dialog on API 33+ (creating the default
123
+ * channel first). On older API levels no dialog exists and the callback
124
+ * fires immediately with the current state. The callback runs on the main thread.
125
+ */
126
+ @JvmStatic
127
+ fun requestPermission(activity: Activity, callback: (PermissionStatus) -> Unit) {
128
+ val ctx = activity.applicationContext
129
+ appContext = appContext ?: ctx
130
+ NotificationRenderer.ensureDefaultChannel(ctx)
131
+ // An explicit permission request lifts a previous unregister().
132
+ prefs(ctx).unregistered = false
133
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || isRuntimeGranted(ctx)) {
134
+ val status = permissionStatus()
135
+ callback(status)
136
+ if (status == PermissionStatus.AUTHORIZED) runCatching { fetchToken() }
137
+ upsertIfChanged("permission")
138
+ return
139
+ }
140
+ PermissionRequestActivity.request(activity) { granted ->
141
+ prefs(ctx).permissionAsked = true
142
+ val status = permissionStatus()
143
+ callback(status)
144
+ if (granted) runCatching { fetchToken() }
145
+ upsertIfChanged("permission")
146
+ }
147
+ }
148
+
149
+ @JvmStatic
150
+ fun permissionStatus(): PermissionStatus {
151
+ val ctx = appContext ?: return PermissionStatus.NOT_DETERMINED
152
+ val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
153
+ return PermissionStatus.resolve(
154
+ sdkInt = Build.VERSION.SDK_INT,
155
+ runtimePermissionGranted = isRuntimeGranted(ctx),
156
+ notificationsEnabled = nm?.areNotificationsEnabled() ?: true,
157
+ askedBefore = prefs(ctx).permissionAsked,
158
+ )
159
+ }
160
+
161
+ /** Fetches the current FCM token (requires `firebase-messaging` in the app) and upserts it. */
162
+ @JvmStatic
163
+ fun fetchAndRegisterToken() {
164
+ appContext?.let { stateStoreProvider(it).unregistered = false }
165
+ fetchToken()
166
+ }
167
+
168
+ private fun fetchToken() {
169
+ if (!fcmAvailable()) {
170
+ Log.w(TAG, "firebase-messaging is not on the classpath; use registerToken(token) instead")
171
+ return
172
+ }
173
+ tokenFetcher(
174
+ { registerToken(it) },
175
+ { Log.w(TAG, "FCM token fetch failed: ${it?.message}") },
176
+ )
177
+ }
178
+
179
+ /** Manual path: hand the SDK an FCM token you obtained yourself. */
180
+ @JvmStatic
181
+ fun registerToken(token: String) {
182
+ val ctx = appContext
183
+ if (token.isBlank()) return
184
+ if (ctx == null) {
185
+ Log.w(TAG, "registerToken before SwissKnife.configure; token dropped")
186
+ return
187
+ }
188
+ prefs(ctx).apply { unregistered = false; this.token = token }
189
+ upsertIfChanged("token")
190
+ }
191
+
192
+ /** Token rotation from [SwissKnifeMessagingService.onNewToken]; safe before configure. */
193
+ internal fun onNewToken(context: Context, token: String) {
194
+ if (token.isBlank()) return
195
+ val ctx = context.applicationContext ?: context
196
+ if (appContext == null) appContext = ctx
197
+ val store = stateStoreProvider(ctx)
198
+ // deleteToken() from unregister() can rotate the token; don't silently re-register.
199
+ if (store.unregistered) return
200
+ store.token = token
201
+ upsertIfChanged("new-token")
202
+ }
203
+
204
+ /**
205
+ * Called by Identity on logOut/reset/wipe: the next device upsert carries an
206
+ * explicit `user_id: null` until the server acknowledges it (persisted, so it
207
+ * survives a process restart). Unknown identity after relaunch never sets this.
208
+ */
209
+ internal fun markUserUnlinkPending(context: Context) {
210
+ val ctx = context.applicationContext ?: context
211
+ if (appContext == null) appContext = ctx
212
+ stateStoreProvider(ctx).pendingUnlink = true
213
+ upsertIfChanged("unlink")
214
+ }
215
+
216
+ /** Marks the device as unregistered (token null) and deletes the FCM token when possible. */
217
+ @JvmStatic
218
+ fun unregister() {
219
+ val ctx = appContext ?: return
220
+ val store = stateStoreProvider(ctx)
221
+ store.token = null
222
+ store.unregistered = true
223
+ executor.execute { upsert(ctx, force = true) }
224
+ if (fcmAvailable()) FcmBridge.deleteToken()
225
+ }
226
+
227
+ /**
228
+ * Call from your launcher activity's `onCreate` (with `intent`) and
229
+ * `onNewIntent`. Returns the parsed open, tracks `opened` / `action`, and
230
+ * notifies [addOpenedListener] listeners. Returns null for intents that are
231
+ * not swiss-knife pushes, and for an intent already handled.
232
+ */
233
+ @JvmStatic
234
+ fun handleIntent(intent: Intent?): NotificationOpen? {
235
+ if (intent == null || intent.getBooleanExtra(PushKeys.HANDLED, false)) return null
236
+ val open = PushPayload.fromIntent(intent) ?: return null
237
+ intent.putExtra(PushKeys.HANDLED, true)
238
+ // A recreated/redelivered intent may not carry our HANDLED extra; dedupe by delivery too.
239
+ val key = "${open.deliveryId ?: open.messageId}|${open.actionId.orEmpty()}"
240
+ synchronized(handledKeys) {
241
+ if (!handledKeys.add(key)) return null
242
+ if (handledKeys.size > 64) handledKeys.remove(handledKeys.first())
243
+ }
244
+ val ctx = appContext
245
+ val did = open.deliveryId
246
+ val mid = open.messageId
247
+ if (did != null && mid != null) {
248
+ val type = if (open.actionId != null) "action" else "opened"
249
+ if (ctx != null) trackEvent(ctx, did, mid, type, open.actionId)
250
+ else synchronized(pendingTracks) { pendingTracks.add(PendingTrack(did, mid, type, open.actionId)) } // flushed on attach
251
+ }
252
+ dispatchOpen(open)
253
+ return open
254
+ }
255
+
256
+ /**
257
+ * Listener for taps. If a tap was handled before any listener existed (cold
258
+ * start), the most recent one is replayed once to the first listener.
259
+ */
260
+ @JvmStatic
261
+ fun addOpenedListener(listener: (NotificationOpen) -> Unit) {
262
+ openedListeners.add(listener)
263
+ // Drain atomically so each buffered open reaches exactly one consumer.
264
+ val drained = synchronized(pendingOpens) { pendingOpens.toList().also { pendingOpens.clear() } }
265
+ for (p in drained) runCatching { listener(p) }
266
+ }
267
+
268
+ /**
269
+ * The open that launched the app, if no listener has consumed it yet
270
+ * (`getInitialNotification` for bridges). Consuming it removes it from the
271
+ * replay buffer, so it is delivered exactly once.
272
+ */
273
+ @JvmStatic
274
+ fun consumeInitialOpen(): NotificationOpen? =
275
+ synchronized(pendingOpens) { pendingOpens.removeFirstOrNull() }
276
+
277
+ @JvmStatic
278
+ fun removeOpenedListener(listener: (NotificationOpen) -> Unit) {
279
+ openedListeners.remove(listener)
280
+ }
281
+
282
+ // --- internals ---------------------------------------------------------
283
+
284
+ private fun dispatchOpen(open: NotificationOpen) {
285
+ if (openedListeners.isEmpty()) {
286
+ synchronized(pendingOpens) {
287
+ pendingOpens.addLast(open)
288
+ if (pendingOpens.size > 16) pendingOpens.removeFirst()
289
+ }
290
+ return
291
+ }
292
+ for (l in openedListeners) runCatching { l(open) }
293
+ }
294
+
295
+ internal fun trackEvent(ctx: Context, deliveryId: String, messageId: String, type: String, actionId: String? = null) {
296
+ executor.execute {
297
+ runCatching {
298
+ val q = eventQueueProvider(ctx)
299
+ q.enqueue(q.newItem(deliveryId, messageId, type, actionId))
300
+ q.scheduleFlush(ctx)
301
+ }.onFailure { Log.w(TAG, "track $type failed: ${it.message}") }
302
+ }
303
+ }
304
+
305
+ internal fun upsertIfChanged(reason: String) {
306
+ val ctx = appContext ?: return
307
+ executor.execute { upsert(ctx, force = false, reason = reason) }
308
+ }
309
+
310
+ /** Builds the request from current state. Exposed for tests. */
311
+ internal fun buildDeviceInfo(ctx: Context, token: String?, unlinkUser: Boolean = false): PushDeviceInfo {
312
+ val id = runCatching { Identity.current() }.getOrNull()
313
+ val pkg = ctx.packageName
314
+ val appVersion = runCatching {
315
+ ctx.packageManager.getPackageInfo(pkg, 0).versionName
316
+ }.getOrNull()
317
+ return PushDeviceInfo(
318
+ installId = DeviceID.get(ctx),
319
+ token = token,
320
+ packageName = pkg,
321
+ permission = permissionStatus(),
322
+ userId = id?.userId,
323
+ unlinkUser = unlinkUser,
324
+ anonymousId = id?.anonymousId?.takeIf { it.isNotEmpty() },
325
+ appVersion = appVersion,
326
+ sdkVersion = com.appswissknife.context.DeviceContextProvider.SDK_VERSION,
327
+ osVersion = Build.VERSION.RELEASE,
328
+ locale = Locale.getDefault().toLanguageTag(),
329
+ timezone = TimeZone.getDefault().id,
330
+ )
331
+ }
332
+
333
+ private fun upsert(ctx: Context, force: Boolean, reason: String = "explicit") {
334
+ if (!isConfigured()) return
335
+ val store = stateStoreProvider(ctx)
336
+ val token = store.token
337
+ // Never registered and no token: nothing to tell the server.
338
+ if (token == null && store.fingerprint == null) return
339
+ val info = try {
340
+ buildDeviceInfo(ctx, token, unlinkUser = store.pendingUnlink)
341
+ } catch (t: Throwable) {
342
+ Log.w(TAG, "device info unavailable: ${t.message}")
343
+ return
344
+ }
345
+ // A pending unlink must reach the server even when the fingerprint is unchanged.
346
+ if (!PushDedupe.shouldUpsert(store, info, nowMs(), force || store.pendingUnlink)) return
347
+ try {
348
+ val resp = httpProvider().simplePost(DEVICES_PATH, info.toJson().toString())
349
+ if (resp.code in 200..299) {
350
+ store.fingerprint = info.fingerprint()
351
+ store.upsertedAtMs = nowMs()
352
+ // Only what was actually sent is acknowledged.
353
+ if (info.unlinkUser) store.pendingUnlink = false
354
+ } else {
355
+ Log.w(TAG, "device upsert ($reason) rejected: ${resp.code}")
356
+ }
357
+ } catch (e: IOException) {
358
+ Log.w(TAG, "device upsert ($reason) failed: ${e.message}")
359
+ }
360
+ }
361
+
362
+ private fun isRuntimeGranted(ctx: Context): Boolean =
363
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
364
+ ctx.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
365
+
366
+ private fun prefs(ctx: Context) = stateStoreProvider(ctx)
367
+
368
+ @androidx.annotation.VisibleForTesting
369
+ internal fun resetForTesting() {
370
+ appContext = null
371
+ attached = false
372
+ openedListeners.clear()
373
+ synchronized(pendingOpens) { pendingOpens.clear() }
374
+ synchronized(pendingTracks) { pendingTracks.clear() }
375
+ synchronized(handledKeys) { handledKeys.clear() }
376
+ lifecycleCallbacks = null
377
+ fcmAvailable = { FcmBridge.isAvailable() }
378
+ tokenFetcher = { ok, err -> FcmBridge.fetchToken(ok, err) }
379
+ executor = Executor { it.run() }
380
+ }
381
+
382
+ @androidx.annotation.VisibleForTesting
383
+ internal fun setContextForTesting(context: Context) {
384
+ appContext = context.applicationContext
385
+ }
386
+ }
387
+
388
+ /** SharedPreferences-backed [PushStateStore]. */
389
+ internal class PrefsPushStateStore(context: Context) : PushStateStore {
390
+ private val sp = context.applicationContext.getSharedPreferences("swissknife_push", Context.MODE_PRIVATE)
391
+ override var token: String?
392
+ get() = sp.getString("token", null)
393
+ set(v) { sp.edit().apply { if (v == null) remove("token") else putString("token", v) }.apply() }
394
+ override var fingerprint: String?
395
+ get() = sp.getString("fingerprint", null)
396
+ set(v) { sp.edit().apply { if (v == null) remove("fingerprint") else putString("fingerprint", v) }.apply() }
397
+ override var upsertedAtMs: Long
398
+ get() = sp.getLong("upserted_at", 0L)
399
+ set(v) { sp.edit().putLong("upserted_at", v).apply() }
400
+ override var permissionAsked: Boolean
401
+ get() = sp.getBoolean("permission_asked", false)
402
+ set(v) { sp.edit().putBoolean("permission_asked", v).apply() }
403
+ override var unregistered: Boolean
404
+ get() = sp.getBoolean("unregistered", false)
405
+ set(v) { sp.edit().putBoolean("unregistered", v).apply() }
406
+ override var pendingUnlink: Boolean
407
+ get() = sp.getBoolean("pending_unlink", false)
408
+ set(v) { sp.edit().putBoolean("pending_unlink", v).apply() }
409
+ }
410
+
411
+ /**
412
+ * The only place that names Firebase classes outside the messaging service.
413
+ * Loaded lazily; every entry point is guarded by [isAvailable].
414
+ */
415
+ internal object FcmBridge {
416
+ fun isAvailable(): Boolean = try {
417
+ Class.forName("com.google.firebase.messaging.FirebaseMessaging")
418
+ true
419
+ } catch (_: Throwable) {
420
+ false
421
+ }
422
+
423
+ fun fetchToken(onToken: (String) -> Unit, onError: (Throwable?) -> Unit) {
424
+ try {
425
+ com.google.firebase.messaging.FirebaseMessaging.getInstance().token
426
+ .addOnCompleteListener { t ->
427
+ val v = if (t.isSuccessful) t.result else null
428
+ if (v.isNullOrBlank()) onError(t.exception) else onToken(v)
429
+ }
430
+ } catch (t: Throwable) {
431
+ onError(t)
432
+ }
433
+ }
434
+
435
+ fun deleteToken() {
436
+ runCatching { com.google.firebase.messaging.FirebaseMessaging.getInstance().deleteToken() }
437
+ }
438
+ }