@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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/CHANGELOG.md +473 -2
- package/LICENSE +21 -0
- package/README.md +279 -47
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +20 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/GENERATED.md +1 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +111 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +312 -65
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +705 -96
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +29 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +24 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +343 -0
- package/ios/SwissKnifeJSON.swift +24 -2
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/GENERATED.md +1 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
- package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
- package/ios-notification-service/vendor/GENERATED.md +11 -0
- package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +27 -6
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +27 -6
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +2 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +2 -0
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +13 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +16 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +50 -9
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- 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
|
+
}
|