@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
@@ -15,6 +15,10 @@ import com.appswissknife.models.StoreProduct
15
15
  import com.appswissknife.models.StoreProductDiscount
16
16
  import com.appswissknife.models.SubscriptionPeriod
17
17
  import com.appswissknife.offerings.SimplePrice
18
+ import com.appswissknife.offerings.SimpleSubscriptionPeriod
19
+ import java.util.concurrent.ConcurrentHashMap
20
+ import java.util.concurrent.CountDownLatch
21
+ import java.util.concurrent.TimeUnit
18
22
 
19
23
  class PlayPriceEnrichmentProvider(
20
24
  private val billingClientProvider: () -> BillingClient?,
@@ -29,38 +33,45 @@ class PlayPriceEnrichmentProvider(
29
33
  }
30
34
 
31
35
  /**
32
- * Query live [ProductDetails] for [productIds]. Blocks (≤5s) on Play's async
33
- * callback via a latch — the caller is already on a background thread
34
- * (OfferingsRepository fetch thread), matching the pre-refactor contract.
36
+ * Query live [ProductDetails] for [productIds], as subscriptions and as
37
+ * one-time products. Play takes one product type per query and leaves the
38
+ * ids of the other type out of its answer, so both queries run, in parallel,
39
+ * and their answers are merged (a product id is unique across both types in
40
+ * an app). Blocks (≤5s in all) on Play's callbacks via a latch: the caller is
41
+ * already on a background thread (the offerings fetch thread).
35
42
  */
36
43
  private fun loadProductDetails(productIds: List<String>): Map<String, ProductDetails> {
37
44
  val client = billingClientProvider() ?: return emptyMap()
38
45
  if (!client.isReady) return emptyMap()
39
46
  if (productIds.isEmpty()) return emptyMap()
40
- val params = QueryProductDetailsParams.newBuilder()
41
- .setProductList(productIds.map { pid ->
42
- QueryProductDetailsParams.Product.newBuilder()
43
- .setProductId(pid)
44
- .setProductType(BillingClient.ProductType.SUBS)
45
- .build()
46
- })
47
- .build()
48
- val latch = java.util.concurrent.CountDownLatch(1)
49
- var result: Map<String, ProductDetails> = emptyMap()
50
- client.queryProductDetailsAsync(params) { billingResult, productDetailsResult ->
51
- if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
52
- result = productDetailsResult.productDetailsList.associateBy { it.productId }
53
- } else {
54
- Log.w(TAG, "queryProductDetailsAsync returned ${billingResult.responseCode}: ${billingResult.debugMessage}")
47
+ val found = ConcurrentHashMap<String, ProductDetails>()
48
+ val latch = CountDownLatch(PRODUCT_TYPES.size)
49
+ for (type in PRODUCT_TYPES) {
50
+ val params = QueryProductDetailsParams.newBuilder()
51
+ .setProductList(productIds.map { pid ->
52
+ QueryProductDetailsParams.Product.newBuilder()
53
+ .setProductId(pid)
54
+ .setProductType(type)
55
+ .build()
56
+ })
57
+ .build()
58
+ client.queryProductDetailsAsync(params) { billingResult, productDetailsResult ->
59
+ if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
60
+ productDetailsResult.productDetailsList.forEach { found[it.productId] = it }
61
+ } else {
62
+ Log.w(TAG, "queryProductDetailsAsync($type) returned ${billingResult.responseCode}: ${billingResult.debugMessage}")
63
+ }
64
+ latch.countDown()
55
65
  }
56
- latch.countDown()
57
66
  }
58
- runCatching { latch.await(5, java.util.concurrent.TimeUnit.SECONDS) }
59
- return result
67
+ runCatching { latch.await(5, TimeUnit.SECONDS) }
68
+ // A copy: an answer that lands after the timeout must not change the result.
69
+ return HashMap(found)
60
70
  }
61
71
 
62
72
  companion object {
63
73
  private const val TAG = "SwissKnife.Offerings"
74
+ private val PRODUCT_TYPES = listOf(BillingClient.ProductType.SUBS, BillingClient.ProductType.INAPP)
64
75
  }
65
76
  }
66
77
 
