This repository has been archived by the owner on May 6, 2024. It is now read-only.
/
CourseUpgradeHelper.swift
476 lines (393 loc) · 19.9 KB
/
CourseUpgradeHelper.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
//
// CourseUpgradeHelper.swift
// edX
//
// Created by Muhammad Umer on 16/12/2021.
// Copyright © 2021 edX. All rights reserved.
//
import Foundation
import MessageUI
import KeychainSwift
import StoreKit
let CourseUpgradeCompletionNotification = "CourseUpgradeCompletionNotification"
private let IAPKeychainKey = "CourseUpgradeIAPKeyChainKey"
struct CourseUpgradeModel {
let courseID: String
let blockID: String?
let screen: CourseUpgradeScreen
}
protocol CourseUpgradeHelperDelegate: AnyObject {
func hideAlertAction()
}
class CourseUpgradeHelper: NSObject {
typealias Environment = OEXAnalyticsProvider
static let shared = CourseUpgradeHelper()
private lazy var unlockController = ValuePropUnlockViewContainer()
weak private(set) var delegate: CourseUpgradeHelperDelegate?
private(set) var completion: (()-> ())? = nil
private lazy var keychain = KeychainSwift()
enum CompletionState {
case initial
case payment
case fulfillment(showLoader: Bool)
case success(_ courseID: String, _ componentID: String?)
case error(PurchaseError, Error?)
}
// These error actions are used to send in analytics
enum ErrorAction: String {
case refreshToRetry = "refresh"
case reloadPrice = "reload_price"
case emailSupport = "get_help"
case close = "close"
}
// These alert actions are used to send in analytics
enum AlertAction: String {
case close = "close"
case continueWithoutUpdate = "continue_without_update"
case getHelp = "get_help"
case refresh = "refresh"
}
private(set) var courseUpgradeModel: CourseUpgradeModel?
// These times are being used in analytics
private var startTime: CFTimeInterval?
private var refreshTime: CFTimeInterval?
private var paymentStartTime: CFTimeInterval?
private var contentUpgradeTime: CFTimeInterval?
private var environment: Environment?
private var pacing: String?
private var courseID: CourseBlockID?
private var blockID: CourseBlockID?
private var screen: CourseUpgradeScreen = .none
private var localizedCoursePrice: String?
weak private(set) var upgradeHadler: CourseUpgradeHandler?
private override init() { }
func setupHelperData(environment: Environment, pacing: String, courseID: CourseBlockID, blockID: CourseBlockID? = nil, localizedCoursePrice: String, screen: CourseUpgradeScreen) {
self.environment = environment
self.pacing = pacing
self.courseID = courseID
self.blockID = blockID
self.localizedCoursePrice = localizedCoursePrice
self.screen = screen
}
func resetUpgradeModel() {
courseUpgradeModel = nil
delegate = nil
}
func clearData() {
environment = nil
pacing = nil
courseID = nil
blockID = nil
localizedCoursePrice = nil
screen = .none
refreshTime = nil
startTime = nil
resetUpgradeModel()
}
func handleCourseUpgrade(upgradeHadler: CourseUpgradeHandler, state: CompletionState, delegate: CourseUpgradeHelperDelegate? = nil) {
self.delegate = delegate
self.upgradeHadler = upgradeHadler
switch state {
case .initial:
startTime = CFAbsoluteTimeGetCurrent()
break
case .payment:
paymentStartTime = CFAbsoluteTimeGetCurrent()
break
case .fulfillment(let show):
contentUpgradeTime = CFAbsoluteTimeGetCurrent()
if upgradeHadler.upgradeMode == .userInitiated {
let endTime = CFAbsoluteTimeGetCurrent() - (paymentStartTime ?? 0)
environment?.analytics.trackCourseUpgradePaymentTime(courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, elapsedTime: endTime.millisecond)
}
if show {
showLoader()
}
break
case .success(let courseID, let blockID):
courseUpgradeModel = CourseUpgradeModel(courseID: courseID, blockID: blockID, screen: screen)
if upgradeHadler.upgradeMode == .userInitiated {
postSuccessNotification()
}
else {
showSilentRefreshAlert()
}
break
case .error(let type, let error):
if type == .paymentError {
if let error = error as? SKError, error.code == .paymentCancelled {
environment?.analytics.trackCourseUpgradePaymentError(name: .CourseUpgradePaymentCancelError, biName: .CourseUpgradePaymentCancelError, courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, paymentError: upgradeHadler.formattedError)
}
else {
environment?.analytics.trackCourseUpgradePaymentError(name: .CourseUpgradePaymentError, biName: .CourseUpgradePaymentError, courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, paymentError: upgradeHadler.formattedError)
}
}
else {
environment?.analytics.trackCourseUpgradeError(courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, upgradeError: upgradeHadler.formattedError, flowType: upgradeHadler.upgradeMode.rawValue)
}
removeLoader(success: false, removeView: type != .verifyReceiptError)
break
}
}
func showSuccess() {
guard let topController = UIApplication.shared.topMostController() else { return }
topController.showBottomActionSnackBar(message: Strings.CourseUpgrade.successMessage, textSize: .xSmall, autoDismiss: true, duration: 3)
let contentTime = CFAbsoluteTimeGetCurrent() - (contentUpgradeTime ?? 0)
environment?.analytics.trackCourseUpgradeDuration(isRefresh: false, courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, elapsedTime: contentTime.millisecond, flowType: upgradeHadler?.upgradeMode.rawValue ?? "")
if let refreshTime = refreshTime {
let refreshEndTime = CFAbsoluteTimeGetCurrent() - refreshTime
environment?.analytics.trackCourseUpgradeDuration(isRefresh: true, courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, elapsedTime: refreshEndTime.millisecond, flowType: upgradeHadler?.upgradeMode.rawValue ?? "")
}
let endTime = CFAbsoluteTimeGetCurrent() - (startTime ?? 0)
environment?.analytics.trackCourseUpgradeSuccess(courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice ?? "", screen: screen, elapsedTime: endTime.millisecond, flowType: upgradeHadler?.upgradeMode.rawValue ?? "")
clearData()
}
func showError() {
guard let topController = UIApplication.shared.topMostController() else { return }
// not showing any error if payment is canceled by user
if case .error (let type, let error) = upgradeHadler?.state, type == .paymentError,
let error = error as? SKError, error.code == .paymentCancelled {
return
}
let alertController = UIAlertController().showAlert(withTitle: Strings.CourseUpgrade.FailureAlert.alertTitle, message: upgradeHadler?.errorMessage, cancelButtonTitle: nil, onViewController: topController) { _, _, _ in }
if case .error (let type, let error) = upgradeHadler?.state, type == .verifyReceiptError && error?.errorCode != 409 {
alertController.addButton(withTitle: Strings.CourseUpgrade.FailureAlert.refreshToRetry, style: .default) { [weak self] _ in
self?.trackUpgradeErrorAction(errorAction: ErrorAction.refreshToRetry)
self?.refreshTime = CFAbsoluteTimeGetCurrent()
self?.upgradeHadler?.reverifyPayment()
}
}
if case .complete = upgradeHadler?.state, completion != nil {
alertController.addButton(withTitle: Strings.CourseUpgrade.FailureAlert.refreshToRetry, style: .default) {[weak self] _ in
self?.trackUpgradeErrorAction(errorAction: ErrorAction.refreshToRetry)
self?.refreshTime = CFAbsoluteTimeGetCurrent()
self?.showLoader()
self?.completion?()
self?.completion = nil
}
}
alertController.addButton(withTitle: Strings.CourseUpgrade.FailureAlert.getHelp) { [weak self] _ in
self?.trackUpgradeErrorAction(errorAction: ErrorAction.emailSupport)
self?.launchEmailComposer(errorMessage: "Error: \(self?.upgradeHadler?.formattedError ?? "")")
}
alertController.addButton(withTitle: Strings.close, style: .default) { [weak self] _ in
self?.trackUpgradeErrorAction(errorAction: ErrorAction.close)
if self?.unlockController.isVisible == true {
self?.unlockController.removeView() {
self?.hideAlertAction()
}
}
else {
self?.hideAlertAction()
}
}
}
func showRestorePurchasesAlert(environment: Environment?) {
guard let topController = UIApplication.shared.topMostController() else { return }
let alertController = UIAlertController().showAlert(withTitle: Strings.CourseUpgrade.Restore.alertTitle, message: Strings.CourseUpgrade.Restore.alertMessage, cancelButtonTitle: nil, onViewController: topController) { _, _, _ in }
alertController.addButton(withTitle: Strings.CourseUpgrade.FailureAlert.getHelp) { [weak self] _ in
self?.launchEmailComposer(errorMessage: "Error: restore_purchases")
environment?.analytics.trackRestoreSuccessAlertAction(action: AlertAction.getHelp.rawValue)
}
alertController.addButton(withTitle: Strings.close, style: .default) { _ in
environment?.analytics.trackRestoreSuccessAlertAction(action: AlertAction.close.rawValue)
}
}
func showLoader(forceShow: Bool = false) {
if (!unlockController.isVisible && upgradeHadler?.upgradeMode == .userInitiated) || forceShow {
unlockController.showView()
}
}
func removeLoader(success: Bool? = false, removeView: Bool? = false, completion: (()-> ())? = nil) {
self.completion = completion
if success == true {
courseUpgradeModel = nil
}
if unlockController.isVisible, removeView == true {
unlockController.removeView() { [weak self] in
self?.courseUpgradeModel = nil
if success == true {
self?.showSuccess()
} else {
self?.showError()
}
}
} else if success == false {
showError()
}
}
private func trackUpgradeErrorAction(errorAction: ErrorAction) {
environment?.analytics.trackCourseUpgradeErrorAction(courseID: courseID ?? "", blockID: blockID, pacing: pacing ?? "", coursePrice: localizedCoursePrice, screen: screen, errorAction: errorAction.rawValue, upgradeError: upgradeHadler?.formattedError ?? "", flowType: upgradeHadler?.upgradeMode.rawValue ?? "")
}
private func hideAlertAction() {
delegate?.hideAlertAction()
clearData()
}
private func showSilentRefreshAlert() {
guard let topController = UIApplication.shared.topMostController() else { return }
let alertController = UIAlertController().alert(withTitle: Strings.CourseUpgrade.SuccessAlert.silentAlertTitle, message: Strings.CourseUpgrade.SuccessAlert.silentAlertMessage, cancelButtonTitle: nil) { _, _, _ in }
alertController.addButton(withTitle: Strings.CourseUpgrade.SuccessAlert.silentAlertRefresh, style: .default) {[weak self] _ in
self?.showLoader(forceShow: true)
self?.popToEnrolledCourses()
self?.trackCourseUpgradeNewEexperienceAlertAction(action: AlertAction.refresh.rawValue)
}
alertController.addButton(withTitle: Strings.CourseUpgrade.SuccessAlert.silentAlertContinue, style: .default) {[weak self] _ in
self?.resetUpgradeModel()
self?.trackCourseUpgradeNewEexperienceAlertAction(action: AlertAction.continueWithoutUpdate.rawValue)
}
topController.present(alertController, animated: true, completion: nil)
}
private func trackCourseUpgradeNewEexperienceAlertAction(action: String) {
environment?.analytics.trackCourseUpgradeNewEexperienceAlertAction(courseID: courseID ?? "", pacing: pacing ?? "", screen: screen, flowType: upgradeHadler?.upgradeMode.rawValue ?? "", action: action)
}
private func popToEnrolledCourses() {
dismiss { [weak self] in
guard let topController = UIApplication.shared.topMostController(),
let tabController = topController.navigationController?.viewControllers.first(where: {$0 is EnrolledCoursesViewController}) else {
self?.postSuccessNotification()
return
}
tabController.navigationController?.popToRootViewController(animated: false)
self?.markCourseContentRefresh()
self?.postSuccessNotification()
}
}
private func markCourseContentRefresh() {
guard let course = upgradeHadler?.course else { return }
let courseQuerier = OEXRouter.shared().environment.dataManager.courseDataManager.querierForCourseWithID(courseID: course.course_id ?? "", environment: OEXRouter.shared().environment)
courseQuerier.needsRefresh = true
}
private func dismiss(completion: @escaping () -> Void) {
if let rootController = UIApplication.shared.window?.rootViewController, rootController.presentedViewController != nil {
rootController.dismiss(animated: true) {
completion()
}
}
else {
completion()
}
}
private func postSuccessNotification() {
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: CourseUpgradeCompletionNotification), object: nil))
}
}
extension CourseUpgradeHelper: MFMailComposeViewControllerDelegate {
fileprivate func launchEmailComposer(errorMessage: String) {
guard let controller = UIApplication.shared.topMostController() else { return }
if !MFMailComposeViewController.canSendMail() {
guard let supportEmail = OEXRouter.shared().environment.config.feedbackEmailAddress() else { return }
UIAlertController().showAlert(withTitle: Strings.CourseUpgrade.emailNotSetupTitle, message: Strings.CourseUpgrade.emailNotSetupMessage(email: supportEmail), onViewController: controller)
} else {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.navigationBar.tintColor = OEXStyles.shared().navigationItemTintColor()
mail.setSubject(Strings.CourseUpgrade.getSupportEmailSubject)
let body = EmailTemplates.supportEmailMessageTemplate(error: errorMessage)
mail.setMessageBody(body, isHTML: false)
if let fbAddress = OEXRouter.shared().environment.config.feedbackEmailAddress() {
mail.setToRecipients([fbAddress])
}
controller.present(mail, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
guard let controller = UIApplication.shared.topMostController() else { return }
controller.dismiss(animated: true) { [weak self] in
if self?.unlockController.isVisible == true {
self?.unlockController.removeView() {
self?.hideAlertAction()
}
}
else {
self?.hideAlertAction()
}
}
}
}
// Handle Keychain
// Save inprogress in-app in the keychain for partially fulfilled IAP
extension CourseUpgradeHelper {
// Test Func for deleting data
func removekeyChain() {
keychain.delete(IAPKeychainKey)
}
func saveIAPInKeychain(_ sku: String?) {
guard let sku = sku,
let userName = OEXSession.shared()?.currentUser?.username, !sku.isEmpty else { return }
var purchases = savedIAPSKUsFromKeychain()
let existingPurchases = purchases[userName]?.filter { $0.identifier == sku}
if existingPurchases?.isEmpty ?? true {
let purchase = InappPurchase(with: sku, status: false)
if purchases[userName] == nil {
purchases[userName] = [purchase]
}
else {
purchases[userName]?.append(purchase)
}
}
if let data = try? NSKeyedArchiver.archivedData(withRootObject: purchases, requiringSecureCoding: false) {
keychain.set(data, forKey: IAPKeychainKey)
}
}
func removeIAPSKUFromKeychain(_ sku: String?) {
guard let sku = sku,
let userName = OEXSession.shared()?.currentUser?.username, !sku.isEmpty else { return }
var purchases = savedIAPSKUsFromKeychain()
let userPurchases = purchases[userName]?.filter { $0.identifier == sku && $0.status == false}
if !(userPurchases?.isEmpty ?? true) {
purchases[userName]?.removeAll(where: { $0.identifier == sku})
}
if let data = try? NSKeyedArchiver.archivedData(withRootObject: purchases, requiringSecureCoding: false) {
keychain.set(data, forKey: IAPKeychainKey)
}
}
func markIAPSKUCompleteInKeychain(_ sku: String?) {
guard let sku = sku,
let userName = OEXSession.shared()?.currentUser?.username, !sku.isEmpty else { return }
var purchases = savedIAPSKUsFromKeychain()
let userPurchases = purchases[userName] ?? []
for userPurchase in userPurchases where userPurchase.identifier == sku {
userPurchase.status = true
}
purchases[userName] = userPurchases
if let data = try? NSKeyedArchiver.archivedData(withRootObject: purchases, requiringSecureCoding: false) {
keychain.set(data, forKey: IAPKeychainKey)
}
}
private func savedIAPSKUsFromKeychain() -> [String : [InappPurchase]] {
guard let data = keychain.getData(IAPKeychainKey),
let purchases = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: [InappPurchase.self, NSDictionary.self, NSString.self, NSArray.self], from: data) as? [String : [InappPurchase]] ?? [:]
else { return [:] }
return purchases
}
func savedUnfinishedIAPSKUsForCurrentUser() -> [String]? {
guard let userName = OEXSession.shared()?.currentUser?.username else { return nil }
let purchases = savedIAPSKUsFromKeychain()
let unfinishedPurchases = purchases[userName]?.filter( { return $0.status == false })
return unfinishedPurchases?.compactMap { $0.identifier }
}
}
class InappPurchase: NSObject, NSCoding, NSSecureCoding {
var status: Bool = false
var identifier: String = ""
static var supportsSecureCoding: Bool {
return true
}
required init?(coder: NSCoder) {
identifier = coder.decodeObject(forKey: "identifier") as? String ?? ""
status = coder.decodeBool(forKey: "status")
}
init(with identifier: String, status: Bool) {
self.status = status
self.identifier = identifier
}
func encode(with coder: NSCoder) {
coder.encode(identifier, forKey: "identifier")
coder.encode(status, forKey: "status")
}
}
extension Error {
var errorCode:Int? {
return (self as NSError).code
}
}