-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PushNotificationsManager.swift
489 lines (392 loc) · 17.9 KB
/
PushNotificationsManager.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
import Foundation
import WordPressShared
import UserNotifications
import CocoaLumberjack
import UserNotifications
/// The purpose of this helper is to encapsulate all the tasks related to Push Notifications Registration + Handling,
/// including iOS "Actionable" Notifications.
///
final public class PushNotificationsManager: NSObject {
/// Returns the shared PushNotificationsManager instance.
///
@objc static let shared = PushNotificationsManager()
/// Stores the Apple's Push Notifications Token
///
@objc var deviceToken: String? {
get {
return UserDefaults.standard.string(forKey: Device.tokenKey) ?? String()
}
set {
UserDefaults.standard.set(newValue, forKey: Device.tokenKey)
}
}
/// Stores the WordPress.com Device identifier
///
@objc var deviceId: String? {
get {
return UserDefaults.standard.string(forKey: Device.idKey) ?? String()
}
set {
UserDefaults.standard.set(newValue, forKey: Device.idKey)
}
}
/// Returns the SharedApplication instance. This is meant for Unit Testing purposes.
///
@objc var sharedApplication: UIApplication {
return UIApplication.shared
}
/// Returns the Application Execution State. This is meant for Unit Testing purposes.
///
@objc var applicationState: UIApplication.State {
return sharedApplication.applicationState
}
/// Registers the device for Remote Notifications: Badge + Sounds + Alerts
///
@objc func registerForRemoteNotifications() {
sharedApplication.registerForRemoteNotifications()
}
/// Checks asynchronously if Notifications are enabled in the Device's Settings, or not.
///
@objc func loadAuthorizationStatus(completion: @escaping ((_ authorized: UNAuthorizationStatus) -> Void)) {
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
completion(settings.authorizationStatus)
}
}
}
// MARK: - Token Setup
/// Registers the Device Token agains WordPress.com backend, if there's a default account.
///
/// - Note: Support will also be initialized. The token will be persisted across App Sessions.
///
@objc func registerDeviceToken(_ tokenData: Data) {
// Don't bother registering for WordPress anything if the user isn't logged in
guard AccountHelper.isDotcomAvailable() else {
return
}
// Token Cleanup
let newToken = tokenData.hexString
// Register device with Zendesk
ZendeskUtils.setNeedToRegisterDevice(newToken)
if deviceToken != newToken {
DDLogInfo("Device Token has changed! OLD Value: \(String(describing: deviceToken)), NEW value: \(newToken)")
} else {
DDLogInfo("Device Token received in didRegisterForRemoteNotificationsWithDeviceToken: \(newToken)")
}
deviceToken = newToken
// Register against WordPress.com
let noteService = NotificationSettingsService(managedObjectContext: ContextManager.sharedInstance().mainContext)
noteService.registerDeviceForPushNotifications(newToken, success: { deviceId in
DDLogVerbose("Successfully registered Device ID \(deviceId) for Push Notifications")
self.deviceId = deviceId
}, failure: { error in
DDLogError("Unable to register Device for Push Notifications: \(error)")
})
}
/// Perform cleanup when the registration for iOS notifications failed
///
/// - Parameter error: Details the reason of failure
///
@objc func registrationDidFail(_ error: NSError) {
DDLogError("Failed to register for push notifications: \(error)")
unregisterDeviceToken()
}
/// Unregister the device from WordPress.com notifications
///
@objc func unregisterDeviceToken() {
// It's possible for the unregister server call to fail, so always unregister the device locally
// to fix https://github.com/wordpress-mobile/WordPress-iOS/issues/11779.
if UIApplication.shared.isRegisteredForRemoteNotifications {
UIApplication.shared.unregisterForRemoteNotifications()
}
guard let knownDeviceId = deviceId else {
return
}
ZendeskUtils.unregisterDevice()
let noteService = NotificationSettingsService(managedObjectContext: ContextManager.sharedInstance().mainContext)
noteService.unregisterDeviceForPushNotifications(knownDeviceId, success: {
DDLogInfo("Successfully unregistered Device ID \(knownDeviceId) for Push Notifications!")
self.deviceToken = nil
self.deviceId = nil
}, failure: { error in
DDLogError("Unable to unregister push for Device ID \(knownDeviceId): \(error)")
})
}
// MARK: - Handling Notifications
/// Handles a Remote Notification
///
/// - Parameters:
/// - userInfo: The Notification's Payload
/// - userInteraction: Indicates if the user interacted with the Push Notification
/// - completionHandler: A callback, to be executed on completion
///
@objc func handleNotification(_ userInfo: NSDictionary, userInteraction: Bool = false, completionHandler: ((UIBackgroundFetchResult) -> Void)?) {
DDLogVerbose("Received push notification:\nPayload: \(userInfo)\n")
DDLogVerbose("Current Application state: \(applicationState.rawValue)")
// Badge: Update
if let badgeCountNumber = userInfo.number(forKeyPath: Notification.badgePath)?.intValue {
sharedApplication.applicationIconBadgeNumber = badgeCountNumber
}
// Badge: Reset
guard let type = userInfo.string(forKey: Notification.typeKey), type != Notification.badgeResetValue else {
return
}
// Analytics
trackNotification(with: userInfo)
// Handling!
let handlers = [handleSupportNotification,
handleAuthenticationNotification,
handleInactiveNotification,
handleBackgroundNotification,
handleQuickStartLocalNotification]
for handler in handlers {
if handler(userInfo, userInteraction, completionHandler) {
break
}
}
}
/// Tracks a Notification Event
///
/// - Parameter userInfo: The Notification's Payload
///
func trackNotification(with userInfo: NSDictionary) {
var properties = [String: String]()
if let noteId = userInfo.number(forKey: Notification.identifierKey) {
properties[Tracking.identifierKey] = noteId.stringValue
}
if let type = userInfo.string(forKey: Notification.typeKey) {
properties[Tracking.typeKey] = type
}
if let theToken = deviceToken {
properties[Tracking.tokenKey] = theToken
}
let event: WPAnalyticsStat = (applicationState == .background) ? .pushNotificationReceived : .pushNotificationAlertPressed
WPAnalytics.track(event, withProperties: properties)
}
}
// MARK: - Handlers: Should be private, but... are open due to Unit Testing requirements!
//
extension PushNotificationsManager {
/// Handles a Support Remote Notification
///
/// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock),
/// we'll temporarily keep it as public. Sorry.
///
/// - Parameters:
/// - userInfo: The Notification's Payload
/// - completionHandler: A callback, to be executed on completion
///
/// - Returns: True when handled. False otherwise
///
@objc func handleSupportNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool {
guard let type = userInfo.string(forKey: ZendeskUtils.PushNotificationIdentifiers.key),
type == ZendeskUtils.PushNotificationIdentifiers.type else {
return false
}
DispatchQueue.main.async {
ZendeskUtils.pushNotificationReceived()
}
WPAnalytics.track(.supportReceivedResponseFromSupport)
if applicationState == .background {
WPTabBarController.sharedInstance().showMeScene()
}
completionHandler?(.newData)
return true
}
/// Handles a WordPress.com Push Authentication Notification
///
/// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock),
/// we'll temporarily keep it as public. Sorry.
///
/// - Parameters:
/// - userInfo: The Notification's Payload
/// - completionHandler: A callback, to be executed on completion
///
/// - Returns: True when handled. False otherwise
///
@objc func handleAuthenticationNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool {
// WordPress.com Push Authentication Notification
// Due to the Background Notifications entitlement, any given Push Notification's userInfo might be received
// while the app is in BG, and when it's about to become active. In order to prevent UI glitches, let's skip
// notifications when in BG mode. Still, we don't wanna relay that BG notification!
//
let authenticationManager = PushAuthenticationManager()
guard authenticationManager.isAuthenticationNotification(userInfo) else {
return false
}
/// This is a (hopefully temporary) workaround. A Push Authentication must be dealt with whenever:
///
/// 1. When the user interacts with a Push Notification
/// 2. When the App is in Foreground
///
/// As per iOS 13 there are certain scenarios in which the `applicationState` may be `.background` when the user pressed over the Alert.
/// By means of the `userInteraction` flag, we're just working around the new SDK behavior.
///
/// Proper fix involves a full refactor, and definitely stop checking on `applicationState`, since it's not reliable anymore.
///
if applicationState != .background || userInteraction {
authenticationManager.handleAuthenticationNotification(userInfo)
} else {
DDLogInfo("Skipping handling authentication notification due to app being in background or user not interacting with it.")
}
completionHandler?(.newData)
return true
}
/// A handler for a 2fa auth notification approval action.
///
/// - Parameter userInfo: The Notification's Payload
/// - Returns: True if successful. False otherwise.
///
@objc func handleAuthenticationApprovedAction(_ userInfo: NSDictionary) -> Bool {
let authenticationManager = PushAuthenticationManager()
guard authenticationManager.isAuthenticationNotification(userInfo) else {
return false
}
authenticationManager.handleAuthenticationApprovedAction(userInfo)
return true
}
/// Handles a Notification while in Inactive Mode
///
/// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock),
/// we'll temporarily keep it as public. Sorry.
///
/// - Parameters:
/// - userInfo: The Notification's Payload
/// - completionHandler: A callback, to be executed on completion
///
/// - Returns: True when handled. False otherwise
///
@objc func handleInactiveNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool {
guard applicationState == .inactive else {
return false
}
guard let notificationId = userInfo.number(forKey: Notification.identifierKey)?.stringValue else {
return false
}
WPTabBarController.sharedInstance().showNotificationsTabForNote(withID: notificationId)
completionHandler?(.newData)
return true
}
/// Handles a Notification while in Active OR Background Modes
///
/// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock),
/// we'll temporarily keep it as public. Sorry.
///
/// - Parameters:
/// - userInfo: The Notification's Payload
/// - completionHandler: A callback, to be executed on completion
///
/// - Returns: True when handled. False otherwise
///
@objc func handleBackgroundNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool {
guard userInfo.number(forKey: Notification.identifierKey)?.stringValue != nil else {
return false
}
guard applicationState == .background else {
return false
}
guard let mediator = NotificationSyncMediator() else {
completionHandler?(.failed)
return true
}
DDLogInfo("Running Notifications Background Fetch...")
mediator.sync { error, newData in
DDLogInfo("Finished Notifications Background Fetch!")
let result = newData ? UIBackgroundFetchResult.newData : .noData
completionHandler?(result)
}
return true
}
}
// MARK: - Nested Types
//
extension PushNotificationsManager {
enum Device {
static let tokenKey = "apnsDeviceToken"
static let idKey = "notification_device_id"
}
enum Notification {
static let badgePath = "aps.badge"
static let identifierKey = "note_id"
static let typeKey = "type"
static let originKey = "origin"
static let badgeResetValue = "badge-reset"
static let local = "qs-local-notification"
static let bloggingPrompts = "blogging-prompts-notification"
}
enum Tracking {
static let identifierKey = "push_notification_note_id"
static let typeKey = "push_notification_type"
static let tokenKey = "push_notification_token"
}
}
// MARK: - Quick Start notifications
extension PushNotificationsManager {
/// Handles a Quick Start Local Notification
///
/// - Note: This should actually be *private*. BUT: for unit testing purposes (within ObjC code, because of OCMock),
/// we'll temporarily keep it as public. Sorry.
///
/// - Parameters:
/// - userInfo: The Notification's Payload
/// - completionHandler: A callback, to be executed on completion
///
/// - Returns: True when handled. False otherwise
@objc func handleQuickStartLocalNotification(_ userInfo: NSDictionary, userInteraction: Bool, completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool {
guard let type = userInfo.string(forKey: Notification.typeKey),
type == Notification.local else {
return false
}
if WPTabBarController.sharedInstance()?.presentedViewController != nil {
WPTabBarController.sharedInstance()?.dismiss(animated: false)
}
WPTabBarController.sharedInstance()?.showMySitesTab()
if let taskName = userInfo.string(forKey: QuickStartTracking.taskNameKey),
let quickStartType = userInfo.string(forKey: QuickStartTracking.quickStartTypeKey) {
WPAnalytics.track(.quickStartNotificationTapped,
withProperties: [QuickStartTracking.taskNameKey: taskName,
WPAnalytics.WPAppAnalyticsKeyQuickStartSiteType: quickStartType])
}
completionHandler?(.newData)
return true
}
func postNotification(for tour: QuickStartTour, quickStartType: QuickStartType) {
deletePendingLocalNotifications()
let content = UNMutableNotificationContent()
content.title = tour.title
content.body = tour.description
content.sound = UNNotificationSound.default
content.userInfo = [Notification.typeKey: Notification.local,
QuickStartTracking.taskNameKey: tour.analyticsKey]
guard let futureDate = Calendar.current.date(byAdding: .day,
value: Constants.localNotificationIntervalInDays,
to: Date()) else {
return
}
let trigger = UNCalendarNotificationTrigger(dateMatching: futureDate.components, repeats: false)
let request = UNNotificationRequest(identifier: Constants.localNotificationIdentifier,
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request)
WPAnalytics.track(.quickStartNotificationStarted,
withProperties: [QuickStartTracking.taskNameKey: tour.analyticsKey,
WPAnalytics.WPAppAnalyticsKeyQuickStartSiteType: quickStartType.key])
}
@objc func deletePendingLocalNotifications() {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [Constants.localNotificationIdentifier])
}
private enum Constants {
static let localNotificationIntervalInDays = 2
static let localNotificationIdentifier = "QuickStartTourNotificationIdentifier"
}
private enum QuickStartTracking {
static let taskNameKey = "task_name"
static let quickStartTypeKey = "site_type"
}
}
private extension Date {
var components: DateComponents {
return Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second],
from: self)
}
}