@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,143 @@
1
+ package com.appswissknife.notifications
2
+
3
+ import android.content.Context
4
+ import android.util.Log
5
+ import androidx.work.BackoffPolicy
6
+ import androidx.work.Constraints
7
+ import androidx.work.ExistingWorkPolicy
8
+ import androidx.work.NetworkType
9
+ import androidx.work.OneTimeWorkRequestBuilder
10
+ import androidx.work.WorkManager
11
+ import androidx.work.Worker
12
+ import androidx.work.WorkerParameters
13
+ import com.appswissknife.net.BackendHttpClient
14
+ import com.appswissknife.net.OfflineQueueItem
15
+ import com.appswissknife.net.OfflineQueueStore
16
+ import org.json.JSONArray
17
+ import org.json.JSONObject
18
+ import java.io.File
19
+ import java.io.IOException
20
+ import java.text.SimpleDateFormat
21
+ import java.util.Date
22
+ import java.util.Locale
23
+ import java.util.TimeZone
24
+ import java.util.UUID
25
+ import java.util.concurrent.TimeUnit
26
+
27
+ /** One queued `received` / `opened` / `action` event. */
28
+ internal data class PushEventItem(
29
+ override val id: String,
30
+ val deliveryId: String,
31
+ val messageId: String,
32
+ val type: String,
33
+ val actionId: String?,
34
+ val occurredAt: String,
35
+ ) : OfflineQueueItem {
36
+ override fun toJson(): JSONObject = JSONObject().apply {
37
+ put("id", id)
38
+ put("delivery_id", deliveryId)
39
+ put("message_id", messageId)
40
+ put("type", type)
41
+ if (actionId != null) put("action_id", actionId)
42
+ put("occurred_at", occurredAt)
43
+ }
44
+
45
+ /** The wire shape inside `events[]` (no local `id`). */
46
+ fun toWire(): JSONObject = toJson().apply { remove("id") }
47
+
48
+ companion object {
49
+ fun parse(o: JSONObject) = PushEventItem(
50
+ id = o.getString("id"),
51
+ deliveryId = o.getString("delivery_id"),
52
+ messageId = o.getString("message_id"),
53
+ type = o.getString("type"),
54
+ actionId = o.optString("action_id").takeIf { it.isNotEmpty() },
55
+ occurredAt = o.optString("occurred_at"),
56
+ )
57
+
58
+ fun isoNow(nowMs: Long = System.currentTimeMillis()): String =
59
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
60
+ .apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(nowMs))
61
+ }
62
+ }
63
+
64
+ /** Disk-backed queue for `POST /api/sdk/push/events`, reusing [OfflineQueueStore]. */
65
+ internal class PushEventQueue(
66
+ private val store: OfflineQueueStore<PushEventItem>,
67
+ private val batchSize: Int = 50,
68
+ ) {
69
+ companion object {
70
+ const val PATH = "/api/sdk/push/events"
71
+ const val WORK_NAME = "swissknife.push_events_flush"
72
+
73
+ fun forContext(context: Context): PushEventQueue = PushEventQueue(
74
+ OfflineQueueStore(
75
+ directory = File(context.applicationContext.filesDir, "swissknife/push-events"),
76
+ name = "push-events",
77
+ parser = PushEventItem::parse,
78
+ maxItems = 1_000,
79
+ maxBytes = 1L * 1024 * 1024,
80
+ )
81
+ )
82
+ }
83
+
84
+ fun enqueue(item: PushEventItem): Boolean = try {
85
+ store.append(item)
86
+ true
87
+ } catch (e: IOException) {
88
+ false
89
+ }
90
+
91
+ fun pendingCount(): Int = store.count()
92
+
93
+ fun buildBody(batch: List<PushEventItem>): JSONObject =
94
+ JSONObject().put("events", JSONArray().also { a -> batch.forEach { a.put(it.toWire()) } })
95
+
96
+ /**
97
+ * Drains the queue in batches. Returns true when empty, false when a batch
98
+ * failed transiently (caller should retry later). 4xx (other than 429)
99
+ * drops the batch: it will never succeed.
100
+ */
101
+ fun flushSync(http: BackendHttpClient): Boolean {
102
+ while (true) {
103
+ val batch = store.readAll().take(batchSize)
104
+ if (batch.isEmpty()) return true
105
+ val resp = try {
106
+ http.simplePost(PATH, buildBody(batch).toString())
107
+ } catch (e: IOException) {
108
+ Log.w("SwissKnife.Push", "events flush failed: ${e.message}")
109
+ return false
110
+ }
111
+ when {
112
+ resp.code in 200..299 -> store.remove(batch.map { it.id }.toSet())
113
+ resp.code == 429 || resp.code >= 500 -> return false
114
+ else -> { // permanent rejection (bad payload / auth): drop, don't wedge the queue
115
+ Log.w("SwissKnife.Push", "events batch rejected ${resp.code}; dropping ${batch.size}")
116
+ store.remove(batch.map { it.id }.toSet())
117
+ }
118
+ }
119
+ }
120
+ }
121
+
122
+ fun scheduleFlush(context: Context) {
123
+ val request = OneTimeWorkRequestBuilder<PushEventsFlushWorker>()
124
+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
125
+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
126
+ .build()
127
+ runCatching {
128
+ WorkManager.getInstance(context.applicationContext)
129
+ .enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.KEEP, request)
130
+ }.onFailure { Log.w("SwissKnife.Push", "WorkManager unavailable: ${it.message}") }
131
+ }
132
+
133
+ fun newItem(deliveryId: String, messageId: String, type: String, actionId: String? = null) =
134
+ PushEventItem(UUID.randomUUID().toString(), deliveryId, messageId, type, actionId, PushEventItem.isoNow())
135
+ }
136
+
137
+ class PushEventsFlushWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
138
+ override fun doWork(): Result {
139
+ val queue = PushEventQueue.forContext(applicationContext)
140
+ val ok = runCatching { queue.flushSync(BackendHttpClient.shared) }.getOrDefault(false)
141
+ return if (ok) Result.success() else if (runAttemptCount < 6) Result.retry() else Result.failure()
142
+ }
143
+ }
@@ -0,0 +1,72 @@
1
+ package com.appswissknife.notifications
2
+
3
+ import android.content.Intent
4
+
5
+ /** Reserved FCM `data` / launcher-intent extra keys (see push contract). */
6
+ object PushKeys {
7
+ const val MESSAGE_ID = "sk_m"
8
+ const val DELIVERY_ID = "sk_d"
9
+ const val LINK = "sk_link"
10
+ const val IMAGE = "sk_img"
11
+ const val TITLE = "sk_title"
12
+ const val BODY = "sk_body"
13
+
14
+ /** Optional: set on a notification action PendingIntent to report an `action` event. */
15
+ const val ACTION = "sk_action"
16
+
17
+ /** Set on an Intent after [SwissKnifeNotifications.handleIntent] processed it (dedupe). */
18
+ const val HANDLED = "sk_handled"
19
+
20
+ internal val RESERVED = setOf(MESSAGE_ID, DELIVERY_ID, LINK, IMAGE, TITLE, BODY, ACTION, HANDLED)
21
+
22
+ internal fun isSystemKey(k: String) =
23
+ k.startsWith("google.") || k.startsWith("gcm.") || k.startsWith("gcm_") ||
24
+ k == "from" || k == "collapse_key" || k == "message_type" || k == "message_id"
25
+ }
26
+
27
+ /** A tapped notification: the deep link plus the app's custom data. */
28
+ data class NotificationOpen(
29
+ val messageId: String?,
30
+ val deliveryId: String?,
31
+ val link: String?,
32
+ val imageUrl: String?,
33
+ val title: String?,
34
+ val body: String?,
35
+ val actionId: String?,
36
+ /** Custom data keys (reserved `sk_*` and FCM system keys removed). */
37
+ val data: Map<String, String>,
38
+ )
39
+
40
+ internal object PushPayload {
41
+ /** Null when the map carries no swiss-knife message/delivery id (not our push). */
42
+ fun fromMap(map: Map<String, String?>): NotificationOpen? {
43
+ val m = map[PushKeys.MESSAGE_ID]?.takeIf { it.isNotBlank() }
44
+ val d = map[PushKeys.DELIVERY_ID]?.takeIf { it.isNotBlank() }
45
+ if (m == null && d == null) return null
46
+ val custom = LinkedHashMap<String, String>()
47
+ for ((k, v) in map) {
48
+ if (v == null || k in PushKeys.RESERVED || PushKeys.isSystemKey(k)) continue
49
+ custom[k] = v
50
+ }
51
+ return NotificationOpen(
52
+ messageId = m,
53
+ deliveryId = d,
54
+ link = map[PushKeys.LINK]?.takeIf { it.isNotBlank() },
55
+ imageUrl = map[PushKeys.IMAGE]?.takeIf { it.isNotBlank() },
56
+ title = map[PushKeys.TITLE],
57
+ body = map[PushKeys.BODY],
58
+ actionId = map[PushKeys.ACTION]?.takeIf { it.isNotBlank() },
59
+ data = custom,
60
+ )
61
+ }
62
+
63
+ fun fromIntent(intent: Intent?): NotificationOpen? {
64
+ val extras = intent?.extras ?: return null
65
+ val map = HashMap<String, String?>()
66
+ for (k in extras.keySet()) {
67
+ @Suppress("DEPRECATION")
68
+ (extras.get(k) as? String)?.let { map[k] = it }
69
+ }
70
+ return fromMap(map)
71
+ }
72
+ }
@@ -0,0 +1,89 @@
1
+ package com.appswissknife.notifications
2
+
3
+ import org.json.JSONObject
4
+ import java.security.MessageDigest
5
+
6
+ /** Inputs for `POST /api/sdk/push/devices`. */
7
+ internal data class PushDeviceInfo(
8
+ val installId: String,
9
+ val token: String?,
10
+ val packageName: String,
11
+ val permission: PermissionStatus,
12
+ /** Null when identity is unknown (e.g. after relaunch) OR logged out; see [unlinkUser]. */
13
+ val userId: String?,
14
+ /**
15
+ * True only when a logout/reset/wipe happened and the server has not yet
16
+ * acknowledged it: then (and only then) a null [userId] is sent as explicit
17
+ * JSON null, which the server treats as "unlink". Not part of [fingerprint].
18
+ */
19
+ val unlinkUser: Boolean = false,
20
+ val anonymousId: String?,
21
+ val appVersion: String?,
22
+ val sdkVersion: String?,
23
+ val osVersion: String?,
24
+ val locale: String?,
25
+ val timezone: String?,
26
+ ) {
27
+ /** Field order is fixed so [fingerprint] is stable. */
28
+ private fun fields(): List<Pair<String, Any?>> = listOf(
29
+ "install_id" to installId,
30
+ "platform" to "android",
31
+ "provider" to "fcm",
32
+ "token" to token,
33
+ "bundle_id" to packageName,
34
+ "permission_status" to permission.wire,
35
+ "user_id" to userId,
36
+ "anonymous_id" to anonymousId,
37
+ "app_version" to appVersion,
38
+ "sdk_version" to sdkVersion,
39
+ "os_version" to osVersion,
40
+ "locale" to locale,
41
+ "timezone" to timezone,
42
+ )
43
+
44
+ /**
45
+ * `token` (null = unregistered) is always present, with explicit JSON null.
46
+ * `user_id` is omitted unless identity knows a user; it is an explicit JSON
47
+ * null only when [unlinkUser] is set (server unlinks). Other nulls are
48
+ * omitted (server keeps the stored value).
49
+ */
50
+ fun toJson(): JSONObject = JSONObject().also { o ->
51
+ for ((k, v) in fields()) {
52
+ if (v != null) o.put(k, v)
53
+ else if (k == "token" || (k == "user_id" && unlinkUser)) o.put(k, JSONObject.NULL)
54
+ }
55
+ }
56
+
57
+ /** SHA-256 over the ordered fields; equal fingerprints mean the server already has this state. */
58
+ fun fingerprint(): String {
59
+ val canonical = fields().joinToString("\u0001") { (k, v) -> "$k=${v ?: "\u0000"}" }
60
+ return MessageDigest.getInstance("SHA-256").digest(canonical.toByteArray())
61
+ .joinToString("") { "%02x".format(it) }
62
+ }
63
+ }
64
+
65
+ /** Persisted (token, fingerprint, time, asked-flag) state. */
66
+ internal interface PushStateStore {
67
+ var token: String?
68
+ var fingerprint: String?
69
+ var upsertedAtMs: Long
70
+ var permissionAsked: Boolean
71
+
72
+ /** Set by unregister(); blocks auto-registration (onNewToken, attach) until an explicit register / permission request. */
73
+ var unregistered: Boolean
74
+
75
+ /** Persisted: a logout/reset/wipe still has to be acknowledged by the server as an unlink. */
76
+ var pendingUnlink: Boolean
77
+ }
78
+
79
+ /** Decides whether an upsert is needed. */
80
+ internal object PushDedupe {
81
+ /** Re-upsert at least this often even when nothing changed (keeps last_seen fresh). */
82
+ const val REFRESH_MS = 7L * 24 * 60 * 60 * 1000
83
+
84
+ fun shouldUpsert(store: PushStateStore, info: PushDeviceInfo, nowMs: Long, force: Boolean): Boolean {
85
+ if (force) return true
86
+ if (store.fingerprint != info.fingerprint()) return true
87
+ return nowMs - store.upsertedAtMs >= REFRESH_MS
88
+ }
89
+ }
@@ -0,0 +1,57 @@
1
+ package com.appswissknife.notifications
2
+
3
+ import android.content.Context
4
+ import com.google.firebase.messaging.FirebaseMessagingService
5
+ import com.google.firebase.messaging.RemoteMessage
6
+
7
+ /**
8
+ * Drop-in FCM service. Register it in your manifest (the Expo plugin does
9
+ * this for you):
10
+ *
11
+ * ```xml
12
+ * <service android:name="com.appswissknife.notifications.SwissKnifeMessagingService" android:exported="false">
13
+ * <intent-filter><action android:name="com.google.firebase.MESSAGING_EVENT"/></intent-filter>
14
+ * </service>
15
+ * ```
16
+ *
17
+ * Apps with their own `FirebaseMessagingService` should instead forward to
18
+ * the static [handle] and [onNewToken] helpers.
19
+ */
20
+ open class SwissKnifeMessagingService : FirebaseMessagingService() {
21
+
22
+ override fun onNewToken(token: String) {
23
+ super.onNewToken(token)
24
+ SwissKnifeMessagingService.onNewToken(applicationContext, token)
25
+ }
26
+
27
+ override fun onMessageReceived(message: RemoteMessage) {
28
+ super.onMessageReceived(message)
29
+ handle(applicationContext, message)
30
+ }
31
+
32
+ companion object {
33
+ /**
34
+ * Forward a message from your own service. Returns true when it was a
35
+ * swiss-knife push (or an entitlements invalidate) and has been handled.
36
+ */
37
+ @JvmStatic
38
+ fun handle(context: Context, remoteMessage: RemoteMessage): Boolean {
39
+ val n = remoteMessage.notification
40
+ return PushMessageHandler.handle(
41
+ context,
42
+ IncomingPush(
43
+ data = remoteMessage.data,
44
+ notificationTitle = n?.title,
45
+ notificationBody = n?.body,
46
+ notificationImage = n?.imageUrl?.toString(),
47
+ ),
48
+ )
49
+ }
50
+
51
+ /** Forward `onNewToken` from your own service. */
52
+ @JvmStatic
53
+ fun onNewToken(context: Context, token: String) {
54
+ SwissKnifeNotifications.onNewToken(context, token)
55
+ }
56
+ }
57
+ }