@app-swiss-knife/react-native-sdk 0.1.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.
- package/README.md +182 -0
- package/SwissKnifePurchases.podspec +40 -0
- package/android/build.gradle +89 -0
- package/android/gradle.properties +3 -0
- package/android/src/main/AndroidManifest.xml +26 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
- package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
- package/android/vendor/GENERATED.md +10 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
- package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
- package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
- package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
- package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
- package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
- package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
- package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
- package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
- package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
- package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
- package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
- package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
- package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
- package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
- package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
- package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
- package/ios/SwissKnifeCrashReporting.m +32 -0
- package/ios/SwissKnifeCrashReporting.swift +186 -0
- package/ios/SwissKnifeJSON.swift +347 -0
- package/ios/SwissKnifePurchases.m +124 -0
- package/ios/SwissKnifePurchases.swift +523 -0
- package/ios/vendor/GENERATED.md +10 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
- package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
- package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
- package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
- package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
- package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
- package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
- package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
- package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
- package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
- package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
- package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
- package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
- package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
- package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
- package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
- package/lib/commonjs/attribution.js +55 -0
- package/lib/commonjs/attribution.js.map +1 -0
- package/lib/commonjs/identity.js +126 -0
- package/lib/commonjs/identity.js.map +1 -0
- package/lib/commonjs/index.js +118 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +646 -0
- package/lib/commonjs/modules/analytics.js.map +1 -0
- package/lib/commonjs/modules/attachments.js +169 -0
- package/lib/commonjs/modules/attachments.js.map +1 -0
- package/lib/commonjs/modules/crash-reporting.js +1327 -0
- package/lib/commonjs/modules/crash-reporting.js.map +1 -0
- package/lib/commonjs/modules/ids.js +50 -0
- package/lib/commonjs/modules/ids.js.map +1 -0
- package/lib/commonjs/modules/log.js +59 -0
- package/lib/commonjs/modules/log.js.map +1 -0
- package/lib/commonjs/modules/offline-store.js +44 -0
- package/lib/commonjs/modules/offline-store.js.map +1 -0
- package/lib/commonjs/modules/performance.js +494 -0
- package/lib/commonjs/modules/performance.js.map +1 -0
- package/lib/commonjs/native/module.js +41 -0
- package/lib/commonjs/native/module.js.map +1 -0
- package/lib/commonjs/native/spec.js +26 -0
- package/lib/commonjs/native/spec.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/purchases.js +194 -0
- package/lib/commonjs/purchases.js.map +1 -0
- package/lib/commonjs/types.js +236 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/module/attribution.js +51 -0
- package/lib/module/attribution.js.map +1 -0
- package/lib/module/identity.js +122 -0
- package/lib/module/identity.js.map +1 -0
- package/lib/module/index.js +36 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/modules/analytics.js +642 -0
- package/lib/module/modules/analytics.js.map +1 -0
- package/lib/module/modules/attachments.js +162 -0
- package/lib/module/modules/attachments.js.map +1 -0
- package/lib/module/modules/crash-reporting.js +1320 -0
- package/lib/module/modules/crash-reporting.js.map +1 -0
- package/lib/module/modules/ids.js +44 -0
- package/lib/module/modules/ids.js.map +1 -0
- package/lib/module/modules/log.js +54 -0
- package/lib/module/modules/log.js.map +1 -0
- package/lib/module/modules/offline-store.js +39 -0
- package/lib/module/modules/offline-store.js.map +1 -0
- package/lib/module/modules/performance.js +491 -0
- package/lib/module/modules/performance.js.map +1 -0
- package/lib/module/native/module.js +34 -0
- package/lib/module/native/module.js.map +1 -0
- package/lib/module/native/spec.js +22 -0
- package/lib/module/native/spec.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/purchases.js +187 -0
- package/lib/module/purchases.js.map +1 -0
- package/lib/module/types.js +230 -0
- package/lib/module/types.js.map +1 -0
- package/lib/typescript/commonjs/attribution.d.ts +24 -0
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
- package/lib/typescript/commonjs/identity.d.ts +37 -0
- package/lib/typescript/commonjs/identity.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +15 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
- package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
- package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/log.d.ts +12 -0
- package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
- package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/module.d.ts +6 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
- package/lib/typescript/commonjs/native/spec.d.ts +119 -0
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/purchases.d.ts +68 -0
- package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
- package/lib/typescript/commonjs/types.d.ts +384 -0
- package/lib/typescript/commonjs/types.d.ts.map +1 -0
- package/lib/typescript/module/attribution.d.ts +24 -0
- package/lib/typescript/module/attribution.d.ts.map +1 -0
- package/lib/typescript/module/identity.d.ts +37 -0
- package/lib/typescript/module/identity.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +15 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +127 -0
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
- package/lib/typescript/module/modules/attachments.d.ts +50 -0
- package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
- package/lib/typescript/module/modules/ids.d.ts +17 -0
- package/lib/typescript/module/modules/ids.d.ts.map +1 -0
- package/lib/typescript/module/modules/log.d.ts +12 -0
- package/lib/typescript/module/modules/log.d.ts.map +1 -0
- package/lib/typescript/module/modules/offline-store.d.ts +9 -0
- package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +75 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -0
- package/lib/typescript/module/native/module.d.ts +6 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -0
- package/lib/typescript/module/native/spec.d.ts +119 -0
- package/lib/typescript/module/native/spec.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/purchases.d.ts +68 -0
- package/lib/typescript/module/purchases.d.ts.map +1 -0
- package/lib/typescript/module/types.d.ts +384 -0
- package/lib/typescript/module/types.d.ts.map +1 -0
- package/package.json +115 -0
- package/react-native.config.js +23 -0
- package/src/attribution.ts +56 -0
- package/src/identity.ts +133 -0
- package/src/index.ts +54 -0
- package/src/modules/analytics.ts +689 -0
- package/src/modules/attachments.ts +222 -0
- package/src/modules/crash-reporting.ts +1577 -0
- package/src/modules/ids.ts +41 -0
- package/src/modules/log.ts +56 -0
- package/src/modules/offline-store.ts +51 -0
- package/src/modules/performance.ts +589 -0
- package/src/native/module.ts +47 -0
- package/src/native/spec.ts +183 -0
- package/src/purchases.ts +214 -0
- package/src/types.ts +470 -0
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/entitlements/EntitlementsRepository.kt
|
|
2
|
+
//
|
|
3
|
+
// Phase 6 commit 2 — disk-cached CustomerInfo + backend-authoritative
|
|
4
|
+
// entitlement state. Replaces PHC's in-process cache; the backend at
|
|
5
|
+
// /api/sdk/entitlements/check is the source of truth per the user-locked
|
|
6
|
+
// decision (backend, not PHC, owns entitlements).
|
|
7
|
+
//
|
|
8
|
+
// Storage pattern mirrors Phase 2.2's EventQueueStore: atomic write-then-
|
|
9
|
+
// rename + tolerant parse on read. We use cacheDir (not filesDir) because
|
|
10
|
+
// the OS may evict it under pressure - that just falls through to a re-fetch
|
|
11
|
+
// from the backend, which is fine.
|
|
12
|
+
//
|
|
13
|
+
// 24h offline grace: while online, every refresh() pull updates the cache
|
|
14
|
+
// timestamp; current() returns cached CustomerInfo if the cache is within
|
|
15
|
+
// the grace window. Past the window we still return whatever the cache has
|
|
16
|
+
// (so the app is never starved entirely on a flaky network) but the gateway
|
|
17
|
+
// is responsible for re-fetching opportunistically.
|
|
18
|
+
//
|
|
19
|
+
// FCM silent-invalidate: handleSilentFCM() is a stub here - the actual FCM
|
|
20
|
+
// service registration is a follow-up (out of scope for Phase 6). It calls
|
|
21
|
+
// invalidate() + a fire-and-forget refresh, which the host app's
|
|
22
|
+
// FirebaseMessagingService can hook into when they get a data-only push from
|
|
23
|
+
// /api/webhooks/google/* that the backend forwards.
|
|
24
|
+
//
|
|
25
|
+
// Thread safety: a single ReentrantLock guards all on-disk operations + the
|
|
26
|
+
// in-memory snapshot. The backend HTTP call happens OUTSIDE the lock to
|
|
27
|
+
// avoid serialising network IO behind disk IO.
|
|
28
|
+
|
|
29
|
+
package com.appswissknife.entitlements
|
|
30
|
+
|
|
31
|
+
import android.content.Context
|
|
32
|
+
import android.util.Log
|
|
33
|
+
import androidx.annotation.VisibleForTesting
|
|
34
|
+
import com.appswissknife.models.CustomerInfo
|
|
35
|
+
import com.appswissknife.models.EntitlementInfo
|
|
36
|
+
import com.appswissknife.models.EntitlementInfos
|
|
37
|
+
import com.appswissknife.models.OwnershipType
|
|
38
|
+
import com.appswissknife.models.PeriodType
|
|
39
|
+
import com.appswissknife.models.Store
|
|
40
|
+
import com.appswissknife.models.VerificationResult
|
|
41
|
+
import org.json.JSONObject
|
|
42
|
+
import java.io.File
|
|
43
|
+
import java.io.IOException
|
|
44
|
+
import java.util.Collections
|
|
45
|
+
import java.util.Date
|
|
46
|
+
import java.util.concurrent.ExecutorService
|
|
47
|
+
import java.util.concurrent.Executors
|
|
48
|
+
import java.util.concurrent.locks.ReentrantLock
|
|
49
|
+
import kotlin.concurrent.withLock
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Persisted, lazily-refreshed CustomerInfo store.
|
|
53
|
+
*
|
|
54
|
+
* Single instance per process - construct one in [com.appswissknife.SwissKnife.configure]
|
|
55
|
+
* and pass it to [com.appswissknife.purchases.BillingClientGateway]. Tests
|
|
56
|
+
* use [setOverrideForTesting] to inject a deterministic instance.
|
|
57
|
+
*/
|
|
58
|
+
class EntitlementsRepository internal constructor(
|
|
59
|
+
private val context: Context,
|
|
60
|
+
private val serverUrl: String,
|
|
61
|
+
private val apiKey: String,
|
|
62
|
+
private val userIdProvider: () -> String,
|
|
63
|
+
internal val clock: () -> Long = System::currentTimeMillis,
|
|
64
|
+
private val executor: ExecutorService = Executors.newSingleThreadExecutor { r ->
|
|
65
|
+
Thread(r, "swissknife-entitlements").apply { isDaemon = true }
|
|
66
|
+
},
|
|
67
|
+
) {
|
|
68
|
+
|
|
69
|
+
private val lock = ReentrantLock()
|
|
70
|
+
private val listeners = Collections.synchronizedSet(mutableSetOf<(CustomerInfo) -> Unit>())
|
|
71
|
+
|
|
72
|
+
/** In-memory mirror of the on-disk snapshot. Null = no cache. */
|
|
73
|
+
@Volatile private var cached: CachedSnapshot? = null
|
|
74
|
+
|
|
75
|
+
init {
|
|
76
|
+
// Eagerly hydrate from disk on construction so [current] doesn't have to
|
|
77
|
+
// touch IO. Failure here is tolerated - the cache is just empty.
|
|
78
|
+
runCatching { readFromDisk() }.onSuccess { cached = it }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Synchronously return whatever CustomerInfo is on disk - or null if we
|
|
83
|
+
* have nothing yet. Within the 24h grace window the result is trustworthy
|
|
84
|
+
* for read-only purposes (entitlement gating). Past the window the gateway
|
|
85
|
+
* should call [refresh] before relying on it.
|
|
86
|
+
*/
|
|
87
|
+
fun current(): CustomerInfo? = cached?.customerInfo
|
|
88
|
+
|
|
89
|
+
/** True if the cached snapshot is within the 24h offline grace window. */
|
|
90
|
+
fun isFresh(): Boolean {
|
|
91
|
+
val snap = cached ?: return false
|
|
92
|
+
return clock() - snap.fetchedAt <= GRACE_MILLIS
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Replace the cached snapshot. Called by the gateway after a successful
|
|
97
|
+
* purchase (which already roundtripped through /api/sdk/subscriptions/validate
|
|
98
|
+
* and so reflects authoritative state), to avoid an immediate redundant
|
|
99
|
+
* refresh() round-trip.
|
|
100
|
+
*/
|
|
101
|
+
fun set(info: CustomerInfo) {
|
|
102
|
+
val snap = CachedSnapshot(info, clock())
|
|
103
|
+
lock.withLock {
|
|
104
|
+
cached = snap
|
|
105
|
+
runCatching { writeToDisk(snap) }
|
|
106
|
+
.onFailure { Log.w(TAG, "failed to persist CustomerInfo", it) }
|
|
107
|
+
}
|
|
108
|
+
notifyListeners(info)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Drop the cache entirely. Next [refresh] will go all the way to the
|
|
113
|
+
* backend. Called by [handleSilentFCM] and by hosts that need to force a
|
|
114
|
+
* re-pull (e.g. on `logIn`).
|
|
115
|
+
*/
|
|
116
|
+
fun invalidate() {
|
|
117
|
+
lock.withLock {
|
|
118
|
+
cached = null
|
|
119
|
+
runCatching { cacheFile.delete() }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Fetch fresh state from the backend and update the cache. The supplied
|
|
125
|
+
* [entitlementKeys] are the entitlement identifiers the host cares about
|
|
126
|
+
* - the backend's `/api/sdk/entitlements/check` is keyed and we need at
|
|
127
|
+
* least one key to call it. If empty, [refresh] is a no-op that returns
|
|
128
|
+
* the existing cache verbatim.
|
|
129
|
+
*
|
|
130
|
+
* Synchronous + blocking. Callers on the main thread MUST wrap this
|
|
131
|
+
* (the [BillingClientGateway] schedules it on an Executor; tests run it
|
|
132
|
+
* synchronously).
|
|
133
|
+
*/
|
|
134
|
+
@Throws(IOException::class)
|
|
135
|
+
fun refresh(entitlementKeys: Set<String>): CustomerInfo {
|
|
136
|
+
if (entitlementKeys.isEmpty()) {
|
|
137
|
+
return current() ?: emptyCustomerInfo(userIdProvider())
|
|
138
|
+
}
|
|
139
|
+
val activeKeys = mutableSetOf<String>()
|
|
140
|
+
for (key in entitlementKeys) {
|
|
141
|
+
if (checkEntitlement(key)) activeKeys.add(key)
|
|
142
|
+
}
|
|
143
|
+
// Rebuild CustomerInfo from the per-key responses. We keep ALL keys
|
|
144
|
+
// queried in `.all` and the subset that came back has_access=true in
|
|
145
|
+
// `.active` - matching RC parity (.all is the universe of known
|
|
146
|
+
// entitlements; .active filters to has_access).
|
|
147
|
+
val now = Date(clock())
|
|
148
|
+
val infos = entitlementKeys.associateWith { k ->
|
|
149
|
+
backendEntitlement(
|
|
150
|
+
identifier = k,
|
|
151
|
+
isActive = k in activeKeys,
|
|
152
|
+
latestPurchaseDate = cached?.customerInfo?.entitlements?.all?.get(k)?.latestPurchaseDate,
|
|
153
|
+
expirationDate = cached?.customerInfo?.entitlements?.all?.get(k)?.expirationDate,
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
val activeMap = infos.filterKeys { it in activeKeys }
|
|
157
|
+
val customerInfo = backendCustomerInfo(
|
|
158
|
+
userId = userIdProvider(),
|
|
159
|
+
all = infos,
|
|
160
|
+
active = activeMap,
|
|
161
|
+
requestDate = now,
|
|
162
|
+
)
|
|
163
|
+
set(customerInfo)
|
|
164
|
+
return customerInfo
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Silent-push handler stub. Wire your `FirebaseMessagingService.onMessageReceived`
|
|
169
|
+
* to call this with the data payload; the backend marks the relevant
|
|
170
|
+
* notifications with a `swissknife.invalidate` key so the host can route
|
|
171
|
+
* only those messages here.
|
|
172
|
+
*
|
|
173
|
+
* The actual FCM service registration is out of scope for Phase 6.
|
|
174
|
+
*/
|
|
175
|
+
fun handleSilentFCM(data: Map<String, String>, entitlementKeys: Set<String>) {
|
|
176
|
+
if (data["swissknife.invalidate"] != "true") return
|
|
177
|
+
invalidate()
|
|
178
|
+
executor.execute {
|
|
179
|
+
runCatching { refresh(entitlementKeys) }
|
|
180
|
+
.onFailure { Log.w(TAG, "background refresh after FCM invalidate failed", it) }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Subscribe to CustomerInfo updates (in addition to push from the gateway). */
|
|
185
|
+
fun addListener(listener: (CustomerInfo) -> Unit) {
|
|
186
|
+
listeners.add(listener)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
fun removeListener(listener: (CustomerInfo) -> Unit) {
|
|
190
|
+
listeners.remove(listener)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// --- Internals ----------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
private fun notifyListeners(info: CustomerInfo) {
|
|
196
|
+
val snapshot = synchronized(listeners) { listeners.toList() }
|
|
197
|
+
snapshot.forEach { runCatching { it(info) } }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
@VisibleForTesting
|
|
201
|
+
internal val cacheFile: File
|
|
202
|
+
get() {
|
|
203
|
+
val dir = File(context.cacheDir, "swissknife")
|
|
204
|
+
if (!dir.exists()) dir.mkdirs()
|
|
205
|
+
return File(dir, "customerInfo.json")
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
private fun writeToDisk(snap: CachedSnapshot) {
|
|
209
|
+
val temp = File(cacheFile.parentFile, "${cacheFile.name}.tmp")
|
|
210
|
+
val json = encode(snap)
|
|
211
|
+
temp.writeText(json)
|
|
212
|
+
if (!temp.renameTo(cacheFile)) {
|
|
213
|
+
// renameTo failure (rare on local FS): fall back to direct overwrite.
|
|
214
|
+
cacheFile.writeText(json)
|
|
215
|
+
temp.delete()
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private fun readFromDisk(): CachedSnapshot? {
|
|
220
|
+
if (!cacheFile.exists()) return null
|
|
221
|
+
val text = runCatching { cacheFile.readText() }.getOrNull() ?: return null
|
|
222
|
+
return runCatching { decode(text) }.getOrNull()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Call /api/sdk/entitlements/check for a single key. Returns has_access.
|
|
227
|
+
* Network or 4xx/5xx → throws IOException (the caller decides whether to
|
|
228
|
+
* surface).
|
|
229
|
+
*
|
|
230
|
+
* Round-D: routed through the unified BackendHttpClient transport.
|
|
231
|
+
* Pre-Round-D used `Authorization: Bearer ...` which the backend's
|
|
232
|
+
* `withApiKeyAuth` middleware ignored — every check was returning 401
|
|
233
|
+
* in production. simpleBackendGet stamps `X-API-Key` per the route
|
|
234
|
+
* contract.
|
|
235
|
+
*/
|
|
236
|
+
@Throws(IOException::class)
|
|
237
|
+
private fun checkEntitlement(key: String): Boolean {
|
|
238
|
+
val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
|
|
239
|
+
val (code, body) = client.simpleGet(
|
|
240
|
+
path = "/api/sdk/entitlements/check",
|
|
241
|
+
query = listOf(
|
|
242
|
+
"user_id" to userIdProvider(),
|
|
243
|
+
"entitlement" to key,
|
|
244
|
+
),
|
|
245
|
+
allow404 = true,
|
|
246
|
+
)
|
|
247
|
+
if (code == 404) return false // entitlement key not configured
|
|
248
|
+
val json = JSONObject(body)
|
|
249
|
+
return json.optBoolean("has_access", false)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
companion object {
|
|
253
|
+
private const val TAG = "SwissKnife.Entitlements"
|
|
254
|
+
|
|
255
|
+
/** 24-hour offline grace per the locked decision. */
|
|
256
|
+
const val GRACE_MILLIS: Long = 24L * 60 * 60 * 1000
|
|
257
|
+
|
|
258
|
+
@Volatile private var override: EntitlementsRepository? = null
|
|
259
|
+
|
|
260
|
+
/** Test seam: inject a pre-built repo. Pass null to clear. */
|
|
261
|
+
@VisibleForTesting
|
|
262
|
+
fun setOverrideForTesting(repo: EntitlementsRepository?) {
|
|
263
|
+
override = repo
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
fun get(context: Context, serverUrl: String, apiKey: String, userIdProvider: () -> String): EntitlementsRepository {
|
|
267
|
+
override?.let { return it }
|
|
268
|
+
return EntitlementsRepository(context.applicationContext, serverUrl, apiKey, userIdProvider)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// --- JSON encoding -----------------------------------------------------
|
|
272
|
+
// We hand-roll the JSON rather than pull in kotlinx-serialization to keep
|
|
273
|
+
// the SDK dependency footprint small. The format is private to this
|
|
274
|
+
// class - readers tolerate missing/unknown fields.
|
|
275
|
+
|
|
276
|
+
private fun encode(snap: CachedSnapshot): String {
|
|
277
|
+
val ci = snap.customerInfo
|
|
278
|
+
val json = JSONObject()
|
|
279
|
+
json.put("schemaVersion", 1)
|
|
280
|
+
json.put("fetchedAt", snap.fetchedAt)
|
|
281
|
+
json.put("originalAppUserId", ci.originalAppUserId)
|
|
282
|
+
json.put("firstSeen", ci.firstSeen.time)
|
|
283
|
+
json.put("requestDate", ci.requestDate.time)
|
|
284
|
+
ci.originalPurchaseDate?.let { json.put("originalPurchaseDate", it.time) }
|
|
285
|
+
ci.latestExpirationDate?.let { json.put("latestExpirationDate", it.time) }
|
|
286
|
+
ci.managementURL?.let { json.put("managementURL", it) }
|
|
287
|
+
json.put("activeSubscriptions", org.json.JSONArray(ci.activeSubscriptions.toList()))
|
|
288
|
+
json.put("allPurchasedProductIds", org.json.JSONArray(ci.allPurchasedProductIds.toList()))
|
|
289
|
+
val datesObj = JSONObject()
|
|
290
|
+
ci.allPurchaseDates.forEach { (k, v) -> datesObj.put(k, v.time) }
|
|
291
|
+
json.put("allPurchaseDates", datesObj)
|
|
292
|
+
val entAll = JSONObject()
|
|
293
|
+
ci.entitlements.all.forEach { (k, e) -> entAll.put(k, encodeEntitlement(e)) }
|
|
294
|
+
json.put("entitlementsAll", entAll)
|
|
295
|
+
val entActive = JSONObject()
|
|
296
|
+
ci.entitlements.active.forEach { (k, e) -> entActive.put(k, encodeEntitlement(e)) }
|
|
297
|
+
json.put("entitlementsActive", entActive)
|
|
298
|
+
return json.toString()
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
private fun encodeEntitlement(e: EntitlementInfo): JSONObject {
|
|
302
|
+
val o = JSONObject()
|
|
303
|
+
o.put("identifier", e.identifier)
|
|
304
|
+
o.put("isActive", e.isActive)
|
|
305
|
+
o.put("willRenew", e.willRenew)
|
|
306
|
+
o.put("productIdentifier", e.productIdentifier)
|
|
307
|
+
e.productPlanIdentifier?.let { o.put("productPlanIdentifier", it) }
|
|
308
|
+
e.latestPurchaseDate?.let { o.put("latestPurchaseDate", it.time) }
|
|
309
|
+
e.expirationDate?.let { o.put("expirationDate", it.time) }
|
|
310
|
+
e.unsubscribeDetectedAt?.let { o.put("unsubscribeDetectedAt", it.time) }
|
|
311
|
+
e.billingIssueDetectedAt?.let { o.put("billingIssueDetectedAt", it.time) }
|
|
312
|
+
o.put("isSandbox", e.isSandbox)
|
|
313
|
+
o.put("periodType", e.periodType.name)
|
|
314
|
+
o.put("store", e.store.name)
|
|
315
|
+
o.put("ownershipType", e.ownershipType.name)
|
|
316
|
+
return o
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private fun decode(text: String): CachedSnapshot? {
|
|
320
|
+
val json = JSONObject(text)
|
|
321
|
+
val fetchedAt = json.optLong("fetchedAt", 0L)
|
|
322
|
+
val originalAppUserId = json.optString("originalAppUserId", "")
|
|
323
|
+
val firstSeen = Date(json.optLong("firstSeen", 0L))
|
|
324
|
+
val requestDate = Date(json.optLong("requestDate", 0L))
|
|
325
|
+
val originalPurchaseDate = json.optLong("originalPurchaseDate", -1L).takeIf { it >= 0 }?.let(::Date)
|
|
326
|
+
val latestExpirationDate = json.optLong("latestExpirationDate", -1L).takeIf { it >= 0 }?.let(::Date)
|
|
327
|
+
val managementURL = json.optString("managementURL").takeIf { it.isNotEmpty() }
|
|
328
|
+
val activeSubscriptions = mutableSetOf<String>()
|
|
329
|
+
json.optJSONArray("activeSubscriptions")?.let { arr ->
|
|
330
|
+
for (i in 0 until arr.length()) activeSubscriptions.add(arr.optString(i))
|
|
331
|
+
}
|
|
332
|
+
val allPurchasedProductIds = mutableSetOf<String>()
|
|
333
|
+
json.optJSONArray("allPurchasedProductIds")?.let { arr ->
|
|
334
|
+
for (i in 0 until arr.length()) allPurchasedProductIds.add(arr.optString(i))
|
|
335
|
+
}
|
|
336
|
+
val allPurchaseDates = mutableMapOf<String, Date>()
|
|
337
|
+
json.optJSONObject("allPurchaseDates")?.let { obj ->
|
|
338
|
+
val keys = obj.keys()
|
|
339
|
+
while (keys.hasNext()) {
|
|
340
|
+
val k = keys.next()
|
|
341
|
+
allPurchaseDates[k] = Date(obj.optLong(k, 0L))
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
val entAll = mutableMapOf<String, EntitlementInfo>()
|
|
345
|
+
json.optJSONObject("entitlementsAll")?.let { obj ->
|
|
346
|
+
val keys = obj.keys()
|
|
347
|
+
while (keys.hasNext()) {
|
|
348
|
+
val k = keys.next()
|
|
349
|
+
val e = decodeEntitlement(obj.optJSONObject(k)!!)
|
|
350
|
+
entAll[k] = e
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
val entActive = mutableMapOf<String, EntitlementInfo>()
|
|
354
|
+
json.optJSONObject("entitlementsActive")?.let { obj ->
|
|
355
|
+
val keys = obj.keys()
|
|
356
|
+
while (keys.hasNext()) {
|
|
357
|
+
val k = keys.next()
|
|
358
|
+
val e = decodeEntitlement(obj.optJSONObject(k)!!)
|
|
359
|
+
entActive[k] = e
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
val infos = SimpleEntitlementInfos(entAll, entActive, VerificationResult.NOT_REQUESTED)
|
|
363
|
+
val ci = SimpleCustomerInfo(
|
|
364
|
+
entitlements = infos,
|
|
365
|
+
originalAppUserId = originalAppUserId,
|
|
366
|
+
firstSeen = firstSeen,
|
|
367
|
+
originalPurchaseDate = originalPurchaseDate,
|
|
368
|
+
latestExpirationDate = latestExpirationDate,
|
|
369
|
+
allPurchaseDates = allPurchaseDates,
|
|
370
|
+
activeSubscriptions = activeSubscriptions,
|
|
371
|
+
allPurchasedProductIds = allPurchasedProductIds,
|
|
372
|
+
managementURL = managementURL,
|
|
373
|
+
requestDate = requestDate,
|
|
374
|
+
)
|
|
375
|
+
return CachedSnapshot(ci, fetchedAt)
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private fun decodeEntitlement(o: JSONObject): EntitlementInfo {
|
|
379
|
+
return SimpleEntitlementInfo(
|
|
380
|
+
identifier = o.optString("identifier"),
|
|
381
|
+
isActive = o.optBoolean("isActive"),
|
|
382
|
+
willRenew = o.optBoolean("willRenew"),
|
|
383
|
+
productIdentifier = o.optString("productIdentifier"),
|
|
384
|
+
productPlanIdentifier = o.optString("productPlanIdentifier").takeIf { it.isNotEmpty() },
|
|
385
|
+
latestPurchaseDate = o.optLong("latestPurchaseDate", -1L).takeIf { it >= 0 }?.let(::Date),
|
|
386
|
+
expirationDate = o.optLong("expirationDate", -1L).takeIf { it >= 0 }?.let(::Date),
|
|
387
|
+
unsubscribeDetectedAt = o.optLong("unsubscribeDetectedAt", -1L).takeIf { it >= 0 }?.let(::Date),
|
|
388
|
+
billingIssueDetectedAt = o.optLong("billingIssueDetectedAt", -1L).takeIf { it >= 0 }?.let(::Date),
|
|
389
|
+
isSandbox = o.optBoolean("isSandbox"),
|
|
390
|
+
periodType = runCatching { PeriodType.valueOf(o.optString("periodType", "NORMAL")) }
|
|
391
|
+
.getOrDefault(PeriodType.NORMAL),
|
|
392
|
+
store = runCatching { Store.valueOf(o.optString("store", "PLAY_STORE").uppercase()) }
|
|
393
|
+
.getOrDefault(Store.PLAY_STORE),
|
|
394
|
+
ownershipType = runCatching { OwnershipType.valueOf(o.optString("ownershipType", "PURCHASED")) }
|
|
395
|
+
.getOrDefault(OwnershipType.PURCHASED),
|
|
396
|
+
)
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
private fun emptyCustomerInfo(userId: String): CustomerInfo = SimpleCustomerInfo(
|
|
400
|
+
entitlements = SimpleEntitlementInfos(emptyMap(), emptyMap(), VerificationResult.NOT_REQUESTED),
|
|
401
|
+
originalAppUserId = userId,
|
|
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 fun backendEntitlement(
|
|
413
|
+
identifier: String,
|
|
414
|
+
isActive: Boolean,
|
|
415
|
+
latestPurchaseDate: Date?,
|
|
416
|
+
expirationDate: Date?,
|
|
417
|
+
): EntitlementInfo = SimpleEntitlementInfo(
|
|
418
|
+
identifier = identifier,
|
|
419
|
+
isActive = isActive,
|
|
420
|
+
willRenew = true,
|
|
421
|
+
productIdentifier = "",
|
|
422
|
+
productPlanIdentifier = null,
|
|
423
|
+
latestPurchaseDate = latestPurchaseDate,
|
|
424
|
+
expirationDate = expirationDate,
|
|
425
|
+
unsubscribeDetectedAt = null,
|
|
426
|
+
billingIssueDetectedAt = null,
|
|
427
|
+
isSandbox = false,
|
|
428
|
+
periodType = PeriodType.NORMAL,
|
|
429
|
+
store = Store.PLAY_STORE,
|
|
430
|
+
ownershipType = OwnershipType.PURCHASED,
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
private fun backendCustomerInfo(
|
|
434
|
+
userId: String,
|
|
435
|
+
all: Map<String, EntitlementInfo>,
|
|
436
|
+
active: Map<String, EntitlementInfo>,
|
|
437
|
+
requestDate: Date,
|
|
438
|
+
): CustomerInfo = SimpleCustomerInfo(
|
|
439
|
+
entitlements = SimpleEntitlementInfos(all, active, VerificationResult.NOT_REQUESTED),
|
|
440
|
+
originalAppUserId = userId,
|
|
441
|
+
firstSeen = Date(),
|
|
442
|
+
originalPurchaseDate = null,
|
|
443
|
+
latestExpirationDate = null,
|
|
444
|
+
allPurchaseDates = emptyMap(),
|
|
445
|
+
activeSubscriptions = emptySet(),
|
|
446
|
+
allPurchasedProductIds = emptySet(),
|
|
447
|
+
managementURL = null,
|
|
448
|
+
requestDate = requestDate,
|
|
449
|
+
)
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Immutable on-disk snapshot wrapper. */
|
|
454
|
+
internal data class CachedSnapshot(
|
|
455
|
+
val customerInfo: CustomerInfo,
|
|
456
|
+
/** Wall-clock millis at fetch time - used for 24h grace check. */
|
|
457
|
+
val fetchedAt: Long,
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
/** Concrete CustomerInfo backed by plain data fields. Public so the gateway
|
|
461
|
+
* and tests can build instances without touching the interface directly. */
|
|
462
|
+
data class SimpleCustomerInfo(
|
|
463
|
+
override val entitlements: EntitlementInfos,
|
|
464
|
+
override val originalAppUserId: String,
|
|
465
|
+
override val firstSeen: Date,
|
|
466
|
+
override val originalPurchaseDate: Date?,
|
|
467
|
+
override val latestExpirationDate: Date?,
|
|
468
|
+
override val allPurchaseDates: Map<String, Date>,
|
|
469
|
+
override val activeSubscriptions: Set<String>,
|
|
470
|
+
override val allPurchasedProductIds: Set<String>,
|
|
471
|
+
override val managementURL: String?,
|
|
472
|
+
override val requestDate: Date,
|
|
473
|
+
) : CustomerInfo
|
|
474
|
+
|
|
475
|
+
data class SimpleEntitlementInfos(
|
|
476
|
+
override val all: Map<String, EntitlementInfo>,
|
|
477
|
+
override val active: Map<String, EntitlementInfo>,
|
|
478
|
+
override val verification: VerificationResult,
|
|
479
|
+
) : EntitlementInfos
|
|
480
|
+
|
|
481
|
+
data class SimpleEntitlementInfo(
|
|
482
|
+
override val identifier: String,
|
|
483
|
+
override val isActive: Boolean,
|
|
484
|
+
override val willRenew: Boolean,
|
|
485
|
+
override val latestPurchaseDate: Date?,
|
|
486
|
+
override val expirationDate: Date?,
|
|
487
|
+
override val productIdentifier: String,
|
|
488
|
+
override val productPlanIdentifier: String?,
|
|
489
|
+
override val isSandbox: Boolean,
|
|
490
|
+
override val unsubscribeDetectedAt: Date?,
|
|
491
|
+
override val billingIssueDetectedAt: Date?,
|
|
492
|
+
override val periodType: PeriodType,
|
|
493
|
+
override val store: Store,
|
|
494
|
+
override val ownershipType: OwnershipType,
|
|
495
|
+
) : EntitlementInfo
|