blob: 0204396c5726973a51f02591fab3d838c1e3900a (
plain)
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
|
//
// NotificationManager.swift
// MullvadVPN
//
// Created by pronebird on 31/05/2021.
// Copyright © 2021 Mullvad VPN AB. All rights reserved.
//
import Foundation
import UserNotifications
import Logging
import UIKit
protocol NotificationManagerDelegate: AnyObject {
func notificationManagerDidUpdateInAppNotifications(_ manager: NotificationManager, notifications: [InAppNotificationDescriptor])
}
fileprivate protocol NotificationProviderDelegate: AnyObject {
func notificationProviderDidInvalidate(_ notificationProvider: NotificationProvider)
}
class NotificationProvider {
fileprivate weak var delegate: NotificationProviderDelegate?
var identifier: String {
return "default"
}
func invalidate() {
let executor = { () -> Void in
self.delegate?.notificationProviderDidInvalidate(self)
}
if Thread.isMainThread {
executor()
} else {
DispatchQueue.main.async(execute: executor)
}
}
}
protocol SystemNotificationProvider {
/// Unique provider identifier used to identify requests
var identifier: String { get }
/// Notification request if available, otherwise `nil`
var notificationRequest: UNNotificationRequest? { get }
/// Whether any pending requests should be removed
var shouldRemovePendingRequests: Bool { get }
/// Whether any delivered requests should be removed
var shouldRemoveDeliveredRequests: Bool { get }
}
protocol InAppNotificationProvider {
/// Unique provider identifier used to identify notifications
var identifier: String { get }
/// In-app notification descriptor
var notificationDescriptor: InAppNotificationDescriptor? { get }
}
class NotificationManager: NotificationProviderDelegate {
private lazy var logger = Logger(label: "NotificationManager")
var notificationProviders: [NotificationProvider] = [] {
willSet {
assert(Thread.isMainThread)
}
didSet {
for notificationProvider in notificationProviders {
notificationProvider.delegate = self
}
}
}
private var inAppNotificationDescriptors: [InAppNotificationDescriptor] = []
weak var delegate: NotificationManagerDelegate? {
willSet {
assert(Thread.isMainThread)
}
didSet {
// Pump in-app notifications when changing delegate.
if !inAppNotificationDescriptors.isEmpty {
delegate?.notificationManagerDidUpdateInAppNotifications(self, notifications: inAppNotificationDescriptors)
}
}
}
func updateNotifications() {
assert(Thread.isMainThread)
var newSystemNotificationRequests = [UNNotificationRequest]()
var newInAppNotificationDescriptors = [InAppNotificationDescriptor]()
var pendingRequestIdentifiersToRemove = [String]()
var deliveredRequestIdentifiersToRemove = [String]()
for notificationProvider in notificationProviders {
if let notificationProvider = notificationProvider as? SystemNotificationProvider {
if notificationProvider.shouldRemovePendingRequests {
pendingRequestIdentifiersToRemove.append(notificationProvider.identifier)
}
if notificationProvider.shouldRemoveDeliveredRequests {
deliveredRequestIdentifiersToRemove.append(notificationProvider.identifier)
}
if let request = notificationProvider.notificationRequest {
newSystemNotificationRequests.append(request)
}
}
if let notificationProvider = notificationProvider as? InAppNotificationProvider {
if let descriptor = notificationProvider.notificationDescriptor {
newInAppNotificationDescriptors.append(descriptor)
}
}
}
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removePendingNotificationRequests(withIdentifiers: pendingRequestIdentifiersToRemove)
notificationCenter.removeDeliveredNotifications(withIdentifiers: deliveredRequestIdentifiersToRemove)
requestNotificationPermissions { (granted) in
guard granted else { return }
for newRequest in newSystemNotificationRequests {
notificationCenter.add(newRequest) { (error) in
if let error = error {
self.logger.error("Failed to add notification request with identifier \(newRequest.identifier). Error: \(error.localizedDescription)")
}
}
}
}
inAppNotificationDescriptors = newInAppNotificationDescriptors
delegate?.notificationManagerDidUpdateInAppNotifications(self, notifications: newInAppNotificationDescriptors)
}
// MARK: - Private
private func requestNotificationPermissions(completion: @escaping (Bool) -> Void) {
let authorizationOptions: UNAuthorizationOptions = [.alert, .sound, .provisional]
let userNotificationCenter = UNUserNotificationCenter.current()
userNotificationCenter.getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
userNotificationCenter.requestAuthorization(options: authorizationOptions) { (granted, error) in
if let error = error {
self.logger.error("Failed to obtain user notifications authorization: \(error.localizedDescription)")
}
completion(granted)
}
case .authorized, .provisional:
completion(true)
case .denied, .ephemeral:
fallthrough
@unknown default:
completion(false)
}
}
}
// MARK: - NotificationProviderDelegate
func notificationProviderDidInvalidate(_ notificationProvider: NotificationProvider) {
assert(Thread.isMainThread)
// Invalidate system notification
if let notificationProvider = notificationProvider as? SystemNotificationProvider {
let notificationCenter = UNUserNotificationCenter.current()
if notificationProvider.shouldRemovePendingRequests {
notificationCenter.removePendingNotificationRequests(withIdentifiers: [notificationProvider.identifier])
}
if notificationProvider.shouldRemoveDeliveredRequests {
notificationCenter.removeDeliveredNotifications(withIdentifiers: [notificationProvider.identifier])
}
if let request = notificationProvider.notificationRequest {
requestNotificationPermissions { (granted) in
guard granted else { return }
notificationCenter.add(request) { (error) in
if let error = error {
self.logger.error("Failed to add notification request with identifier \(request.identifier). Error: \(error.localizedDescription)")
}
}
}
}
}
// Invalidate in-app notification
if let notificationProvider = notificationProvider as? InAppNotificationProvider {
var newNotificationDescriptors = inAppNotificationDescriptors
if let replaceNotificationDescriptor = notificationProvider.notificationDescriptor {
newNotificationDescriptors = notificationProviders.compactMap { (notificationProvider) -> InAppNotificationDescriptor? in
if replaceNotificationDescriptor.identifier == notificationProvider.identifier {
return replaceNotificationDescriptor
} else {
return inAppNotificationDescriptors.first { (descriptor) in
return descriptor.identifier == notificationProvider.identifier
}
}
}
} else {
newNotificationDescriptors.removeAll { (descriptor) in
return descriptor.identifier == notificationProvider.identifier
}
}
inAppNotificationDescriptors = newNotificationDescriptors
delegate?.notificationManagerDidUpdateInAppNotifications(self, notifications: inAppNotificationDescriptors)
}
}
}
|