@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +473 -2
- package/LICENSE +21 -0
- package/README.md +279 -47
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +20 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/GENERATED.md +1 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +111 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +312 -65
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +705 -96
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +29 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +24 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +343 -0
- package/ios/SwissKnifeJSON.swift +24 -2
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/GENERATED.md +1 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
- package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
- package/ios-notification-service/vendor/GENERATED.md +11 -0
- package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +27 -6
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +27 -6
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +2 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +2 -0
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +13 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +16 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +50 -9
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// packages/swiss-knife-android/src/main/java/com/appswissknife/entitlements/EntitlementsRepository.kt
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// /api/sdk/entitlements/
|
|
6
|
-
//
|
|
3
|
+
// Disk-cached CustomerInfo + backend-authoritative entitlement state. The
|
|
4
|
+
// backend is the source of truth: refresh() reads the user's whole entitlement
|
|
5
|
+
// set from /api/sdk/entitlements/list (iOS reads the same route), or asks
|
|
6
|
+
// /api/sdk/entitlements/check about each key a host names.
|
|
7
7
|
//
|
|
8
8
|
// Storage pattern mirrors Phase 2.2's EventQueueStore: atomic write-then-
|
|
9
9
|
// rename + tolerant parse on read. We use cacheDir (not filesDir) because
|
|
@@ -38,11 +38,15 @@ import com.appswissknife.models.OwnershipType
|
|
|
38
38
|
import com.appswissknife.models.PeriodType
|
|
39
39
|
import com.appswissknife.models.Store
|
|
40
40
|
import com.appswissknife.models.VerificationResult
|
|
41
|
+
import org.json.JSONException
|
|
41
42
|
import org.json.JSONObject
|
|
42
43
|
import java.io.File
|
|
43
44
|
import java.io.IOException
|
|
45
|
+
import java.text.SimpleDateFormat
|
|
44
46
|
import java.util.Collections
|
|
45
47
|
import java.util.Date
|
|
48
|
+
import java.util.Locale
|
|
49
|
+
import java.util.TimeZone
|
|
46
50
|
import java.util.concurrent.ExecutorService
|
|
47
51
|
import java.util.concurrent.Executors
|
|
48
52
|
import java.util.concurrent.locks.ReentrantLock
|
|
@@ -83,24 +87,48 @@ class EntitlementsRepository internal constructor(
|
|
|
83
87
|
* have nothing yet. Within the 24h grace window the result is trustworthy
|
|
84
88
|
* for read-only purposes (entitlement gating). Past the window the gateway
|
|
85
89
|
* should call [refresh] before relying on it.
|
|
90
|
+
*
|
|
91
|
+
* Only the current user's: a snapshot read for another subject (the app was
|
|
92
|
+
* configured with a different appUserID on a later launch, or a logIn or
|
|
93
|
+
* logOut changed the user) counts as no cache, as iOS drops it, so one
|
|
94
|
+
* user's entitlements are never shown to another.
|
|
86
95
|
*/
|
|
87
|
-
fun current(): CustomerInfo? =
|
|
96
|
+
fun current(): CustomerInfo? = currentUsersSnapshot()?.customerInfo
|
|
88
97
|
|
|
89
|
-
/** True if the cached snapshot is within the 24h offline grace window. */
|
|
98
|
+
/** True if the current user's cached snapshot is within the 24h offline grace window. */
|
|
90
99
|
fun isFresh(): Boolean {
|
|
91
|
-
val snap =
|
|
100
|
+
val snap = currentUsersSnapshot() ?: return false
|
|
92
101
|
return clock() - snap.fetchedAt <= GRACE_MILLIS
|
|
93
102
|
}
|
|
94
103
|
|
|
95
104
|
/**
|
|
96
|
-
* Replace the cached snapshot
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* refresh() round-trip.
|
|
105
|
+
* Replace the cached snapshot with [info], which belongs to
|
|
106
|
+
* [CustomerInfo.originalAppUserId]. Ignored when that is not the current
|
|
107
|
+
* user.
|
|
100
108
|
*/
|
|
101
109
|
fun set(info: CustomerInfo) {
|
|
102
|
-
|
|
110
|
+
store(info, subject = info.originalAppUserId)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private fun currentUsersSnapshot(): CachedSnapshot? =
|
|
114
|
+
cached?.takeIf { it.subject == userIdProvider() }
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Cache [info], read for [subject], and tell every listener, unless the
|
|
118
|
+
* current user is no longer [subject]: a read that was in flight when a
|
|
119
|
+
* logIn or logOut landed must not become the new user's cache, nor reach
|
|
120
|
+
* the listeners after the switch.
|
|
121
|
+
*/
|
|
122
|
+
private fun store(info: CustomerInfo, subject: String) {
|
|
123
|
+
val snap = CachedSnapshot(info, clock(), subject)
|
|
103
124
|
lock.withLock {
|
|
125
|
+
// Checked under the lock, so a user switch that changes the subject and
|
|
126
|
+
// then invalidates either fails this check or finds the snapshot
|
|
127
|
+
// written and drops it, from memory and disk.
|
|
128
|
+
if (subject != userIdProvider()) {
|
|
129
|
+
Log.i(TAG, "the user changed while their entitlements were read; not caching them")
|
|
130
|
+
return
|
|
131
|
+
}
|
|
104
132
|
cached = snap
|
|
105
133
|
runCatching { writeToDisk(snap) }
|
|
106
134
|
.onFailure { Log.w(TAG, "failed to persist CustomerInfo", it) }
|
|
@@ -121,11 +149,22 @@ class EntitlementsRepository internal constructor(
|
|
|
121
149
|
}
|
|
122
150
|
|
|
123
151
|
/**
|
|
124
|
-
* Fetch fresh state from the backend
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
152
|
+
* Fetch fresh state from the backend, update the cache and tell every
|
|
153
|
+
* listener.
|
|
154
|
+
*
|
|
155
|
+
* With no [entitlementKeys] (what the SDK itself passes) it reads the user's
|
|
156
|
+
* whole entitlement set from `/api/sdk/entitlements/list`, as iOS does: every
|
|
157
|
+
* entitlement the app defines, active or not, with its product, store,
|
|
158
|
+
* period type and dates, plus the user's active subscriptions and purchase
|
|
159
|
+
* dates. With keys it asks `/api/sdk/entitlements/check` about each one and
|
|
160
|
+
* knows only whether it is active.
|
|
161
|
+
*
|
|
162
|
+
* A failed read throws [IOException] and leaves the cache as it was, so a
|
|
163
|
+
* paying user keeps access through a network error.
|
|
164
|
+
*
|
|
165
|
+
* The answer is cached only while the user it was read for is still the
|
|
166
|
+
* current one; if a logIn or logOut landed meanwhile it is returned to the
|
|
167
|
+
* caller but neither cached nor announced.
|
|
129
168
|
*
|
|
130
169
|
* Synchronous + blocking. Callers on the main thread MUST wrap this
|
|
131
170
|
* (the [BillingClientGateway] schedules it on an Executor; tests run it
|
|
@@ -133,12 +172,16 @@ class EntitlementsRepository internal constructor(
|
|
|
133
172
|
*/
|
|
134
173
|
@Throws(IOException::class)
|
|
135
174
|
fun refresh(entitlementKeys: Set<String>): CustomerInfo {
|
|
175
|
+
val userId = userIdProvider()
|
|
136
176
|
if (entitlementKeys.isEmpty()) {
|
|
137
|
-
|
|
177
|
+
val customerInfo = fetchEntitlementList(userId)
|
|
178
|
+
store(customerInfo, userId)
|
|
179
|
+
return customerInfo
|
|
138
180
|
}
|
|
181
|
+
val previous = currentUsersSnapshot()?.customerInfo
|
|
139
182
|
val activeKeys = mutableSetOf<String>()
|
|
140
183
|
for (key in entitlementKeys) {
|
|
141
|
-
if (checkEntitlement(key)) activeKeys.add(key)
|
|
184
|
+
if (checkEntitlement(key, userId)) activeKeys.add(key)
|
|
142
185
|
}
|
|
143
186
|
// Rebuild CustomerInfo from the per-key responses. We keep ALL keys
|
|
144
187
|
// queried in `.all` and the subset that came back has_access=true in
|
|
@@ -149,18 +192,18 @@ class EntitlementsRepository internal constructor(
|
|
|
149
192
|
backendEntitlement(
|
|
150
193
|
identifier = k,
|
|
151
194
|
isActive = k in activeKeys,
|
|
152
|
-
latestPurchaseDate =
|
|
153
|
-
expirationDate =
|
|
195
|
+
latestPurchaseDate = previous?.entitlements?.all?.get(k)?.latestPurchaseDate,
|
|
196
|
+
expirationDate = previous?.entitlements?.all?.get(k)?.expirationDate,
|
|
154
197
|
)
|
|
155
198
|
}
|
|
156
199
|
val activeMap = infos.filterKeys { it in activeKeys }
|
|
157
200
|
val customerInfo = backendCustomerInfo(
|
|
158
|
-
userId =
|
|
201
|
+
userId = userId,
|
|
159
202
|
all = infos,
|
|
160
203
|
active = activeMap,
|
|
161
204
|
requestDate = now,
|
|
162
205
|
)
|
|
163
|
-
|
|
206
|
+
store(customerInfo, userId)
|
|
164
207
|
return customerInfo
|
|
165
208
|
}
|
|
166
209
|
|
|
@@ -234,12 +277,12 @@ class EntitlementsRepository internal constructor(
|
|
|
234
277
|
* contract.
|
|
235
278
|
*/
|
|
236
279
|
@Throws(IOException::class)
|
|
237
|
-
private fun checkEntitlement(key: String): Boolean {
|
|
280
|
+
private fun checkEntitlement(key: String, userId: String): Boolean {
|
|
238
281
|
val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
|
|
239
282
|
val (code, body) = client.simpleGet(
|
|
240
283
|
path = "/api/sdk/entitlements/check",
|
|
241
284
|
query = listOf(
|
|
242
|
-
"user_id" to
|
|
285
|
+
"user_id" to userId,
|
|
243
286
|
"entitlement" to key,
|
|
244
287
|
),
|
|
245
288
|
allow404 = true,
|
|
@@ -249,6 +292,26 @@ class EntitlementsRepository internal constructor(
|
|
|
249
292
|
return json.optBoolean("has_access", false)
|
|
250
293
|
}
|
|
251
294
|
|
|
295
|
+
/**
|
|
296
|
+
* Read [userId]'s whole entitlement set from `/api/sdk/entitlements/list`.
|
|
297
|
+
* An empty body means no entitlements. A network error, a non-2xx answer or
|
|
298
|
+
* a body that is not JSON throws [IOException].
|
|
299
|
+
*/
|
|
300
|
+
@Throws(IOException::class)
|
|
301
|
+
private fun fetchEntitlementList(userId: String): CustomerInfo {
|
|
302
|
+
val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
|
|
303
|
+
val (_, body) = client.simpleGet(
|
|
304
|
+
path = "/api/sdk/entitlements/list",
|
|
305
|
+
query = listOf("user_id" to userId),
|
|
306
|
+
)
|
|
307
|
+
if (body.isBlank()) return emptyCustomerInfo(userId)
|
|
308
|
+
return try {
|
|
309
|
+
parseEntitlementList(JSONObject(body), userId, Date(clock()))
|
|
310
|
+
} catch (e: JSONException) {
|
|
311
|
+
throw IOException("/api/sdk/entitlements/list returned a body that is not JSON", e)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
252
315
|
companion object {
|
|
253
316
|
private const val TAG = "SwissKnife.Entitlements"
|
|
254
317
|
|
|
@@ -278,6 +341,7 @@ class EntitlementsRepository internal constructor(
|
|
|
278
341
|
val json = JSONObject()
|
|
279
342
|
json.put("schemaVersion", 1)
|
|
280
343
|
json.put("fetchedAt", snap.fetchedAt)
|
|
344
|
+
json.put("subject", snap.subject)
|
|
281
345
|
json.put("originalAppUserId", ci.originalAppUserId)
|
|
282
346
|
json.put("firstSeen", ci.firstSeen.time)
|
|
283
347
|
json.put("requestDate", ci.requestDate.time)
|
|
@@ -372,7 +436,10 @@ class EntitlementsRepository internal constructor(
|
|
|
372
436
|
managementURL = managementURL,
|
|
373
437
|
requestDate = requestDate,
|
|
374
438
|
)
|
|
375
|
-
|
|
439
|
+
// A cache written before the subject was stored belongs to its
|
|
440
|
+
// CustomerInfo's user, which the SDK always set to the user it read for.
|
|
441
|
+
val subject = json.optString("subject").ifEmpty { originalAppUserId }
|
|
442
|
+
return CachedSnapshot(ci, fetchedAt, subject)
|
|
376
443
|
}
|
|
377
444
|
|
|
378
445
|
private fun decodeEntitlement(o: JSONObject): EntitlementInfo {
|
|
@@ -396,6 +463,106 @@ class EntitlementsRepository internal constructor(
|
|
|
396
463
|
)
|
|
397
464
|
}
|
|
398
465
|
|
|
466
|
+
// --- /api/sdk/entitlements/list ----------------------------------------
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* The `/api/sdk/entitlements/list` answer as a [CustomerInfo], read the way
|
|
470
|
+
* iOS reads it: a missing field takes a safe default, so a partial answer
|
|
471
|
+
* still gives the entitlements it has. Every entitlement the app defines is
|
|
472
|
+
* in `all`; `active` holds the ones with `is_active`.
|
|
473
|
+
*/
|
|
474
|
+
@VisibleForTesting
|
|
475
|
+
internal fun parseEntitlementList(json: JSONObject, userId: String, now: Date): CustomerInfo {
|
|
476
|
+
val all = mutableMapOf<String, EntitlementInfo>()
|
|
477
|
+
json.optJSONObject("entitlements")?.let { obj ->
|
|
478
|
+
val keys = obj.keys()
|
|
479
|
+
while (keys.hasNext()) {
|
|
480
|
+
val key = keys.next()
|
|
481
|
+
val e = obj.optJSONObject(key) ?: continue
|
|
482
|
+
all[key] = SimpleEntitlementInfo(
|
|
483
|
+
identifier = key,
|
|
484
|
+
isActive = e.optBoolean("is_active", false),
|
|
485
|
+
willRenew = e.optBoolean("will_renew", false),
|
|
486
|
+
latestPurchaseDate = parseDate(e.opt("latest_purchase_date")),
|
|
487
|
+
expirationDate = parseDate(e.opt("expiration_date")),
|
|
488
|
+
productIdentifier = e.stringOrNull("product_identifier").orEmpty(),
|
|
489
|
+
productPlanIdentifier = e.stringOrNull("product_plan_identifier"),
|
|
490
|
+
isSandbox = e.optBoolean("is_sandbox", false),
|
|
491
|
+
unsubscribeDetectedAt = parseDate(e.opt("unsubscribe_detected_at")),
|
|
492
|
+
billingIssueDetectedAt = parseDate(e.opt("billing_issue_detected_at")),
|
|
493
|
+
periodType = when (e.stringOrNull("period_type")?.lowercase()) {
|
|
494
|
+
"trial" -> PeriodType.TRIAL
|
|
495
|
+
"intro" -> PeriodType.INTRO
|
|
496
|
+
"prepaid" -> PeriodType.PREPAID
|
|
497
|
+
else -> PeriodType.NORMAL
|
|
498
|
+
},
|
|
499
|
+
store = storeOf(e.stringOrNull("store")),
|
|
500
|
+
ownershipType = when (e.stringOrNull("ownership_type")?.lowercase()) {
|
|
501
|
+
"family_shared", "familyshared" -> OwnershipType.FAMILY_SHARED
|
|
502
|
+
else -> OwnershipType.PURCHASED
|
|
503
|
+
},
|
|
504
|
+
)
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
val allPurchaseDates = mutableMapOf<String, Date>()
|
|
508
|
+
json.optJSONObject("all_purchase_dates")?.let { obj ->
|
|
509
|
+
val keys = obj.keys()
|
|
510
|
+
while (keys.hasNext()) {
|
|
511
|
+
val productId = keys.next()
|
|
512
|
+
parseDate(obj.opt(productId))?.let { allPurchaseDates[productId] = it }
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
val activeSubscriptions = mutableSetOf<String>()
|
|
516
|
+
json.optJSONArray("active_subscriptions")?.let { arr ->
|
|
517
|
+
for (i in 0 until arr.length()) arr.optString(i).takeIf { it.isNotEmpty() }?.let(activeSubscriptions::add)
|
|
518
|
+
}
|
|
519
|
+
return SimpleCustomerInfo(
|
|
520
|
+
entitlements = SimpleEntitlementInfos(
|
|
521
|
+
all = all,
|
|
522
|
+
active = all.filterValues { it.isActive },
|
|
523
|
+
verification = VerificationResult.NOT_REQUESTED,
|
|
524
|
+
),
|
|
525
|
+
originalAppUserId = json.stringOrNull("original_app_user_id") ?: userId,
|
|
526
|
+
firstSeen = parseDate(json.opt("first_seen")) ?: now,
|
|
527
|
+
originalPurchaseDate = parseDate(json.opt("original_purchase_date")),
|
|
528
|
+
latestExpirationDate = parseDate(json.opt("latest_expiration_date")),
|
|
529
|
+
allPurchaseDates = allPurchaseDates,
|
|
530
|
+
activeSubscriptions = activeSubscriptions,
|
|
531
|
+
// Everything the user ever bought: a lifetime unlock has a purchase
|
|
532
|
+
// date but is not an active subscription.
|
|
533
|
+
allPurchasedProductIds = allPurchaseDates.keys + activeSubscriptions,
|
|
534
|
+
managementURL = json.stringOrNull("management_url"),
|
|
535
|
+
requestDate = now,
|
|
536
|
+
)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private fun storeOf(raw: String?): Store = when (raw?.lowercase()) {
|
|
540
|
+
null -> Store.UNKNOWN_STORE
|
|
541
|
+
"play_store", "playstore" -> Store.PLAY_STORE
|
|
542
|
+
"app_store", "appstore" -> Store.APP_STORE
|
|
543
|
+
else -> runCatching { Store.valueOf(raw.uppercase()) }.getOrDefault(Store.UNKNOWN_STORE)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** An ISO 8601 date (the server's `toISOString()`, with or without millis) or epoch millis. */
|
|
547
|
+
private fun parseDate(raw: Any?): Date? {
|
|
548
|
+
if (raw is Number) return Date(raw.toLong())
|
|
549
|
+
val iso = raw as? String ?: return null
|
|
550
|
+
if (iso.isEmpty()) return null
|
|
551
|
+
for (pattern in ISO_PATTERNS) {
|
|
552
|
+
val format = SimpleDateFormat(pattern, Locale.US).apply {
|
|
553
|
+
timeZone = TimeZone.getTimeZone("UTC")
|
|
554
|
+
isLenient = false
|
|
555
|
+
}
|
|
556
|
+
runCatching { format.parse(iso) }.getOrNull()?.let { return it }
|
|
557
|
+
}
|
|
558
|
+
return null
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
private val ISO_PATTERNS = listOf("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ssXXX")
|
|
562
|
+
|
|
563
|
+
private fun JSONObject.stringOrNull(key: String): String? =
|
|
564
|
+
if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
|
|
565
|
+
|
|
399
566
|
private fun emptyCustomerInfo(userId: String): CustomerInfo = SimpleCustomerInfo(
|
|
400
567
|
entitlements = SimpleEntitlementInfos(emptyMap(), emptyMap(), VerificationResult.NOT_REQUESTED),
|
|
401
568
|
originalAppUserId = userId,
|
|
@@ -455,6 +622,8 @@ internal data class CachedSnapshot(
|
|
|
455
622
|
val customerInfo: CustomerInfo,
|
|
456
623
|
/** Wall-clock millis at fetch time - used for 24h grace check. */
|
|
457
624
|
val fetchedAt: Long,
|
|
625
|
+
/** The user (backend subject) this snapshot was read for; only that user is served it. */
|
|
626
|
+
val subject: String,
|
|
458
627
|
)
|
|
459
628
|
|
|
460
629
|
/** Concrete CustomerInfo backed by plain data fields. Public so the gateway
|
|
@@ -279,6 +279,7 @@ object Identity {
|
|
|
279
279
|
explicitUserId = null
|
|
280
280
|
identityGeneration += 1
|
|
281
281
|
}
|
|
282
|
+
runCatching { com.appswissknife.notifications.SwissKnifeNotifications.markUserUnlinkPending(ctx) }
|
|
282
283
|
val newSnapshot = current()
|
|
283
284
|
executor.execute {
|
|
284
285
|
SwissKnife.getGateway().logOut(
|
|
@@ -287,11 +288,21 @@ object Identity {
|
|
|
287
288
|
onSuccess()
|
|
288
289
|
},
|
|
289
290
|
onError = { err ->
|
|
290
|
-
// The local snapshot is already anonymous — surface the
|
|
291
|
-
// gateway error but don't roll back. Hosts treat logout
|
|
292
|
-
// failures as recoverable; the SDK state is consistent.
|
|
293
291
|
notifyChange(previousSnapshot, newSnapshot)
|
|
294
|
-
|
|
292
|
+
// The gateway is already anonymous (after reset() or
|
|
293
|
+
// wipe(), or no logIn ever happened). Identity is
|
|
294
|
+
// anonymous too, so the logout has nothing left to do:
|
|
295
|
+
// resolve, as iOS does, instead of rejecting with
|
|
296
|
+
// LOG_OUT_ANONYMOUS_USER_ERROR.
|
|
297
|
+
if (err.code == com.appswissknife.models.PurchasesErrorCode.LogOutAnonymousUserError) {
|
|
298
|
+
onSuccess()
|
|
299
|
+
} else {
|
|
300
|
+
// The local snapshot is already anonymous — surface
|
|
301
|
+
// the gateway error but don't roll back. Hosts treat
|
|
302
|
+
// logout failures as recoverable; the SDK state is
|
|
303
|
+
// consistent.
|
|
304
|
+
onError(err)
|
|
305
|
+
}
|
|
295
306
|
},
|
|
296
307
|
)
|
|
297
308
|
}
|
|
@@ -299,7 +310,10 @@ object Identity {
|
|
|
299
310
|
|
|
300
311
|
/**
|
|
301
312
|
* Rotate in-memory state but keep persistent storage. Matches the
|
|
302
|
-
* SKAnalytics-style reset semantic — "switch test user" UX.
|
|
313
|
+
* SKAnalytics-style reset semantic — "switch test user" UX. Purchases go
|
|
314
|
+
* back to the anonymous user too: [SwissKnife.appUserID] is the anonymous
|
|
315
|
+
* id and [SwissKnife.getCustomerInfo] no longer serves the previous user's
|
|
316
|
+
* entitlements.
|
|
303
317
|
*/
|
|
304
318
|
fun reset() {
|
|
305
319
|
val previousSnapshot = current()
|
|
@@ -308,6 +322,11 @@ object Identity {
|
|
|
308
322
|
identityGeneration += 1
|
|
309
323
|
}
|
|
310
324
|
entitlementsRepo?.invalidate()
|
|
325
|
+
// The purchases gateway holds the user's id and entitlements too
|
|
326
|
+
// (logIn handed them over): without this, appUserID and
|
|
327
|
+
// getCustomerInfo() kept answering for the user just reset.
|
|
328
|
+
SwissKnife.identityResetLocalState()
|
|
329
|
+
appContext?.let { c -> runCatching { com.appswissknife.notifications.SwissKnifeNotifications.markUserUnlinkPending(c) } }
|
|
311
330
|
val newSnapshot = current()
|
|
312
331
|
notifyChange(previousSnapshot, newSnapshot)
|
|
313
332
|
}
|
|
@@ -315,7 +334,8 @@ object Identity {
|
|
|
315
334
|
/**
|
|
316
335
|
* Hard wipe: clears EncryptedSharedPreferences DeviceID, drops the
|
|
317
336
|
* entitlements cache. GDPR-delete / test-build cleanup. Next
|
|
318
|
-
* `current()` regenerates DeviceID.
|
|
337
|
+
* `current()` regenerates DeviceID. Purchases go back to the (new)
|
|
338
|
+
* anonymous user, as with [reset].
|
|
319
339
|
*/
|
|
320
340
|
fun wipe(context: Context) {
|
|
321
341
|
val previousSnapshot = current()
|
|
@@ -325,6 +345,9 @@ object Identity {
|
|
|
325
345
|
}
|
|
326
346
|
DeviceID.wipe(context)
|
|
327
347
|
entitlementsRepo?.invalidate()
|
|
348
|
+
// After DeviceID.wipe, so the gateway's anonymous subject is the new id.
|
|
349
|
+
SwissKnife.identityResetLocalState()
|
|
350
|
+
runCatching { com.appswissknife.notifications.SwissKnifeNotifications.markUserUnlinkPending(context) }
|
|
328
351
|
val newSnapshot = current()
|
|
329
352
|
notifyChange(previousSnapshot, newSnapshot)
|
|
330
353
|
}
|
|
@@ -387,6 +410,8 @@ object Identity {
|
|
|
387
410
|
* [configure] here would reset the identity back to the seed user and
|
|
388
411
|
* silently undo a `logIn(...)` that landed between the two halves.
|
|
389
412
|
*/
|
|
413
|
+
internal fun entitlementsRepository(): EntitlementsRepository? = entitlementsRepo
|
|
414
|
+
|
|
390
415
|
internal fun _attachEntitlementsRepository(repository: EntitlementsRepository?) {
|
|
391
416
|
synchronized(lock) {
|
|
392
417
|
this.entitlementsRepo = repository
|
|
@@ -21,6 +21,11 @@ open class PurchasesError(
|
|
|
21
21
|
override val cause: Throwable? = null,
|
|
22
22
|
) : Throwable(message, cause) {
|
|
23
23
|
|
|
24
|
+
/** Safe backend diagnostics; absent for billing and transport failures. */
|
|
25
|
+
val httpStatus: Int? get() = (cause as? com.appswissknife.net.BillingBackendException)?.httpStatus
|
|
26
|
+
val backendErrorCode: String? get() = (cause as? com.appswissknife.net.BillingBackendException)?.errorCode
|
|
27
|
+
val requestId: String? get() = (cause as? com.appswissknife.net.BillingBackendException)?.requestId
|
|
28
|
+
|
|
24
29
|
/** Convenience: anything that did not succeed and was NOT a user-cancel. */
|
|
25
30
|
val underlyingErrorMessage: String? get() = cause?.message
|
|
26
31
|
|
|
@@ -1,30 +1,29 @@
|
|
|
1
1
|
// packages/swiss-knife-android/src/main/java/com/appswissknife/net/BackendHttpClient.kt
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
3
|
+
// The single HTTP client for every backend call the SDK makes. Mirror of
|
|
4
|
+
// `Sources/SwissKnifeiOS/Net/BackendHttpClient.swift`.
|
|
5
5
|
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
// matches ONLY this file. Modules that need a one-shot send/receive
|
|
10
|
-
// (FlushEventsWorker, SetAttributesWorker, SKCrashReporting fallback,
|
|
11
|
-
// SKPerformance fallback, EntitlementsRepository, OfferingsRepository)
|
|
12
|
-
// go through `BackendHttpClient.simplePost` / `.simpleGet` (no retries —
|
|
13
|
-
// the caller is the retry layer); modules that want the full retry/auth/base-url policy
|
|
14
|
-
// (Identity, Attribution, BillingClientGateway.validate) go through
|
|
15
|
-
// `BackendHttpClient.shared` (production) or a `BackendHttpClient.create`
|
|
16
|
-
// (tests / pre-configure callers).
|
|
6
|
+
// No other file in packages/swiss-knife-android/src/main/ opens an
|
|
7
|
+
// HttpURLConnection to the backend (notifications/NotificationRenderer opens
|
|
8
|
+
// one only to download a notification's image from its own URL).
|
|
17
9
|
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
// -
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
10
|
+
// Telemetry has one pipeline: analytics events, captured errors and crash
|
|
11
|
+
// reports, and performance data are items on IngestClient's durable queue,
|
|
12
|
+
// which drains to `POST /ingest` through `BackendHttpClient.shared`.
|
|
13
|
+
//
|
|
14
|
+
// The other callers:
|
|
15
|
+
// - One-shot send/receive through `simplePost` / `simpleGet` (no retries;
|
|
16
|
+
// the caller is the retry layer): attributes/SetAttributesWorker,
|
|
17
|
+
// crashreporting/SKCrashReporting (user feedback only),
|
|
18
|
+
// performance/SKPerformance (only while IngestClient is not wired),
|
|
19
|
+
// notifications/SwissKnifeNotifications and PushEventQueue (push device
|
|
20
|
+
// registration and push events), entitlements/EntitlementsRepository,
|
|
21
|
+
// offerings/OfferingsRepository.
|
|
22
|
+
// - `postIgnoringResponse` / `postRaw` with a retry budget, on
|
|
23
|
+
// `BackendHttpClient.shared` or a pinned `BackendHttpClient.create(...)`:
|
|
24
|
+
// identity/Identity (identify), attribution/Attribution (install).
|
|
25
|
+
// - [BackendHttpClientAdapter], the `BillingHttpClient` that
|
|
26
|
+
// purchases/BillingClientGateway validates receipts through.
|
|
28
27
|
//
|
|
29
28
|
// Design decisions:
|
|
30
29
|
// - Adds `X-API-Key` automatically using the configResolver lambda.
|
|
@@ -451,11 +450,9 @@ internal class BackendHttpClient(
|
|
|
451
450
|
}
|
|
452
451
|
|
|
453
452
|
/**
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
* data classes so callers can keep their handleResponse(...) branches
|
|
458
|
-
* unchanged.
|
|
453
|
+
* What [BackendHttpClient.simplePost] returns: the status code and the
|
|
454
|
+
* server's Retry-After, so the caller that owns the retries
|
|
455
|
+
* (SetAttributesWorker, PushEventQueue, ...) can decide what to do next.
|
|
459
456
|
*/
|
|
460
457
|
internal data class SimpleHttpResponse(
|
|
461
458
|
val code: Int,
|
|
@@ -477,14 +474,15 @@ internal data class SimpleHttpResponse(
|
|
|
477
474
|
* directly. Any future caller MUST do the same; passing `Authorization`
|
|
478
475
|
* will leave the request unauthenticated.
|
|
479
476
|
*/
|
|
480
|
-
internal class BackendHttpClientAdapter
|
|
477
|
+
internal class BackendHttpClientAdapter(
|
|
478
|
+
private val transport: BackendTransport = UrlConnectionBackendTransport(),
|
|
479
|
+
) : com.appswissknife.purchases.BillingHttpClient {
|
|
481
480
|
@Throws(IOException::class)
|
|
482
481
|
override fun post(url: String, body: String, headers: Map<String, String>): String {
|
|
483
482
|
val u = java.net.URL(url)
|
|
484
483
|
val baseUrl = "${u.protocol}://${u.authority}"
|
|
485
484
|
val pathAndQuery = u.path + (u.query?.let { "?$it" } ?: "")
|
|
486
485
|
val apiKey = headers["X-API-Key"] ?: ""
|
|
487
|
-
val transport = UrlConnectionBackendTransport()
|
|
488
486
|
val fullHeaders = mapOf(
|
|
489
487
|
"Content-Type" to (headers["Content-Type"] ?: "application/json"),
|
|
490
488
|
"Accept" to "application/json",
|
|
@@ -493,7 +491,10 @@ internal class BackendHttpClientAdapter : com.appswissknife.purchases.BillingHtt
|
|
|
493
491
|
val urlObj = java.net.URL("$baseUrl$pathAndQuery")
|
|
494
492
|
val r = transport.perform("POST", urlObj, fullHeaders, body.toByteArray(Charsets.UTF_8))
|
|
495
493
|
if (!r.success) throw IOException(r.error?.message ?: "network error", r.error)
|
|
496
|
-
if (r.code !in 200..299)
|
|
494
|
+
if (r.code !in 200..299) {
|
|
495
|
+
val json = try { JSONObject(r.body) } catch (_: Exception) { null }
|
|
496
|
+
throw BillingBackendException(r.code, json?.optString("error_code"), json?.optString("request_id"))
|
|
497
|
+
}
|
|
497
498
|
return r.body
|
|
498
499
|
}
|
|
499
500
|
}
|
|
@@ -514,3 +515,27 @@ internal object ConfigBridge {
|
|
|
514
515
|
|
|
515
516
|
fun snapshot(): BackendConfig = supplier()
|
|
516
517
|
}
|
|
518
|
+
|
|
519
|
+
/** Never retain the raw body: provider errors can echo a receipt or token. */
|
|
520
|
+
internal class BillingBackendException(
|
|
521
|
+
val httpStatus: Int,
|
|
522
|
+
code: String?,
|
|
523
|
+
requestId: String?,
|
|
524
|
+
) : IOException("HTTP $httpStatus: ${SAFE_MESSAGES[code] ?: "Purchase validation failed"}") {
|
|
525
|
+
val errorCode: String? = code?.takeIf { SAFE_MESSAGES.containsKey(it) }
|
|
526
|
+
val requestId: String? = requestId?.takeIf {
|
|
527
|
+
it.matches(Regex("[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"))
|
|
528
|
+
}
|
|
529
|
+
companion object {
|
|
530
|
+
private val SAFE_MESSAGES = mapOf(
|
|
531
|
+
"missing_required_fields" to "Missing required purchase validation fields",
|
|
532
|
+
"invalid_request" to "Invalid purchase validation request",
|
|
533
|
+
"invalid_platform" to "Invalid purchase platform",
|
|
534
|
+
"android_package_missing" to "Android package is not configured",
|
|
535
|
+
"store_credentials_missing" to "Store credentials are not configured for this app",
|
|
536
|
+
"receipt_invalid" to "The store could not validate this purchase",
|
|
537
|
+
"purchase_ownership_conflict" to "This purchase belongs to another user",
|
|
538
|
+
"validation_unavailable" to "Purchase validation is temporarily unavailable",
|
|
539
|
+
)
|
|
540
|
+
}
|
|
541
|
+
}
|