@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
@@ -1,36 +1,37 @@
1
1
  // packages/swiss-knife-android/src/main/java/com/appswissknife/offerings/OfferingsRepository.kt
2
2
  //
3
- // Phase 6 commit 4 — fetch offerings from the backend and enrich with live
4
- // Play Billing prices.
3
+ // Offerings from the backend, priced live by the store.
5
4
  //
6
- // Backend contract: we use the existing /api/sdk/paywalls/show endpoint
7
- // (keyed by paywall_slug) as the source of truth for which products exist
8
- // in the user's current paywall variant. Output shape:
9
- // { paywall_id, slug, render_url, config, products_with_prices: [{
10
- // id, product_id, name, platform, duration_days, price, position,
11
- // badge_text, is_highlighted }], experiment_id, variant_id }
5
+ // Two reads, the same two iOS has:
12
6
  //
13
- // Why paywalls/show and not a brand-new /api/sdk/offerings endpoint:
14
- // - paywalls/show is the only endpoint today that returns the product set
15
- // in a per-user, experiment-resolved shape. Building a separate
16
- // /api/sdk/offerings would duplicate the variant-resolution logic that
17
- // paywalls/show already owns.
18
- // - The host app already knows the paywall slug it wants to render (paywall
19
- // selection is a product decision, not an SDK auto-resolution).
20
- // - Phase 5 (iOS) hasn't added a /api/sdk/offerings either as of branch
21
- // creation, so contracts stay aligned across platforms.
7
+ // - current(): the project's offerings, from `GET /api/sdk/offerings`. Every
8
+ // active paywall is an Offering whose packages are its products, and the
9
+ // server names the current one. This is what `SwissKnife.getOfferings()`
10
+ // (and React Native's `Purchases.getOfferings()`) returns, with the same
11
+ // contract as iOS `OfferingsService.current()`. Shape:
12
+ // { current_offering_id, offerings: [{ identifier, server_description,
13
+ // metadata, packages: [{ identifier, package_type, product_identifier,
14
+ // platform, duration_days, price, name }] }] }
22
15
  //
23
- // Price enrichment: paywalls/show returns the backend's last-known price
24
- // (set in the dashboard). For Play purchases the live price comes from
25
- // queryProductDetailsAsync at purchase time. We enrich each product with the
26
- // Play Billing ProductDetails when available so the dashboard's price drift
27
- // vs Play store is reflected in the UI.
16
+ // - current(paywallSlug, userId): one paywall, from `/api/sdk/paywalls/show`,
17
+ // with the variant an experiment assigned this user. Shape:
18
+ // { paywall_id, slug, render_url, config, products_with_prices: [{
19
+ // id, product_id, name, platform, duration_days, price, position,
20
+ // badge_text, is_highlighted }], experiment_id, variant_id }
28
21
  //
29
- // Cache: 1-hour in-memory cache. paywalls/show is keyed by user (assignment
30
- // is sticky) so the cache key includes (paywallSlug, userId).
22
+ // Both keep only the active store's products (`platform`), and price each one
23
+ // through the store's PriceEnrichmentProvider (Play or RuStore). A product the
24
+ // store cannot price (offline, not uploaded yet) keeps the dashboard price.
25
+ //
26
+ // Cache: 1 hour in memory. The catalogue is the same for every user; a
27
+ // paywall is keyed by (paywallSlug, userId) because experiment assignment is
28
+ // sticky per user. An answer the store priced none of (Play not connected,
29
+ // or its queries failed) is kept for a minute only, so the store's prices
30
+ // replace the dashboard's as soon as the store answers.
31
31
 
32
32
  package com.appswissknife.offerings
33
33
 
34
+ import android.util.Log
34
35
  import com.appswissknife.models.Offering
35
36
  import com.appswissknife.models.Offerings
36
37
  import com.appswissknife.models.Package
@@ -41,6 +42,9 @@ import com.appswissknife.models.StoreProductDiscount
41
42
  import com.appswissknife.models.SubscriptionPeriod
42
43
  import com.appswissknife.purchases.BillingHttpClient
43
44
  import com.appswissknife.purchases.PriceEnrichmentProvider
45
+ import com.appswissknife.purchases.ProductKindHint
46
+ import org.json.JSONArray
47
+ import org.json.JSONException
44
48
  import org.json.JSONObject
45
49
  import java.io.IOException
46
50
  import java.util.concurrent.ConcurrentHashMap
