-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathBlogDetailsViewController.swift
More file actions
325 lines (261 loc) · 10.9 KB
/
BlogDetailsViewController.swift
File metadata and controls
325 lines (261 loc) · 10.9 KB
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
import UIKit
import WordPressData
import WordPressKit
import WordPressShared
import WordPressUI
import Reachability
import Gridicons
public protocol BlogDetailsPresentationDelegate: AnyObject {
func presentBlogDetailsViewController(_ viewController: UIViewController)
}
public class BlogDetailsViewController: UIViewController {
public var blog: Blog
public private(set) var tableView: UITableView?
public private(set) var tableViewModel: BlogDetailsTableViewModel?
public var isScrollEnabled = false
public weak var presentationDelegate: BlogDetailsPresentationDelegate?
public var isSidebarModeEnabled = false
public weak var presentedSiteSettingsViewController: UIViewController?
private lazy var blogService = BlogService(coreDataStack: ContextManager.shared)
private var hasLoggedDomainCreditPromptShownEvent = false
private(set) var showXMLRPCDisabled: Bool = false
init(blog: Blog) {
self.blog = blog
self.isScrollEnabled = false
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
let tableView: UITableView
if isSidebarModeEnabled {
tableView = UITableView(frame: .zero, style: .grouped)
} else if isScrollEnabled {
tableView = UITableView(frame: .zero, style: .insetGrouped)
} else {
tableView = IntrinsicTableView(frame: .zero, style: .insetGrouped)
tableView.isScrollEnabled = false
}
self.tableView = tableView
tableViewModel = BlogDetailsTableViewModel(blog: blog, viewController: self)
tableViewModel?.configure(tableView: tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
if isSidebarModeEnabled {
tableView.separatorStyle = .none
additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
}
view.addSubview(tableView)
view.pinSubviewToAllEdges(tableView)
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(pulledToRefreshTriggered), for: .valueChanged)
tableView.refreshControl = refreshControl
tableView.accessibilityIdentifier = "Blog Details Table"
tableView.cellLayoutMarginsFollowReadableWidth = true
WPStyleGuide.configureColors(view: view, tableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
hasLoggedDomainCreditPromptShownEvent = false
preloadMetadata()
if let account = blog.account, account.userID == nil {
let service = AccountService(coreDataStack: ContextManager.shared)
service.updateUserDetails(for: account, success: nil, failure: nil)
}
observeManagedObjectContextObjectsDidChangeNotification()
observeGravatarImageUpdate()
downloadGravatarImage()
checkXMLRPCStatus()
registerForTraitChanges([UITraitHorizontalSizeClass.self], action: #selector(handleTraitChanges))
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observeWillEnterForegroundNotification()
tableViewModel?.viewWillAppear()
// Configure and reload table data when appearing to ensure pending comment count is updated
configureTableViewData()
reloadTableViewPreservingSelection()
preloadBlogData()
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
createUserActivity()
WPAnalytics.track(.mySiteSiteMenuShown)
if shouldShowJetpackInstallCard() {
WPAnalytics.track(.jetpackInstallFullPluginCardViewed, properties: [WPAppAnalyticsKeyTabSource: "site_menu"])
}
if shouldShowBlaze() {
BlazeEventsTracker.trackEntryPointDisplayed(for: .menuItem)
}
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopObservingWillEnterForegroundNotification()
}
@objc private func handleTraitChanges() {
configureTableViewData()
reloadTableViewPreservingSelection()
}
public func reloadTableViewPreservingSelection() {
tableViewModel?.reloadTableViewPreservingSelection()
}
public func configureTableViewData() {
tableViewModel?.configureTableViewData()
}
public func `switch`(to blog: Blog) {
self.blog = blog
showInitialDetailsForBlog()
tableView?.reloadData()
preloadMetadata()
}
public func showInitialDetailsForBlog() {
tableViewModel?.showInitialDetailsForBlog()
}
public func updateTableView(completion: (() -> Void)?) {
let completionBlock = completion ?? {}
blogService.syncBlogAndAllMetadata(blog) { [weak self] in
self?.configureTableViewData()
self?.reloadTableViewPreservingSelection()
completionBlock()
}
}
public func pulledToRefresh(with refreshControl: UIRefreshControl, onCompletion completion: (() -> Void)?) {
let completionBlock = completion ?? {}
updateTableView { [weak refreshControl] in
DispatchQueue.main.async {
refreshControl?.endRefreshing()
completionBlock()
}
}
}
private func preloadBlogData() {
// only preload on wifi
guard ReachabilityUtils.internetReachability?.isReachableViaWiFi() == true else {
return
}
preloadComments()
preloadMetadata()
preloadDomains()
}
private func preloadComments() {
let commentService = CommentService(coreDataStack: ContextManager.shared)
if CommentService.shouldRefreshCache(for: blog) {
commentService.syncComments(for: blog, withStatus: CommentStatusFilterAll, success: nil, failure: nil)
}
}
public func preloadMetadata() {
blogService.syncBlogAndAllMetadata(blog) { [weak self] in
self?.configureTableViewData()
self?.reloadTableViewPreservingSelection()
}
}
private func preloadDomains() {
guard shouldAddDomainRegistrationRow() else {
return
}
blogService.refreshDomains(for: blog, success: nil, failure: nil)
}
private func checkXMLRPCStatus() {
guard blog.isSelfHosted, let xmlrpcApi = blog.xmlrpcApi,
let username = blog.username, let password = blog.password else {
showXMLRPCDisabled = false
return
}
Task { @MainActor in
let isEnabled = await xmlrpcApi.isEnabled(username: username, password: password)
let wasDisabled = self.showXMLRPCDisabled
self.showXMLRPCDisabled = !isEnabled
if wasDisabled != self.showXMLRPCDisabled {
self.configureTableViewData()
self.reloadTableViewPreservingSelection()
}
}
}
public func showRemoveSiteAlert() {
let model = UIDevice.current.localizedModel
let message = String(format: NSLocalizedString(
"Are you sure you want to continue?\n All site data will be removed from your %@.",
comment: "Title for the remove site confirmation alert, %@ will be replaced with iPhone/iPad/iPod Touch"
), model)
let destructiveTitle = NSLocalizedString("Remove Site", comment: "Button to remove a site from the app")
let alertStyle: UIAlertController.Style = UIDevice.isPad() ? .alert : .actionSheet
let alertController = UIAlertController(title: nil, message: message, preferredStyle: alertStyle)
alertController.addCancelActionWithTitle(SharedStrings.Button.cancel, handler: nil)
alertController.addDestructiveActionWithTitle(destructiveTitle) { [weak self] _ in
self?.confirmRemoveSite()
}
present(alertController, animated: true)
}
@objc private func pulledToRefreshTriggered(_ control: UIRefreshControl) {
pulledToRefresh(with: control, onCompletion: {})
}
@objc private func handleDataModelChange(_ notification: NSNotification) {
guard let deletedObjects = notification.userInfo?[NSDeletedObjectsKey] as? Set<NSManagedObject> else {
return
}
if deletedObjects.contains(blog) {
navigationController?.popToRootViewController(animated: false)
return
}
if blog.account == nil || blog.account?.isDeleted == true {
return
}
guard let updatedObjects = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> else {
return
}
if updatedObjects.contains(blog) || (blog.settings != nil && updatedObjects.contains(blog.settings!)) {
configureTableViewData()
reloadTableViewPreservingSelection()
}
}
@objc private func handleWillEnterForeground(_ notification: NSNotification) {
configureTableViewData()
reloadTableViewPreservingSelection()
checkXMLRPCStatus()
}
private func observeManagedObjectContextObjectsDidChangeNotification() {
let context = ContextManager.shared.mainContext
NotificationCenter.default.addObserver(
self,
selector: #selector(handleDataModelChange(_:)),
name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
object: context
)
}
private func observeWillEnterForegroundNotification() {
NotificationCenter.default.addObserver(
self,
selector: #selector(handleWillEnterForeground(_:)),
name: UIApplication.willEnterForegroundNotification,
object: nil
)
}
private func stopObservingWillEnterForegroundNotification() {
NotificationCenter.default.removeObserver(
self,
name: UIApplication.willEnterForegroundNotification,
object: nil
)
}
}
extension BlogDetailsViewController: UIViewControllerTransitioningDelegate {
public func presentationController(
forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController
) -> UIPresentationController? {
if presented is FancyAlertViewController {
return FancyAlertPresentationController(
presentedViewController: presented,
presenting: presenting
)
}
return nil
}
}
extension BlogDetailsViewController: UIAdaptivePresentationControllerDelegate {
public func presentationControllerWillDismiss(_ presentationController: UIPresentationController) {
if presentationController.presentedViewController == presentedSiteSettingsViewController {
tableView?.deselectSelectedRowWithAnimation(true)
}
}
}