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
|
//
// NotificationManager.swift
// MullvadVPN
//
// Created by pronebird on 31/05/2021.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadLogging
import UserNotifications
final class NotificationManager: NotificationProviderDelegate {
private lazy var logger = Logger(label: "NotificationManager")
private var _notificationProviders: [NotificationProvider] = []
private var inAppNotificationDescriptors: [InAppNotificationDescriptor] = []
var notificationProviders: [NotificationProvider] {
get {
_notificationProviders
}
set(newNotificationProviders) {
dispatchPrecondition(condition: .onQueue(.main))
for oldNotificationProvider in _notificationProviders {
oldNotificationProvider.delegate = nil
}
for newNotificationProvider in newNotificationProviders {
newNotificationProvider.delegate = self
}
_notificationProviders = newNotificationProviders.sorted { $0.priority > $1.priority }
}
}
weak var delegate: NotificationManagerDelegate? {
didSet {
dispatchPrecondition(condition: .onQueue(.main))
// Pump in-app notifications when changing delegate.
if !inAppNotificationDescriptors.isEmpty {
delegate?.notificationManagerDidUpdateInAppNotifications(
self,
notifications: inAppNotificationDescriptors
)
}
}
}
nonisolated(unsafe) static let shared = NotificationManager()
private init() {}
func updateNotifications() {
dispatchPrecondition(condition: .onQueue(.main))
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.domainIdentifier)
}
if notificationProvider.shouldRemoveDeliveredRequests {
deliveredRequestIdentifiersToRemove.append(notificationProvider.identifier.domainIdentifier)
}
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
guard let error else { return }
self.logger.error(
error: error,
message: "Failed to add notification request with identifier \(newRequest.identifier)."
)
}
}
}
inAppNotificationDescriptors = newInAppNotificationDescriptors
delegate?.notificationManagerDidUpdateInAppNotifications(
self,
notifications: newInAppNotificationDescriptors
)
}
func handleSystemNotificationResponse(_ response: UNNotificationResponse) {
dispatchPrecondition(condition: .onQueue(.main))
guard
let sourceProvider = notificationProviders.first(where: { notificationProvider in
guard let notificationProvider = notificationProvider as? SystemNotificationProvider else {
return false
}
return response.notification.request.identifier == notificationProvider.identifier.domainIdentifier
})
else {
logger.warning(
"Received response with request identifier: \(response.notification.request.identifier) that didn't map to any notification provider"
)
return
}
let notificationResponse = NotificationResponse(
providerIdentifier: sourceProvider.identifier,
actionIdentifier: response.actionIdentifier,
systemResponse: response
)
delegate?.notificationManager(self, didReceiveResponse: notificationResponse)
}
// 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 {
self.logger.error(
error: error,
message: "Failed to obtain user notifications authorization"
)
}
completion(granted)
}
case .authorized, .provisional:
completion(true)
case .denied, .ephemeral:
fallthrough
@unknown default:
completion(false)
}
}
}
// MARK: - NotificationProviderDelegate
func notificationProviderDidInvalidate(_ notificationProvider: NotificationProvider) {
dispatchPrecondition(condition: .onQueue(.main))
// Invalidate system notification
if let notificationProvider = notificationProvider as? SystemNotificationProvider {
let notificationCenter = UNUserNotificationCenter.current()
if notificationProvider.shouldRemovePendingRequests {
notificationCenter.removePendingNotificationRequests(withIdentifiers: [
notificationProvider.identifier.domainIdentifier
])
}
if notificationProvider.shouldRemoveDeliveredRequests {
notificationCenter.removeDeliveredNotifications(withIdentifiers: [
notificationProvider.identifier.domainIdentifier
])
}
if let request = notificationProvider.notificationRequest {
requestNotificationPermissions { granted in
guard granted else { return }
notificationCenter.add(request) { error in
if let error {
self.logger.error(
"""
Failed to add notification request with identifier \
\(request.identifier). Error: \(error.localizedDescription)
"""
)
}
}
}
}
}
invalidateInAppNotification(notificationProvider)
}
private func invalidateInAppNotification(_ notificationProvider: NotificationProvider) {
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
descriptor.identifier == notificationProvider.identifier
}
}
}
} else {
newNotificationDescriptors.removeAll { descriptor in
descriptor.identifier == notificationProvider.identifier
}
}
inAppNotificationDescriptors = newNotificationDescriptors
delegate?.notificationManagerDidUpdateInAppNotifications(
self,
notifications: inAppNotificationDescriptors
)
}
}
func notificationProvider(_ notificationProvider: NotificationProvider, didReceiveAction actionIdentifier: String) {
dispatchPrecondition(condition: .onQueue(.main))
let notificationResponse = NotificationResponse(
providerIdentifier: notificationProvider.identifier,
actionIdentifier: actionIdentifier
)
delegate?.notificationManager(self, didReceiveResponse: notificationResponse)
}
}
|