-
Notifications
You must be signed in to change notification settings - Fork 22
/
TriggerSessionManager.swift
552 lines (469 loc) · 14.7 KB
/
TriggerSessionManager.swift
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//
// File.swift
//
//
// Created by Yusuf Tör on 29/04/2022.
//
// swiftlint:disable type_body_length file_length
import UIKit
import StoreKit
import Combine
actor TriggerSessionManager {
/// The list of all potential trigger sessions, keyed by the trigger event name, created after receiving the config.
private var pendingTriggerSessions: [String: TriggerSession] = [:]
/// The active trigger session.
var activeTriggerSession: TriggerSession?
private unowned let storage: Storage
private unowned let configManager: ConfigManager
private unowned let appSessionManager: AppSessionManager
private unowned let identityManager: IdentityManager
private unowned let delegate: SessionEventsDelegate
private unowned let sessionEventsManager: SessionEventsManager
/// A local count for transactions used within the trigger session.
private var transactionCount: TriggerSession.Transaction.Count?
@MainActor
private var observerCancellables: [AnyCancellable] = []
private var configListener: AnyCancellable?
enum LoadState {
case start
case end
case fail
}
init(
delegate: SessionEventsDelegate,
sessionEventsManager: SessionEventsManager,
storage: Storage,
configManager: ConfigManager,
appSessionManager: AppSessionManager,
identityManager: IdentityManager
) {
self.delegate = delegate
self.sessionEventsManager = sessionEventsManager
self.storage = storage
self.configManager = configManager
self.appSessionManager = appSessionManager
self.identityManager = identityManager
Task {
await listenForConfig()
await addObservers()
}
}
private func listenForConfig() {
configListener = configManager.configState
.compactMap { $0.getConfig() }
.sink(
receiveCompletion: { _ in },
receiveValue: { [weak self] config in
guard let self = self else {
return
}
Task {
await self.createSessions(from: config)
}
}
)
}
@MainActor
private func addObservers() async {
NotificationCenter.default
.publisher(for: UIApplication.willEnterForegroundNotification)
.sink { [weak self] _ in
Task {
await self?.willEnterForeground()
}
}
.store(in: &observerCancellables)
NotificationCenter.default
.publisher(for: UIApplication.didEnterBackgroundNotification)
.sink { [weak self] _ in
Task {
await self?.didEnterBackground()
}
}
.store(in: &observerCancellables)
}
private func willEnterForeground() async {
activeTriggerSession?.id = UUID().uuidString
activeTriggerSession?.endAt = nil
await enqueueCurrentTriggerSession()
}
private func didEnterBackground() async {
activeTriggerSession?.endAt = Date()
await enqueueCurrentTriggerSession()
}
// MARK: - Session Lifecycle
/// Creates a session for each potential trigger on config and manual paywall presentation and sends them off to the server.
func createSessions(from config: Config) async {
// Loop through triggers and create a session for each.
let isUserSubscribed = Superwall.shared.subscriptionStatus == .active
for trigger in config.triggers {
let pendingTriggerSession = TriggerSessionManagerLogic.createPendingTriggerSession(
configRequestId: configManager.config?.requestId,
userAttributes: identityManager.userAttributes,
isSubscribed: isUserSubscribed,
eventName: trigger.eventName,
appSession: appSessionManager.appSession
)
pendingTriggerSessions[trigger.eventName] = pendingTriggerSession
}
// Send the sessions back to the server.
await enqueuePendingTriggerSessions()
}
/// Active a pending trigger session.
///
/// - Parameters:
/// - presentationInfo: Information about the paywall presentation.
/// - presentingViewController: What view the paywall will be presented on, if any.
/// - paywall: The response from the server associated with the paywall
func activateSession(
for presentationInfo: PresentationInfo,
on presentingViewController: UIViewController? = nil,
paywall: Paywall? = nil,
triggerResult: InternalTriggerResult?,
trackEvent: (Trackable) async -> TrackingResult = Superwall.shared.track
) async -> String? {
guard let eventName = presentationInfo.eventName else {
// The paywall is being presented by identifier, which is what the debugger uses,
// and that's not supported.
return nil
}
guard var session = pendingTriggerSessions[eventName] else {
return nil
}
guard let outcome = TriggerSessionManagerLogic.outcome(
presentationInfo: presentationInfo,
presentingViewController: presentingViewController,
paywall: paywall,
triggerResult: triggerResult?.toPublicType()
) else {
return nil
}
// Update trigger session
session.userAttributes = JSON(identityManager.userAttributes)
session.presentationOutcome = outcome.presentationOutcome
session.trigger = outcome.trigger
session.paywall = outcome.paywall
session.products = TriggerSession.Products(
allProducts: paywall?.swProducts ?? [],
loadingInfo: paywall?.productsLoadingInfo
)
session.appSession = appSessionManager.appSession
self.activeTriggerSession = session
pendingTriggerSessions[eventName] = nil
if let triggerResult = triggerResult {
let trackedEvent = InternalSuperwallEvent.TriggerFire(
triggerResult: triggerResult,
sessionId: session.id,
triggerName: eventName
)
_ = await trackEvent(trackedEvent)
}
switch outcome.presentationOutcome {
case .holdout,
.noRuleMatch:
await endSession()
case .paywall:
await enqueueCurrentTriggerSession()
}
return session.id
}
/// Ends the active trigger session and resets it to `nil`.
func endSession() async {
guard var currentTriggerSession = activeTriggerSession else {
return
}
// Send off current trigger session
currentTriggerSession.endAt = Date()
activeTriggerSession = currentTriggerSession
await enqueueCurrentTriggerSession()
// Recreate a pending trigger session
let eventName = currentTriggerSession.trigger.eventName
let isUserSubscribed = Superwall.shared.subscriptionStatus == .active
let pendingTriggerSession = TriggerSessionManagerLogic.createPendingTriggerSession(
configRequestId: configManager.config?.requestId,
userAttributes: identityManager.userAttributes,
isSubscribed: isUserSubscribed,
eventName: eventName,
products: currentTriggerSession.products.allProducts,
appSession: appSessionManager.appSession
)
pendingTriggerSessions[eventName] = pendingTriggerSession
// Reset state of current trigger session
transactionCount = nil
activeTriggerSession = nil
}
/// Queues the trigger session to be sent back to the server.
private func enqueueCurrentTriggerSession() async {
guard var triggerSession = activeTriggerSession else {
return
}
let isUserSubscribed = Superwall.shared.subscriptionStatus == .active
triggerSession.isSubscribed = isUserSubscribed
await delegate.enqueue(triggerSession)
}
/// Queues all the pending trigger sessions to be sent back to the server.
private func enqueuePendingTriggerSessions() async {
let isUserSubscribed = Superwall.shared.subscriptionStatus == .active
for eventName in pendingTriggerSessions.keys {
guard var pendingTriggerSession = pendingTriggerSessions[eventName] else {
continue
}
pendingTriggerSession.isSubscribed = isUserSubscribed
pendingTriggerSessions[eventName] = pendingTriggerSession
}
let triggerSessionsArray = Array(pendingTriggerSessions.values)
await delegate.enqueue(triggerSessionsArray)
}
// MARK: - App Session
/// Adds the latest app session to the trigger
func updateAppSession(to appSession: AppSession) async {
activeTriggerSession?.appSession = appSession
for eventName in pendingTriggerSessions.keys {
var pendingTriggerSession = pendingTriggerSessions[eventName]
pendingTriggerSession?.appSession = appSession
pendingTriggerSessions[eventName] = pendingTriggerSession
}
await enqueuePendingTriggerSessions()
await enqueueCurrentTriggerSession()
}
// MARK: - Paywall
/// Tracks when the paywall was opened
func trackPaywallOpen() async {
activeTriggerSession?.paywall?.action.openAt = Date()
await enqueueCurrentTriggerSession()
}
/// Tracks when paywall was closed and then ends the session.
func trackPaywallClose() async {
activeTriggerSession?.paywall?.action.closeAt = Date()
await endSession()
}
// MARK: - Webview Load
/// Tracks when a webview started to load.
func trackWebviewLoad(
forPaywallId paywallId: String,
state: LoadState
) async {
// Check the webview that's loading is for the active trigger session paywall.
// Without this check preloading paywalls could intefere.
guard paywallId == activeTriggerSession?.paywall?.databaseId else {
return
}
switch state {
case .start:
activeTriggerSession?
.paywall?
.webviewLoading
.startAt = Date()
case .end:
activeTriggerSession?
.paywall?
.webviewLoading
.endAt = Date()
case .fail:
activeTriggerSession?
.paywall?
.webviewLoading
.failAt = Date()
}
await enqueueCurrentTriggerSession()
}
// MARK: - Paywall Response Load
/// Tracks when a paywall started to load.
func trackPaywallResponseLoad(
forPaywallId paywallId: String?,
state: LoadState
) async {
if paywallId == nil {
return
}
// Otherwise, we check against the databaseId of the paywall
guard paywallId == activeTriggerSession?.paywall?.databaseId else {
return
}
switch state {
case .start:
activeTriggerSession?
.paywall?
.responseLoading
.startAt = Date()
case .end:
activeTriggerSession?
.paywall?
.responseLoading
.endAt = Date()
case .fail:
activeTriggerSession?
.paywall?
.responseLoading
.failAt = Date()
}
await enqueueCurrentTriggerSession()
}
// MARK: - Products
/// Tracks when products started to load.
func trackProductsLoad(
forPaywallId paywallId: String,
state: LoadState
) async {
guard paywallId == activeTriggerSession?.paywall?.databaseId else {
return
}
switch state {
case .start:
activeTriggerSession?
.products
.loadingInfo?
.startAt = Date()
case .end:
activeTriggerSession?
.products
.loadingInfo?
.endAt = Date()
case .fail:
activeTriggerSession?
.products
.loadingInfo?
.failAt = Date()
}
await enqueueCurrentTriggerSession()
}
// MARK: - Transactions
func trackBeginTransaction(
of product: StoreProduct
) async {
// Determine local transaction count, per trigger session.
if transactionCount != nil {
transactionCount?.start += 1
} else {
transactionCount = .init(start: 1)
}
let productIndex = activeTriggerSession?
.products
.allProducts
.firstIndex {
$0.productIdentifier == product.productIdentifier
} ?? 0
activeTriggerSession?.transaction = await .init(
startAt: Date(),
count: transactionCount,
product: .init(from: product, index: productIndex)
)
await enqueueCurrentTriggerSession()
}
/// When a transaction error occurred.
func trackTransactionError() async {
transactionCount?.fail += 1
activeTriggerSession?
.transaction?
.count = transactionCount
activeTriggerSession?
.transaction?
.endAt = Date()
activeTriggerSession?
.transaction?
.status = .fail
await enqueueCurrentTriggerSession()
activeTriggerSession?
.transaction = nil
}
/// When a transaction has been abandoned.
func trackTransactionAbandon() async {
transactionCount?.abandon += 1
activeTriggerSession?
.transaction?
.count = transactionCount
activeTriggerSession?
.transaction?
.status = .abandon
activeTriggerSession?
.transaction?
.endAt = Date()
await enqueueCurrentTriggerSession()
activeTriggerSession?
.transaction = nil
}
/// When a transaction is restored. A restore is triggered without any other transaction occurring.
func trackTransactionRestoration(
withId id: String? = nil,
product: StoreProduct? = nil
) async {
if transactionCount != nil {
transactionCount?.restore += 1
} else {
transactionCount = .init(restore: 1)
}
var transaction: TriggerSession.Transaction
var transactingProduct: TriggerSession.Transaction.Product?
if let product = product {
let productIndex = activeTriggerSession?
.products
.allProducts
.firstIndex {
$0.productIdentifier == product.productIdentifier
} ?? 0
transactingProduct = await .init(from: product, index: productIndex)
}
let date = Date()
transaction = .init(
id: id,
startAt: date,
endAt: date,
count: transactionCount,
status: .complete,
product: transactingProduct
)
activeTriggerSession?
.transaction = transaction
await enqueueCurrentTriggerSession()
activeTriggerSession?
.transaction = nil
}
func trackPendingTransaction() async {
transactionCount?.fail += 1
activeTriggerSession?
.transaction?
.count = transactionCount
activeTriggerSession?
.transaction?
.status = .fail
activeTriggerSession?
.transaction?
.endAt = Date()
await enqueueCurrentTriggerSession()
activeTriggerSession?
.transaction = nil
}
func trackTransactionSucceeded(
withId id: String?,
for product: StoreProduct,
isFreeTrialAvailable: Bool
) async {
transactionCount?.complete += 1
activeTriggerSession?
.transaction?
.count = transactionCount
activeTriggerSession?
.transaction?
.id = id
activeTriggerSession?
.transaction?
.endAt = Date()
activeTriggerSession?
.transaction?
.status = .complete
activeTriggerSession?
.paywall?
.action
.convertedAt = Date()
let transactionOutcome = TriggerSessionManagerLogic.getTransactionOutcome(
for: product,
isFreeTrialAvailable: isFreeTrialAvailable
)
activeTriggerSession?
.transaction?
.outcome = transactionOutcome
await enqueueCurrentTriggerSession()
activeTriggerSession?
.transaction = nil
}
}