@@ -69,12 +80,18 @@ class PlayPriceEnrichmentProvider(
69
80
  private class StoreProductFromPlayBilling(
70
81
  private val pd: ProductDetails,
71
82
  private val backendName: String,
72
- ) : StoreProduct {
83
+ ) : StoreProduct, ProductKindHint {
73
84
  override val id: String = pd.productId
74
85
  override val localizedTitle: String = pd.title.ifEmpty { backendName }
75
86
  override val localizedDescription: String = pd.description
87
+ override val isOneTime: Boolean = pd.productType == BillingClient.ProductType.INAPP
88
+
89
+ /** The recurring phase of a subscription's base plan: its price after any offer. */
90
+ private val basePhase: ProductDetails.PricingPhase? =
91
+ pd.subscriptionOfferDetails?.firstOrNull()?.pricingPhases?.pricingPhaseList?.lastOrNull()
92
+
76
93
  override val price: Price by lazy {
77
- val phase = pd.subscriptionOfferDetails?.firstOrNull()?.pricingPhases?.pricingPhaseList?.lastOrNull()
94
+ val phase = basePhase
78
95
  if (phase != null) {
79
96
  SimplePrice(
80
97
  formatted = phase.formattedPrice,
@@ -94,7 +111,21 @@ private class StoreProductFromPlayBilling(
94
111
  }
95
112
  }
96
113
  }
97
- override val subscriptionPeriod: SubscriptionPeriod? = null
114
+
115
+ /** The base plan's billing period; null for a one-time product. */
116
+ override val subscriptionPeriod: SubscriptionPeriod? = basePhase?.billingPeriod?.let(::billingPeriodOf)
98
117
  override val introductoryDiscount: StoreProductDiscount? = null
99
118
  override val discounts: List<StoreProductDiscount> = emptyList()
100
119
  }
120
+
121
+ /** A Play billing period in ISO 8601 ("P1W", "P1M", "P3M", "P1Y") as a [SubscriptionPeriod]. */
122
+ internal fun billingPeriodOf(iso: String): SubscriptionPeriod? {
123
+ val match = Regex("^P(\\d+)([DWMY])$").matchEntire(iso) ?: return null
124
+ val unit = when (match.groupValues[2]) {
125
+ "D" -> SubscriptionPeriod.Unit.DAY
126
+ "W" -> SubscriptionPeriod.Unit.WEEK
127
+ "M" -> SubscriptionPeriod.Unit.MONTH
128
+ else -> SubscriptionPeriod.Unit.YEAR
129
+ }
130
+ return SimpleSubscriptionPeriod(match.groupValues[1].toInt(), unit)
131
+ }
@@ -0,0 +1,21 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/purchases/ProductKindHint.kt
2
+ package com.appswissknife.purchases
3
+
4
+ /**
5
+ * What the SDK knows about a product's kind before it asks the store.
6
+ *
7
+ * Play takes a product type (SUBS or INAPP) on every product query and answers
8
+ * a query for the wrong type with nothing. The SDK's own
9
+ * [com.appswissknife.models.StoreProduct]s carry this hint so a purchase asks
10
+ * for the right type first: a Play-priced product knows its type from Play, a
11
+ * backend-priced one from the product the server describes. A product without
12
+ * the hint (one the host or the React Native bridge built from an id) is asked
13
+ * for as a subscription first, then as a one-time product.
14
+ *
15
+ * Public so the React Native bridge can label a one-time product
16
+ * `NON_SUBSCRIPTION`. A host may implement it on a product it builds itself.
17
+ */
18
+ interface ProductKindHint {
19
+ /** True for a one-time product (Play INAPP, consumable or not), false for a subscription. */
20
+ val isOneTime: Boolean
21
+ }
@@ -97,6 +97,20 @@ interface PurchasesGateway {
97
97
 
98
98
  fun logOut(onSuccess: (CustomerInfo) -> Unit, onError: (PurchasesError) -> Unit)
99
99
 
100
+ /**
101
+ * [com.appswissknife.identity.Identity.reset] or `Identity.wipe` left no
102
+ * user. Drop the explicit user id a [logIn] (or `configure(appUserID)`) set,
103
+ * so [getAppUserID] is the anonymous id again, and clear the entitlement
104
+ * cache in memory and on disk, so [getCustomerInfo] reads the anonymous
105
+ * user's entitlements instead of serving that user's. When a user was
106
+ * dropped, tell the CustomerInfo listeners the anonymous user's
107
+ * CustomerInfo, with no entitlements. Local only: no store call and no
108
+ * backend call. Mirror of iOS `SwissKnife.identityResetLocalState()`.
109
+ *
110
+ * The default does nothing, for a gateway that keeps no user of its own.
111
+ */
112
+ fun resetToAnonymous() {}
113
+
100
114
  // --- Subscriber attributes ------------------------------------------------
101
115
  //
102
116
  // Removed in Phase 3 of the RC rip-and-replace. Attributes now flow to our
@@ -0,0 +1,59 @@
1
+ <!-- packages/react-native-sdk/android/src/main/AndroidManifest.xml -->
2
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+ package="com.swissknife.purchases">
4
+ <!-- Required by Play Billing v8. -->
5
+ <uses-permission android:name="com.android.vending.BILLING" />
6
+
7
+ <!--
8
+ Mirrors packages/swiss-knife-android/src/main/AndroidManifest.xml. The SDK
9
+ is vendored into this Gradle module rather than linked as an AAR, so this
10
+ manifest has to carry what the AAR's manifest would otherwise have merged
11
+ into the host app.
12
+
13
+ dataExtractionRules excludes the SDK's persistent device-id
14
+ SharedPreferences file from cloud backup + device transfer. We deliberately
15
+ do NOT set android:allowBackup: as a library we don't want to override the
16
+ host app's global backup choice. The per-file exclusion in
17
+ res/xml/swissknife_data_extraction_rules.xml (vendored into vendor/res)
18
+ achieves the goal narrowly.
19
+
20
+ Host apps that set their own android:dataExtractionRules must add
21
+ tools:replace="android:dataExtractionRules" — same as they would have had
22
+ to with the published AAR.
23
+ -->
24
+ <!-- Runtime notification permission on API 33+ (Notifications.requestPermission). -->
25
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
26
+
27
+ <application
28
+ android:dataExtractionRules="@xml/swissknife_data_extraction_rules">
29
+ <!--
30
+ Transparent trampoline that owns the POST_NOTIFICATIONS dialog. The
31
+ vendoring script only copies the SDK's java/ and res/ trees, so the
32
+ library manifest's declaration never reaches this module: declare it
33
+ here or requestPermission throws ActivityNotFoundException.
34
+ -->
35
+ <activity
36
+ android:name="com.appswissknife.notifications.PermissionRequestActivity"
37
+ android:exported="false"
38
+ android:theme="@android:style/Theme.Translucent.NoTitleBar" />
39
+
40
+ <!-- Auto-registers the RuStoreGateway with the base SDK at process
41
+ start, the moment this add-on is on the classpath. Merely depending
42
+ on this artifact opts a build in; default builds never merge this. -->
43
+ <provider
44
+ android:name="com.appswissknife.rustore.RuStoreInitProvider"
45
+ android:authorities="${applicationId}.swissknife-rustore-init"
46
+ android:exported="false"
47
+ android:initOrder="100" />
48
+
49
+ <!-- The RuStore Pay SDK self-configures from two manifest meta-data
50
+ entries the CONSUMER provides (the existing withRuStorePay config
51
+ plugin / the Phase-4 plugin already inject these, so this add-on
52
+ does NOT declare them to avoid a duplicate-meta-data merge conflict):
53
+ <meta-data android:name="console_app_id_value" android:value="<RuStore Console app id>" />
54
+ <meta-data android:name="sdk_pay_scheme_value" android:value="<deeplink scheme>" />
55
+ The deeplink <intent-filter android:scheme="..."> that returns from
56
+ the RuStore payment UI must also be on the consumer's launcher
57
+ Activity, which forwards onNewIntent to the Pay SDK — see README. -->
58
+ </application>
59
+ </manifest>
@@ -0,0 +1,428 @@
1
+ // packages/swiss-knife-android-rustore/src/main/java/com/appswissknife/rustore/RuStoreGateway.kt
2
+ //
3
+ // RuStore implementation of the base SDK's PurchasesGateway, on the RuStore
4
+ // **Pay** SDK (`ru.rustore.sdk:pay`) — the current SDK, same generation as the
5
+ // `pay` RN wrapper the host app ships. Drives purchases, validates them
6
+ // server-side against the same Swiss Knife backend as Play/StoreKit (POST
7
+ // /api/sdk/subscriptions/validate with store="rustore"), then reads entitlements
8
+ // through the shared, backend-authoritative EntitlementsRepository.
9
+ //
10
+ // RuStore Pay self-configures from manifest meta-data (`console_app_id_value`,
11
+ // `sdk_pay_scheme_value`) that the consumer's config plugin sets — this gateway
12
+ // creates no client, it just uses RuStorePayClient.instance.
13
+ //
14
+ // Compile-verified against ru.rustore.sdk:pay:10.3.0. API notes: interactors are
15
+ // methods (getPurchaseInteractor()); `Purchase` is a sealed interface — productId
16
+ // + the typed status live on the SubscriptionPurchase/ProductPurchase subtypes;
17
+ // value classes (ProductId/PurchaseId/…) unwrap via `.value`. All RuStore sites
18
+ // are marked `// RUSTORE SDK`.
19
+ package com.appswissknife.rustore
20
+
21
+ import android.app.Activity
22
+ import android.content.Context
23
+ import com.appswissknife.StoreTransactionResult
24
+ import com.appswissknife.entitlements.EntitlementsRepository
25
+ import com.appswissknife.entitlements.SimpleCustomerInfo
26
+ import com.appswissknife.entitlements.SimpleEntitlementInfos
27
+ import com.appswissknife.identity.Identity
28
+ import com.appswissknife.models.CustomerInfo
29
+ import com.appswissknife.models.LogLevel
30
+ import com.appswissknife.models.Offerings
31
+ import com.appswissknife.models.Package
32
+ import com.appswissknife.models.PurchasesError
33
+ import com.appswissknife.models.PurchasesErrorCode
34
+ import com.appswissknife.models.StoreProduct
35
+ import com.appswissknife.models.StoreTransaction
36
+ import com.appswissknife.models.VerificationResult
37
+ import com.appswissknife.purchases.BillingHttpClient
38
+ import com.appswissknife.purchases.PriceEnrichmentProvider
39
+ import com.appswissknife.purchases.PurchasesGateway
40
+ import com.appswissknife.purchases.RetryingBillingHttpClient
41
+ import org.json.JSONObject
42
+ import java.io.IOException
43
+ import java.util.Collections
44
+ import java.util.Date
45
+ import java.util.UUID
46
+ import java.util.concurrent.ExecutorService
47
+ import java.util.concurrent.Executors
48
+ import java.util.concurrent.atomic.AtomicBoolean
49
+ // RUSTORE SDK — Pay
50
+ import ru.rustore.sdk.pay.RuStorePayClient
51
+ import ru.rustore.sdk.pay.model.PreferredPurchaseType
52
+ import ru.rustore.sdk.pay.model.AppUserId
53
+ import ru.rustore.sdk.pay.model.ProductId
54
+ import ru.rustore.sdk.pay.model.ProductPurchase
55
+ import ru.rustore.sdk.pay.model.ProductPurchaseParams
56
+ import ru.rustore.sdk.pay.model.ProductPurchaseStatus
57
+ import ru.rustore.sdk.pay.model.SubscriptionPurchase
58
+ import ru.rustore.sdk.pay.model.SubscriptionPurchaseStatus
59
+
60
+ class RuStoreGateway(
61
+ // Validate goes through the base SDK's unified backend transport (the one the
62
+ // Play gateway uses), retrying 5xx / 429 / transport failures. It used to open
63
+ // its own HttpURLConnection with a 15 s timeout and no retry, so one blip
64
+ // failed a purchase the user had already paid for.
65
+ private val httpClient: BillingHttpClient = RetryingBillingHttpClient(),
66
+ ) : PurchasesGateway {
67
+
68
+ @Volatile private var entitlementsRepo: EntitlementsRepository? = null
69
+ @Volatile private var serverUrl: String = ""
70
+ @Volatile private var apiKey: String = ""
71
+ @Volatile private var packageName: String = ""
72
+ @Volatile private var explicitAppUserId: String? = null
73
+
74
+ /**
75
+ * Last-resort anonymous subject, used ONLY when [Identity] has no application
76
+ * context yet (a call before `SwissKnife.configure`). Minted per process and
77
+ * never persisted, which is why it must not be the normal path: see
78
+ * [getAppUserID]. Unified `$SKAnonymousID:` prefix across iOS / Android / RN.
79
+ */
80
+ @Volatile private var fallbackAnonymousAppUserId: String = newFallbackAnonymousId()
81
+
82
+ private val configured = AtomicBoolean(false)
83
+ private val executor: ExecutorService =
84
+ Executors.newSingleThreadExecutor { r ->
85
+ Thread(r, "swissknife-rustore").apply { isDaemon = true }
86
+ }
87
+ private val customerInfoListeners =
88
+ Collections.synchronizedSet(mutableSetOf<(CustomerInfo) -> Unit>())
89
+
90
+ // RUSTORE SDK — the Pay client is a singleton self-configured from manifest meta-data.
91
+ private val purchaseInteractor get() = RuStorePayClient.instance.getPurchaseInteractor()
92
+
93
+ override fun configure(
94
+ context: Context,
95
+ apiKey: String,
96
+ appUserID: String?,
97
+ proxyURL: String?,
98
+ useAmazon: Boolean,
99
+ ) {
100
+ if (!configured.compareAndSet(false, true)) return
101
+ val ctx = context.applicationContext
102
+ this.serverUrl = proxyURL?.trimEnd('/').orEmpty()
103
+ this.apiKey = apiKey
104
+ this.explicitAppUserId = appUserID
105
+ this.packageName = ctx.packageName
106
+
107
+ entitlementsRepo = EntitlementsRepository.get(
108
+ context = ctx,
109
+ serverUrl = serverUrl,
110
+ apiKey = apiKey,
111
+ userIdProvider = { getAppUserID() },
112
+ )
113
+ }
114
+
115
+ override fun isConfigured(): Boolean = configured.get()
116
+
117
+ /**
118
+ * The subject purchases and entitlements are keyed on. Same rule as the Play
119
+ * gateway (BillingClientGateway.getAppUserID) and iOS `backendSubjectId()`: an
120
+ * explicit id wins, otherwise the [Identity] snapshot.
121
+ *
122
+ * The anonymous subject used to be a UUID minted per process. It was sent as
123
+ * `user_id` on validate and passed to RuStore as the purchase's AppUserId,
124
+ * while `/api/sdk/users/identify` and the entitlements lookup after a restart
125
+ * used `Identity.current().anonymousId` (the persisted DeviceID). A purchase
126
+ * made before login was therefore keyed to an id that died with the process:
127
+ * after a restart the entitlement was not found and never merged into the
128
+ * account.
129
+ */
130
+ override fun getAppUserID(): String {
131
+ explicitAppUserId?.takeIf { it.isNotEmpty() }?.let { return it }
132
+ val snapshot = Identity.current()
133
+ val fromIdentity = snapshot.userId ?: snapshot.anonymousId
134
+ return fromIdentity.takeIf { it.isNotEmpty() } ?: fallbackAnonymousAppUserId
135
+ }
136
+
137
+ /** Anonymous iff neither this gateway nor [Identity] holds an explicit user. */
138
+ override fun isAnonymous(): Boolean =
139
+ explicitAppUserId == null && Identity.current().userId == null
140
+
141
+ override fun priceEnrichmentProvider(): PriceEnrichmentProvider =
142
+ RuStorePriceEnrichmentProvider()
143
+
144
+ override fun getCustomerInfo(
145
+ onSuccess: (CustomerInfo) -> Unit,
146
+ onError: (PurchasesError) -> Unit,
147
+ ) {
148
+ val repo = entitlementsRepo
149
+ val cached = repo?.current()
150
+ if (cached != null && repo.isFresh()) {
151
+ onSuccess(cached); return
152
+ }
153
+ executor.execute {
154
+ runCatching { repo?.refresh(emptySet()) ?: emptyCustomerInfo() }
155
+ .onSuccess(onSuccess)
156
+ .onFailure { cached?.let(onSuccess) ?: onError(toPurchasesError(it)) }
157
+ }
158
+ }
159
+
160
+ override fun getOfferings(
161
+ onSuccess: (Offerings) -> Unit,
162
+ onError: (PurchasesError) -> Unit,
163
+ ) {
164
+ // Offerings come from the backend via OfferingsRepository (wired by
165
+ // SwissKnife.configure using this gateway's priceEnrichmentProvider).
166
+ onError(
167
+ PurchasesError.Unknown(
168
+ "RuStoreGateway does not own offerings; use getOfferingsForPaywall"
169
+ )
170
+ )
171
+ }
172
+
173
+ override fun purchasePackage(
174
+ activity: Activity,
175
+ packageToPurchase: Package,
176
+ onSuccess: (StoreTransactionResult) -> Unit,
177
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
178
+ ) {
179
+ purchaseStoreProduct(activity, packageToPurchase.product, onSuccess, onError)
180
+ }
181
+
182
+ override fun purchaseStoreProduct(
183
+ activity: Activity,
184
+ product: StoreProduct,
185
+ onSuccess: (StoreTransactionResult) -> Unit,
186
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
187
+ ) {
188
+ // RUSTORE SDK — launch the Pay flow. RuStore returns from its payment UI via
189
+ // the deeplink scheme (the consumer Activity forwards onNewIntent to the Pay
190
+ // SDK's IntentInteractor — see README), so no Activity is passed here.
191
+ purchaseInteractor.purchase(
192
+ params = ProductPurchaseParams(productId = ProductId(product.id), appUserId = AppUserId(getAppUserID())),
193
+ preferredPurchaseType = PreferredPurchaseType.ONE_STEP,
194
+ )
195
+ .addOnSuccessListener { result ->
196
+ // ProductPurchaseResult: productId, purchaseId, invoiceId, orderId? (value classes).
197
+ finishSuccessfulPurchase(
198
+ productId = result.productId.value,
199
+ purchaseId = result.purchaseId.value,
200
+ invoiceId = result.invoiceId.value,
201
+ transactionId = (result.orderId?.value ?: result.invoiceId.value),
202
+ onSuccess = onSuccess,
203
+ onError = onError,
204
+ )
205
+ }
206
+ .addOnFailureListener { t ->
207
+ onError(toPurchasesError(t), isUserCancellation(t))
208
+ }
209
+ }
210
+
211
+ // Internal (not private) so the module's JVM tests can drive the
212
+ // validate -> refresh -> callback path without the RuStore Pay SDK.
213
+ internal fun finishSuccessfulPurchase(
214
+ productId: String,
215
+ purchaseId: String,
216
+ invoiceId: String,
217
+ transactionId: String,
218
+ onSuccess: (StoreTransactionResult) -> Unit,
219
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
220
+ ) {
221
+ executor.execute {
222
+ try {
223
+ // 1) Server-validate FIRST (backend is authoritative for entitlements).
224
+ validatePurchaseWithBackend(productId, purchaseId, invoiceId)
225
+ // 2) Refresh entitlements from the backend.
226
+ val info = runCatching { entitlementsRepo?.refresh(emptySet()) }.getOrNull()
227
+ ?: entitlementsRepo?.current()
228
+ ?: emptyCustomerInfo()
229
+ // NOTE: one-step Pay purchases auto-complete — no confirm step. (Two-step
230
+ // would require purchaseInteractor.confirmTwoStepPurchase(PurchaseId(...)).)
231
+ onSuccess(
232
+ StoreTransactionResult(
233
+ transaction = storeTransaction(productId, transactionId, purchaseId),
234
+ customerInfo = info,
235
+ )
236
+ )
237
+ } catch (e: Exception) {
238
+ onError(toPurchasesError(e), false)
239
+ }
240
+ }
241
+ }
242
+
243
+ override fun restorePurchases(
244
+ onSuccess: (CustomerInfo) -> Unit,
245
+ onError: (PurchasesError) -> Unit,
246
+ ) {
247
+ // RUSTORE SDK — getPurchases() resolves to a List<Purchase> directly.
248
+ purchaseInteractor.getPurchases()
249
+ .addOnSuccessListener { purchases ->
250
+ executor.execute {
251
+ val errors = mutableListOf<Throwable>()
252
+ for (p in purchases) {
253
+ // Purchase is a sealed interface; productId + the typed status live
254
+ // on the subtypes. Re-assert still-relevant purchases (subscriptions:
255
+ // ACTIVE; one-time products: PAID/CONFIRMED).
256
+ val productId: String? = when (p) {
257
+ is SubscriptionPurchase ->
258
+ if (p.status == SubscriptionPurchaseStatus.ACTIVE) p.productId.value else null
259
+ is ProductPurchase ->
260
+ if (p.status == ProductPurchaseStatus.PAID ||
261
+ p.status == ProductPurchaseStatus.CONFIRMED
262
+ ) p.productId.value else null
263
+ else -> null
264
+ }
265
+ if (productId != null) {
266
+ runCatching {
267
+ validatePurchaseWithBackend(productId, p.purchaseId.value, p.invoiceId.value)
268
+ }.onFailure { errors.add(it) }
269
+ }
270
+ }
271
+ val info = try {
272
+ entitlementsRepo?.refresh(emptySet()) ?: emptyCustomerInfo()
273
+ } catch (e: Exception) {
274
+ entitlementsRepo?.current() ?: emptyCustomerInfo()
275
+ }
276
+ if (errors.isNotEmpty() && purchases.isNotEmpty()) {
277
+ onError(
278
+ PurchasesError.NetworkError(
279
+ "restore: ${errors.size}/${purchases.size} validate calls failed"
280
+ )
281
+ )
282
+ } else {
283
+ onSuccess(info)
284
+ }
285
+ }
286
+ }
287
+ .addOnFailureListener { onError(toPurchasesError(it)) }
288
+ }
289
+
290
+ override fun logIn(
291
+ appUserID: String,
292
+ onSuccess: (CustomerInfo, created: Boolean) -> Unit,
293
+ onError: (PurchasesError) -> Unit,
294
+ ) {
295
+ explicitAppUserId = appUserID
296
+ val repo = entitlementsRepo
297
+ repo?.invalidate()
298
+ executor.execute {
299
+ // The new user's entitlements. A read that fails does not fail the logIn
300
+ // (the identify call already went through): it answers with no
301
+ // entitlements, and the next getCustomerInfo() reads them again. Same as
302
+ // the Play gateway.
303
+ onSuccess(runCatching { repo?.refresh(emptySet()) }.getOrNull() ?: emptyCustomerInfo(), false)
304
+ }
305
+ }
306
+
307
+ override fun logOut(
308
+ onSuccess: (CustomerInfo) -> Unit,
309
+ onError: (PurchasesError) -> Unit,
310
+ ) {
311
+ if (explicitAppUserId == null) {
312
+ onError(PurchasesError(PurchasesErrorCode.LogOutAnonymousUserError, "Already anonymous"))
313
+ return
314
+ }
315
+ explicitAppUserId = null
316
+ // Rotates the pre-configure fallback only. The post-logout subject is the
317
+ // Identity anonymous id, which survives logout (same as the Play gateway
318
+ // and iOS).
319
+ fallbackAnonymousAppUserId = newFallbackAnonymousId()
320
+ entitlementsRepo?.invalidate()
321
+ onSuccess(emptyCustomerInfo())
322
+ }
323
+
324
+ /**
325
+ * Back to the anonymous user after `Identity.reset()` / `Identity.wipe()`,
326
+ * as the Play gateway does (see [PurchasesGateway.resetToAnonymous]).
327
+ * RuStore is not contacted.
328
+ */
329
+ override fun resetToAnonymous() {
330
+ val droppedUser = explicitAppUserId
331
+ explicitAppUserId = null
332
+ fallbackAnonymousAppUserId = newFallbackAnonymousId()
333
+ entitlementsRepo?.invalidate()
334
+ if (droppedUser == null) return
335
+ // Taken while the subject is the anonymous id; announced on the executor,
336
+ // after any entitlement read already running there.
337
+ val anonymous = emptyCustomerInfo()
338
+ executor.execute {
339
+ synchronized(customerInfoListeners) { customerInfoListeners.toList() }
340
+ .forEach { runCatching { it(anonymous) } }
341
+ }
342
+ }
343
+
344
+ override fun setLogLevel(level: LogLevel) {
345
+ // RuStore Pay has no runtime log-level knob. No-op for parity.
346
+ }
347
+
348
+ override fun addCustomerInfoListener(listener: (CustomerInfo) -> Unit) {
349
+ customerInfoListeners.add(listener)
350
+ entitlementsRepo?.addListener(listener)
351
+ }
352
+
353
+ override fun removeCustomerInfoListener(listener: (CustomerInfo) -> Unit) {
354
+ customerInfoListeners.remove(listener)
355
+ entitlementsRepo?.removeListener(listener)
356
+ }
357
+
358
+ // --- Backend validation ------------------------------------------------
359
+
360
+ /**
361
+ * POST the RuStore purchase to the shared validator. Body matches the
362
+ * /api/sdk/subscriptions/validate contract ({platform, receipt_data, user_id});
363
+ * receipt_data is "packageName:productId:purchaseId", which
364
+ * the backend checks with the RuStore subscription V5 or invoice V2 API.
365
+ * The backend also checks that the RuStore purchase's AppUserId equals
366
+ * user_id, which is why both come from [getAppUserID].
367
+ */
368
+ @Throws(IOException::class)
369
+ private fun validatePurchaseWithBackend(productId: String, purchaseId: String, invoiceId: String) {
370
+ if (serverUrl.isEmpty()) throw IOException("RuStore: no proxyURL configured for validation")
371
+ val body = JSONObject().apply {
372
+ put("platform", "rustore")
373
+ put("receipt_data", "$packageName:$productId:$purchaseId")
374
+ put("user_id", getAppUserID())
375
+ put("invoice_id", invoiceId)
376
+ }.toString()
377
+ httpClient.post(
378
+ url = "$serverUrl/api/sdk/subscriptions/validate",
379
+ body = body,
380
+ headers = mapOf(
381
+ "X-API-Key" to apiKey,
382
+ "Content-Type" to "application/json",
383
+ ),
384
+ )
385
+ }
386
+
387
+ private fun storeTransaction(
388
+ productId: String,
389
+ transactionId: String,
390
+ purchaseId: String,
391
+ ): StoreTransaction = object : StoreTransaction {
392
+ override val productIdentifier: String = productId
393
+ override val transactionIdentifier: String = transactionId
394
+ override val purchaseDate: Date = Date()
395
+ override val purchaseToken: String = purchaseId
396
+ override val quantity: Int = 1
397
+ }
398
+
399
+ private fun emptyCustomerInfo(): CustomerInfo = SimpleCustomerInfo(
400
+ entitlements = SimpleEntitlementInfos(emptyMap(), emptyMap(), VerificationResult.NOT_REQUESTED),
401
+ originalAppUserId = getAppUserID(),
402
+ firstSeen = Date(),
403
+ originalPurchaseDate = null,
404
+ latestExpirationDate = null,
405
+ allPurchaseDates = emptyMap(),
406
+ activeSubscriptions = emptySet(),
407
+ allPurchasedProductIds = emptySet(),
408
+ managementURL = null,
409
+ requestDate = Date(),
410
+ )
411
+
412
+ private companion object {
413
+ fun newFallbackAnonymousId(): String =
414
+ "\$SKAnonymousID:${UUID.randomUUID().toString().replace("-", "")}"
415
+
416
+ // RUSTORE SDK — cancellation is delivered to the failure listener as an
417
+ // exception (no sealed result case). Heuristic until the exact type is known.
418
+ fun isUserCancellation(t: Throwable): Boolean =
419
+ t is ru.rustore.sdk.pay.model.RuStorePaymentException.ProductPurchaseCancelled
420
+
421
+ fun toPurchasesError(t: Throwable): PurchasesError = when {
422
+ t is PurchasesError -> t
423
+ isUserCancellation(t) -> PurchasesError.PurchaseCancelled(t.message ?: "Cancelled")
424
+ t is IOException -> PurchasesError.NetworkError(t.message ?: "Network error", t)
425
+ else -> PurchasesError.Unknown(t.message ?: "Unknown error", t)
426
+ }
427
+ }
428
+ }