@@ -57,10 +61,43 @@ class OfferingsRepository(
57
61
  private val clock: () -> Long = System::currentTimeMillis,
58
62
  ) {
59
63
 
60
- private data class CacheEntry(val offerings: Offerings, val fetchedAt: Long)
64
+ private data class CacheEntry(val offerings: Offerings, val fetchedAt: Long, val ttlMillis: Long) {
65
+ fun isFreshAt(now: Long): Boolean = now - fetchedAt < ttlMillis
66
+ }
61
67
 
62
68
  private val cache = ConcurrentHashMap<String, CacheEntry>()
63
69
 
70
+ /** Guards [catalogCache]; held across the fetch so concurrent callers share one. */
71
+ private val catalogLock = Any()
72
+ @Volatile private var catalogCache: CacheEntry? = null
73
+
74
+ private val storeTags: Set<String> = platformTags.map { it.lowercase() }.toSet()
75
+
76
+ /**
77
+ * The project's offerings: every active paywall as an [Offering], from
78
+ * `GET /api/sdk/offerings`, each package priced by the store. Same contract
79
+ * as iOS `OfferingsService.current()`:
80
+ *
81
+ * - [Offerings.current] is the offering the server marks current
82
+ * (`current_offering_id`: the paywall flagged current, else the oldest
83
+ * active one), or the only offering when the server marks none;
84
+ * - each offering keeps only this store's packages, in the server's order;
85
+ * - a package's identifier and type are the server's.
86
+ *
87
+ * Served from a 1 hour in-memory cache (a minute when the store priced
88
+ * nothing); callers that arrive during a fetch wait for it instead of
89
+ * starting another.
90
+ */
91
+ @Throws(IOException::class)
92
+ fun current(): Offerings {
93
+ synchronized(catalogLock) {
94
+ catalogCache?.takeIf { it.isFreshAt(clock()) }?.let { return it.offerings }
95
+ val entry = parseCatalog(fetchJson("/api/sdk/offerings", emptyList()))
96
+ catalogCache = entry
97
+ return entry.offerings
98
+ }
99
+ }
100
+
64
101
  /**
65
102
  * Fetch the offerings for [paywallSlug] for the given [userId]. Goes to
66
103
  * /api/sdk/paywalls/show, optionally enriches each product with live
@@ -70,59 +107,101 @@ class OfferingsRepository(
70
107
  @Throws(IOException::class)
71
108
  fun current(paywallSlug: String, userId: String): Offerings {
72
109
  val key = "$paywallSlug:$userId"
73
- cache[key]?.takeIf { clock() - it.fetchedAt < CACHE_TTL_MILLIS }?.let { return it.offerings }
74
- val raw = fetchPaywallsShow(paywallSlug, userId)
75
- val parsed = parseAndEnrich(raw, paywallSlug)
76
- cache[key] = CacheEntry(parsed, clock())
77
- return parsed
110
+ cache[key]?.takeIf { it.isFreshAt(clock()) }?.let { return it.offerings }
111
+ val raw = fetchJson(
112
+ "/api/sdk/paywalls/show",
113
+ listOf("paywall_slug" to paywallSlug, "user_id" to userId),
114
+ )
115
+ val entry = parseAndEnrich(raw, paywallSlug)
116
+ cache[key] = entry
117
+ return entry.offerings
78
118
  }
79
119
 
80
120
  /** Invalidate the cache - useful on logIn/logOut (user assignment changes). */
81
121
  fun invalidate() {
82
122
  cache.clear()
123
+ catalogCache = null
83
124
  }
84
125
 
85
126
  // --- Internals ---------------------------------------------------------
86
127
 
128
+ /**
129
+ * GET [path] through the unified BackendHttpClient transport, which stamps
130
+ * the `X-API-Key` header the `withApiKeyAuth` routes read. A non-2xx answer
131
+ * or a body that is not a JSON object is an [IOException].
132
+ */
87
133
  @Throws(IOException::class)
88
- private fun fetchPaywallsShow(paywallSlug: String, userId: String): JSONObject {
89
- // Round-D: routed through the unified BackendHttpClient transport.
90
- // The pre-Round-D path issued the GET directly and (incorrectly) sent
91
- // `Authorization: Bearer ...` — the backend `paywalls/show` route
92
- // uses `withApiKeyAuth` (X-API-Key). simpleBackendGet stamps the
93
- // right header.
134
+ private fun fetchJson(path: String, query: List<Pair<String, String>>): JSONObject {
94
135
  val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
95
- val (_, text) = client.simpleGet(
96
- path = "/api/sdk/paywalls/show",
97
- query = listOf(
98
- "paywall_slug" to paywallSlug,
99
- "user_id" to userId,
100
- ),
101
- )
102
- return JSONObject(text)
136
+ val (_, text) = client.simpleGet(path = path, query = query)
137
+ return try {
138
+ JSONObject(text)
139
+ } catch (e: JSONException) {
140
+ throw IOException("$path: malformed response", e)
141
+ }
142
+ }
143
+
144
+ private fun parseCatalog(raw: JSONObject): CacheEntry {
145
+ val offerings = raw.optJSONArray("offerings") ?: JSONArray()
146
+ val parsed = mutableListOf<CatalogOffering>()
147
+ for (i in 0 until offerings.length()) {
148
+ val o = offerings.optJSONObject(i) ?: continue
149
+ val identifier = o.optString("identifier")
150
+ if (identifier.isEmpty()) continue
151
+ val packages = o.optJSONArray("packages") ?: JSONArray()
152
+ val storePackages = (0 until packages.length())
153
+ .mapNotNull { packages.optJSONObject(it) }
154
+ .map { p ->
155
+ CatalogPackage(
156
+ identifier = p.stringOrNull("identifier"),
157
+ packageType = p.stringOrNull("package_type"),
158
+ product = backendProduct(p, idKey = "product_identifier"),
159
+ )
160
+ }
161
+ .filter { it.product.productId.isNotEmpty() && it.product.isForThisStore() }
162
+ parsed.add(
163
+ CatalogOffering(
164
+ identifier = identifier,
165
+ description = o.stringOrNull("server_description") ?: identifier,
166
+ metadata = o.optJSONObject("metadata").toMap(),
167
+ packages = storePackages,
168
+ )
169
+ )
170
+ }
171
+ val storeProducts = parsed.flatMap { o -> o.packages.map { it.product } }
172
+ val priced = priceByStore(storeProducts)
173
+ val all = LinkedHashMap<String, Offering>()
174
+ for (o in parsed) {
175
+ all[o.identifier] = SimpleOffering(
176
+ identifier = o.identifier,
177
+ serverDescription = o.description,
178
+ metadata = o.metadata,
179
+ availablePackages = o.packages.map { p ->
180
+ SimplePackage(
181
+ identifier = p.identifier ?: p.product.productId,
182
+ packageType = p.packageType?.let(::packageTypeOf) ?: p.product.durationDays.toPackageType(),
183
+ product = priced[p.product.productId] ?: StoreProductFromBackend(p.product),
184
+ offeringIdentifier = o.identifier,
185
+ )
186
+ },
187
+ )
188
+ }
189
+ val current = raw.stringOrNull("current_offering_id")?.let { all[it] } ?: all.values.singleOrNull()
190
+ return cacheEntry(SimpleOfferings(all = all, current = current), storeProducts, priced)
103
191
  }
104
192
 
105
- private fun parseAndEnrich(raw: JSONObject, paywallSlug: String): Offerings {
106
- val productsJson = raw.optJSONArray("products_with_prices") ?: org.json.JSONArray()
193
+ private fun parseAndEnrich(raw: JSONObject, paywallSlug: String): CacheEntry {
194
+ val productsJson = raw.optJSONArray("products_with_prices") ?: JSONArray()
107
195
  val backendProducts = mutableListOf<BackendProduct>()
108
196
  for (i in 0 until productsJson.length()) {
109
197
  val o = productsJson.optJSONObject(i) ?: continue
110
- backendProducts.add(
111
- BackendProduct(
112
- productId = o.optString("product_id"),
113
- name = o.optString("name"),
114
- platform = o.optString("platform"),
115
- durationDays = o.optInt("duration_days"),
116
- backendPrice = o.optDouble("price", 0.0),
117
- )
118
- )
198
+ backendProducts.add(backendProduct(o, idKey = "product_id"))
119
199
  }
120
200
  // Filter to the active store's products (Play: play/android; RuStore: rustore).
121
- val tagsLower = platformTags.map { it.lowercase() }.toSet()
122
- val storeProducts = backendProducts.filter { it.platform.lowercase() in tagsLower }
201
+ val storeProducts = backendProducts.filter { it.isForThisStore() }
123
202
  // Enrich with live store prices; ids the store can't resolve fall back to
124
203
  // the backend-priced product.
125
- val enriched = priceProvider?.enrich(storeProducts.associate { it.productId to it.name }) ?: emptyMap()
204
+ val enriched = priceByStore(storeProducts)
126
205
  val packages = storeProducts.map { bp ->
127
206
  val storeProduct = enriched[bp.productId] ?: StoreProductFromBackend(bp)
128
207
  SimplePackage(
@@ -143,12 +222,70 @@ class OfferingsRepository(
143
222
  ),
144
223
  availablePackages = packages,
145
224
  )
146
- return SimpleOfferings(
147
- all = mapOf(paywallSlug to offering),
148
- current = offering,
225
+ return cacheEntry(
226
+ SimpleOfferings(all = mapOf(paywallSlug to offering), current = offering),
227
+ storeProducts,
228
+ enriched,
229
+ )
230
+ }
231
+
232
+ /**
233
+ * [offerings] as fetched now, kept for an hour, or for a minute when the
234
+ * store priced none of its [products] (dashboard prices only): Play not
235
+ * connected yet, or its queries failed.
236
+ */
237
+ private fun cacheEntry(
238
+ offerings: Offerings,
239
+ products: List<BackendProduct>,
240
+ priced: Map<String, StoreProduct>,
241
+ ): CacheEntry {
242
+ val storePricedNothing = priceProvider != null && products.isNotEmpty() && priced.isEmpty()
243
+ return CacheEntry(
244
+ offerings,
245
+ fetchedAt = clock(),
246
+ ttlMillis = if (storePricedNothing) UNPRICED_CACHE_TTL_MILLIS else CACHE_TTL_MILLIS,
149
247
  )
150
248
  }
151
249
 
250
+ private fun BackendProduct.isForThisStore(): Boolean = platform.lowercase() in storeTags
251
+
252
+ /**
253
+ * Live store prices for [products], keyed by product id. A store failure
254
+ * leaves every product on its dashboard price rather than failing the read.
255
+ */
256
+ private fun priceByStore(products: List<BackendProduct>): Map<String, StoreProduct> {
257
+ val provider = priceProvider ?: return emptyMap()
258
+ if (products.isEmpty()) return emptyMap()
259
+ return try {
260
+ provider.enrich(products.associate { it.productId to it.name })
261
+ } catch (e: RuntimeException) {
262
+ Log.w(TAG, "store price lookup failed; using dashboard prices", e)
263
+ emptyMap()
264
+ }
265
+ }
266
+
267
+ private fun backendProduct(o: JSONObject, idKey: String) = BackendProduct(
268
+ productId = o.optString(idKey),
269
+ name = o.optString("name"),
270
+ platform = o.optString("platform"),
271
+ durationDays = o.optInt("duration_days"),
272
+ backendPrice = o.optDouble("price", 0.0),
273
+ productType = o.stringOrNull("product_type"),
274
+ )
275
+
276
+ /** The server's `package_type` (see the offerings route); iOS maps the same strings. */
277
+ private fun packageTypeOf(raw: String): PackageType = when (raw) {
278
+ "monthly" -> PackageType.MONTHLY
279
+ "annual" -> PackageType.ANNUAL
280
+ "weekly" -> PackageType.WEEKLY
281
+ "lifetime" -> PackageType.LIFETIME
282
+ "six_month" -> PackageType.SIX_MONTH
283
+ "three_month" -> PackageType.THREE_MONTH
284
+ "two_month" -> PackageType.TWO_MONTH
285
+ "custom" -> PackageType.CUSTOM
286
+ else -> PackageType.UNKNOWN
287
+ }
288
+
152
289
  private fun Int.toPackageType(): PackageType = when (this) {
153
290
  in 0..0 -> PackageType.LIFETIME
154
291
  in 1..7 -> PackageType.WEEKLY
@@ -159,11 +296,47 @@ class OfferingsRepository(
159
296
  else -> PackageType.UNKNOWN
160
297
  }
161
298
 
299
+ private data class CatalogOffering(
300
+ val identifier: String,
301
+ val description: String,
302
+ val metadata: Map<String, Any?>,
303
+ val packages: List<CatalogPackage>,
304
+ )
305
+
306
+ private data class CatalogPackage(
307
+ val identifier: String?,
308
+ val packageType: String?,
309
+ val product: BackendProduct,
310
+ )
311
+
162
312
  companion object {
313
+ private const val TAG = "SwissKnife.Offerings"
163
314
  private const val CACHE_TTL_MILLIS: Long = 60L * 60 * 1000 // 1h
315
+ private const val UNPRICED_CACHE_TTL_MILLIS: Long = 60L * 1000 // 1 min
164
316
  }
165
317
  }
166
318
 
319
+ // --- JSON helpers ------------------------------------------------------------
320
+
321
+ /** A string field, or null when it is absent, JSON null or empty. */
322
+ private fun JSONObject.stringOrNull(key: String): String? =
323
+ if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
324
+
325
+ /** A JSON object as plain Kotlin values: nested objects as maps, arrays as lists. */
326
+ private fun JSONObject?.toMap(): Map<String, Any?> {
327
+ if (this == null) return emptyMap()
328
+ val out = LinkedHashMap<String, Any?>()
329
+ for (key in keys()) out[key] = opt(key).toPlain()
330
+ return out
331
+ }
332
+
333
+ private fun Any?.toPlain(): Any? = when (this) {
334
+ null, JSONObject.NULL -> null
335
+ is JSONObject -> toMap()
336
+ is JSONArray -> (0 until length()).map { opt(it).toPlain() }
337
+ else -> this
338
+ }
339
+
167
340
  // --- Backend DTO -----------------------------------------------------------
168
341
 
169
342
  private data class BackendProduct(
@@ -172,7 +345,17 @@ private data class BackendProduct(
172
345
  val platform: String,
173
346
  val durationDays: Int,
174
347
  val backendPrice: Double,
175
- )
348
+ /** The server's product type when it sends one (auto_renewable, non_renewing, consumable, non_consumable). */
349
+ val productType: String?,
350
+ ) {
351
+ /**
352
+ * One-time (Play INAPP) per what the server describes: a consumable or
353
+ * non-consumable, or, when the server sends no product type, a zero-day
354
+ * duration, which is how the server and iOS mark a lifetime unlock.
355
+ */
356
+ val isOneTime: Boolean
357
+ get() = productType?.let { it == "consumable" || it == "non_consumable" } ?: (durationDays == 0)
358
+ }
176
359
 
177
360
  // --- Public model impls ----------------------------------------------------
178
361
 
@@ -198,7 +381,7 @@ data class SimplePackage(
198
381
  /** StoreProduct sourced from a backend BackendProduct - used when
199
382
  * queryProductDetailsAsync hasn't returned anything for this id (offline /
200
383
  * not yet uploaded to Play). */
201
- private class StoreProductFromBackend(private val bp: BackendProduct) : StoreProduct {
384
+ private class StoreProductFromBackend(private val bp: BackendProduct) : StoreProduct, ProductKindHint {
202
385
  override val id: String = bp.productId
203
386
  override val localizedTitle: String = bp.name
204
387
  override val localizedDescription: String = bp.name
@@ -207,13 +390,32 @@ private class StoreProductFromBackend(private val bp: BackendProduct) : StorePro
207
390
  currencyCode = "USD",
208
391
  amountMicros = (bp.backendPrice * 1_000_000).toLong(),
209
392
  )
210
- override val subscriptionPeriod: SubscriptionPeriod? = null
393
+ override val isOneTime: Boolean = bp.isOneTime
394
+ /** From the dashboard duration, as iOS's backend-priced product; null for a one-time product. */
395
+ override val subscriptionPeriod: SubscriptionPeriod? =
396
+ if (bp.isOneTime) null else subscriptionPeriodFromDays(bp.durationDays)
211
397
  override val introductoryDiscount: StoreProductDiscount? = null
212
398
  override val discounts: List<StoreProductDiscount> = emptyList()
213
399
  }
214
400
 
401
+ /** iOS `OfferingsService.subscriptionPeriodFromDays`, for the same dashboard durations. */
402
+ private fun subscriptionPeriodFromDays(days: Int): SubscriptionPeriod? = when (days) {
403
+ 0 -> null
404
+ 7 -> SimpleSubscriptionPeriod(1, SubscriptionPeriod.Unit.WEEK)
405
+ in 28..32 -> SimpleSubscriptionPeriod(1, SubscriptionPeriod.Unit.MONTH)
406
+ in 85..95 -> SimpleSubscriptionPeriod(3, SubscriptionPeriod.Unit.MONTH)
407
+ in 175..190 -> SimpleSubscriptionPeriod(6, SubscriptionPeriod.Unit.MONTH)
408
+ in 360..370 -> SimpleSubscriptionPeriod(1, SubscriptionPeriod.Unit.YEAR)
409
+ else -> SimpleSubscriptionPeriod(days, SubscriptionPeriod.Unit.DAY)
410
+ }
411
+
215
412
  data class SimplePrice(
216
413
  override val formatted: String,
217
414
  override val currencyCode: String,
218
415
  override val amountMicros: Long,
219
416
  ) : Price
417
+
418
+ data class SimpleSubscriptionPeriod(
419
+ override val value: Int,
420
+ override val unit: SubscriptionPeriod.Unit,
421
+ ) : SubscriptionPeriod
@@ -158,6 +158,7 @@ class SKTransaction(
158
158
 
159
159
  internal fun toJSON(): JSONObject = JSONObject().apply {
160
160
  put("traceId", traceId)
161
+ put("spanId", spanId)
161
162
  put("name", name)
162
163
  put("op", op)
163
164
  put("startTimestamp", ISO_DATE.format(startTime))