This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 444
/
Copy pathBuyVPNViewController.swift
315 lines (244 loc) · 8.89 KB
/
BuyVPNViewController.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
// Copyright 2020 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import Shared
import Preferences
import StoreKit
import os.log
import DesignSystem
class BuyVPNViewController: VPNSetupLoadingController {
let iapObserver: IAPObserver
private var iapRestoreTimer: Timer?
var activeSubcriptionChoice: SubscriptionType = .yearly {
didSet {
buyVPNView.activeSubcriptionChoice = activeSubcriptionChoice
}
}
init(iapObserver: IAPObserver) {
self.iapObserver = iapObserver
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
private var buyVPNView = BuyVPNView(with: .yearly)
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.VPN.vpnName
view.backgroundColor = BraveVPNCommonUI.UX.purpleBackgroundColor
navigationItem.standardAppearance = BraveVPNCommonUI.navigationBarAppearance
navigationItem.scrollEdgeAppearance = BraveVPNCommonUI.navigationBarAppearance
navigationItem.rightBarButtonItem = .init(
title: Strings.VPN.restorePurchases, style: .done,
target: self, action: #selector(restorePurchasesAction))
let buyTitle = Preferences.VPN.freeTrialUsed.value
? Strings.VPN.activateSubscriptionAction.capitalized
: Strings.VPN.freeTrialPeriodAction.capitalized
let buyButton = BraveGradientButton(gradient: .backgroundGradient1).then {
$0.titleLabel?.font = .systemFont(ofSize: 15, weight: .bold)
$0.titleLabel?.textAlignment = .center
$0.setTitle(buyTitle, for: .normal)
$0.snp.makeConstraints {
$0.height.equalTo(50)
}
$0.layer.do {
$0.cornerRadius = 24
$0.cornerCurve = .continuous
$0.masksToBounds = true
}
$0.addTarget(self, action: #selector(startSubscriptionAction), for: .touchUpInside)
}
let redeemButton = UIButton().then {
$0.setTitle(Strings.VPN.vpnRedeemCodeButtonActionTitle, for: .normal)
$0.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
$0.titleLabel?.textAlignment = .center
$0.addTarget(self, action: #selector(redeemOfferSubscriptionCode), for: .touchUpInside)
}
let seperator = UIView().then {
$0.backgroundColor = UIColor.white.withAlphaComponent(0.1)
$0.snp.makeConstraints { make in
make.height.equalTo(1)
}
}
view.addSubview(buyVPNView)
view.addSubview(seperator)
view.addSubview(buyButton)
view.addSubview(redeemButton)
buyVPNView.snp.makeConstraints {
$0.leading.trailing.top.equalToSuperview()
}
seperator.snp.makeConstraints() {
$0.top.equalTo(buyVPNView.snp.bottom)
$0.leading.trailing.equalToSuperview()
}
buyButton.snp.makeConstraints() {
$0.top.equalTo(seperator.snp.bottom).inset(-12)
$0.leading.trailing.equalToSuperview().inset(24)
}
redeemButton.snp.makeConstraints() {
$0.top.equalTo(buyButton.snp.bottom).inset(-12)
$0.bottom.equalToSuperview().inset(24)
$0.centerX.equalToSuperview()
}
buyVPNView.monthlySubButton
.addTarget(self, action: #selector(monthlySubscriptionAction), for: .touchUpInside)
buyVPNView.yearlySubButton
.addTarget(self, action: #selector(yearlySubscriptionAction), for: .touchUpInside)
iapObserver.delegate = self
Preferences.VPN.popupShowed.value = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// navigationItem.standardAppearance does not support tinting the back button for some
// reason, so we still must apply a custom tint to the bar
navigationController?.navigationBar.tintColor = .white
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Reset styling set above
navigationController?.navigationBar.tintColor = UINavigationBar.appearance().tintColor
}
// MARK: - Button Actions
@objc func yearlySubscriptionAction() {
activeSubcriptionChoice = .yearly
}
@objc func monthlySubscriptionAction() {
activeSubcriptionChoice = .monthly
}
@objc func closeView() {
dismiss(animated: true)
}
@objc func restorePurchasesAction() {
isLoading = true
SKPaymentQueue.default().restoreCompletedTransactions()
if iapRestoreTimer != nil {
iapRestoreTimer?.invalidate()
iapRestoreTimer = nil
}
// Adding 1 minute timer for restore
iapRestoreTimer = Timer.scheduledTimer(
timeInterval: 1.minutes,
target: self,
selector: #selector(handleRestoreTimeoutFailure),
userInfo: nil,
repeats: false)
}
@objc func startSubscriptionAction() {
addPaymentForSubcription(type: activeSubcriptionChoice)
}
@objc func redeemOfferSubscriptionCode() {
// Open the redeem code sheet
SKPaymentQueue.default().presentCodeRedemptionSheet()
}
private func addPaymentForSubcription(type: SubscriptionType) {
var subscriptionProduct: SKProduct?
switch type {
case .yearly:
subscriptionProduct = VPNProductInfo.yearlySubProduct
case .monthly:
subscriptionProduct = VPNProductInfo.monthlySubProduct
}
guard let subscriptionProduct = subscriptionProduct else {
Logger.module.error("Failed to retrieve \(type.rawValue) subcription product")
return
}
isLoading = true
let payment = SKPayment(product: subscriptionProduct)
SKPaymentQueue.default().add(payment)
}
}
// MARK: - IAPObserverDelegate
extension BuyVPNViewController: IAPObserverDelegate {
func purchasedOrRestoredProduct(validateReceipt: Bool) {
DispatchQueue.main.async {
self.isLoading = false
}
// Not using `push` since we don't want the user to go back.
DispatchQueue.main.async {
self.navigationController?.setViewControllers(
[InstallVPNViewController()],
animated: true)
}
if validateReceipt {
BraveVPN.validateReceiptData()
}
}
func purchaseFailed(error: IAPObserver.PurchaseError) {
// Handle Transaction or Restore error
guard isLoading else {
return
}
handleTransactionError(error: error)
}
func handlePromotedInAppPurchase() {
// No-op In app purchase promotion is handled on bvc
}
@objc func handleRestoreTimeoutFailure() {
// Handle Restore error from timeout
guard isLoading else {
return
}
let errorRestore = SKError(SKError.unknown, userInfo: ["detail": "time-out"])
handleTransactionError(error: .transactionError(error: errorRestore))
}
private func handleTransactionError(error: IAPObserver.PurchaseError) {
DispatchQueue.main.async {
self.isLoading = false
// User intentionally tapped to cancel purchase , no need to show any alert on our side.
if case .transactionError(let err) = error, err?.code == SKError.paymentCancelled {
return
}
// For all other errors, we attach associated code for easier debugging.
// See SKError.h for list of all codes.
let message = Strings.VPN.vpnErrorPurchaseFailedBody
let alert = UIAlertController(
title: Strings.VPN.vpnErrorPurchaseFailedTitle,
message: message,
preferredStyle: .alert)
let ok = UIAlertAction(title: Strings.OKString, style: .default, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true)
}
}
}
class VPNSetupLoadingController: UIViewController {
private var overlayView: UIView?
var isLoading: Bool = false {
didSet {
overlayView?.removeFromSuperview()
// Disable Action bar button while loading
navigationItem.rightBarButtonItem?.isEnabled = !isLoading
// Prevent dismissing the modal by swipe
navigationController?.isModalInPresentation = isLoading == true
if !isLoading { return }
let overlay = UIView().then {
$0.backgroundColor = UIColor.black.withAlphaComponent(0.5)
let activityIndicator = UIActivityIndicatorView().then {
$0.startAnimating()
$0.autoresizingMask = [.flexibleWidth, .flexibleHeight]
$0.style = .large
$0.color = .white
}
$0.addSubview(activityIndicator)
}
view.addSubview(overlay)
overlay.snp.makeConstraints {
$0.edges.equalToSuperview()
}
overlayView = overlay
}
}
}
extension BraveGradient {
public static var backgroundGradient1: BraveGradient {
.init(
stops: [
.init(color: UIColor(rgb: 0x8b10c6), position: 0.22),
.init(color: UIColor(rgb: 0xd02480), position: 0.7),
.init(color: UIColor(rgb: 0xe95e3c), position: 0.96),
],
angle: .figmaDegrees(138)
)
}
}