-
Notifications
You must be signed in to change notification settings - Fork 35
/
RemoteNotificationHandler.swift
265 lines (227 loc) · 8.85 KB
/
RemoteNotificationHandler.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
//
// RemoteNotificationHandler.swift
// Multisig
//
// Created by Dmitry Bespalov on 05.08.20.
// Copyright © 2020 Gnosis Ltd. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
import Firebase
class RemoteNotificationHandler {
@UserDefault(key: "io.gnosis.multisig.deviceID")
private var storedDeviceID: String?
@EnumDefault(key: "io.gnosis.multisig.authorizationStatus")
private var authorizationStatus: UNAuthorizationStatus?
@UserDefault(key: "io.gnosis.multisig.pushToken")
private var token: String?
private var queue = DispatchQueue(label: "RemoteNotificationHandlerQueue")
func setUpMessaging(delegate: MessagingDelegate & UNUserNotificationCenterDelegate) {
logDebug("Setting up notification handling")
Messaging.messaging().delegate = delegate
// https://firebase.google.com/docs/cloud-messaging/ios/client
// for devices running iOS 10 and above, you must assign your delegate object to the UNUserNotificationCenter
// object to receive display notifications, and the FIRMessaging object to receive data messages,
// before your app finishes launching.
UNUserNotificationCenter.current().delegate = delegate
}
// MARK: - Events
func appStarted() {
logDebug("App started")
if storedDeviceID == nil {
storedDeviceID = UUID().uuidString
}
monitorAuthorizationStatus()
}
func appEnteredForeground() {
logDebug("App Entered Foreground")
cleanUpDeliveredNotifications()
}
func pushTokenUpdated(_ token: String) {
logDebug("Push token updated")
self.token = token
if authorizationStatus != nil {
registerAll()
}
}
func safeAdded(address: Address) {
logDebug("Safe added: \(address)")
if authorizationStatus == nil {
requestUserPermissionAndRegister()
} else {
register(addresses: [address])
}
}
func safeRemoved(address: Address) {
logDebug("Safe removed: \(address)")
unregister(address: address)
}
/// For add / remove signing key
func signingKeyUpdated() {
logDebug("Signing key updated")
registerAll()
}
func received(notification userInfo: [AnyHashable: Any]) {
assert(Thread.isMainThread)
logDebug("Received notification: \(userInfo)")
self.showDetails(userInfo)
}
// MARK: - implementation
private func cleanUpDeliveredNotifications() {
UIApplication.shared.applicationIconBadgeNumber = 0
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
logDebug("Cleaning up delivered notifications")
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}
}
private func monitorAuthorizationStatus() {
if let previousAuthorization = authorizationStatus {
UNUserNotificationCenter.current().getNotificationSettings { settings in
logDebug("Old permission: \(previousAuthorization), new permission: \(settings.authorizationStatus)")
if settings.authorizationStatus.hasPermission && !previousAuthorization.hasPermission {
// authorization changed to granted
self.requestUserPermissionAndRegister()
} else {
// authorization either not changed or not granted
self.setStatus(settings.authorizationStatus)
if settings.authorizationStatus.hasPermission {
self.registerAll()
}
}
}
} else if Safe.count > 0 {
requestUserPermissionAndRegister()
}
}
private func requestUserPermissionAndRegister() {
if !Thread.isMainThread {
DispatchQueue.main.async { self.requestUserPermissionAndRegister() }
return
}
logDebug("requesting permissions for notifications")
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if let error = error {
LogService.shared.error("Notification authorization error: \(error)")
return
}
if granted {
logDebug("User gave permission for notifications")
DispatchQueue.main.async {
logDebug("registering remote notifications")
UIApplication.shared.registerForRemoteNotifications()
}
// At the time when permission granted, the token will be
// already set, so we need to register all stored safes
self.registerAll()
}
self.updateAuthorizationStatus()
}
}
private func setStatus(_ status: UNAuthorizationStatus) {
DispatchQueue.main.async {
logDebug("Saving authorization status")
self.authorizationStatus = status
self.track(status)
}
}
private func updateAuthorizationStatus() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
logDebug("Got current notification settings")
self.setStatus(settings.authorizationStatus)
}
}
private func track(_ status: UNAuthorizationStatus) {
Tracker.shared.setUserProperty(status.trackingStatus.rawValue,
for: TrackingUserProperty.pushInfo)
}
private func register(addresses: [Address]) {
guard let token = self.token else { return }
queue.async { [unowned self] in
let appConfig = App.configuration.app
var timestamp: String?
if let _ = try? App.shared.keychainService.data(forKey: KeychainKey.ownerPrivateKey.rawValue) {
// add timestamp if there is a signing key
timestamp = String(Int(Date().timeIntervalSince1970 * 1_000))
}
do {
try App.shared.safeTransactionService
.register(deviceID: self.storedDeviceID!,
safes: addresses,
token: token,
bundle: appConfig.bundleIdentifier,
version: appConfig.marketingVersion,
buildNumber: appConfig.buildVersion,
timestamp: timestamp)
} catch {
logError("Failed to register device", error)
}
}
}
private func unregister(address: Address) {
queue.async { [unowned self] in
do {
try App.shared.safeTransactionService.unregister(deviceID: self.storedDeviceID!, address: address)
} catch {
logError("Failed to unregister device", error)
}
}
}
private func registerAll() {
let addresses = Safe.all.map { Address(exactly: $0.address ?? "") }
register(addresses: addresses)
}
private func showDetails(_ userInfo: [AnyHashable : Any]) {
UIApplication.shared.applicationIconBadgeNumber = 0
let payload = NotificationPayload(userInfo: userInfo)
do {
guard let rawAddress = payload.address,
let safeAddress = Address(rawAddress) else { return }
guard try Safe.exists(safeAddress.checksummed) else {
unregister(address: safeAddress)
return
}
Safe.select(address: rawAddress)
App.shared.viewState.switchTab(.transactions)
} catch {
logError("Error during opening notification", error)
}
}
}
fileprivate func logDebug(_ msg: String) {
LogService.shared.debug("PUSH: " + msg)
}
fileprivate func logError(_ msg: String, _ error: Error) {
LogService.shared.error(msg + ": \(error)", error: error)
}
extension UNAuthorizationStatus {
var hasPermission: Bool {
self == .authorized || self == .provisional
}
}
extension UNAuthorizationStatus: CustomStringConvertible {
public var description: String {
switch self {
case .authorized: return "Authorized (granted)"
case .denied: return "Denied"
case .notDetermined: return "Not Determined"
case .provisional: return "Provisional (granted)"
case .ephemeral: return "Ephemeral (granted)"
@unknown default: return "Unknown: \(rawValue)"
}
}
}
extension UNAuthorizationStatus {
fileprivate var trackingStatus: TrackingPushState {
switch self {
case .authorized, .provisional, .ephemeral:
return .enabled
case .denied:
return .disabled
case .notDetermined:
return .unknown
@unknown default:
return .unknown
}
}
}