@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,204 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/attributes/SetAttributesWorker.kt
|
|
2
|
+
//
|
|
3
|
+
// CoroutineWorker that POSTs a single user-attributes payload to our backend.
|
|
4
|
+
// Parallel in shape to [com.appswissknife.analytics.FlushEventsWorker]:
|
|
5
|
+
// - Same exponential-back-off policy (BackoffPolicy.EXPONENTIAL, 1s base).
|
|
6
|
+
// - Same 5-attempt cap via runAttemptCount (0-indexed; DLQ on the 5th).
|
|
7
|
+
// - Same error-class semantics:
|
|
8
|
+
// 2xx → success
|
|
9
|
+
// 4xx (not 429) → dead-letter immediately, no retry
|
|
10
|
+
// 429 → retry, surface Retry-After in output
|
|
11
|
+
// 5xx / IOException → retry until cap, then DLQ
|
|
12
|
+
//
|
|
13
|
+
// Differences vs FlushEventsWorker:
|
|
14
|
+
// - The payload IS the input Data — no disk queue. Attributes are
|
|
15
|
+
// infrequent (a handful per session) so WM's own SQLite-backed queue is
|
|
16
|
+
// enough persistence. We don't need an EventQueueStore equivalent.
|
|
17
|
+
// - Dead-letter means "drop the payload + log a warning". There is no
|
|
18
|
+
// separate DLQ file (same policy as FlushEventsWorker).
|
|
19
|
+
|
|
20
|
+
package com.appswissknife.attributes
|
|
21
|
+
|
|
22
|
+
import android.content.Context
|
|
23
|
+
import android.util.Log
|
|
24
|
+
import androidx.annotation.VisibleForTesting
|
|
25
|
+
import androidx.work.CoroutineWorker
|
|
26
|
+
import androidx.work.Data
|
|
27
|
+
import androidx.work.WorkerParameters
|
|
28
|
+
import java.io.IOException
|
|
29
|
+
import java.net.URL
|
|
30
|
+
|
|
31
|
+
internal class SetAttributesWorker(
|
|
32
|
+
appContext: Context,
|
|
33
|
+
params: WorkerParameters,
|
|
34
|
+
) : CoroutineWorker(appContext, params) {
|
|
35
|
+
|
|
36
|
+
companion object {
|
|
37
|
+
const val TAG = "SwissKnife.SetAttrsWorker"
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* After this many attempts (including the original), give up and DLQ.
|
|
41
|
+
* Counts against [androidx.work.ListenableWorker.getRunAttemptCount]
|
|
42
|
+
* (0-indexed: first run = 0, first retry = 1, ...).
|
|
43
|
+
*/
|
|
44
|
+
const val MAX_ATTEMPTS = 5
|
|
45
|
+
|
|
46
|
+
const val KEY_API_KEY = "api_key"
|
|
47
|
+
const val KEY_SERVER_URL = "server_url"
|
|
48
|
+
const val KEY_BODY = "body"
|
|
49
|
+
|
|
50
|
+
// Output keys mirror FlushEventsWorker so external observers can
|
|
51
|
+
// process both pipelines uniformly.
|
|
52
|
+
const val OUTPUT_HTTP_STATUS = "http_status"
|
|
53
|
+
const val OUTPUT_RETRY_AFTER_SECONDS = "retry_after_seconds"
|
|
54
|
+
const val OUTPUT_DEAD_LETTERED = "dead_lettered"
|
|
55
|
+
|
|
56
|
+
private const val DEFAULT_BASE_URL = "https://api.swiss-knife.dev"
|
|
57
|
+
private const val ENDPOINT_PATH = "/api/sdk/users/attributes"
|
|
58
|
+
|
|
59
|
+
fun buildInput(apiKey: String, serverURL: String, body: String): Data =
|
|
60
|
+
Data.Builder()
|
|
61
|
+
.putString(KEY_API_KEY, apiKey)
|
|
62
|
+
.putString(KEY_SERVER_URL, serverURL)
|
|
63
|
+
.putString(KEY_BODY, body)
|
|
64
|
+
.build()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
@VisibleForTesting
|
|
68
|
+
internal var httpClient: HttpClient = UrlConnectionHttpClient()
|
|
69
|
+
|
|
70
|
+
override suspend fun doWork(): Result {
|
|
71
|
+
val apiKey = inputData.getString(KEY_API_KEY).orEmpty()
|
|
72
|
+
val serverURL = inputData.getString(KEY_SERVER_URL).orEmpty()
|
|
73
|
+
val body = inputData.getString(KEY_BODY).orEmpty()
|
|
74
|
+
if (apiKey.isEmpty()) {
|
|
75
|
+
Log.w(TAG, "missing api_key input; skipping setAttributes")
|
|
76
|
+
return Result.success()
|
|
77
|
+
}
|
|
78
|
+
if (body.isEmpty()) {
|
|
79
|
+
Log.w(TAG, "missing body input; nothing to send")
|
|
80
|
+
return Result.success()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
val baseURL = serverURL.ifEmpty { DEFAULT_BASE_URL }
|
|
84
|
+
val endpoint = URL(baseURL.trimEnd('/') + ENDPOINT_PATH)
|
|
85
|
+
|
|
86
|
+
val response = try {
|
|
87
|
+
httpClient.post(endpoint, apiKey, body)
|
|
88
|
+
} catch (e: IOException) {
|
|
89
|
+
return retryOrDeadLetter(
|
|
90
|
+
reason = "network error: ${e.message}",
|
|
91
|
+
httpStatus = null,
|
|
92
|
+
retryAfterSeconds = null,
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return handleResponse(response)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private fun handleResponse(response: HttpResponse): Result {
|
|
100
|
+
val code = response.code
|
|
101
|
+
return when {
|
|
102
|
+
code in 200..299 -> {
|
|
103
|
+
Result.success(
|
|
104
|
+
Data.Builder().putInt(OUTPUT_HTTP_STATUS, code).build()
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
code == 429 -> {
|
|
108
|
+
val retryAfter = response.retryAfterSeconds
|
|
109
|
+
if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
|
|
110
|
+
deadLetter("429 after $MAX_ATTEMPTS attempts")
|
|
111
|
+
Result.success(
|
|
112
|
+
Data.Builder()
|
|
113
|
+
.putInt(OUTPUT_HTTP_STATUS, code)
|
|
114
|
+
.putBoolean(OUTPUT_DEAD_LETTERED, true)
|
|
115
|
+
.apply { if (retryAfter != null) putLong(OUTPUT_RETRY_AFTER_SECONDS, retryAfter) }
|
|
116
|
+
.build()
|
|
117
|
+
)
|
|
118
|
+
} else {
|
|
119
|
+
Result.retry()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
code in 400..499 -> {
|
|
123
|
+
// 4xx (not 429) → permanent rejection (bad payload, invalid
|
|
124
|
+
// reserved key, missing auth). Retrying won't change the bytes
|
|
125
|
+
// we're sending; DLQ immediately.
|
|
126
|
+
deadLetter("client error $code")
|
|
127
|
+
Result.success(
|
|
128
|
+
Data.Builder()
|
|
129
|
+
.putInt(OUTPUT_HTTP_STATUS, code)
|
|
130
|
+
.putBoolean(OUTPUT_DEAD_LETTERED, true)
|
|
131
|
+
.build()
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
else -> {
|
|
135
|
+
retryOrDeadLetter(
|
|
136
|
+
reason = "server error $code",
|
|
137
|
+
httpStatus = code,
|
|
138
|
+
retryAfterSeconds = response.retryAfterSeconds,
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private fun retryOrDeadLetter(
|
|
145
|
+
reason: String,
|
|
146
|
+
httpStatus: Int?,
|
|
147
|
+
retryAfterSeconds: Long?,
|
|
148
|
+
): Result {
|
|
149
|
+
return if (runAttemptCount + 1 >= MAX_ATTEMPTS) {
|
|
150
|
+
deadLetter("$reason after $MAX_ATTEMPTS attempts")
|
|
151
|
+
Result.success(
|
|
152
|
+
Data.Builder()
|
|
153
|
+
.apply {
|
|
154
|
+
if (httpStatus != null) putInt(OUTPUT_HTTP_STATUS, httpStatus)
|
|
155
|
+
if (retryAfterSeconds != null) putLong(OUTPUT_RETRY_AFTER_SECONDS, retryAfterSeconds)
|
|
156
|
+
putBoolean(OUTPUT_DEAD_LETTERED, true)
|
|
157
|
+
}
|
|
158
|
+
.build()
|
|
159
|
+
)
|
|
160
|
+
} else {
|
|
161
|
+
Log.w(TAG, "setAttributes attempt ${runAttemptCount + 1}/$MAX_ATTEMPTS failed ($reason); retrying")
|
|
162
|
+
Result.retry()
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private fun deadLetter(reason: String) {
|
|
167
|
+
Log.w(TAG, "dead-lettering setAttributes payload; reason=$reason")
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Minimal HTTP abstraction so tests can inject a fake without spinning a
|
|
172
|
+
* MockWebServer for every branch. MockWebServer is still used in the
|
|
173
|
+
* higher-level integration test for AttributesClient.
|
|
174
|
+
*/
|
|
175
|
+
@VisibleForTesting
|
|
176
|
+
internal interface HttpClient {
|
|
177
|
+
fun post(url: URL, apiKey: String, body: String): HttpResponse
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
@VisibleForTesting
|
|
181
|
+
internal data class HttpResponse(
|
|
182
|
+
val code: Int,
|
|
183
|
+
val retryAfterSeconds: Long? = null,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Round-D default — delegates to the unified [com.appswissknife.net.BackendHttpClient]
|
|
188
|
+
* transport. The worker keeps owning the retry policy (runAttemptCount
|
|
189
|
+
* + WM backoff) so we call the transport-level helper at zero retries
|
|
190
|
+
* to avoid double-counting.
|
|
191
|
+
*/
|
|
192
|
+
private class UrlConnectionHttpClient : HttpClient {
|
|
193
|
+
override fun post(url: URL, apiKey: String, body: String): HttpResponse {
|
|
194
|
+
// Reconstruct (baseUrl, path) from the URL the caller built and
|
|
195
|
+
// route through the unified BackendHttpClient transport. The
|
|
196
|
+
// worker still owns retries — `simplePost` doesn't retry.
|
|
197
|
+
val baseUrl = "${url.protocol}://${url.authority}"
|
|
198
|
+
val path = url.path + (url.query?.let { "?$it" } ?: "")
|
|
199
|
+
val client = com.appswissknife.net.BackendHttpClient.create(apiKey, baseUrl)
|
|
200
|
+
val r = client.simplePost(path = path, body = body)
|
|
201
|
+
return HttpResponse(code = r.code, retryAfterSeconds = r.retryAfterSeconds)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/attribution/Attribution.kt
|
|
2
|
+
//
|
|
3
|
+
// Wave 2 of the SDK architectural audit — Attribution module on Android.
|
|
4
|
+
// Mirror of `SwissKnife.Attribution` in packages/swiss-knife-ios/. Closes
|
|
5
|
+
// the same capability gap: the backend's `/api/sdk/attribution/install`
|
|
6
|
+
// route was wired but had ZERO callers from the SDK, so every Android
|
|
7
|
+
// install resolved as `attribution_method = "organic"`.
|
|
8
|
+
//
|
|
9
|
+
// Public surface (Configuration / ResolvedAttribution / collectAndRegister
|
|
10
|
+
// / registerInstall) is intentionally close to the iOS module to keep
|
|
11
|
+
// the cross-platform mental model consistent. Implementation differs
|
|
12
|
+
// where Android idioms require it:
|
|
13
|
+
//
|
|
14
|
+
// - **No ATT** on Android — `Configuration.autoPromptATT` is iOS-only
|
|
15
|
+
// parity and a no-op here. The Play Store equivalent (Google Play
|
|
16
|
+
// "Advertising ID" being readable) is governed by Play Services
|
|
17
|
+
// consent and the user's device settings, NOT a runtime prompt
|
|
18
|
+
// the SDK initiates.
|
|
19
|
+
// - **AdvertisingIdClient + InstallReferrerClient are pluggable
|
|
20
|
+
// seams.** This keeps the Wave 2 commit transitive-dependency
|
|
21
|
+
// free (no `play-services-ads-identifier` / `installreferrer`
|
|
22
|
+
// hard requirements; hosts that ship those libraries inject a
|
|
23
|
+
// real implementation via `Attribution.setCollectorsForTesting`
|
|
24
|
+
// in tests, and a production wire-up via `setProductionCollectors`).
|
|
25
|
+
// Apps that DO have the libs can call `registerInstall(...)`
|
|
26
|
+
// directly with whatever IDs they collected — same shape as iOS's
|
|
27
|
+
// manual path.
|
|
28
|
+
// - **Persistence via EncryptedSharedPreferences** (already used by
|
|
29
|
+
// DeviceID and AttributesClient — reusing the same prefs file
|
|
30
|
+
// keeps the threat model coherent). Key `attribution_resolved`
|
|
31
|
+
// stores the JSON-encoded ResolvedAttribution.
|
|
32
|
+
//
|
|
33
|
+
// Thread safety: state mutation goes through a single `Any` lock and a
|
|
34
|
+
// dedicated single-thread executor for the POST so callers don't
|
|
35
|
+
// experience NetworkOnMainThreadException.
|
|
36
|
+
|
|
37
|
+
package com.appswissknife.attribution
|
|
38
|
+
|
|
39
|
+
import android.content.Context
|
|
40
|
+
import android.content.SharedPreferences
|
|
41
|
+
import androidx.annotation.VisibleForTesting
|
|
42
|
+
import com.appswissknife.SwissKnife
|
|
43
|
+
import com.appswissknife.identity.Identity
|
|
44
|
+
import com.appswissknife.models.PurchasesError
|
|
45
|
+
import com.appswissknife.net.BackendHttpClientAdapter
|
|
46
|
+
import com.appswissknife.purchases.BillingHttpClient
|
|
47
|
+
import org.json.JSONObject
|
|
48
|
+
import java.io.IOException
|
|
49
|
+
import java.text.SimpleDateFormat
|
|
50
|
+
import java.util.Date
|
|
51
|
+
import java.util.Locale
|
|
52
|
+
import java.util.TimeZone
|
|
53
|
+
import java.util.concurrent.ExecutorService
|
|
54
|
+
import java.util.concurrent.Executors
|
|
55
|
+
|
|
56
|
+
object Attribution {
|
|
57
|
+
|
|
58
|
+
/** Configuration captured at `SwissKnife.configure(...)` time. */
|
|
59
|
+
data class Configuration(
|
|
60
|
+
/**
|
|
61
|
+
* iOS parity field — a no-op on Android because the runtime
|
|
62
|
+
* advertising-ID consent model is the device's, not the SDK's.
|
|
63
|
+
* Hosts that want their own consent prompt can simply skip the
|
|
64
|
+
* SDK's auto-collect by setting `sendInstallOnFirstLaunch=false`
|
|
65
|
+
* and calling `registerInstall(...)` explicitly.
|
|
66
|
+
*/
|
|
67
|
+
val autoPromptATT: Boolean = true,
|
|
68
|
+
/** Pull advertising_id via the injected collector. */
|
|
69
|
+
val collectAdvertisingId: Boolean = true,
|
|
70
|
+
/** Pull install_referrer via the injected collector. */
|
|
71
|
+
val collectInstallReferrer: Boolean = true,
|
|
72
|
+
/** Run the install POST automatically on first launch. */
|
|
73
|
+
val sendInstallOnFirstLaunch: Boolean = true,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
/** Resolved attribution from the backend. JSON-encoded under
|
|
77
|
+
* `attribution_resolved` in EncryptedSharedPreferences. */
|
|
78
|
+
data class ResolvedAttribution(
|
|
79
|
+
val method: String,
|
|
80
|
+
val campaignId: String?,
|
|
81
|
+
val resolvedAt: Long,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
// ---- Internal state ----------------------------------------------------
|
|
85
|
+
|
|
86
|
+
private val lock = Any()
|
|
87
|
+
|
|
88
|
+
@Volatile private var appContext: Context? = null
|
|
89
|
+
@Volatile private var serverUrl: String = ""
|
|
90
|
+
@Volatile private var apiKey: String = ""
|
|
91
|
+
@Volatile private var configuration: Configuration = Configuration()
|
|
92
|
+
@Volatile private var cached: ResolvedAttribution? = null
|
|
93
|
+
@Volatile private var prefs: SharedPreferences? = null
|
|
94
|
+
|
|
95
|
+
/** Pluggable HTTP client. Tests inject a MockWebServer-fronted fake. */
|
|
96
|
+
@Volatile
|
|
97
|
+
@VisibleForTesting
|
|
98
|
+
internal var httpClient: BillingHttpClient = BackendHttpClientAdapter()
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* AdvertisingId collector. The production wire-up uses
|
|
102
|
+
* `AdvertisingIdClient` from `play-services-ads-identifier`, but
|
|
103
|
+
* this Wave-2 commit ships with a no-op default so the SDK does
|
|
104
|
+
* not impose a transitive on every consumer. Hosts that want the
|
|
105
|
+
* collector enable it via `setProductionCollectors(...)` or supply
|
|
106
|
+
* their own via the same setter.
|
|
107
|
+
*/
|
|
108
|
+
@Volatile
|
|
109
|
+
@VisibleForTesting
|
|
110
|
+
internal var advertisingIdCollector: AdvertisingIdCollector = NoopAdvertisingIdCollector()
|
|
111
|
+
|
|
112
|
+
/** Install referrer collector — same rationale as the IDFA one. */
|
|
113
|
+
@Volatile
|
|
114
|
+
@VisibleForTesting
|
|
115
|
+
internal var installReferrerCollector: InstallReferrerCollector = NoopInstallReferrerCollector()
|
|
116
|
+
|
|
117
|
+
private val executor: ExecutorService = Executors.newSingleThreadExecutor { r ->
|
|
118
|
+
Thread(r, "swissknife-attribution").apply { isDaemon = true }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ---- Public surface ----------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/** Latest resolved attribution. Null if no install POST has succeeded. */
|
|
124
|
+
fun resolved(): ResolvedAttribution? {
|
|
125
|
+
loadFromDiskIfNeeded()
|
|
126
|
+
return cached
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Auto-collect (advertising_id + install_referrer via the injected
|
|
131
|
+
* collectors) and POST `/api/sdk/attribution/install`. Idempotent —
|
|
132
|
+
* second call returns the cached value WITHOUT a second POST.
|
|
133
|
+
*
|
|
134
|
+
* Callbacks fire on the executor thread; hosts that need main-
|
|
135
|
+
* thread delivery wrap with `Handler(Looper.getMainLooper()).post`.
|
|
136
|
+
*/
|
|
137
|
+
fun collectAndRegister(
|
|
138
|
+
context: Context,
|
|
139
|
+
onSuccess: (ResolvedAttribution?) -> Unit,
|
|
140
|
+
onError: (PurchasesError) -> Unit,
|
|
141
|
+
) {
|
|
142
|
+
loadFromDiskIfNeeded()
|
|
143
|
+
cached?.let { onSuccess(it); return }
|
|
144
|
+
val ctx = context.applicationContext
|
|
145
|
+
executor.execute {
|
|
146
|
+
val advId = if (configuration.collectAdvertisingId) {
|
|
147
|
+
runCatching { advertisingIdCollector.get(ctx) }.getOrNull()
|
|
148
|
+
} else null
|
|
149
|
+
val referrer = if (configuration.collectInstallReferrer) {
|
|
150
|
+
runCatching { installReferrerCollector.get(ctx) }.getOrNull()
|
|
151
|
+
} else null
|
|
152
|
+
try {
|
|
153
|
+
val result = postInstall(advertisingId = advId, referrer = referrer)
|
|
154
|
+
onSuccess(result)
|
|
155
|
+
} catch (e: Throwable) {
|
|
156
|
+
onError(toPurchasesError(e))
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Manual install registration. Hosts that prompt for advertising-ID
|
|
163
|
+
* consent themselves, or collect a referrer outside the SDK, call
|
|
164
|
+
* this directly with whatever they captured. Idempotent.
|
|
165
|
+
*/
|
|
166
|
+
fun registerInstall(
|
|
167
|
+
advertisingId: String? = null,
|
|
168
|
+
referrer: String? = null,
|
|
169
|
+
onSuccess: (ResolvedAttribution?) -> Unit,
|
|
170
|
+
onError: (PurchasesError) -> Unit,
|
|
171
|
+
) {
|
|
172
|
+
loadFromDiskIfNeeded()
|
|
173
|
+
cached?.let { onSuccess(it); return }
|
|
174
|
+
executor.execute {
|
|
175
|
+
try {
|
|
176
|
+
val result = postInstall(advertisingId = advertisingId, referrer = referrer)
|
|
177
|
+
onSuccess(result)
|
|
178
|
+
} catch (e: Throwable) {
|
|
179
|
+
onError(toPurchasesError(e))
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ---- Internal: SwissKnife wiring ---------------------------------------
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Called by `SwissKnife.configure(...)` to snapshot the configuration
|
|
188
|
+
* and (when `sendInstallOnFirstLaunch=true`) kick off a background
|
|
189
|
+
* install registration. Fire-and-forget.
|
|
190
|
+
*/
|
|
191
|
+
internal fun configure(
|
|
192
|
+
context: Context,
|
|
193
|
+
serverUrl: String,
|
|
194
|
+
apiKey: String,
|
|
195
|
+
configuration: Configuration,
|
|
196
|
+
) {
|
|
197
|
+
synchronized(lock) {
|
|
198
|
+
this.appContext = context.applicationContext
|
|
199
|
+
this.serverUrl = serverUrl.trimEnd('/')
|
|
200
|
+
this.apiKey = apiKey
|
|
201
|
+
this.configuration = configuration
|
|
202
|
+
this.prefs = openPrefs(context.applicationContext)
|
|
203
|
+
}
|
|
204
|
+
if (configuration.sendInstallOnFirstLaunch) {
|
|
205
|
+
collectAndRegister(
|
|
206
|
+
context = context.applicationContext,
|
|
207
|
+
onSuccess = { /* cached, log-less */ },
|
|
208
|
+
onError = { /* best-effort */ },
|
|
209
|
+
)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---- Internal: HTTP + persistence --------------------------------------
|
|
214
|
+
|
|
215
|
+
private fun postInstall(
|
|
216
|
+
advertisingId: String?,
|
|
217
|
+
referrer: String?,
|
|
218
|
+
): ResolvedAttribution? {
|
|
219
|
+
val ctx = appContext ?: return null
|
|
220
|
+
if (apiKey.isEmpty()) return null
|
|
221
|
+
val identity = Identity.current()
|
|
222
|
+
val anonymousId = identity.anonymousId
|
|
223
|
+
// For an anonymous user, user_id falls back to the anonymous_id
|
|
224
|
+
// since the backend's appUsers row keys off `externalUserId`.
|
|
225
|
+
val userId = identity.userId ?: anonymousId
|
|
226
|
+
|
|
227
|
+
val bodyJson = JSONObject().apply {
|
|
228
|
+
put("user_id", userId)
|
|
229
|
+
put("anonymous_id", anonymousId)
|
|
230
|
+
if (advertisingId != null && advertisingId.isNotEmpty()) {
|
|
231
|
+
put("advertising_id", advertisingId)
|
|
232
|
+
}
|
|
233
|
+
if (referrer != null && referrer.isNotEmpty()) {
|
|
234
|
+
put("referrer", referrer)
|
|
235
|
+
}
|
|
236
|
+
put("user_agent", buildUserAgent(ctx))
|
|
237
|
+
put("installed_at", isoNow())
|
|
238
|
+
}
|
|
239
|
+
val body = bodyJson.toString()
|
|
240
|
+
val headers = mapOf(
|
|
241
|
+
"Content-Type" to "application/json",
|
|
242
|
+
"X-API-Key" to apiKey,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
// Round-D: when BackendHttpClient.shared is wired (SwissKnife.configure
|
|
246
|
+
// path), use it so attribution shares the unified retry policy.
|
|
247
|
+
// The test seam (`httpClient`) takes precedence so AttributionTest's
|
|
248
|
+
// MockWebServer-injected client still works.
|
|
249
|
+
val backend = try { com.appswissknife.net.BackendHttpClient.shared } catch (_: Throwable) { null }
|
|
250
|
+
if (backend != null && httpClient is BackendHttpClientAdapter) {
|
|
251
|
+
try {
|
|
252
|
+
val responseBody = backend.postRaw(
|
|
253
|
+
path = "/api/sdk/attribution/install",
|
|
254
|
+
body = body,
|
|
255
|
+
maxRetries = 1,
|
|
256
|
+
)
|
|
257
|
+
val resolved = decodeResolved(responseBody) ?: return null
|
|
258
|
+
persist(resolved)
|
|
259
|
+
return resolved
|
|
260
|
+
} catch (e: com.appswissknife.net.BackendRejected) {
|
|
261
|
+
throw IOException(e.serverMessage ?: "attribution rejected (${e.code})", e)
|
|
262
|
+
} catch (e: com.appswissknife.net.BackendUnavailable) {
|
|
263
|
+
throw IOException(e.serverMessage ?: "attribution unavailable (${e.code})", e)
|
|
264
|
+
} catch (_: com.appswissknife.net.BackendNotConfigured) {
|
|
265
|
+
// shared not configured — fall through to httpClient seam.
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Legacy path for callers without a configured BackendHttpClient
|
|
270
|
+
// (test fakes, pre-configure flows). One inline retry on transient
|
|
271
|
+
// IO. Mirrors Identity's policy.
|
|
272
|
+
var attempt = 0
|
|
273
|
+
var lastError: Throwable? = null
|
|
274
|
+
while (attempt < 2) {
|
|
275
|
+
try {
|
|
276
|
+
val responseBody = httpClient.post(
|
|
277
|
+
url = "$serverUrl/api/sdk/attribution/install",
|
|
278
|
+
body = body,
|
|
279
|
+
headers = headers,
|
|
280
|
+
)
|
|
281
|
+
val resolved = decodeResolved(responseBody) ?: return null
|
|
282
|
+
persist(resolved)
|
|
283
|
+
return resolved
|
|
284
|
+
} catch (e: IOException) {
|
|
285
|
+
lastError = e
|
|
286
|
+
attempt += 1
|
|
287
|
+
if (attempt < 2) {
|
|
288
|
+
try { Thread.sleep(1_000) }
|
|
289
|
+
catch (_: InterruptedException) {
|
|
290
|
+
Thread.currentThread().interrupt()
|
|
291
|
+
throw e
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
throw IOException(lastError?.message ?: "attribution failed", lastError)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private fun decodeResolved(body: String): ResolvedAttribution? {
|
|
300
|
+
return try {
|
|
301
|
+
val json = JSONObject(body)
|
|
302
|
+
val method = json.optString("attribution_method", "organic")
|
|
303
|
+
val campaignId = if (json.isNull("campaign_id") || !json.has("campaign_id")) null
|
|
304
|
+
else json.optString("campaign_id").takeIf { it.isNotEmpty() }
|
|
305
|
+
ResolvedAttribution(
|
|
306
|
+
method = method,
|
|
307
|
+
campaignId = campaignId,
|
|
308
|
+
resolvedAt = System.currentTimeMillis(),
|
|
309
|
+
)
|
|
310
|
+
} catch (_: Throwable) {
|
|
311
|
+
null
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private fun persist(resolution: ResolvedAttribution) {
|
|
316
|
+
val payload = JSONObject().apply {
|
|
317
|
+
put("method", resolution.method)
|
|
318
|
+
put("campaignId", resolution.campaignId ?: JSONObject.NULL)
|
|
319
|
+
put("resolvedAt", resolution.resolvedAt)
|
|
320
|
+
}.toString()
|
|
321
|
+
synchronized(lock) {
|
|
322
|
+
cached = resolution
|
|
323
|
+
prefs?.edit()?.putString(KEY_RESOLVED, payload)?.apply()
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private fun loadFromDiskIfNeeded() {
|
|
328
|
+
if (cached != null) return
|
|
329
|
+
val p = prefs ?: return
|
|
330
|
+
val raw = p.getString(KEY_RESOLVED, null) ?: return
|
|
331
|
+
synchronized(lock) {
|
|
332
|
+
if (cached != null) return
|
|
333
|
+
try {
|
|
334
|
+
val json = JSONObject(raw)
|
|
335
|
+
cached = ResolvedAttribution(
|
|
336
|
+
method = json.optString("method", "organic"),
|
|
337
|
+
campaignId = if (json.isNull("campaignId") || !json.has("campaignId")) null
|
|
338
|
+
else json.optString("campaignId").takeIf { it.isNotEmpty() },
|
|
339
|
+
resolvedAt = json.optLong("resolvedAt", System.currentTimeMillis()),
|
|
340
|
+
)
|
|
341
|
+
} catch (_: Throwable) {
|
|
342
|
+
p.edit().remove(KEY_RESOLVED).apply()
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ---- Test seams --------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
@VisibleForTesting
|
|
350
|
+
internal fun _resetForTesting() {
|
|
351
|
+
synchronized(lock) {
|
|
352
|
+
cached = null
|
|
353
|
+
appContext = null
|
|
354
|
+
serverUrl = ""
|
|
355
|
+
apiKey = ""
|
|
356
|
+
configuration = Configuration()
|
|
357
|
+
prefs = null
|
|
358
|
+
httpClient = BackendHttpClientAdapter()
|
|
359
|
+
advertisingIdCollector = NoopAdvertisingIdCollector()
|
|
360
|
+
installReferrerCollector = NoopInstallReferrerCollector()
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
@VisibleForTesting
|
|
365
|
+
internal fun _setHttpClientForTesting(client: BillingHttpClient) {
|
|
366
|
+
httpClient = client
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
@VisibleForTesting
|
|
370
|
+
internal fun _setCollectorsForTesting(
|
|
371
|
+
adv: AdvertisingIdCollector,
|
|
372
|
+
referrer: InstallReferrerCollector,
|
|
373
|
+
) {
|
|
374
|
+
advertisingIdCollector = adv
|
|
375
|
+
installReferrerCollector = referrer
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
@VisibleForTesting
|
|
379
|
+
internal fun _awaitForTesting() {
|
|
380
|
+
executor.submit {}.get()
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ---- Helpers -----------------------------------------------------------
|
|
384
|
+
|
|
385
|
+
private fun openPrefs(ctx: Context): SharedPreferences {
|
|
386
|
+
// Reuse the same EncryptedSharedPreferences file as
|
|
387
|
+
// AttributesClient/DeviceID — keeps the threat model coherent.
|
|
388
|
+
// Failure path falls back to plain prefs so the SDK keeps working
|
|
389
|
+
// on devices where Tink/KeyStore init fails.
|
|
390
|
+
return try {
|
|
391
|
+
val masterKey = androidx.security.crypto.MasterKey.Builder(ctx)
|
|
392
|
+
.setKeyScheme(androidx.security.crypto.MasterKey.KeyScheme.AES256_GCM)
|
|
393
|
+
.build()
|
|
394
|
+
androidx.security.crypto.EncryptedSharedPreferences.create(
|
|
395
|
+
ctx,
|
|
396
|
+
PREFS_FILE,
|
|
397
|
+
masterKey,
|
|
398
|
+
androidx.security.crypto.EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
|
399
|
+
androidx.security.crypto.EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
|
|
400
|
+
)
|
|
401
|
+
} catch (_: Throwable) {
|
|
402
|
+
ctx.getSharedPreferences("${PREFS_FILE}_fallback", Context.MODE_PRIVATE)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private fun isoNow(): String {
|
|
407
|
+
val fmt = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
|
408
|
+
fmt.timeZone = TimeZone.getTimeZone("UTC")
|
|
409
|
+
return fmt.format(Date())
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
private fun buildUserAgent(ctx: Context): String {
|
|
413
|
+
val pkg = ctx.packageName
|
|
414
|
+
val version = runCatching {
|
|
415
|
+
ctx.packageManager.getPackageInfo(pkg, 0).versionName ?: "?"
|
|
416
|
+
}.getOrElse { "?" }
|
|
417
|
+
return "$pkg/$version (Android)"
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private fun toPurchasesError(t: Throwable): PurchasesError = when (t) {
|
|
421
|
+
is PurchasesError -> t
|
|
422
|
+
is IOException -> PurchasesError.NetworkError(t.message ?: "Network error", t)
|
|
423
|
+
else -> PurchasesError.Unknown(t.message ?: "Unknown error", t)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private const val PREFS_FILE = "com.appswissknife.attribution.v1"
|
|
427
|
+
private const val KEY_RESOLVED = "attribution_resolved"
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Pluggable advertising_id source. Default impl returns null so the
|
|
431
|
+
* SDK does not impose a GMS transitive on every consumer. */
|
|
432
|
+
interface AdvertisingIdCollector {
|
|
433
|
+
fun get(context: Context): String?
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
internal class NoopAdvertisingIdCollector : AdvertisingIdCollector {
|
|
437
|
+
override fun get(context: Context): String? = null
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Pluggable install_referrer source. Default impl returns null. */
|
|
441
|
+
interface InstallReferrerCollector {
|
|
442
|
+
fun get(context: Context): String?
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
internal class NoopInstallReferrerCollector : InstallReferrerCollector {
|
|
446
|
+
override fun get(context: Context): String? = null
|
|
447
|
+
}
|