@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,80 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/models/Offerings.kt
|
|
2
|
+
//
|
|
3
|
+
// Phase 6 — own offerings / package / product types. Replaces PHC's
|
|
4
|
+
// `com.revenuecat.purchases.Offerings`/`Offering`/`Package` and
|
|
5
|
+
// `com.revenuecat.purchases.models.StoreProduct`/`Price`.
|
|
6
|
+
//
|
|
7
|
+
// Interfaces, not data classes, so the parity tests can keep mock()-ing them
|
|
8
|
+
// without standing up a full BillingClient ProductDetails graph.
|
|
9
|
+
package com.appswissknife.models
|
|
10
|
+
|
|
11
|
+
/** All available [Offering]s keyed by identifier; [current] is the one most apps render. */
|
|
12
|
+
interface Offerings {
|
|
13
|
+
val all: Map<String, Offering>
|
|
14
|
+
val current: Offering?
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A named bundle of [Package]s — typically corresponds to a paywall variant. */
|
|
18
|
+
interface Offering {
|
|
19
|
+
val identifier: String
|
|
20
|
+
val serverDescription: String
|
|
21
|
+
/** Free-form server-side JSON metadata for custom paywall logic. */
|
|
22
|
+
val metadata: Map<String, Any?>
|
|
23
|
+
val availablePackages: List<Package>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A purchasable unit inside an [Offering]: a [StoreProduct] plus a typed bucket. */
|
|
27
|
+
interface Package {
|
|
28
|
+
val identifier: String
|
|
29
|
+
val packageType: PackageType
|
|
30
|
+
/** Underlying store product (Play Billing on Android). */
|
|
31
|
+
val product: StoreProduct
|
|
32
|
+
/** Owning offering identifier — RC parity. */
|
|
33
|
+
val offeringIdentifier: String
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A Google Play product (subscription or one-time). Mirror of RC's StoreProduct
|
|
38
|
+
* shape; values are populated by [com.appswissknife.purchases.BillingClientGateway]
|
|
39
|
+
* from `ProductDetails`.
|
|
40
|
+
*/
|
|
41
|
+
interface StoreProduct {
|
|
42
|
+
/** Stable product identifier — what we send to the backend / Play. */
|
|
43
|
+
val id: String
|
|
44
|
+
val localizedTitle: String
|
|
45
|
+
val localizedDescription: String
|
|
46
|
+
val price: Price
|
|
47
|
+
/** Subscription period; null for non-renewing / one-time products. */
|
|
48
|
+
val subscriptionPeriod: SubscriptionPeriod?
|
|
49
|
+
val introductoryDiscount: StoreProductDiscount?
|
|
50
|
+
val discounts: List<StoreProductDiscount>
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Localized price. RC parity: tests use `formatted` (e.g. "$4.99") and
|
|
55
|
+
* `currencyCode` (e.g. "USD"). `amountMicros` is the raw Play Billing value.
|
|
56
|
+
*/
|
|
57
|
+
interface Price {
|
|
58
|
+
/** Pre-formatted, localized price string from the store. */
|
|
59
|
+
val formatted: String
|
|
60
|
+
/** ISO-4217 currency code. */
|
|
61
|
+
val currencyCode: String
|
|
62
|
+
/** Price in micro-units of [currencyCode]; matches Play Billing's units. */
|
|
63
|
+
val amountMicros: Long
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface SubscriptionPeriod {
|
|
67
|
+
val value: Int
|
|
68
|
+
val unit: Unit
|
|
69
|
+
|
|
70
|
+
enum class Unit { DAY, WEEK, MONTH, YEAR }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface StoreProductDiscount {
|
|
74
|
+
val identifier: String?
|
|
75
|
+
val price: Price
|
|
76
|
+
val paymentMode: PaymentMode
|
|
77
|
+
val subscriptionPeriod: SubscriptionPeriod
|
|
78
|
+
|
|
79
|
+
enum class PaymentMode { FREE_TRIAL, PAY_AS_YOU_GO, PAY_UP_FRONT }
|
|
80
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/models/PurchasesError.kt
|
|
2
|
+
//
|
|
3
|
+
// Phase 6 — own typed error hierarchy. Replaces RC's [PurchasesError] /
|
|
4
|
+
// [PurchasesErrorCode]. Mirror of RC parity: same `code` enum names callers
|
|
5
|
+
// were already switching on. Sealed (not interface) because every variant is
|
|
6
|
+
// fully known up-front and we want exhaustive `when` for downstream code.
|
|
7
|
+
//
|
|
8
|
+
// Each subclass has `cause: Throwable?` so [BillingClientGateway] can attach
|
|
9
|
+
// the original Play Billing exception/code for diagnostics without losing the
|
|
10
|
+
// typed surface.
|
|
11
|
+
package com.appswissknife.models
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A typed purchases failure. Maps roughly 1:1 onto RC's PurchasesErrorCode.
|
|
15
|
+
* The [code] enum lets pattern-matching consumers stay terse; subclasses exist
|
|
16
|
+
* for callers that want the typed branch.
|
|
17
|
+
*/
|
|
18
|
+
open class PurchasesError(
|
|
19
|
+
open val code: PurchasesErrorCode,
|
|
20
|
+
override val message: String,
|
|
21
|
+
override val cause: Throwable? = null,
|
|
22
|
+
) : Throwable(message, cause) {
|
|
23
|
+
|
|
24
|
+
/** Convenience: anything that did not succeed and was NOT a user-cancel. */
|
|
25
|
+
val underlyingErrorMessage: String? get() = cause?.message
|
|
26
|
+
|
|
27
|
+
// -- Subclasses (sealed-ish; we keep the base class open so [BillingClientGateway]
|
|
28
|
+
// can construct an "other-code" PurchasesError without forcing a subclass). --
|
|
29
|
+
|
|
30
|
+
class PurchaseCancelled(message: String = "User cancelled the purchase", cause: Throwable? = null) :
|
|
31
|
+
PurchasesError(PurchasesErrorCode.PurchaseCancelledError, message, cause)
|
|
32
|
+
|
|
33
|
+
class PaymentPending(message: String = "Payment is pending", cause: Throwable? = null) :
|
|
34
|
+
PurchasesError(PurchasesErrorCode.PaymentPendingError, message, cause)
|
|
35
|
+
|
|
36
|
+
class ProductNotAvailable(message: String = "Product not available for purchase", cause: Throwable? = null) :
|
|
37
|
+
PurchasesError(PurchasesErrorCode.ProductNotAvailableForPurchaseError, message, cause)
|
|
38
|
+
|
|
39
|
+
class NetworkError(message: String = "Network error", cause: Throwable? = null) :
|
|
40
|
+
PurchasesError(PurchasesErrorCode.NetworkError, message, cause)
|
|
41
|
+
|
|
42
|
+
class ReceiptAlreadyInUse(message: String = "Receipt already in use", cause: Throwable? = null) :
|
|
43
|
+
PurchasesError(PurchasesErrorCode.ReceiptAlreadyInUseError, message, cause)
|
|
44
|
+
|
|
45
|
+
class StoreProblem(message: String = "Store error", cause: Throwable? = null) :
|
|
46
|
+
PurchasesError(PurchasesErrorCode.StoreProblemError, message, cause)
|
|
47
|
+
|
|
48
|
+
class PurchaseInvalid(message: String = "Purchase invalid", cause: Throwable? = null) :
|
|
49
|
+
PurchasesError(PurchasesErrorCode.PurchaseInvalidError, message, cause)
|
|
50
|
+
|
|
51
|
+
class Unknown(message: String = "Unknown error", cause: Throwable? = null) :
|
|
52
|
+
PurchasesError(PurchasesErrorCode.UnknownError, message, cause)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Error-code enum. RC parity — same names callers already switch on.
|
|
57
|
+
* Not exhaustive of RC's catalog: only codes [BillingClientGateway] can
|
|
58
|
+
* actually produce + the few special cases (PurchaseCancelledError /
|
|
59
|
+
* NetworkError) that consumers handle distinctly.
|
|
60
|
+
*/
|
|
61
|
+
enum class PurchasesErrorCode {
|
|
62
|
+
UnknownError,
|
|
63
|
+
PurchaseCancelledError,
|
|
64
|
+
StoreProblemError,
|
|
65
|
+
PurchaseNotAllowedError,
|
|
66
|
+
PurchaseInvalidError,
|
|
67
|
+
ProductNotAvailableForPurchaseError,
|
|
68
|
+
ProductAlreadyPurchasedError,
|
|
69
|
+
ReceiptAlreadyInUseError,
|
|
70
|
+
InvalidReceiptError,
|
|
71
|
+
MissingReceiptFileError,
|
|
72
|
+
NetworkError,
|
|
73
|
+
InvalidCredentialsError,
|
|
74
|
+
UnexpectedBackendResponseError,
|
|
75
|
+
ReceiptInUseByOtherSubscriberError,
|
|
76
|
+
InvalidAppUserIdError,
|
|
77
|
+
OperationAlreadyInProgressError,
|
|
78
|
+
UnknownBackendError,
|
|
79
|
+
InvalidAppleSubscriptionKeyError,
|
|
80
|
+
IneligibleError,
|
|
81
|
+
InsufficientPermissionsError,
|
|
82
|
+
PaymentPendingError,
|
|
83
|
+
InvalidSubscriberAttributesError,
|
|
84
|
+
LogOutAnonymousUserError,
|
|
85
|
+
ConfigurationError,
|
|
86
|
+
UnsupportedError,
|
|
87
|
+
EmptySubscriberAttributesError,
|
|
88
|
+
CustomerInfoError,
|
|
89
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/models/StoreTransaction.kt
|
|
2
|
+
//
|
|
3
|
+
// Phase 6 — own StoreTransaction. Populated by [BillingClientGateway] from
|
|
4
|
+
// Play Billing's `Purchase` after a successful purchase + backend validate.
|
|
5
|
+
package com.appswissknife.models
|
|
6
|
+
|
|
7
|
+
import java.util.Date
|
|
8
|
+
|
|
9
|
+
interface StoreTransaction {
|
|
10
|
+
val productIdentifier: String
|
|
11
|
+
/** Stable transaction identifier — Play's `orderId`. */
|
|
12
|
+
val transactionIdentifier: String
|
|
13
|
+
val purchaseDate: Date
|
|
14
|
+
/** Raw Play Billing purchase token; sent to backend for receipt validation. */
|
|
15
|
+
val purchaseToken: String
|
|
16
|
+
val quantity: Int
|
|
17
|
+
}
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
// packages/swiss-knife-android/src/main/java/com/appswissknife/net/BackendHttpClient.kt
|
|
2
|
+
//
|
|
3
|
+
// Round-C/D Android port — single HTTP client for every backend call the
|
|
4
|
+
// SDK makes. Mirror of `Sources/SwissKnifeiOS/Net/BackendHttpClient.swift`.
|
|
5
|
+
//
|
|
6
|
+
// Collapses every per-feature low-level transport callsite into this
|
|
7
|
+
// single file. As of Round D the grep invariant is:
|
|
8
|
+
// grep -rn HttpURLConnection packages/swiss-knife-android/src/main/
|
|
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).
|
|
17
|
+
//
|
|
18
|
+
// Collapsed callsites:
|
|
19
|
+
// - analytics/FlushEventsWorker (events batch — legacy fallback path)
|
|
20
|
+
// - crashreporting/SKCrashReporting (5 separate transports — fallback)
|
|
21
|
+
// - performance/SKPerformance (transactions + sessions — fallback)
|
|
22
|
+
// - purchases/BillingClientGateway.validatePurchaseWithBackend
|
|
23
|
+
// - entitlements/EntitlementsRepository
|
|
24
|
+
// - offerings/OfferingsRepository
|
|
25
|
+
// - attributes/SetAttributesWorker
|
|
26
|
+
// - identity/IdentityNetwork
|
|
27
|
+
// - attribution/Attribution.registerInstall
|
|
28
|
+
//
|
|
29
|
+
// Design decisions:
|
|
30
|
+
// - Adds `X-API-Key` automatically using the configResolver lambda.
|
|
31
|
+
// Callers never thread the API key through their own argument list.
|
|
32
|
+
// - Base URL falls back to https://api.swiss-knife.dev when serverURL is
|
|
33
|
+
// null/empty (matches iOS).
|
|
34
|
+
// - One retry policy via ExponentialBackoff. maxRetries is per-call so
|
|
35
|
+
// Identity can keep a tight 3-retry budget while ingest uses 5.
|
|
36
|
+
// - Distinguishes 4xx (terminal) from 5xx / network (retriable). 429 is
|
|
37
|
+
// retried with respect for the Retry-After header.
|
|
38
|
+
// - Decoding is delegated to caller-supplied parser lambdas — each
|
|
39
|
+
// feature owns its own response shape; no monolithic wrapper.
|
|
40
|
+
// - Synchronous (blocking) by design. Background-thread / worker callers
|
|
41
|
+
// wrap as needed; iOS uses async/await, Kotlin callers wrap in
|
|
42
|
+
// coroutines or thread pools (mostly already WorkManager workers).
|
|
43
|
+
|
|
44
|
+
package com.appswissknife.net
|
|
45
|
+
|
|
46
|
+
import androidx.annotation.VisibleForTesting
|
|
47
|
+
import org.json.JSONObject
|
|
48
|
+
import java.io.BufferedReader
|
|
49
|
+
import java.io.IOException
|
|
50
|
+
import java.io.InputStreamReader
|
|
51
|
+
import java.net.HttpURLConnection
|
|
52
|
+
import java.net.URL
|
|
53
|
+
import java.net.URLEncoder
|
|
54
|
+
import java.text.SimpleDateFormat
|
|
55
|
+
import java.util.Date
|
|
56
|
+
import java.util.Locale
|
|
57
|
+
import java.util.TimeZone
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolved configuration at request time. Refreshed on every call so a
|
|
61
|
+
* `configure` mid-flight picks up the new apiKey / baseURL.
|
|
62
|
+
*/
|
|
63
|
+
internal data class BackendConfig(
|
|
64
|
+
val apiKey: String,
|
|
65
|
+
val baseUrl: String?,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Outcome of a single HTTP attempt. `success=true` covers ANY well-formed
|
|
70
|
+
* HTTP response (including 4xx/5xx) — the retry loop interprets `code`.
|
|
71
|
+
* `success=false` is reserved for transport-level failures (DNS, socket).
|
|
72
|
+
*/
|
|
73
|
+
internal data class BackendHttpResponse(
|
|
74
|
+
val success: Boolean,
|
|
75
|
+
val code: Int,
|
|
76
|
+
val body: String,
|
|
77
|
+
val retryAfterMillis: Long?,
|
|
78
|
+
val serverDateMillis: Long?,
|
|
79
|
+
val error: Throwable? = null,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Thin transport seam — tests inject a fake. Production uses
|
|
84
|
+
* [UrlConnectionBackendTransport].
|
|
85
|
+
*/
|
|
86
|
+
internal interface BackendTransport {
|
|
87
|
+
fun perform(method: String, url: URL, headers: Map<String, String>, body: ByteArray?): BackendHttpResponse
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
internal class UrlConnectionBackendTransport(
|
|
91
|
+
private val connectTimeoutMs: Int = 10_000,
|
|
92
|
+
private val readTimeoutMs: Int = 10_000,
|
|
93
|
+
) : BackendTransport {
|
|
94
|
+
override fun perform(
|
|
95
|
+
method: String,
|
|
96
|
+
url: URL,
|
|
97
|
+
headers: Map<String, String>,
|
|
98
|
+
body: ByteArray?,
|
|
99
|
+
): BackendHttpResponse {
|
|
100
|
+
val conn = try {
|
|
101
|
+
url.openConnection() as HttpURLConnection
|
|
102
|
+
} catch (e: IOException) {
|
|
103
|
+
return BackendHttpResponse(false, 0, "", null, null, e)
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
conn.requestMethod = method
|
|
107
|
+
conn.connectTimeout = connectTimeoutMs
|
|
108
|
+
conn.readTimeout = readTimeoutMs
|
|
109
|
+
for ((k, v) in headers) conn.setRequestProperty(k, v)
|
|
110
|
+
if (body != null) {
|
|
111
|
+
conn.doOutput = true
|
|
112
|
+
conn.outputStream.use { it.write(body) }
|
|
113
|
+
}
|
|
114
|
+
val code = conn.responseCode
|
|
115
|
+
val retryAfter = conn.getHeaderField("Retry-After")?.toLongOrNull()?.let { it * 1000L }
|
|
116
|
+
val dateHeader = conn.getHeaderField("Date")
|
|
117
|
+
val serverMillis = parseHttpDate(dateHeader)
|
|
118
|
+
val stream = if (code in 200..299) conn.inputStream else conn.errorStream
|
|
119
|
+
val responseBody = stream?.let {
|
|
120
|
+
BufferedReader(InputStreamReader(it, Charsets.UTF_8)).use { r -> r.readText() }
|
|
121
|
+
}.orEmpty()
|
|
122
|
+
return BackendHttpResponse(
|
|
123
|
+
success = true,
|
|
124
|
+
code = code,
|
|
125
|
+
body = responseBody,
|
|
126
|
+
retryAfterMillis = retryAfter,
|
|
127
|
+
serverDateMillis = serverMillis,
|
|
128
|
+
)
|
|
129
|
+
} catch (e: IOException) {
|
|
130
|
+
return BackendHttpResponse(false, 0, "", null, null, e)
|
|
131
|
+
} finally {
|
|
132
|
+
runCatching { conn.disconnect() }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Parse HTTP `Date` header (RFC 7231 IMF-fixdate). */
|
|
137
|
+
private fun parseHttpDate(raw: String?): Long? {
|
|
138
|
+
if (raw.isNullOrBlank()) return null
|
|
139
|
+
return runCatching {
|
|
140
|
+
val fmt = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply {
|
|
141
|
+
timeZone = TimeZone.getTimeZone("GMT")
|
|
142
|
+
}
|
|
143
|
+
fmt.parse(raw)?.time
|
|
144
|
+
}.getOrNull()
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Thrown by [BackendHttpClient] for terminal 4xx (no retries) responses.
|
|
150
|
+
*/
|
|
151
|
+
internal class BackendRejected(val code: Int, val serverMessage: String?) :
|
|
152
|
+
IOException("backend rejected ($code): ${serverMessage ?: ""}")
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Thrown by [BackendHttpClient] after the retry budget is exhausted on
|
|
156
|
+
* 5xx / network errors.
|
|
157
|
+
*/
|
|
158
|
+
internal class BackendUnavailable(val code: Int, val serverMessage: String?, cause: Throwable? = null) :
|
|
159
|
+
IOException("backend unavailable ($code): ${serverMessage ?: ""}", cause)
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Thrown when the SDK hasn't been configured (apiKey empty).
|
|
163
|
+
*/
|
|
164
|
+
internal class BackendNotConfigured : IOException("BackendHttpClient: apiKey not configured")
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Single HTTP primitive for every backend call. Internal — only the
|
|
168
|
+
* per-feature clients (IngestClient, Attribution, ...) should reach for
|
|
169
|
+
* this directly. Production uses [shared] which is wired during
|
|
170
|
+
* [SwissKnife.configure].
|
|
171
|
+
*/
|
|
172
|
+
internal class BackendHttpClient(
|
|
173
|
+
private val transport: BackendTransport = UrlConnectionBackendTransport(),
|
|
174
|
+
private val backoff: ExponentialBackoff = ExponentialBackoff(),
|
|
175
|
+
private val configResolver: () -> BackendConfig,
|
|
176
|
+
private val sleeper: (Long) -> Unit = { Thread.sleep(it) },
|
|
177
|
+
/**
|
|
178
|
+
* Hook that feeds the parsed `Date` HTTP header into the SDK's Clock so
|
|
179
|
+
* subsequent `Clock.now()` calls converge on server time. Default no-op
|
|
180
|
+
* keeps Commit 1 independent of Commit 3 (Clock primitive). Commit 3
|
|
181
|
+
* wires this to `Clock.applyServerTime(...)` at the SwissKnife.configure
|
|
182
|
+
* call site.
|
|
183
|
+
*/
|
|
184
|
+
private val onServerDate: (serverMillis: Long, localObservedMillis: Long) -> Unit = { _, _ -> },
|
|
185
|
+
) {
|
|
186
|
+
|
|
187
|
+
companion object {
|
|
188
|
+
const val DEFAULT_BASE_URL = "https://api.swiss-knife.dev"
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Process-wide shared instance. Wired lazily by SwissKnife.configure;
|
|
192
|
+
* tests construct their own instance with a fake transport.
|
|
193
|
+
*/
|
|
194
|
+
@Volatile
|
|
195
|
+
private var _shared: BackendHttpClient? = null
|
|
196
|
+
|
|
197
|
+
@JvmStatic
|
|
198
|
+
var shared: BackendHttpClient
|
|
199
|
+
get() = _shared ?: synchronized(this) {
|
|
200
|
+
_shared ?: BackendHttpClient(configResolver = { ConfigBridge.snapshot() })
|
|
201
|
+
.also { _shared = it }
|
|
202
|
+
}
|
|
203
|
+
set(value) {
|
|
204
|
+
_shared = value
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Round-D — factory used by modules (EntitlementsRepository,
|
|
209
|
+
* OfferingsRepository, the legacy fallbacks in
|
|
210
|
+
* Analytics/Crash/Performance flush) that hold their own
|
|
211
|
+
* `serverUrl` / `apiKey` and pre-date the `ConfigBridge` wiring
|
|
212
|
+
* in SwissKnife.configure. The returned client is NOT registered
|
|
213
|
+
* as [shared] — it is a one-shot transport tied to the caller's
|
|
214
|
+
* ctor args. Production paths that go through `SwissKnife.configure`
|
|
215
|
+
* should prefer [shared] instead.
|
|
216
|
+
*/
|
|
217
|
+
@JvmStatic
|
|
218
|
+
fun create(apiKey: String, baseUrl: String?): BackendHttpClient =
|
|
219
|
+
BackendHttpClient(
|
|
220
|
+
configResolver = { BackendConfig(apiKey = apiKey, baseUrl = baseUrl) },
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Build a full URL by joining (possibly nil/trimmed) baseURL with the
|
|
225
|
+
* path and appending query parameters. Default production host is
|
|
226
|
+
* https://api.swiss-knife.dev.
|
|
227
|
+
*/
|
|
228
|
+
fun buildURL(
|
|
229
|
+
baseUrl: String?,
|
|
230
|
+
path: String,
|
|
231
|
+
query: List<Pair<String, String>>,
|
|
232
|
+
): URL {
|
|
233
|
+
val base = (if (baseUrl.isNullOrEmpty()) DEFAULT_BASE_URL else baseUrl).trimEnd('/')
|
|
234
|
+
val leading = if (path.startsWith("/")) path else "/$path"
|
|
235
|
+
val sb = StringBuilder(base).append(leading)
|
|
236
|
+
if (query.isNotEmpty()) {
|
|
237
|
+
sb.append('?')
|
|
238
|
+
query.joinToString("&") { (k, v) ->
|
|
239
|
+
"${URLEncoder.encode(k, "UTF-8")}=${URLEncoder.encode(v, "UTF-8")}"
|
|
240
|
+
}.also { sb.append(it) }
|
|
241
|
+
}
|
|
242
|
+
return URL(sb.toString())
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** GET; decode body via parser lambda. */
|
|
247
|
+
@Throws(IOException::class)
|
|
248
|
+
fun <R> get(
|
|
249
|
+
path: String,
|
|
250
|
+
query: List<Pair<String, String>> = emptyList(),
|
|
251
|
+
maxRetries: Int = 3,
|
|
252
|
+
parser: (String) -> R,
|
|
253
|
+
): R {
|
|
254
|
+
val body = getRaw(path, query, maxRetries)
|
|
255
|
+
return parser(body)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** GET returning raw body. */
|
|
259
|
+
@Throws(IOException::class)
|
|
260
|
+
fun getRaw(
|
|
261
|
+
path: String,
|
|
262
|
+
query: List<Pair<String, String>> = emptyList(),
|
|
263
|
+
maxRetries: Int = 3,
|
|
264
|
+
): String {
|
|
265
|
+
val (config, url) = resolveAndBuild(path, query)
|
|
266
|
+
val headers = baseHeaders(config.apiKey)
|
|
267
|
+
return performWithRetries("GET", url, headers, null, maxRetries).body
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** POST a JSON body and parse the response. */
|
|
271
|
+
@Throws(IOException::class)
|
|
272
|
+
fun <R> post(
|
|
273
|
+
path: String,
|
|
274
|
+
body: JSONObject,
|
|
275
|
+
maxRetries: Int = 3,
|
|
276
|
+
parser: (String) -> R,
|
|
277
|
+
): R {
|
|
278
|
+
val raw = postRaw(path, body.toString(), maxRetries)
|
|
279
|
+
return parser(raw)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** POST raw body bytes; return raw body. */
|
|
283
|
+
@Throws(IOException::class)
|
|
284
|
+
fun postRaw(
|
|
285
|
+
path: String,
|
|
286
|
+
body: String,
|
|
287
|
+
maxRetries: Int = 3,
|
|
288
|
+
): String {
|
|
289
|
+
val (config, url) = resolveAndBuild(path, emptyList())
|
|
290
|
+
val headers = baseHeaders(config.apiKey)
|
|
291
|
+
return performWithRetries("POST", url, headers, body.toByteArray(Charsets.UTF_8), maxRetries).body
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** POST and only care about the HTTP status. */
|
|
295
|
+
@Throws(IOException::class)
|
|
296
|
+
fun postIgnoringResponse(
|
|
297
|
+
path: String,
|
|
298
|
+
body: JSONObject,
|
|
299
|
+
maxRetries: Int = 3,
|
|
300
|
+
): Int {
|
|
301
|
+
val (config, url) = resolveAndBuild(path, emptyList())
|
|
302
|
+
val headers = baseHeaders(config.apiKey)
|
|
303
|
+
val r = performWithRetries("POST", url, headers, body.toString().toByteArray(Charsets.UTF_8), maxRetries)
|
|
304
|
+
return r.code
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Send-and-return-status POST for callers that own their OWN retry
|
|
309
|
+
* policy (WorkManager + runAttemptCount + DLQ) and just need the raw
|
|
310
|
+
* HTTP status + Retry-After back. No backoff loop runs here — the
|
|
311
|
+
* outer caller IS the retry layer; double-retrying would multiply the
|
|
312
|
+
* budget and double-count Retry-After.
|
|
313
|
+
*
|
|
314
|
+
* Throws [IOException] on transport failure; returns code + retryAfter
|
|
315
|
+
* for any 2xx/3xx/4xx/5xx response.
|
|
316
|
+
*
|
|
317
|
+
* Replaces the deleted top-level `simpleBackendPost` helper. Routes
|
|
318
|
+
* through the same headers / Clock-skew feed / X-API-Key auto-stamp
|
|
319
|
+
* pipeline as every other BackendHttpClient method.
|
|
320
|
+
*/
|
|
321
|
+
@Throws(IOException::class)
|
|
322
|
+
fun simplePost(
|
|
323
|
+
path: String,
|
|
324
|
+
body: String,
|
|
325
|
+
contentType: String = "application/json",
|
|
326
|
+
): SimpleHttpResponse {
|
|
327
|
+
val (config, url) = resolveAndBuild(path, emptyList())
|
|
328
|
+
val headers = mapOf(
|
|
329
|
+
"Content-Type" to contentType,
|
|
330
|
+
"Accept" to "application/json",
|
|
331
|
+
"X-API-Key" to config.apiKey,
|
|
332
|
+
)
|
|
333
|
+
val r = transport.perform("POST", url, headers, body.toByteArray(Charsets.UTF_8))
|
|
334
|
+
if (!r.success) throw IOException(r.error?.message ?: "network error", r.error)
|
|
335
|
+
feedClockSkew(r)
|
|
336
|
+
return SimpleHttpResponse(
|
|
337
|
+
code = r.code,
|
|
338
|
+
retryAfterSeconds = r.retryAfterMillis?.let { it / 1000L },
|
|
339
|
+
)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Send-and-return GET for callers that own their own caching/grace
|
|
344
|
+
* policies. Throws [IOException] on transport failure; returns
|
|
345
|
+
* `(code, body)` for everything else, including 404 when `allow404=true`.
|
|
346
|
+
* Throws [IOException] on non-allowed non-2xx responses.
|
|
347
|
+
*
|
|
348
|
+
* Replaces the deleted top-level `simpleBackendGet` helper.
|
|
349
|
+
*/
|
|
350
|
+
@Throws(IOException::class)
|
|
351
|
+
fun simpleGet(
|
|
352
|
+
path: String,
|
|
353
|
+
query: List<Pair<String, String>> = emptyList(),
|
|
354
|
+
allow404: Boolean = false,
|
|
355
|
+
): Pair<Int, String> {
|
|
356
|
+
val (config, url) = resolveAndBuild(path, query)
|
|
357
|
+
val headers = mapOf(
|
|
358
|
+
"Accept" to "application/json",
|
|
359
|
+
"X-API-Key" to config.apiKey,
|
|
360
|
+
)
|
|
361
|
+
val r = transport.perform("GET", url, headers, null)
|
|
362
|
+
if (!r.success) throw IOException(r.error?.message ?: "network error", r.error)
|
|
363
|
+
feedClockSkew(r)
|
|
364
|
+
if (r.code == 404 && allow404) return Pair(r.code, r.body)
|
|
365
|
+
if (r.code !in 200..299) throw IOException("$path returned ${r.code}")
|
|
366
|
+
return Pair(r.code, r.body)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
private fun feedClockSkew(r: BackendHttpResponse) {
|
|
370
|
+
val serverMillis = r.serverDateMillis ?: return
|
|
371
|
+
onServerDate(serverMillis, System.currentTimeMillis())
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ----- Internals -----
|
|
375
|
+
|
|
376
|
+
private fun resolveAndBuild(path: String, query: List<Pair<String, String>>): Pair<BackendConfig, URL> {
|
|
377
|
+
val config = configResolver()
|
|
378
|
+
if (config.apiKey.isEmpty()) throw BackendNotConfigured()
|
|
379
|
+
val url = buildURL(config.baseUrl, path, query)
|
|
380
|
+
return Pair(config, url)
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
private fun baseHeaders(apiKey: String): Map<String, String> = mapOf(
|
|
384
|
+
"Content-Type" to "application/json",
|
|
385
|
+
"Accept" to "application/json",
|
|
386
|
+
"X-API-Key" to apiKey,
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Drive the bounded retry loop. Returns on 2xx; throws [BackendRejected]
|
|
391
|
+
* for 4xx (no retries); throws [BackendUnavailable] after the budget is
|
|
392
|
+
* exhausted on 5xx / network. 429 is retried up to maxRetries with
|
|
393
|
+
* Retry-After honoured.
|
|
394
|
+
*/
|
|
395
|
+
@Throws(IOException::class)
|
|
396
|
+
private fun performWithRetries(
|
|
397
|
+
method: String,
|
|
398
|
+
url: URL,
|
|
399
|
+
headers: Map<String, String>,
|
|
400
|
+
body: ByteArray?,
|
|
401
|
+
maxRetries: Int,
|
|
402
|
+
): BackendHttpResponse {
|
|
403
|
+
var attempt = 0
|
|
404
|
+
var lastError: Throwable? = null
|
|
405
|
+
while (true) {
|
|
406
|
+
val r = transport.perform(method, url, headers, body)
|
|
407
|
+
if (!r.success) {
|
|
408
|
+
lastError = r.error
|
|
409
|
+
if (attempt < maxRetries) {
|
|
410
|
+
sleeper(backoff.delay(attempt, null))
|
|
411
|
+
attempt++
|
|
412
|
+
continue
|
|
413
|
+
}
|
|
414
|
+
throw BackendUnavailable(0, lastError?.message ?: "network error", lastError)
|
|
415
|
+
}
|
|
416
|
+
val code = r.code
|
|
417
|
+
if (code in 200..299) {
|
|
418
|
+
// Feed server Date header into Clock on success only — matches iOS.
|
|
419
|
+
r.serverDateMillis?.let { onServerDate(it, System.currentTimeMillis()) }
|
|
420
|
+
return r
|
|
421
|
+
}
|
|
422
|
+
if (code == 429 || code >= 500) {
|
|
423
|
+
if (attempt < maxRetries) {
|
|
424
|
+
sleeper(backoff.delay(attempt, r.retryAfterMillis))
|
|
425
|
+
attempt++
|
|
426
|
+
continue
|
|
427
|
+
}
|
|
428
|
+
throw BackendUnavailable(code, extractMessage(r.body))
|
|
429
|
+
}
|
|
430
|
+
// 4xx (other than 429) → terminal.
|
|
431
|
+
throw BackendRejected(code, extractMessage(r.body))
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
private fun extractMessage(body: String): String? {
|
|
436
|
+
if (body.isEmpty()) return null
|
|
437
|
+
return runCatching {
|
|
438
|
+
val obj = JSONObject(body)
|
|
439
|
+
if (obj.has("error")) obj.optString("error") else null
|
|
440
|
+
}.getOrNull()
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Round-D — minimal HTTP response shape exposed to per-feature default
|
|
446
|
+
* impls (FlushEventsWorker / SetAttributesWorker / SKCrashReporting
|
|
447
|
+
* legacy fallbacks). Mirrors the now-deleted per-feature HttpResponse
|
|
448
|
+
* data classes so callers can keep their handleResponse(...) branches
|
|
449
|
+
* unchanged.
|
|
450
|
+
*/
|
|
451
|
+
internal data class SimpleHttpResponse(
|
|
452
|
+
val code: Int,
|
|
453
|
+
val retryAfterSeconds: Long? = null,
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Round-D — [BillingHttpClient] default implementation that routes
|
|
458
|
+
* through the unified [BackendHttpClient] transport. Replaces the
|
|
459
|
+
* deleted `HttpUrlConnectionClient` so the only file that imports
|
|
460
|
+
* `java.net.HttpURLConnection` is [BackendHttpClient] itself.
|
|
461
|
+
*
|
|
462
|
+
* Header handling: [BackendHttpClient] always stamps `X-API-Key` from
|
|
463
|
+
* the caller's `headers` map. The post-audit cleanup dropped the
|
|
464
|
+
* Bearer→X-API-Key rewrite shim that pre-existed for the Round-D
|
|
465
|
+
* migration window — every production caller
|
|
466
|
+
* (BillingClientGateway.validatePurchaseWithBackend, Identity.identify,
|
|
467
|
+
* Attribution.fetchInstallAttribution) already passes `X-API-Key`
|
|
468
|
+
* directly. Any future caller MUST do the same; passing `Authorization`
|
|
469
|
+
* will leave the request unauthenticated.
|
|
470
|
+
*/
|
|
471
|
+
internal class BackendHttpClientAdapter : com.appswissknife.purchases.BillingHttpClient {
|
|
472
|
+
@Throws(IOException::class)
|
|
473
|
+
override fun post(url: String, body: String, headers: Map<String, String>): String {
|
|
474
|
+
val u = java.net.URL(url)
|
|
475
|
+
val baseUrl = "${u.protocol}://${u.authority}"
|
|
476
|
+
val pathAndQuery = u.path + (u.query?.let { "?$it" } ?: "")
|
|
477
|
+
val apiKey = headers["X-API-Key"] ?: ""
|
|
478
|
+
val transport = UrlConnectionBackendTransport()
|
|
479
|
+
val fullHeaders = mapOf(
|
|
480
|
+
"Content-Type" to (headers["Content-Type"] ?: "application/json"),
|
|
481
|
+
"Accept" to "application/json",
|
|
482
|
+
"X-API-Key" to apiKey,
|
|
483
|
+
)
|
|
484
|
+
val urlObj = java.net.URL("$baseUrl$pathAndQuery")
|
|
485
|
+
val r = transport.perform("POST", urlObj, fullHeaders, body.toByteArray(Charsets.UTF_8))
|
|
486
|
+
if (!r.success) throw IOException(r.error?.message ?: "network error", r.error)
|
|
487
|
+
if (r.code !in 200..299) throw IOException("HTTP ${r.code}")
|
|
488
|
+
return r.body
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Bridge between [BackendHttpClient.shared] and the SwissKnife config.
|
|
494
|
+
* Wave-3 wiring lives in [BackendHttpClient]'s shared lazy init — it calls
|
|
495
|
+
* `ConfigBridge.snapshot()` which reads the current SDK config. The SDK's
|
|
496
|
+
* `configure` registers a snapshot supplier here.
|
|
497
|
+
*/
|
|
498
|
+
internal object ConfigBridge {
|
|
499
|
+
@Volatile
|
|
500
|
+
private var supplier: () -> BackendConfig = { BackendConfig(apiKey = "", baseUrl = null) }
|
|
501
|
+
|
|
502
|
+
fun register(supplier: () -> BackendConfig) {
|
|
503
|
+
this.supplier = supplier
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
fun snapshot(): BackendConfig = supplier()
|
|
507
|
+
}
|