-
Notifications
You must be signed in to change notification settings - Fork 22
/
DependencyContainer.swift
523 lines (466 loc) · 15.7 KB
/
DependencyContainer.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
//
// File.swift
//
//
// Created by Yusuf Tör on 23/12/2022.
//
// swiftlint:disable function_body_length file_length
import UIKit
import Combine
import SystemConfiguration
import StoreKit
/// Contains all of the SDK's core utility objects that are normally directly injected as dependencies.
///
/// This conforms to protocol factory methods which can be used to make objects that have
/// dependencies injected into them.
///
/// Objects only need `unowned` references to the dependencies injected into them because
/// `DependencyContainer` is owned by the `Superwall` class.
final class DependencyContainer {
// swiftlint:disable implicitly_unwrapped_optional
var configManager: ConfigManager!
var identityManager: IdentityManager!
var storeKitManager: StoreKitManager!
var appSessionManager: AppSessionManager!
var sessionEventsManager: SessionEventsManager!
var storage: Storage!
var network: Network!
var paywallManager: PaywallManager!
var paywallRequestManager: PaywallRequestManager!
var deviceHelper: DeviceHelper!
var eventsQueue: EventsQueue!
var debugManager: DebugManager!
var api: Api!
var transactionManager: TransactionManager!
var delegateAdapter: SuperwallDelegateAdapter!
var productPurchaser: ProductPurchaserSK1!
var receiptManager: ReceiptManager!
var purchaseController: PurchaseController!
// swiftlint:enable implicitly_unwrapped_optional
let productsFetcher = ProductsFetcherSK1()
let paywallArchivalManager: PaywallArchivalManager
init(
purchaseController controller: PurchaseController? = nil,
options: SuperwallOptions? = nil
) {
paywallArchivalManager = PaywallArchivalManager()
purchaseController = controller ?? AutomaticPurchaseController(factory: self)
receiptManager = ReceiptManager(
delegate: productsFetcher,
receiptDelegate: purchaseController as? ReceiptDelegate
)
storeKitManager = StoreKitManager(productsFetcher: productsFetcher)
delegateAdapter = SuperwallDelegateAdapter()
storage = Storage(factory: self)
network = Network(factory: self)
paywallRequestManager = PaywallRequestManager(
storeKitManager: storeKitManager,
network: network,
factory: self
)
paywallManager = PaywallManager(
factory: self,
paywallRequestManager: paywallRequestManager
)
configManager = ConfigManager(
options: options,
storeKitManager: storeKitManager,
storage: storage,
network: network,
paywallManager: paywallManager,
factory: self
)
api = Api(networkEnvironment: configManager.options.networkEnvironment)
deviceHelper = DeviceHelper(
api: api,
storage: storage,
factory: self
)
eventsQueue = EventsQueue(
network: network,
configManager: configManager
)
identityManager = IdentityManager(
deviceHelper: deviceHelper,
storage: storage,
configManager: configManager
)
sessionEventsManager = SessionEventsManager(
queue: SessionEventsQueue(
storage: storage,
network: network,
configManager: configManager
),
storage: storage,
network: network,
configManager: configManager,
factory: self
)
// Must be after session events
appSessionManager = AppSessionManager(
configManager: configManager,
identityManager: identityManager,
storage: storage,
delegate: self
)
debugManager = DebugManager(
storage: storage,
factory: self
)
transactionManager = TransactionManager(
storeKitManager: storeKitManager,
receiptManager: receiptManager,
purchaseController: purchaseController,
sessionEventsManager: sessionEventsManager,
eventsQueue: eventsQueue,
factory: self
)
productPurchaser = ProductPurchaserSK1(
storeKitManager: storeKitManager,
receiptManager: receiptManager,
sessionEventsManager: sessionEventsManager,
factory: self
)
}
}
// MARK: - IdentityInfoFactory
extension DependencyContainer: IdentityInfoFactory {
func makeIdentityInfo() -> IdentityInfo {
return IdentityInfo(
aliasId: identityManager.aliasId,
appUserId: identityManager.appUserId
)
}
}
// MARK: - AppManagerDelegate
extension DependencyContainer: AppManagerDelegate {
func didUpdateAppSession(_ appSession: AppSession) async {
await sessionEventsManager.updateAppSession(appSession)
}
}
// MARK: - CacheFactory
extension DependencyContainer: CacheFactory {
func makeCache() -> PaywallViewControllerCache {
return PaywallViewControllerCache(deviceLocaleString: deviceHelper.locale)
}
}
// MARK - PaywallArchivalManager
extension DependencyContainer: PaywallArchivalManagerFactory {
func makePaywallArchivalManager() -> PaywallArchivalManager {
return self.paywallArchivalManager
}
}
// MARK: - DeviceInfofactory
extension DependencyContainer: DeviceHelperFactory {
func makeDeviceInfo() -> DeviceInfo {
return DeviceInfo(
appInstalledAtString: deviceHelper.appInstalledAtString,
locale: deviceHelper.locale
)
}
func makeIsSandbox() -> Bool {
return deviceHelper.isSandbox == "true"
}
func makeSessionDeviceAttributes() async -> [String: Any] {
var attributes = await deviceHelper.getTemplateDevice()
attributes["utcDate"] = nil
attributes["localDate"] = nil
attributes["localDate"] = nil
attributes["localTime"] = nil
attributes["utcTime"] = nil
attributes["utcDateTime"] = nil
attributes["localDateTime"] = nil
return attributes
}
}
// MARK: - DeviceInfofactory
extension DependencyContainer: LocaleIdentifierFactory {
func makeLocaleIdentifier() -> String? {
return configManager.options.localeIdentifier
}
}
// MARK: - ViewControllerFactory
extension DependencyContainer: ViewControllerFactory {
@MainActor
func makePaywallViewController(
for paywall: Paywall,
withCache cache: PaywallViewControllerCache?,
withPaywallArchivalManager archivalManager: PaywallArchivalManager?,
delegate: PaywallViewControllerDelegateAdapter?
) -> PaywallViewController {
let messageHandler = PaywallMessageHandler(
sessionEventsManager: sessionEventsManager,
factory: self
)
let webView = SWWebView(
isMac: deviceHelper.isMac,
sessionEventsManager: sessionEventsManager,
messageHandler: messageHandler
)
let paywallViewController = PaywallViewController(
paywall: paywall,
eventDelegate: Superwall.shared,
delegate: delegate,
deviceHelper: deviceHelper,
factory: self,
storage: storage,
webView: webView,
cache: cache,
paywallArchivalManager: paywallArchivalManager
)
webView.delegate = paywallViewController
messageHandler.delegate = paywallViewController
return paywallViewController
}
@MainActor
func makeDebugViewController(withDatabaseId id: String?) -> DebugViewController {
let viewController = DebugViewController(
storeKitManager: storeKitManager,
network: network,
paywallRequestManager: paywallRequestManager,
paywallManager: paywallManager,
debugManager: debugManager,
factory: self
)
viewController.paywallDatabaseId = id
viewController.modalPresentationStyle = .overFullScreen
return viewController
}
}
extension DependencyContainer: VariablesFactory {
func makeJsonVariables(
products: [ProductVariable]?,
computedPropertyRequests: [ComputedPropertyRequest],
event: EventData?
) async -> JSON {
let templateDeviceDict = await deviceHelper.getDeviceAttributes(
since: event,
computedPropertyRequests: computedPropertyRequests
)
return Variables(
products: products,
params: event?.parameters,
userAttributes: identityManager.userAttributes,
templateDeviceDictionary: templateDeviceDict
).templated()
}
}
// MARK: - PaywallRequestFactory
extension DependencyContainer: RequestFactory {
func makePaywallRequest(
eventData: EventData? = nil,
responseIdentifiers: ResponseIdentifiers,
overrides: PaywallRequest.Overrides? = nil,
isDebuggerLaunched: Bool,
presentationSourceType: String?,
retryCount: Int
) -> PaywallRequest {
return PaywallRequest(
eventData: eventData,
responseIdentifiers: responseIdentifiers,
overrides: overrides ?? PaywallRequest.Overrides(),
isDebuggerLaunched: isDebuggerLaunched,
presentationSourceType: presentationSourceType,
retryCount: retryCount
)
}
func makePresentationRequest(
_ presentationInfo: PresentationInfo,
paywallOverrides: PaywallOverrides? = nil,
presenter: UIViewController? = nil,
isDebuggerLaunched: Bool? = nil,
subscriptionStatus: AnyPublisher<SubscriptionStatus, Never>? = nil,
isPaywallPresented: Bool,
type: PresentationRequestType
) -> PresentationRequest {
return PresentationRequest(
presentationInfo: presentationInfo,
presenter: presenter,
paywallOverrides: paywallOverrides,
flags: .init(
isDebuggerLaunched: isDebuggerLaunched ?? debugManager.isDebuggerLaunched,
subscriptionStatus: subscriptionStatus ?? Superwall.shared.$subscriptionStatus.eraseToAnyPublisher(),
isPaywallPresented: isPaywallPresented,
type: type
)
)
}
}
// MARK: - ApiFactory
extension DependencyContainer: ApiFactory {
func makeHeaders(
fromRequest request: URLRequest,
isForDebugging: Bool,
requestId: String
) async -> [String: String] {
let key = isForDebugging ? storage.debugKey : storage.apiKey
let auth = "Bearer \(key)"
let headers = [
"Authorization": auth,
"X-Platform": "iOS",
"X-Platform-Environment": "SDK",
"X-Platform-Wrapper": deviceHelper.platformWrapper ?? "",
"X-App-User-ID": identityManager.appUserId ?? "",
"X-Alias-ID": identityManager.aliasId,
"X-URL-Scheme": deviceHelper.urlScheme,
"X-Vendor-ID": deviceHelper.vendorId,
"X-App-Version": deviceHelper.appVersion,
"X-OS-Version": deviceHelper.osVersion,
"X-Device-Model": deviceHelper.model,
"X-Device-Locale": deviceHelper.locale,
"X-Device-Language-Code": deviceHelper.languageCode,
"X-Device-Currency-Code": deviceHelper.currencyCode,
"X-Device-Currency-Symbol": deviceHelper.currencySymbol,
"X-Device-Timezone-Offset": deviceHelper.secondsFromGMT,
"X-App-Install-Date": deviceHelper.appInstalledAtString,
"X-Radio-Type": deviceHelper.radioType,
"X-Device-Interface-Style": deviceHelper.interfaceStyle,
"X-SDK-Version": sdkVersion,
"X-Request-Id": requestId,
"X-Bundle-ID": deviceHelper.bundleId,
"X-Low-Power-Mode": deviceHelper.isLowPowerModeEnabled,
"X-Is-Sandbox": deviceHelper.isSandbox,
"X-Subscription-Status": Superwall.shared.subscriptionStatus.description,
"Content-Type": "application/json"
]
return headers
}
func makeDefaultComponents(host: EndpointHost) -> ApiHostConfig {
return self.api.getConfig(host: host)
}
}
// MARK: - Rule Params
extension DependencyContainer: RuleAttributesFactory {
func makeRuleAttributes(
forEvent event: EventData?,
withComputedProperties computedPropertyRequests: [ComputedPropertyRequest]
) async -> JSON {
var userAttributes = identityManager.userAttributes
userAttributes["isLoggedIn"] = identityManager.isLoggedIn
let deviceAttributes = await deviceHelper.getDeviceAttributes(
since: event,
computedPropertyRequests: computedPropertyRequests
)
return JSON([
"user": userAttributes,
"device": deviceAttributes,
"params": event?.parameters.dictionaryObject ?? ""
] as [String: Any])
}
}
// MARK: - TriggerSessionManager
extension DependencyContainer: TriggerSessionManagerFactory {
func makeTriggerSessionManager() -> TriggerSessionManager {
// Separating delegate and sessionEventsManager to support testing.
return TriggerSessionManager(
delegate: sessionEventsManager,
sessionEventsManager: sessionEventsManager,
storage: storage,
configManager: configManager,
appSessionManager: appSessionManager,
identityManager: identityManager
)
}
func getTriggerSessionManager() -> TriggerSessionManager {
return sessionEventsManager.triggerSession
}
}
// MARK: - ConfigManagerFactory
extension DependencyContainer: ConfigManagerFactory {
/// Gets the paywall response from the static config, if the device locale starts with "en" and no more specific version can be found.
func makeStaticPaywall(
withId paywallId: String?,
isDebuggerLaunched: Bool
) -> Paywall? {
if isDebuggerLaunched {
return nil
}
let deviceInfo = makeDeviceInfo()
return ConfigLogic.getStaticPaywall(
withId: paywallId,
config: configManager.config,
deviceLocale: deviceInfo.locale
)
}
}
// MARK: - StoreTransactionFactory
extension DependencyContainer: StoreTransactionFactory {
func makeStoreTransaction(from transaction: SK1Transaction) async -> StoreTransaction {
return StoreTransaction(
transaction: SK1StoreTransaction(transaction: transaction),
configRequestId: configManager.config?.requestId ?? "",
appSessionId: appSessionManager.appSession.id
)
}
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, *)
func makeStoreTransaction(from transaction: SK2Transaction) async -> StoreTransaction {
return StoreTransaction(
transaction: SK2StoreTransaction(transaction: transaction),
configRequestId: configManager.config?.requestId ?? "",
appSessionId: appSessionManager.appSession.id
)
}
}
// MARK: - Options Factory
extension DependencyContainer: OptionsFactory {
func makeSuperwallOptions() -> SuperwallOptions {
return configManager.options
}
}
// MARK: - Triggers Factory
extension DependencyContainer: TriggerFactory {
func makeTriggers() -> Set<String> {
return Set(configManager.triggersByEventName.keys)
}
}
// MARK: - Purchase Controller Factory
extension DependencyContainer: HasExternalPurchaseControllerFactory {
func makeHasExternalPurchaseController() -> Bool {
return purchaseController.isInternal == false
}
}
// MARK: - Feature Flags Factory
extension DependencyContainer: FeatureFlagsFactory {
func makeFeatureFlags() -> FeatureFlags? {
return configManager.config?.featureFlags
}
}
// MARK: - Computed Property Requests Factory
extension DependencyContainer: ComputedPropertyRequestsFactory {
func makeComputedPropertyRequests() -> [ComputedPropertyRequest] {
return configManager.config?.allComputedProperties ?? []
}
}
// MARK: - Purchased Transactions Factory
extension DependencyContainer: PurchasedTransactionsFactory {
func makePurchasingCoordinator() -> PurchasingCoordinator {
return productPurchaser.coordinator
}
func purchase(product: SKProduct) async -> PurchaseResult {
return await productPurchaser.purchase(product: product)
}
func restorePurchases() async -> RestorationResult {
return await productPurchaser.restorePurchases()
}
}
// MARK: - User Attributes Event Factory
extension DependencyContainer: UserAttributesEventFactory {
func makeUserAttributesEvent() -> InternalSuperwallEvent.Attributes {
return InternalSuperwallEvent.Attributes(
appInstalledAtString: deviceHelper.appInstalledAtString,
customParameters: identityManager.userAttributes
)
}
}
// MARK: - Receipt factory
extension DependencyContainer: ReceiptFactory {
func loadPurchasedProducts() async -> Set<StoreProduct>? {
return await receiptManager.loadPurchasedProducts()
}
func refreshReceipt() async {
return await receiptManager.refreshReceipt()
}
func isFreeTrialAvailable(for product: StoreProduct) async -> Bool {
return await receiptManager.isFreeTrialAvailable(for: product)
}
}