-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathAccountVC.swift
473 lines (427 loc) · 22.1 KB
/
AccountVC.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
//
// AccountVC.swift
// Lockdown
//
// Created by Oleg Dreyman on 02.10.2020.
// Copyright © 2020 Confirmed Inc. All rights reserved.
//
import UIKit
import PopupDialog
import PromiseKit
import CocoaLumberjackSwift
final class AccountViewController: BaseViewController, Loadable {
// MARK: - Properties
let tableView = StaticTableView(frame: .zero, style: .grouped)
var activePlans: [Subscription.PlanType] = []
var feedbackFlow: FeedbackFlow?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
do {
view.addSubview(tableView)
tableView.anchors.edges.pin()
tableView.separatorStyle = .singleLine
tableView.cellLayoutMarginsFollowReadableWidth = true
tableView.deselectsCellsAutomatically = true
tableView.tableFooterView = UIView()
tableView.clear()
createTable()
}
do {
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange), name: AccountUI.accountStateDidChange, object: nil)
}
}
@objc
func accountStateDidChange() {
assert(Thread.isMainThread)
self.reloadTable()
}
func reloadTable() {
tableView.clear()
createTable()
tableView.reloadData()
}
func createTable() {
var title = NSLocalizedString("⚠️ Not Signed In", comment: "")
var message: String? = NSLocalizedString("Sign up below to unlock benefits of a Lockdown account.", comment: "")
var firstButton = DefaultCell(title: NSLocalizedString("Sign Up | Sign In", comment: "")) {
// AccountViewController will update itself by observing
// AccountUI.accountStateDidChange notification
AccountUI.presentCreateAccount(on: self)
}
firstButton.backgroundView = UIView()
firstButton.backgroundView?.backgroundColor = UIColor.tunnelsBlue
firstButton.label.textColor = UIColor.white
if let apiCredentials = getAPICredentials() {
message = apiCredentials.email
if getAPICredentialsConfirmed() == true {
title = NSLocalizedString("Signed In", comment: "")
firstButton = DefaultCell(title: NSLocalizedString("Sign Out", comment: "")) {
let confirm = PopupDialog(title: NSLocalizedString("Sign Out?", comment: ""),
message: NSLocalizedString("You'll be signed out from this account.", comment: ""),
image: nil,
buttonAlignment: .horizontal,
transitionStyle: .bounceDown,
preferredWidth: 270,
tapGestureDismissal: true,
panGestureDismissal: false,
hideStatusBar: false,
completion: nil)
confirm.addButtons([
DefaultButton(title: NSLocalizedString("Cancel", comment: ""), dismissOnTap: true) {
},
DefaultButton(title: NSLocalizedString("Sign Out", comment: ""), dismissOnTap: true) { [unowned self] in
URLCache.shared.removeAllCachedResponses()
Client.clearCookies()
clearAPICredentials()
setAPICredentialsConfirmed(confirmed: false)
self.reloadTable()
self.showPopupDialog(title: NSLocalizedString("Success", comment: ""), message: NSLocalizedString("Signed out successfully.", comment: ""), acceptButton: NSLocalizedString("Okay", comment: ""))
},
])
self.present(confirm, animated: true, completion: nil)
}
firstButton.backgroundView?.backgroundColor = UIColor.clear
firstButton.label.textColor = UIColor.systemRed
}
else {
title = "⚠️ Email Not Confirmed"
firstButton = DefaultCell(title: NSLocalizedString("Confirm Email", comment: "")) {
self.showLoadingView()
firstly {
try Client.signInWithEmail(email: apiCredentials.email, password: apiCredentials.password)
}
.done { (signin: SignIn) in
self.hideLoadingView()
// successfully signed in with no errors, show confirmation success
setAPICredentialsConfirmed(confirmed: true)
// logged in and confirmed - update this email with the receipt and refresh VPN credentials
firstly { () -> Promise<SubscriptionEvent> in
try Client.subscriptionEvent()
}
.then { (result: SubscriptionEvent) -> Promise<GetKey> in
try Client.getKey()
}
.done { (getKey: GetKey) in
try setVPNCredentials(id: getKey.id, keyBase64: getKey.b64)
if (getUserWantsVPNEnabled() == true) {
VPNController.shared.restart()
}
}
.catch { error in
// it's okay for this to error out with "no subscription in receipt"
DDLogError("HomeViewController ConfirmEmail subscriptionevent error (ok for it to be \"no subscription in receipt\"): \(error)")
}
let popup = PopupDialog(title: "Success! 🎉",
message: NSLocalizedString("Your account has been confirmed and you're now signed in. You'll get the latest block lists, access to Lockdown Mac, and get critical announcements.", comment: ""),
image: nil,
buttonAlignment: .horizontal,
transitionStyle: .bounceDown,
preferredWidth: 270,
tapGestureDismissal: true,
panGestureDismissal: false,
hideStatusBar: false,
completion: nil)
popup.addButtons([
DefaultButton(title: NSLocalizedString("Okay", comment: ""), dismissOnTap: true) {
self.reloadTable()
}
])
self.present(popup, animated: true, completion: nil)
}
.catch { error in
self.hideLoadingView()
let popup = PopupDialog(title: NSLocalizedString("Check Your Inbox", comment: ""),
message: "\(NSLocalizedString("To complete your signup, click the confirmation link we sent to", comment: "Used in To complete your signup, click the confirmation link we sent to you@gmail.com")) \(apiCredentials.email). \(NSLocalizedString("Be sure to check your spam folder in case it got stuck there.\n\nYou can also request a re-send of the confirmation.", comment: ""))",
image: nil,
buttonAlignment: .vertical,
transitionStyle: .bounceDown,
preferredWidth: 270,
tapGestureDismissal: true,
panGestureDismissal: false,
hideStatusBar: false,
completion: nil)
popup.addButtons([
DefaultButton(title: NSLocalizedString("Okay", comment: ""), dismissOnTap: true) {},
DefaultButton(title: NSLocalizedString("Sign Out", comment: ""), dismissOnTap: true) {
URLCache.shared.removeAllCachedResponses()
Client.clearCookies()
clearAPICredentials()
setAPICredentialsConfirmed(confirmed: false)
self.reloadTable()
self.showPopupDialog(title: NSLocalizedString("Success", comment: ""), message: NSLocalizedString("Signed out successfully.", comment: ""), acceptButton: NSLocalizedString("Okay", comment: ""))
},
DefaultButton(title: NSLocalizedString("Re-send", comment: ""), dismissOnTap: true) {
firstly {
try Client.resendConfirmCode(email: apiCredentials.email)
}
.done { (success: Bool) in
var message = NSLocalizedString("Successfully re-sent your email confirmation to ", comment: "") + apiCredentials.email
if (success == false) {
message = NSLocalizedString("Failed to re-send email confirmation.", comment: "")
}
self.showPopupDialog(title: "", message: message, acceptButton: NSLocalizedString("Okay", comment: ""))
}
.catch { error in
if (self.popupErrorAsNSURLError(error)) {
return
}
else if let apiError = error as? ApiError {
_ = self.popupErrorAsApiError(apiError)
}
else {
self.showPopupDialog(title: NSLocalizedString("Error Re-sending Email Confirmation", comment: ""),
message: "\(error)",
acceptButton: NSLocalizedString("Okay", comment: ""))
}
}
},
])
self.present(popup, animated: true, completion: nil)
}
}
}
}
self.activePlans = []
// show the plan status/button - first check and sync email if it's confirmed, otherwise just use receipt
if let apiCredentials = getAPICredentials(), getAPICredentialsConfirmed() == true {
DDLogInfo("plan status: have confirmed API credentials, using them")
firstly {
try Client.signInWithEmail(email: apiCredentials.email, password: apiCredentials.password)
}
.then { (signin: SignIn) -> Promise<SubscriptionEvent> in
DDLogInfo("plan status: signin result: \(signin)")
return try Client.subscriptionEvent()
}
.then { (result: SubscriptionEvent) -> Promise<[Subscription]> in
DDLogInfo("plan status: subscriptionevent result: \(result)")
return try Client.activeSubscriptions()
}.ensure {
}.done { subscriptions in
DDLogInfo("active-subs: \(subscriptions)")
self.activePlans = subscriptions.map({ $0.planType })
}
.catch { error in
}
}
// not logged in via email, use receipt
else {
firstly {
try Client.signIn()
}.then { _ in
try Client.activeSubscriptions()
}.ensure {
}.done { subscriptions in
self.activePlans = subscriptions.map({ $0.planType })
}.catch { error in
DDLogError("Error reloading subscription: \(error.localizedDescription)")
}
}
let notificationsButton = DefaultCell(title: "", action: { })
let updateNotificationButtonTitle = { (cell: _DefaultCell) in
if PushNotifications.Authorization.getUserWantsNotificationsEnabled(forCategory: .weeklyUpdate) {
cell.label.text = NSLocalizedString("Notifications: On", comment: "")
} else {
cell.label.text = NSLocalizedString("Notifications: Off", comment: "")
}
}
updateNotificationButtonTitle(notificationsButton)
notificationsButton.onSelect { [unowned notificationsButton, unowned self] in
if PushNotifications.Authorization.getUserWantsNotificationsEnabled(forCategory: .weeklyUpdate) {
PushNotifications.Authorization.setUserWantsNotificationsEnabled(false, forCategory: .weeklyUpdate)
updateNotificationButtonTitle(notificationsButton)
} else {
PushNotifications.Authorization.requestWeeklyUpdateAuthorization(presentingDialogOn: self).done { status in
DDLogInfo("New authorization status for push notifications: \(status)")
updateNotificationButtonTitle(notificationsButton)
}.catch { error in
DDLogError("Error updating notification authorization status: \(error.localizedDescription)")
}
}
}
tableView.addRow { (contentView) in
let stack = UIStackView()
stack.axis = .vertical
stack.spacing = 8
contentView.addSubview(stack)
stack.anchors.edges.marginsPin(insets: .init(top: 8, left: 0, bottom: 8, right: 0))
let titleLabel = UILabel()
titleLabel.text = title
titleLabel.font = fontBold18
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 0
stack.addArrangedSubview(titleLabel)
let messageLabel = UILabel()
messageLabel.text = message
messageLabel.font = fontMedium18
messageLabel.textAlignment = .center
messageLabel.numberOfLines = 0
stack.addArrangedSubview(messageLabel)
}
let firstButtons: [SelectableTableViewCell] = [
firstButton,
notificationsButton,
]
for cell in firstButtons {
tableView.addCell(cell)
}
let otherCells = [
// DefaultCell(title: NSLocalizedString("Tutorial", comment: "")) { [unowned self] in
// self.startTutorial()
// },
MakeDefaultCell(
title: NSLocalizedString("What's New", comment: ""),
color: .paywallNew
) {
self.showWhatsNewModal()
},
DefaultCell(title: NSLocalizedString("Why Trust Lockdown", comment: "")) {
self.showWhyTrustPopup()
},
DefaultCell(title: NSLocalizedString("Privacy Policy", comment: "")) {
self.showPrivacyPolicyModal()
},
DefaultCell(title: NSLocalizedString("What is VPN?", comment: "")) {
self.performSegue(withIdentifier: "showWhatIsVPN", sender: self)
},
DefaultCell(title: NSLocalizedString("Support | Feedback", comment: "")) {
self.showPopupDialog(
title: nil,
message: NSLocalizedString("Remember to check our FAQs first for answers to the most frequently asked questions.\n\nIf your question is not answered there, we're happy to provide support and receive feedback via email or through the bug reporting form.", comment: ""),
buttons: [
.custom(title: NSLocalizedString("View FAQs", comment: ""), completion: {
self.showFAQsModal()
}),
.custom(title: NSLocalizedString("Email Us", comment: ""), completion: {
self.emailTeam()
}),
.custom(title: NSLocalizedString("Bug Reporting Form", comment: "")) { [weak self] in
self?.openQuestionnaire()
},
.cancel()
]
)
},
DefaultCell(title: NSLocalizedString("FAQs", comment: "")) {
self.showFAQsModal()
},
DefaultCell(title: NSLocalizedString("Website", comment: "")) {
self.showWebsiteModal()
},
]
for cell in otherCells {
tableView.addCell(cell)
}
if let creds = getAPICredentials() {
tableView.addCell(MakeDefaultCell(
title: .localized("delete_account"),
color: .lockdownRed
) {
self.deleteAccount(userEmail: creds.email)
})
}
#if DEBUG
let fixVPNConfig = DefaultCell(title: "_Fix Firewall Config", action: {
self.showFixFirewallConnectionDialog {
FirewallController.shared.deleteConfigurationAndAddAgain()
}
})
tableView.addCell(fixVPNConfig)
#endif
tableView.addRowCell { (cell) in
cell.textLabel?.text = Bundle.main.versionString
cell.textLabel?.font = fontSemiBold17
cell.textLabel?.textColor = UIColor.systemGray
cell.textLabel?.textAlignment = .right
// removing the bottom separator
cell.separatorInset = .init(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
cell.directionalLayoutMargins = .zero
}
}
func startTutorial() {
// if let tabBarController = tabBarController as? MainTabBarController {
// tabBarController.selectedViewController = tabBarController.homeViewController
// tabBarController.homeViewController.startTutorial()
// }
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "showWhatIsVPN":
if let vc = segue.destination as? WhatIsVpnViewController {
// vc.parentVC = (tabBarController as? MainTabBarController)?.vpnViewController
}
default:
break
}
}
private func openQuestionnaire() {
feedbackFlow?.startFlow()
}
}
// MARK: - Helpers / Extensions
class _DefaultButtonCell: SelectableTableViewCell {
let button = UIButton(type: .system)
}
func DefaultButtonCell(title: String, action: @escaping () -> ()) -> _DefaultButtonCell {
let cell = _DefaultButtonCell()
cell.backgroundView = UIView()
cell.button.setTitle(title, for: .normal)
cell.button.isUserInteractionEnabled = false
cell.button.titleLabel?.font = fontSemiBold17
cell.button.tintColor = .tunnelsBlue
cell.contentView.addSubview(cell.button)
cell.button.anchors.height.equal(21)
cell.button.anchors.edges.marginsPin(insets: .init(top: 8, left: 0, bottom: 8, right: 0))
return cell.onSelect(callback: action)
}
class _DefaultCell: SelectableTableViewCell {
let label = UILabel()
}
func DefaultCell(title: String, action: @escaping () -> ()) -> _DefaultCell {
let cell = _DefaultCell()
cell.label.text = title
cell.label.font = fontSemiBold17
cell.label.textColor = .tunnelsBlue
cell.label.textAlignment = .center
cell.contentView.addSubview(cell.label)
cell.label.anchors.edges.marginsPin(insets: .init(top: 8, left: 0, bottom: 8, right: 0))
return cell.onSelect(callback: action)
}
func MakeDefaultCell(title: String, color: UIColor = .tunnelsBlue, action: @escaping () -> Void) -> _DefaultCell {
let cell = _DefaultCell()
cell.label.text = title
cell.label.font = .semiboldLockdownFont(size: 17)
cell.label.textColor = color
cell.label.textAlignment = .center
cell.contentView.addSubview(cell.label)
cell.label.anchors.edges.marginsPin(insets: .init(top: 8, left: 0, bottom: 8, right: 0))
return cell.onSelect(callback: action)
}
extension AccountViewController: EmailComposable {
private func deleteAccount(userEmail: String) {
let deleteAccountViewController = DeleteMyAccountViewController(userEmail: userEmail)
deleteAccountViewController.modalPresentationStyle = .formSheet
present(deleteAccountViewController, animated: true)
}
}
fileprivate extension _DefaultButtonCell {
func startActivityIndicator() {
let activity = UIActivityIndicatorView()
if let label = button.titleLabel {
label.addSubview(activity)
activity.translatesAutoresizingMaskIntoConstraints = false
activity.centerYAnchor.constraint(equalTo: label.centerYAnchor).isActive = true
activity.leadingAnchor.constraint(equalToSystemSpacingAfter: label.trailingAnchor, multiplier: 1).isActive = true
activity.startAnimating()
}
}
func stopActivityIndicator() {
if let label = button.titleLabel {
let indicators = label.subviews.compactMap { $0 as? UIActivityIndicatorView }
for indicator in indicators {
indicator.stopAnimating()
indicator.removeFromSuperview()
}
}
}
}