-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSuperwallExpoModule.swift
More file actions
408 lines (351 loc) · 12.4 KB
/
SuperwallExpoModule.swift
File metadata and controls
408 lines (351 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import ExpoModulesCore
import SuperwallKit
/// Thread-safe boolean flag that can only be set once.
private final class AtomicFlag {
private var _value = false
private let lock = NSLock()
/// Sets the flag and returns the previous value.
/// Returns `false` on the first call, `true` on subsequent calls.
func testAndSet() -> Bool {
lock.lock()
defer { lock.unlock() }
let prev = _value
_value = true
return prev
}
}
public class SuperwallExpoModule: Module {
public static var shared: SuperwallExpoModule?
private let purchaseController = PurchaseControllerBridge.shared
private var delegate: SuperwallDelegateBridge?
// Paywall Events
private let onPaywallPresent = "onPaywallPresent"
private let onPaywallDismiss = "onPaywallDismiss"
private let onPaywallError = "onPaywallError"
private let onPaywallSkip = "onPaywallSkip"
private let onCustomCallback = "onCustomCallback"
// Custom callback continuations keyed by callbackId
private let callbackLock = NSLock()
private var customCallbackContinuations: [String: CheckedContinuation<CustomCallbackResult, Never>] = [:]
// Purchase Events
private let onPurchase = "onPurchase"
private let onPurchaseRestore = "onPurchaseRestore"
// Legacy Events
private let subscriptionStatusDidChange = "subscriptionStatusDidChange"
private let handleSuperwallEvent = "handleSuperwallEvent"
private let handleCustomPaywallAction = "handleCustomPaywallAction"
private let willDismissPaywall = "willDismissPaywall"
private let willPresentPaywall = "willPresentPaywall"
private let didDismissPaywall = "didDismissPaywall"
private let didPresentPaywall = "didPresentPaywall"
private let paywallWillOpenURL = "paywallWillOpenURL"
private let paywallWillOpenDeepLink = "paywallWillOpenDeepLink"
private let handleLog = "handleLog"
private let willRedeemLink = "willRedeemLink"
private let didRedeemLink = "didRedeemLink"
public required init(appContext: AppContext) {
super.init(appContext: appContext)
SuperwallExpoModule.shared = self
}
public static func emitEvent(_ name: String, _ data: [String: Any]?) {
SuperwallExpoModule.shared?.sendEvent(name, data ?? [:])
}
public func definition() -> ModuleDefinition {
Name("SuperwallExpo")
Events(
onPaywallPresent,
onPaywallDismiss,
onPaywallError,
onPaywallSkip,
onCustomCallback,
onPurchase,
onPurchaseRestore,
// Legacy events
subscriptionStatusDidChange,
handleSuperwallEvent,
handleCustomPaywallAction,
willDismissPaywall,
willPresentPaywall,
didDismissPaywall,
didPresentPaywall,
paywallWillOpenURL,
paywallWillOpenDeepLink,
handleLog,
willRedeemLink,
didRedeemLink
)
AsyncFunction("identify") { (userId: String, options: [String: Any]?, promise: Promise) in
DispatchQueue.main.async {
let identityOptions = IdentityOptions.fromJson(options)
Superwall.shared.identify(userId: userId, options: identityOptions)
promise.resolve(nil)
}
}
AsyncFunction("reset") { (promise: Promise) in
DispatchQueue.main.async {
Superwall.shared.reset()
promise.resolve(nil)
}
}
AsyncFunction("configure") {
(
apiKey: String,
options: [String: Any]?,
usingPurchaseController: Bool,
sdkVersion: String?,
promise: Promise
) in
var superwallOptions: SuperwallOptions?
if let options = options {
superwallOptions = SuperwallOptions.fromJson(options)
}
let promiseSettled = AtomicFlag()
Superwall.configure(
apiKey: apiKey,
purchaseController: usingPurchaseController ? purchaseController : nil,
options: superwallOptions,
completion: {
self.delegate = SuperwallDelegateBridge()
Superwall.shared.delegate = self.delegate
Superwall.shared.setPlatformWrapper("Expo", version: sdkVersion ?? "0.0.0")
if promiseSettled.testAndSet() == false {
promise.resolve(nil)
}
}
)
}
AsyncFunction("getConfigurationStatus") { (promise: Promise) in
let configurationStatus = Superwall.shared.configurationStatus.toString()
promise.resolve(configurationStatus)
}
AsyncFunction("registerPlacement") {
(
placement: String,
params: [String: Any]?,
handlerId: String?,
promise: Promise
) in
var handler: PaywallPresentationHandler?
if let handlerId = handlerId {
handler = PaywallPresentationHandler()
handler?.onPresent { [weak self] paywallInfo in
guard let self = self else { return }
let data =
[
"paywallInfoJson": paywallInfo.toJson(),
"handlerId": handlerId,
] as [String: Any]
self.sendEvent(self.onPaywallPresent, data)
}
handler?.onDismiss { [weak self] paywallInfo, result in
guard let self = self else { return }
let data =
[
"paywallInfoJson": paywallInfo.toJson(),
"result": result.toJson(),
"handlerId": handlerId,
] as [String: Any]
self.sendEvent(self.onPaywallDismiss, data)
}
handler?.onError { [weak self] error in
guard let self = self else { return }
let data =
[
"errorString": error.localizedDescription,
"handlerId": handlerId,
] as [String: Any]
self.sendEvent(self.onPaywallError, data)
}
handler?.onSkip { [weak self] reason in
guard let self = self else { return }
let data =
[
"skippedReason": reason.toJson(),
"handlerId": handlerId,
] as [String: Any]
self.sendEvent(self.onPaywallSkip, data)
}
handler?.onCustomCallback { [weak self] callback async -> CustomCallbackResult in
guard let self = self else { return .failure() }
let callbackId = UUID().uuidString
let data: [String: Any] = [
"callbackId": callbackId,
"name": callback.name,
"variables": callback.variables as Any,
"handlerId": handlerId,
]
return await withCheckedContinuation { continuation in
self.callbackLock.lock()
self.customCallbackContinuations[callbackId] = continuation
self.callbackLock.unlock()
self.sendEvent(self.onCustomCallback, data)
}
}
}
Superwall.shared.register(
placement: placement,
params: params,
handler: handler
) {
promise.resolve(nil)
}
}
AsyncFunction("getAssignments") { (promise: Promise) in
do {
let assignments = try Superwall.shared.getAssignments()
promise.resolve(assignments.map { $0.toJson() })
} catch {
promise.reject(error)
}
}
AsyncFunction("getEntitlements") { (promise: Promise) in
do {
let entitlements = try Superwall.shared.entitlements.toJson()
promise.resolve(entitlements)
} catch {
promise.reject(error)
}
}
AsyncFunction("getSubscriptionStatus") { (promise: Promise) in
print("Getting subscription status")
let subscriptionStatus = Superwall.shared.subscriptionStatus
promise.resolve(subscriptionStatus.toJson())
}
AsyncFunction("setSubscriptionStatus") { (status: [String: Any], promise: Promise) in
DispatchQueue.main.async {
let statusString = (status["status"] as? String)?.uppercased() ?? "UNKNOWN"
let subscriptionStatus: SubscriptionStatus
print("Setting subscription status to: \(statusString)")
switch statusString {
case "UNKNOWN":
subscriptionStatus = .unknown
case "INACTIVE":
subscriptionStatus = .inactive
case "ACTIVE":
if let entitlementsArray = status["entitlements"] as? [[String: Any]] {
let entitlementsSet: Set<Entitlement> = Set(
entitlementsArray.compactMap { item in
if let id = item["id"] as? String {
return Entitlement(id: id)
}
return nil
}
)
subscriptionStatus = .active(entitlementsSet)
} else {
subscriptionStatus = .inactive
}
default:
subscriptionStatus = .unknown
}
Superwall.shared.subscriptionStatus = subscriptionStatus
promise.resolve(nil)
}
}
Function("setInterfaceStyle") { (style: String?) in
var interfaceStyle: InterfaceStyle?
if let style = style {
interfaceStyle = InterfaceStyle.fromString(style: style)
}
Superwall.shared.setInterfaceStyle(to: interfaceStyle)
}
AsyncFunction("getUserAttributes") { (promise: Promise) in
let attributes = Superwall.shared.userAttributes
promise.resolve(attributes)
}
AsyncFunction("getDeviceAttributes") {
return await Superwall.shared.getDeviceAttributes()
}
AsyncFunction("setUserAttributes") { (userAttributes: [String: Any?], promise: Promise) in
DispatchQueue.main.async {
Superwall.shared.setUserAttributes(userAttributes)
promise.resolve(nil)
}
}
AsyncFunction("handleDeepLink") { (url: String, promise: Promise) in
guard let url = URL(string: url) else {
promise.resolve(false)
return
}
let result = Superwall.shared.handleDeepLink(url)
promise.resolve(result)
}
Function("didPurchase") { (result: [String: Any]) in
guard let purchaseResult = PurchaseResult.fromJson(result) else {
return
}
purchaseController.purchaseCompletion?(purchaseResult)
}
Function("didRestore") { (result: [String: Any]) in
guard let restorationResult = RestorationResult.fromJson(result) else {
return
}
purchaseController.restoreCompletion?(restorationResult)
}
AsyncFunction("didHandleCustomCallback") { (callbackId: String, status: String, data: [String: Any]?, promise: Promise) in
self.callbackLock.lock()
let continuation = self.customCallbackContinuations.removeValue(forKey: callbackId)
self.callbackLock.unlock()
guard let continuation = continuation else {
promise.resolve(nil)
return
}
let result: CustomCallbackResult
if status == "success" {
result = .success(data: data)
} else {
result = .failure(data: data)
}
continuation.resume(returning: result)
promise.resolve(nil)
}
AsyncFunction("restorePurchases") { (promise: Promise) in
Task {
let result = await Superwall.shared.restorePurchases()
promise.resolve(result.toJson())
}
}
AsyncFunction("dismiss") { (promise: Promise) in
Superwall.shared.dismiss {
promise.resolve(nil)
}
}
AsyncFunction("confirmAllAssignments") { (promise: Promise) in
Superwall.shared.confirmAllAssignments { assignments in
promise.resolve(assignments.map { $0.toJson() })
}
}
AsyncFunction("getPresentationResult") {
(placement: String, params: [String: Any]?, promise: Promise) in
Superwall.shared.getPresentationResult(forPlacement: placement, params: params) { result in
promise.resolve(result.toJson())
}
}
Function("preloadPaywalls") { (placementNames: [String]) in
Superwall.shared.preloadPaywalls(forPlacements: Set(placementNames))
}
Function("preloadAllPaywalls") {
Superwall.shared.preloadAllPaywalls()
}
Function("setLogLevel") { (level: String) in
let logLevel = LogLevel.fromJson(level)
if let logLevel = logLevel {
Superwall.shared.logLevel = logLevel
}
}
AsyncFunction("setIntegrationAttributes") { (attributes: [String: String], promise: Promise) in
var converted: [IntegrationAttribute: String] = [:]
for (key, value) in attributes {
if let attribute = IntegrationAttribute.fromString(key) {
converted[attribute] = value
}
}
Superwall.shared.setIntegrationAttributes(converted)
promise.resolve(nil)
}
AsyncFunction("getIntegrationAttributes") { (promise: Promise) in
let attributes = Superwall.shared.integrationAttributes
promise.resolve(attributes)
}
}
}