-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathMeViewController.swift
628 lines (519 loc) · 23.7 KB
/
MeViewController.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import UIKit
import WordPressShared
import AutomatticAbout
class MeViewController: UITableViewController {
var handler: ImmuTableViewHandler!
var isSidebarModeEnabled = false
private lazy var headerView = MeHeaderView()
// MARK: - Table View Controller
override init(style: UITableView.Style) {
super.init(style: style)
navigationItem.title = NSLocalizedString("Me", comment: "Me page title")
clearsSelectionOnViewWillAppear = false
}
required convenience init() {
self.init(style: .insetGrouped)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(refreshModelWithNotification(_:)), name: .ZendeskPushNotificationReceivedNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(refreshModelWithNotification(_:)), name: .ZendeskPushNotificationClearedNotification, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if isSidebarModeEnabled {
/// We can't use trait collection here because on iPad .form sheet is still
/// considered to be ` .compact` size class, so it has to be invoked manually.
headerView.configureHorizontalMode()
}
ImmuTable.registerRows([
VerifyEmailRow.self,
NavigationItemRow.self,
IndicatorNavigationItemRow.self,
ButtonRow.self,
DestructiveButtonRow.self
], tableView: self.tableView)
handler = ImmuTableViewHandler(takeOver: self)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
NotificationCenter.default.addObserver(self, selector: #selector(MeViewController.accountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(MeViewController.refreshAccountDetailsAndSettings), name: UIApplication.didBecomeActiveNotification, object: nil)
WPStyleGuide.configureColors(view: view, tableView: tableView)
tableView.accessibilityIdentifier = "Me Table"
reloadViewModel()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.layoutHeaderView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshAccountDetailsAndSettings()
animateDeselectionInteractively()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
registerUserActivity()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Required to update the tableview cell disclosure indicators
reloadViewModel()
}
@objc fileprivate func accountDidChange() {
reloadViewModel()
}
@objc fileprivate func reloadViewModel() {
let account = defaultAccount()
// Warning: If you set the header view after the table model, the
// table's top margin will be wrong.
//
// My guess is the table view adjusts the height of the first section
// based on if there's a header or not.
if let account {
headerView.update(with: MeHeaderViewModel(account: account))
}
tableView.tableHeaderView = headerView
// Then we'll reload the table view model (prompting a table reload)
handler.viewModel = tableViewModel(with: account)
}
private var appSettingsRow: NavigationItemRow {
return NavigationItemRow(
title: RowTitles.appSettings,
icon: UIImage(named: UIDevice.isPad() ? "wpl-tablet" : "wpl-phone")?.withRenderingMode(.alwaysTemplate),
tintColor: .label,
accessoryType: .disclosureIndicator,
action: pushAppSettings(),
accessibilityIdentifier: "appSettings"
)
}
fileprivate func tableViewModel(with account: WPAccount?) -> ImmuTable {
let accessoryType: UITableViewCell.AccessoryType = .disclosureIndicator
let loggedIn = account != nil
var verificationSection: ImmuTableSection?
if let account, account.verificationStatus == .unverified {
verificationSection = ImmuTableSection(rows: [VerifyEmailRow()])
}
let myProfile = NavigationItemRow(
title: RowTitles.myProfile,
icon: UIImage(named: "site-menu-people")?.withRenderingMode(.alwaysTemplate),
tintColor: .label,
accessoryType: accessoryType,
action: pushMyProfile(),
accessibilityIdentifier: "myProfile")
let qrLogin = NavigationItemRow(
title: RowTitles.qrLogin,
icon: UIImage(named: "wpl-capture-photo")?.withRenderingMode(.alwaysTemplate),
tintColor: .label,
accessoryType: accessoryType,
action: presentQRLogin(),
accessibilityIdentifier: "qrLogin")
let accountSettings = NavigationItemRow(
title: RowTitles.accountSettings,
icon: UIImage(named: "wpl-gearshape")?.withRenderingMode(.alwaysTemplate),
tintColor: .label,
accessoryType: accessoryType,
action: pushAccountSettings(),
accessibilityIdentifier: "accountSettings")
let helpAndSupportIndicator = IndicatorNavigationItemRow(
title: RowTitles.support,
icon: UIImage(named: "wpl-help")?.withRenderingMode(.alwaysTemplate),
tintColor: .label,
showIndicator: ZendeskUtils.showSupportNotificationIndicator,
accessoryType: accessoryType,
action: pushHelp())
let logIn = ButtonRow(
title: RowTitles.logIn,
action: presentLogin())
let logOut = DestructiveButtonRow(
title: RowTitles.logOut,
action: logoutRowWasPressed(),
accessibilityIdentifier: "logOutFromWPcomButton")
let wordPressComAccount = HeaderTitles.wpAccount
let shouldShowQRLoginRow = AppConfiguration.qrLoginEnabled && !(account?.settings?.twoStepEnabled ?? false)
var sections: [ImmuTableSection] = []
// Add verification section first if it exists
if let verificationSection {
sections.append(verificationSection)
}
sections.append(contentsOf: [
ImmuTableSection(rows: {
var rows: [ImmuTableRow] = [appSettingsRow]
if loggedIn {
var loggedInRows = [myProfile, accountSettings]
if shouldShowQRLoginRow {
loggedInRows.append(qrLogin)
}
rows = loggedInRows + rows
}
return rows
}()),
ImmuTableSection(rows: [helpAndSupportIndicator]),
])
#if IS_JETPACK
if RemoteFeatureFlag.domainManagement.enabled() && loggedIn && !isSidebarModeEnabled {
sections.append(.init(rows: [
NavigationItemRow(
title: AllDomainsListViewController.Strings.title,
icon: UIImage(named: "wpl-globe")?.withRenderingMode(.alwaysTemplate),
tintColor: .label,
accessoryType: accessoryType,
action: { [weak self] action in
self?.showOrPushController(AllDomainsListViewController())
WPAnalytics.track(.meDomainsTapped)
},
accessibilityIdentifier: "myDomains"
)
])
)
}
#endif
sections.append(
ImmuTableSection(rows: [
ButtonRow(
title: ShareAppContentPresenter.RowConstants.buttonTitle,
textAlignment: .left,
isLoading: sharePresenter.isLoading,
action: displayShareFlow()
),
ButtonRow(
title: RowTitles.about,
textAlignment: .left,
action: pushAbout(),
accessibilityIdentifier: "About"
)
])
)
// last section
sections.append(
.init(headerText: wordPressComAccount, rows: {
return [loggedIn ? logOut : logIn]
}())
)
return ImmuTable(sections: sections)
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let isNewSelection = (indexPath != tableView.indexPathForSelectedRow)
if isNewSelection {
return indexPath
} else {
return nil
}
}
// MARK: - Actions
fileprivate var myProfileViewController: UIViewController? {
guard let account = self.defaultAccount() else {
let error = "Tried to push My Profile without a default account. This shouldn't happen"
assertionFailure(error)
DDLogError("\(error)")
return nil
}
return MyProfileViewController(account: account)
}
fileprivate func pushMyProfile() -> ImmuTableAction {
return { [unowned self] row in
if let myProfileViewController = self.myProfileViewController {
WPAppAnalytics.track(.openedMyProfile)
self.showOrPushController(myProfileViewController)
}
}
}
fileprivate func pushAccountSettings() -> ImmuTableAction {
return { [unowned self] row in
if let account = self.defaultAccount() {
WPAppAnalytics.track(.openedAccountSettings)
guard let controller = AccountSettingsViewController(account: account) else {
return
}
self.showOrPushController(controller)
}
}
}
private func presentQRLogin() -> ImmuTableAction {
return { [weak self] row in
guard let self else {
return
}
self.tableView.deselectSelectedRowWithAnimation(true)
QRLoginCoordinator.present(from: self, origin: .menu)
}
}
func pushAppSettings() -> ImmuTableAction {
return { [unowned self] row in
self.navigateToAppSettings()
}
}
func pushHelp() -> ImmuTableAction {
return { [unowned self] row in
let controller = SupportTableViewController(style: .insetGrouped)
self.showOrPushController(controller)
}
}
private func pushAbout() -> ImmuTableAction {
return { [unowned self] _ in
let configuration = AppAboutScreenConfiguration(sharePresenter: self.sharePresenter)
let controller = AutomatticAboutScreen.controller(appInfo: AppAboutScreenConfiguration.appInfo,
configuration: configuration,
fonts: AppAboutScreenConfiguration.fonts)
self.present(controller, animated: true) {
self.tableView.deselectSelectedRowWithAnimation(true)
}
}
}
func displayShareFlow() -> ImmuTableAction {
return { [unowned self] row in
defer {
self.tableView.deselectSelectedRowWithAnimation(true)
}
guard let selectedIndexPath = self.tableView.indexPathForSelectedRow,
let selectedCell = self.tableView.cellForRow(at: selectedIndexPath) else {
return
}
self.sharePresenter.present(for: AppConstants.shareAppName, in: self, source: .me, sourceView: selectedCell)
}
}
fileprivate func presentLogin() -> ImmuTableAction {
return { [unowned self] row in
self.tableView.deselectSelectedRowWithAnimation(true)
self.promptForLoginOrSignup()
}
}
fileprivate func logoutRowWasPressed() -> ImmuTableAction {
return { [unowned self] row in
self.tableView.deselectSelectedRowWithAnimation(true)
self.displayLogOutAlert()
}
}
/// Selects the My Profile row and pushes the Support view controller
///
@objc public func navigateToMyProfile() {
navigateToTarget(for: RowTitles.myProfile)
}
/// Selects the Account Settings row and pushes the Account Settings view controller
///
@objc public func navigateToAccountSettings() {
navigateToTarget(for: RowTitles.accountSettings)
}
/// Selects the All Domains row and pushes the All Domains view controller
///
public func navigateToAllDomains() {
#if IS_JETPACK
navigateToTarget(for: AllDomainsListViewController.Strings.title)
#endif
}
/// Selects the App Settings row and pushes the App Settings view controller
///
@objc public func navigateToAppSettings(completion: ((AppSettingsViewController) -> Void)? = nil) {
self.selectRowForTitle(appSettingsRow.title)
WPAppAnalytics.track(.openedAppSettings)
let destination = AppSettingsViewController()
self.showOrPushController(destination) {
completion?(destination)
}
}
/// Selects the Help & Support row and pushes the Support view controller
///
@objc public func navigateToHelpAndSupport() {
navigateToTarget(for: RowTitles.support)
}
fileprivate func navigateToTarget(for rowTitle: String) {
let matchRow: ((ImmuTableRow) -> Bool) = { row in
if let row = row as? NavigationItemRow {
return row.title == rowTitle
} else if let row = row as? IndicatorNavigationItemRow {
return row.title == rowTitle
}
return false
}
if let sections = handler?.viewModel.sections,
let section = sections.firstIndex(where: { $0.rows.contains(where: matchRow) }),
let row = sections[section].rows.firstIndex(where: matchRow) {
let indexPath = IndexPath(row: row, section: section)
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
handler.tableView(self.tableView, didSelectRowAt: indexPath)
}
}
private func selectRowForTitle(_ rowTitle: String) {
self.tableView.selectRow(at: indexPathForRowTitle(rowTitle), animated: true, scrollPosition: .middle)
}
private func indexPathForRowTitle(_ rowTitle: String) -> IndexPath? {
let matchRow: ((ImmuTableRow) -> Bool) = { row in
if let row = row as? NavigationItemRow {
return row.title == rowTitle
} else if let row = row as? IndicatorNavigationItemRow {
return row.title == rowTitle
}
return false
}
guard let sections = handler?.viewModel.sections,
let section = sections.firstIndex(where: { $0.rows.contains(where: matchRow) }),
let row = sections[section].rows.firstIndex(where: matchRow) else {
return nil
}
return IndexPath(row: row, section: section)
}
private func showOrPushController(_ controller: UIViewController, completion: (() -> Void)? = nil) {
if let navigationController {
navigationController.pushViewController(controller, animated: true, rightBarButton: self.isSidebarModeEnabled ? nil : self.navigationItem.rightBarButtonItem)
navigationController.transitionCoordinator?.animate(alongsideTransition: nil, completion: { _ in
completion?()
})
} else {
completion?()
}
}
// MARK: - Helpers
// FIXME: (@koke 2015-12-17) Not cool. Let's stop passing managed objects
// and initializing stuff with safer values like userID
fileprivate func defaultAccount() -> WPAccount? {
return try? WPAccount.lookupDefaultWordPressComAccount(in: ContextManager.shared.mainContext)
}
@objc fileprivate func refreshAccountDetailsAndSettings() {
guard let account = defaultAccount(), let api = account.wordPressComRestApi else {
reloadViewModel()
return
}
let accountService = AccountService(coreDataStack: ContextManager.shared)
let accountSettingsService = AccountSettingsService(userID: account.userID.intValue, api: api)
Task {
do {
async let refreshDetails: Void = Self.refreshAccountDetails(with: accountService, account: account)
async let refreshSettings: Void = Self.refreshAccountSettings(with: accountSettingsService)
let _ = try await [refreshDetails, refreshSettings]
self.reloadViewModel()
} catch let error {
DDLogError("\(error.localizedDescription)")
}
}
}
fileprivate static func refreshAccountDetails(with service: AccountService, account: WPAccount) async throws {
return try await withCheckedThrowingContinuation { continuation in
service.updateUserDetails(for: account, success: {
continuation.resume()
}, failure: { error in
continuation.resume(throwing: error)
})
}
}
fileprivate static func refreshAccountSettings(with service: AccountSettingsService) async throws {
return try await withCheckedThrowingContinuation { continuation in
service.refreshSettings { result in
switch result {
case .success: continuation.resume()
case .failure(let error): continuation.resume(throwing: error)
}
}
}
}
// MARK: - LogOut
private func displayLogOutAlert() {
let alert = UIAlertController(title: logOutAlertTitle, message: nil, preferredStyle: .alert)
alert.addActionWithTitle(LogoutAlert.cancelAction, style: .cancel)
alert.addActionWithTitle(LogoutAlert.logoutAction, style: .destructive) { [weak self] _ in
self?.dismiss(animated: true) {
AccountHelper.logOutDefaultWordPressComAccount()
}
}
present(alert, animated: true)
}
private var logOutAlertTitle: String {
let context = ContextManager.shared.mainContext
let count = AbstractPost.countLocalPosts(in: context)
guard count > 0 else {
return LogoutAlert.defaultTitle
}
let format = count > 1 ? LogoutAlert.unsavedTitlePlural : LogoutAlert.unsavedTitleSingular
return String(format: format, count)
}
// MARK: - Private Properties
/// Shows an actionsheet with options to Log In or Create a WordPress site.
/// This is a temporary stop-gap measure to preserve for users only logged
/// into a self-hosted site the ability to create a WordPress.com account.
///
fileprivate func promptForLoginOrSignup() {
Task {
await WordPressDotComAuthenticator().signIn(from: self, context: .default)
}
}
private lazy var sharePresenter: ShareAppContentPresenter = {
let presenter = ShareAppContentPresenter(account: defaultAccount())
presenter.delegate = self
return presenter
}()
}
// MARK: - SearchableActivity Conformance
extension MeViewController: SearchableActivityConvertable {
var activityType: String {
return WPActivityType.me.rawValue
}
var activityTitle: String {
return NSLocalizedString("Me", comment: "Title of the 'Me' tab - used for spotlight indexing on iOS.")
}
var activityKeywords: Set<String>? {
let keyWordString = NSLocalizedString("wordpress, me, settings, account, notification log out, logout, log in, login, help, support",
comment: "This is a comma separated list of keywords used for spotlight indexing of the 'Me' tab.")
let keywordArray = keyWordString.arrayOfTags()
guard !keywordArray.isEmpty else {
return nil
}
return Set(keywordArray)
}
}
// MARK: - Constants
private extension MeViewController {
enum RowTitles {
static let appSettings = NSLocalizedString("App Settings", comment: "Link to App Settings section")
static let myProfile = NSLocalizedString("My Profile", comment: "Link to My Profile section")
static let accountSettings = NSLocalizedString("Account Settings", comment: "Link to Account Settings section")
static let qrLogin = NSLocalizedString("Scan Login Code", comment: "Link to opening the QR login scanner")
static let support = NSLocalizedString("Help & Support", comment: "Link to Help section")
static let logIn = NSLocalizedString("Log In", comment: "Label for logging in to WordPress.com account")
static let logOut = NSLocalizedString("Log Out", comment: "Label for logging out from WordPress.com account")
static let about = AppConstants.Settings.aboutTitle
}
enum HeaderTitles {
static let wpAccount = NSLocalizedString("WordPress.com Account", comment: "WordPress.com sign-in/sign-out section header title")
}
enum LogoutAlert {
static let defaultTitle = AppConstants.Logout.alertTitle
static let unsavedTitleSingular = NSLocalizedString("You have changes to %d post that hasn't been uploaded to your site. Logging out now will delete those changes. Log out anyway?",
comment: "Warning displayed before logging out. The %d placeholder will contain the number of local posts (SINGULAR!)")
static let unsavedTitlePlural = NSLocalizedString("You have changes to %d posts that haven’t been uploaded to your site. Logging out now will delete those changes. Log out anyway?",
comment: "Warning displayed before logging out. The %d placeholder will contain the number of local posts (PLURAL!)")
static let cancelAction = NSLocalizedString("Cancel", comment: "Verb. A button title. Tapping cancels an action.")
static let logoutAction = NSLocalizedString("Log Out", comment: "Button for confirming logging out from WordPress.com account")
}
}
// MARK: - Private Extension for Notification handling
private extension MeViewController {
@objc func refreshModelWithNotification(_ notification: Foundation.Notification) {
reloadViewModel()
}
}
// MARK: - ShareAppContentPresenterDelegate
extension MeViewController: ShareAppContentPresenterDelegate {
func didUpdateLoadingState(_ loading: Bool) {
reloadViewModel()
}
}
// MARK: - Jetpack powered badge
extension MeViewController {
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard section == handler.viewModel.sections.count - 1,
JetpackBrandingVisibility.all.enabled else {
return nil
}
let textProvider = JetpackBrandingTextProvider(screen: JetpackBadgeScreen.me)
return JetpackButton.makeBadgeView(title: textProvider.brandingText(),
target: self,
selector: #selector(jetpackButtonTapped))
}
@objc private func jetpackButtonTapped() {
JetpackBrandingCoordinator.presentOverlay(from: self)
JetpackBrandingAnalyticsHelper.trackJetpackPoweredBadgeTapped(screen: .me)
}
}
private enum Strings {
static let submitFeedback = NSLocalizedString("meMenu.submitFeedback", value: "Send Feedback", comment: "Me tab menu items")
}