-
Notifications
You must be signed in to change notification settings - Fork 21
/
ConfigManager.swift
332 lines (289 loc) · 10.2 KB
/
ConfigManager.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
//
// File.swift
//
//
// Created by Yusuf Tör on 22/06/2022.
//
import UIKit
import Combine
class ConfigManager {
/// A publisher that emits just once only when `config` is non-`nil`.
var hasConfig: AnyPublisher<Config, Error> {
configState
.compactMap { $0.getConfig() }
.first()
.eraseToAnyPublisher()
}
/// The configuration of the Superwall dashboard
var configState = CurrentValueSubject<ConfigState, Error>(.retrieving)
/// Convenience variable to access config.
var config: Config? {
return configState.value.getConfig()
}
/// Options for configuring the SDK.
var options = SuperwallOptions()
/// A dictionary of triggers by their event name.
@DispatchQueueBacked
var triggersByEventName: [String: Trigger] = [:]
/// A memory store of assignments that are yet to be confirmed.
///
/// When the trigger is fired, the assignment is confirmed and stored to disk.
@DispatchQueueBacked
var unconfirmedAssignments: [Experiment.ID: Experiment.Variant] = [:]
private unowned let storeKitManager: StoreKitManager
private unowned let storage: Storage
private unowned let network: Network
private unowned let paywallManager: PaywallManager
/// A task that is non-`nil` when preloading all paywalls.
private var currentPreloadingTask: Task<Void, Never>?
private let factory: RequestFactory & RuleAttributesFactory & ReceiptFactory
init(
options: SuperwallOptions?,
storeKitManager: StoreKitManager,
storage: Storage,
network: Network,
paywallManager: PaywallManager,
factory: RequestFactory & RuleAttributesFactory & ReceiptFactory
) {
if let options = options {
self.options = options
}
self.storeKitManager = storeKitManager
self.storage = storage
self.network = network
self.paywallManager = paywallManager
self.factory = factory
}
func fetchConfiguration() async {
do {
_ = await factory.loadPurchasedProducts()
let config = try await network.getConfig { [weak self] in
self?.configState.send(.retrying)
}
Task { await sendProductsBack(from: config) }
await processConfig(config)
configState.send(.retrieved(config))
Task { await preloadPaywalls() }
} catch {
configState.send(completion: .failure(error))
Logger.debug(
logLevel: .error,
scope: .superwallCore,
message: "Failed to Fetch Configuration",
info: nil,
error: error
)
}
}
private func processConfig(_ config: Config) async {
storage.save(config.featureFlags.disableVerboseEvents, forType: DisableVerboseEvents.self)
triggersByEventName = ConfigLogic.getTriggersByEventName(from: config.triggers)
choosePaywallVariants(from: config.triggers)
await checkForTouchesBeganTrigger(in: config.triggers)
}
/// Reassigns variants and preloads paywalls again.
func reset() {
guard let config = configState.value.getConfig() else {
return
}
unconfirmedAssignments.removeAll()
choosePaywallVariants(from: config.triggers)
Task { await preloadPaywalls() }
}
/// Swizzles the UIWindow's `sendEvent` to intercept the first `began` touch event if
/// config's triggers contain `touches_began`.
private func checkForTouchesBeganTrigger(in triggers: Set<Trigger>) async {
if triggers.contains(where: { $0.eventName == SuperwallEvent.touchesBegan.description }) {
await UIWindow.swizzleSendEvent()
}
}
// MARK: - Assignments
private func choosePaywallVariants(from triggers: Set<Trigger>) {
updateAssignments { confirmedAssignments in
ConfigLogic.chooseAssignments(
fromTriggers: triggers,
confirmedAssignments: confirmedAssignments
)
}
}
/// Gets the assignments from the server and saves them to disk, overwriting any that already exist on disk/in memory.
func getAssignments() async throws {
let config = try await configState
.compactMap { $0.getConfig() }
.throwableAsync()
let triggers = config.triggers
guard !triggers.isEmpty else {
return
}
do {
let assignments = try await network.getAssignments()
updateAssignments { confirmedAssignments in
ConfigLogic.transferAssignmentsFromServerToDisk(
assignments: assignments,
triggers: triggers,
confirmedAssignments: confirmedAssignments,
unconfirmedAssignments: unconfirmedAssignments
)
}
if Superwall.shared.options.paywalls.shouldPreload {
Task { await preloadAllPaywalls() }
}
} catch {
Logger.debug(
logLevel: .error,
scope: .configManager,
message: "Error retrieving assignments.",
error: error
)
}
}
/// Sends an assignment confirmation to the server and updates on-device assignments.
func confirmAssignment(_ assignment: ConfirmableAssignment) {
let postback: AssignmentPostback = .create(from: assignment)
Task { await network.confirmAssignments(postback) }
updateAssignments { confirmedAssignments in
ConfigLogic.move(
assignment,
from: unconfirmedAssignments,
to: confirmedAssignments
)
}
}
/// Performs a given operation on the confirmed assignments, before updating both confirmed
/// and unconfirmed assignments.
///
/// - Parameters:
/// - operation: Provided logic that takes confirmed assignments by ID and returns updated assignments.
private func updateAssignments(
using operation: ([Experiment.ID: Experiment.Variant]) -> ConfigLogic.AssignmentOutcome
) {
var confirmedAssignments = storage.getConfirmedAssignments()
let updatedAssignments = operation(confirmedAssignments)
unconfirmedAssignments = updatedAssignments.unconfirmed
confirmedAssignments = updatedAssignments.confirmed
storage.saveConfirmedAssignments(confirmedAssignments)
}
// MARK: - Preloading Paywalls
private func getTreatmentPaywallIds(from triggers: Set<Trigger>) -> Set<String> {
guard let config = configState.value.getConfig() else {
return []
}
let preloadableTriggers = ConfigLogic.filterTriggers(
triggers,
removing: config.preloadingDisabled
)
if preloadableTriggers.isEmpty {
return []
}
let confirmedAssignments = storage.getConfirmedAssignments()
return ConfigLogic.getActiveTreatmentPaywallIds(
forTriggers: preloadableTriggers,
confirmedAssignments: confirmedAssignments,
unconfirmedAssignments: unconfirmedAssignments
)
}
/// Preloads paywalls.
///
/// A developer can disable preloading of paywalls by setting ``SuperwallOptions/shouldPreloadPaywalls``.
private func preloadPaywalls() async {
guard Superwall.shared.options.paywalls.shouldPreload else {
return
}
await preloadAllPaywalls()
}
/// Preloads paywalls referenced by triggers.
func preloadAllPaywalls() async {
guard currentPreloadingTask == nil else {
return
}
currentPreloadingTask = Task {
guard let config = try? await configState
.compactMap({ $0.getConfig() })
.throwableAsync() else {
return
}
let expressionEvaluator = ExpressionEvaluator(
storage: storage,
factory: factory
)
let triggers = ConfigLogic.filterTriggers(
config.triggers,
removing: config.preloadingDisabled
)
let confirmedAssignments = storage.getConfirmedAssignments()
let paywallIds = await ConfigLogic.getAllActiveTreatmentPaywallIds(
fromTriggers: triggers,
confirmedAssignments: confirmedAssignments,
unconfirmedAssignments: unconfirmedAssignments,
expressionEvaluator: expressionEvaluator
)
await preloadPaywalls(withIdentifiers: paywallIds)
currentPreloadingTask = nil
}
}
/// Preloads paywalls referenced by the provided triggers.
func preloadPaywalls(for eventNames: Set<String>) async {
guard let config = try? await configState
.compactMap({ $0.getConfig() })
.throwableAsync() else {
return
}
let triggersToPreload = config.triggers.filter { eventNames.contains($0.eventName) }
let triggerPaywallIdentifiers = getTreatmentPaywallIds(from: triggersToPreload)
await preloadPaywalls(withIdentifiers: triggerPaywallIdentifiers)
}
/// Preloads paywalls referenced by triggers.
private func preloadPaywalls(withIdentifiers paywallIdentifiers: Set<String>) async {
await withTaskGroup(of: Void.self) { group in
for identifier in paywallIdentifiers {
group.addTask { [weak self] in
guard let self = self else {
return
}
let request = self.factory.makePaywallRequest(
eventData: nil,
responseIdentifiers: .init(paywallId: identifier),
overrides: nil,
isDebuggerLaunched: false,
presentationSourceType: nil,
retryCount: 6
)
let shouldSkip = try? await self.paywallManager.preloadViaPaywallArchivalAndShouldSkipViewControllerCache(form: request)
if (shouldSkip != nil && shouldSkip == true) {
_ = try? await self.paywallManager.getPaywallViewController(
from: request,
isForPresentation: true,
isPreloading: true,
delegate: nil
)
}
}
}
}
}
/// This sends product data back to the dashboard.
private func sendProductsBack(from config: Config) async {
guard config.featureFlags.enablePostback else {
return
}
let milliseconds = 1000
let nanoseconds = UInt64(milliseconds * 1_000_000)
let duration = UInt64(config.postback.postbackDelay) * nanoseconds
do {
try await Task.sleep(nanoseconds: duration)
let productIds = config.postback.productsToPostBack.map { $0.identifier }
let products = try await storeKitManager.getProducts(withIds: productIds)
let postbackProducts = products.productsById.values.map(PostbackProduct.init)
let postback = Postback(products: postbackProducts)
await network.sendPostback(postback)
} catch {
Logger.debug(
logLevel: .error,
scope: .debugViewController,
message: "No Paywall Response",
info: nil,
error: error
)
}
}
}