@datatalks-ab/push-capacitor 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/DatatalksAbPushCapacitor.podspec +21 -0
  2. package/DatatalksPushExtension.podspec +21 -0
  3. package/Package.swift +35 -0
  4. package/README.md +212 -2
  5. package/android/build.gradle +48 -0
  6. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar +0 -0
  7. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.md5 +1 -0
  8. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.sha1 +1 -0
  9. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.sha256 +1 -0
  10. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.sha512 +1 -0
  11. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar +0 -0
  12. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.md5 +1 -0
  13. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.sha1 +1 -0
  14. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.sha256 +1 -0
  15. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.sha512 +1 -0
  16. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module +144 -0
  17. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.md5 +1 -0
  18. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.sha1 +1 -0
  19. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.sha256 +1 -0
  20. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.sha512 +1 -0
  21. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom +63 -0
  22. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.md5 +1 -0
  23. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.sha1 +1 -0
  24. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.sha256 +1 -0
  25. package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.sha512 +1 -0
  26. package/android/maven/se/datatalks/push-android/maven-metadata.xml +13 -0
  27. package/android/maven/se/datatalks/push-android/maven-metadata.xml.md5 +1 -0
  28. package/android/maven/se/datatalks/push-android/maven-metadata.xml.sha1 +1 -0
  29. package/android/maven/se/datatalks/push-android/maven-metadata.xml.sha256 +1 -0
  30. package/android/maven/se/datatalks/push-android/maven-metadata.xml.sha512 +1 -0
  31. package/android/src/main/AndroidManifest.xml +2 -0
  32. package/android/src/main/java/se/datatalks/push/capacitor/DataTalksPushPlugin.java +255 -0
  33. package/dist/esm/definitions.d.ts +92 -0
  34. package/dist/esm/definitions.js +3 -0
  35. package/dist/esm/definitions.js.map +1 -0
  36. package/dist/esm/index.d.ts +4 -0
  37. package/dist/esm/index.js +7 -0
  38. package/dist/esm/index.js.map +1 -0
  39. package/dist/esm/web.d.ts +12 -0
  40. package/dist/esm/web.js +26 -0
  41. package/dist/esm/web.js.map +1 -0
  42. package/dist/plugin.cjs.js +40 -0
  43. package/dist/plugin.cjs.js.map +1 -0
  44. package/dist/plugin.js +43 -0
  45. package/dist/plugin.js.map +1 -0
  46. package/ios/Extension/DataTalksNotificationService.swift +120 -0
  47. package/ios/Extension/DeliveryReporter.swift +50 -0
  48. package/ios/Extension/ExtensionShared.swift +101 -0
  49. package/ios/Extension/PrivacyInfo.xcprivacy +27 -0
  50. package/ios/Extension/PushAttachment.swift +90 -0
  51. package/ios/Sources/DataTalksPushPlugin/Core/AppKeys.swift +35 -0
  52. package/ios/Sources/DataTalksPushPlugin/Core/DataTalksPush.swift +110 -0
  53. package/ios/Sources/DataTalksPushPlugin/Core/DataTalksPushListener.swift +72 -0
  54. package/ios/Sources/DataTalksPushPlugin/Core/DeviceFacts.swift +128 -0
  55. package/ios/Sources/DataTalksPushPlugin/Core/PrivacyInfo.xcprivacy +60 -0
  56. package/ios/Sources/DataTalksPushPlugin/Core/PushApi.swift +64 -0
  57. package/ios/Sources/DataTalksPushPlugin/Core/PushMessage.swift +47 -0
  58. package/ios/Sources/DataTalksPushPlugin/Core/PushRuntime.swift +369 -0
  59. package/ios/Sources/DataTalksPushPlugin/Core/PushStore.swift +465 -0
  60. package/ios/Sources/DataTalksPushPlugin/Core/PushSync.swift +381 -0
  61. package/ios/Sources/DataTalksPushPlugin/Core/SharedContainer.swift +104 -0
  62. package/ios/Sources/DataTalksPushPlugin/DataTalksPushPlugin.swift +197 -0
  63. package/package.json +55 -4
@@ -0,0 +1,60 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>NSPrivacyTracking</key>
6
+ <false/>
7
+ <key>NSPrivacyTrackingDomains</key>
8
+ <array/>
9
+ <key>NSPrivacyCollectedDataTypes</key>
10
+ <array>
11
+ <dict>
12
+ <key>NSPrivacyCollectedDataType</key>
13
+ <string>NSPrivacyCollectedDataTypeDeviceID</string>
14
+ <key>NSPrivacyCollectedDataTypeLinked</key>
15
+ <true/>
16
+ <key>NSPrivacyCollectedDataTypeTracking</key>
17
+ <false/>
18
+ <key>NSPrivacyCollectedDataTypePurposes</key>
19
+ <array>
20
+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
21
+ </array>
22
+ </dict>
23
+ <dict>
24
+ <key>NSPrivacyCollectedDataType</key>
25
+ <string>NSPrivacyCollectedDataTypeUserID</string>
26
+ <key>NSPrivacyCollectedDataTypeLinked</key>
27
+ <true/>
28
+ <key>NSPrivacyCollectedDataTypeTracking</key>
29
+ <false/>
30
+ <key>NSPrivacyCollectedDataTypePurposes</key>
31
+ <array>
32
+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
33
+ </array>
34
+ </dict>
35
+ <dict>
36
+ <key>NSPrivacyCollectedDataType</key>
37
+ <string>NSPrivacyCollectedDataTypeEmailAddress</string>
38
+ <key>NSPrivacyCollectedDataTypeLinked</key>
39
+ <true/>
40
+ <key>NSPrivacyCollectedDataTypeTracking</key>
41
+ <false/>
42
+ <key>NSPrivacyCollectedDataTypePurposes</key>
43
+ <array>
44
+ <string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string>
45
+ </array>
46
+ </dict>
47
+ </array>
48
+ <key>NSPrivacyAccessedAPITypes</key>
49
+ <array>
50
+ <dict>
51
+ <key>NSPrivacyAccessedAPIType</key>
52
+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>
53
+ <key>NSPrivacyAccessedAPITypeReasons</key>
54
+ <array>
55
+ <string>CA92.1</string>
56
+ </array>
57
+ </dict>
58
+ </array>
59
+ </dict>
60
+ </plist>
@@ -0,0 +1,64 @@
1
+ import Foundation
2
+
3
+ /// A service response. `json` is the decoded body; `code` and `detail` come from its `error` object.
4
+ struct ApiResponse {
5
+ let status: Int
6
+ let json: [String: Any]?
7
+ let retryAfterSeconds: Int?
8
+
9
+ var isSuccess: Bool { (200 ..< 300).contains(status) }
10
+
11
+ var code: String? { error?["code"] as? String }
12
+
13
+ var detail: String? { error?["detail"] as? String }
14
+
15
+ private var error: [String: Any]? { json?["error"] as? [String: Any] }
16
+ }
17
+
18
+ enum PushApiError: Error {
19
+ case badUrl
20
+ case noResponse
21
+ }
22
+
23
+ /// A blocking call to the ingress, made on the SDK's queue. Nothing here logs: keys, secrets, tokens and identities pass through it.
24
+ struct PushApi {
25
+ private static let requestTimeout: TimeInterval = 30
26
+
27
+ let baseUrl: String
28
+ let appKey: String
29
+ let session: URLSession
30
+
31
+ /// Throws for a network error, which the contract retries with backoff.
32
+ func call(_ method: String, _ path: String, deviceSecret: String? = nil, body: [String: Any]? = nil) throws -> ApiResponse {
33
+ guard let url = URL(string: baseUrl + path) else { throw PushApiError.badUrl }
34
+
35
+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: Self.requestTimeout)
36
+ request.httpMethod = method
37
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
38
+ request.setValue(appKey, forHTTPHeaderField: "X-DataTalks-App-Key")
39
+ request.setValue(SdkInfo.header, forHTTPHeaderField: "X-DataTalks-SDK")
40
+ if let deviceSecret {
41
+ request.setValue(deviceSecret, forHTTPHeaderField: "X-DataTalks-Device-Secret")
42
+ }
43
+
44
+ if let body {
45
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
46
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
47
+ }
48
+
49
+ let finished = DispatchSemaphore(value: 0)
50
+ var answer: (data: Data?, response: URLResponse?, error: Error?)
51
+ session.dataTask(with: request) { data, response, error in
52
+ answer = (data, response, error)
53
+ finished.signal()
54
+ }.resume()
55
+ finished.wait()
56
+
57
+ if let error = answer.error { throw error }
58
+ guard let response = answer.response as? HTTPURLResponse else { throw PushApiError.noResponse }
59
+
60
+ let json = answer.data.flatMap { (try? JSONSerialization.jsonObject(with: $0)) as? [String: Any] }
61
+ let retryAfter = response.value(forHTTPHeaderField: "Retry-After").flatMap(Int.init)
62
+ return ApiResponse(status: response.statusCode, json: json, retryAfterSeconds: retryAfter)
63
+ }
64
+ }
@@ -0,0 +1,47 @@
1
+ import Foundation
2
+
3
+ /// A Data Talks push, read from its `dt_*` keys (`spec/payload/payload-v1.md`). The system displays `aps`; the app gets the rest.
4
+ struct PushMessage {
5
+ let uid: String?
6
+ let title: String?
7
+ let body: String?
8
+ let image: String?
9
+ let link: String?
10
+ let dataText: String?
11
+
12
+ /// Nil unless the payload has `dt_v`, which marks a Data Talks push.
13
+ init?(userInfo: [AnyHashable: Any]) {
14
+ guard userInfo["dt_v"] != nil else { return nil }
15
+ uid = userInfo["dt_uid"] as? String
16
+ // The text is in both `aps.alert` and `dt_title`/`dt_body`. Prefer the alert: it is what the system displayed.
17
+ let alert = (userInfo["aps"] as? [String: Any])?["alert"]
18
+ title = (alert as? [String: Any])?["title"] as? String ?? userInfo["dt_title"] as? String
19
+ body = (alert as? [String: Any])?["body"] as? String ?? alert as? String ?? userInfo["dt_body"] as? String
20
+ image = userInfo["dt_image"] as? String
21
+ link = userInfo["dt_link"] as? String
22
+ dataText = userInfo["dt_data"] as? String
23
+ }
24
+
25
+ var data: [String: Any]? {
26
+ guard let dataText else { return nil }
27
+ return (try? JSONSerialization.jsonObject(with: Data(dataText.utf8))) as? [String: Any]
28
+ }
29
+
30
+ func toPublic() -> DataTalksMessage {
31
+ DataTalksMessage(uid: uid, title: title, body: body, imageUrl: image, deepLink: link, data: data)
32
+ }
33
+ }
34
+
35
+ /// Which links a tap opens: `https` links go through the system, which resolves the app's universal links. Other schemes must stay
36
+ /// inside the app, so only those the app declares in `CFBundleURLTypes` open. Otherwise the tap has already opened the app.
37
+ enum PushLinks {
38
+ static func target(link: String?, declaredSchemes: Set<String>) -> URL? {
39
+ guard let link, let url = URL(string: link), let scheme = url.scheme?.lowercased() else { return nil }
40
+ return scheme == "https" || declaredSchemes.contains(scheme) ? url : nil
41
+ }
42
+
43
+ static func declaredSchemes(bundle: Bundle = .main) -> Set<String> {
44
+ let types = bundle.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]] ?? []
45
+ return Set(types.flatMap { $0["CFBundleURLSchemes"] as? [String] ?? [] }.map { $0.lowercased() })
46
+ }
47
+ }
@@ -0,0 +1,369 @@
1
+ import Foundation
2
+ import UserNotifications
3
+ #if canImport(UIKit)
4
+ import UIKit
5
+ #endif
6
+
7
+ /// The SDK's state for one app process. All store and sync access goes through `queue`, which also keeps the app's calls in order.
8
+ final class PushRuntime {
9
+ private static let defaultsSuite = "se.datatalks.push"
10
+
11
+ static let shared = PushRuntime(
12
+ store: PushStore(values: KeychainValues(), defaults: UserDefaults(suiteName: defaultsSuite) ?? .standard, shared: SharedContainer.forApp()),
13
+ facts: SystemFacts(),
14
+ session: URLSession(configuration: .ephemeral)
15
+ )
16
+
17
+ // Internal so that tests can wait on it.
18
+ let queue = DispatchQueue(label: "se.datatalks.push")
19
+ private let store: PushStore
20
+ private let sync: PushSync
21
+ private let facts: DeviceFacts
22
+ private let openURL: (URL) -> Void
23
+
24
+ // Accessed on `queue` only.
25
+ private var retry: DispatchWorkItem?
26
+ private var retryAt: Date?
27
+ private var watchingTheApp = false
28
+
29
+ // Guarded by `lock`: read on the main thread when a tap arrives.
30
+ private let lock = NSLock()
31
+ private var currentListener: DataTalksPushListener?
32
+ private var currentOpenLinks = true
33
+
34
+ // A tap that launched the app can arrive before a wrapper sets its listener. The latest one is held for the next listener.
35
+ private var heldOpen: HeldOpen?
36
+
37
+ var listener: DataTalksPushListener? {
38
+ get { locked { currentListener } }
39
+ set {
40
+ let held: HeldOpen? = locked {
41
+ currentListener = newValue
42
+ let waiting = newValue == nil ? nil : heldOpen
43
+ if newValue != nil { heldOpen = nil }
44
+ return waiting
45
+ }
46
+
47
+ if let newValue, let held {
48
+ DispatchQueue.main.async { newValue.onNotificationOpened(deepLink: held.deepLink, data: held.data) }
49
+ }
50
+ }
51
+ }
52
+
53
+ /// `DataTalksPushOptions.openLinks` from the last `initialize`. Not persisted: on iOS a tap always arrives after `initialize`.
54
+ var openLinks: Bool {
55
+ get { locked { currentOpenLinks } }
56
+ set { locked { currentOpenLinks = newValue } }
57
+ }
58
+
59
+ init(store: PushStore, facts: DeviceFacts, session: URLSession, openURL: @escaping (URL) -> Void = PushRuntime.openWithTheSystem) {
60
+ self.store = store
61
+ self.facts = facts
62
+ self.openURL = openURL
63
+
64
+ // `unowned` is safe: the sync lives as long as the runtime, and the runtime as long as the app.
65
+ var report: (DataTalksIdentityResult) -> Void = { _ in }
66
+ sync = PushSync(store: store, facts: facts, session: session, onIdentityResult: { report($0) })
67
+ report = { [unowned self] result in onMain { self.listener?.onIdentityResult(result) } }
68
+ }
69
+
70
+ static func openWithTheSystem(_ url: URL) {
71
+ #if canImport(UIKit)
72
+ UIApplication.shared.open(url)
73
+ #endif
74
+ }
75
+
76
+ func start(appKey: String, baseUrl: String?, openLinks: Bool) {
77
+ self.openLinks = openLinks
78
+ watchTheApp()
79
+ registerWithApns()
80
+ queue.async { [self] in
81
+ if store.appKey != appKey || store.baseUrl != baseUrl {
82
+ store.replaceAppKey(appKey)
83
+ store.baseUrl = baseUrl
84
+ sync.stopped = false
85
+ }
86
+
87
+ store.publishSharedState()
88
+ syncIfDue()
89
+ }
90
+ }
91
+
92
+ func onNewToken(_ token: String) {
93
+ queue.async { [self] in
94
+ if store.updateToken(token), store.appKey != nil { syncNow() }
95
+ }
96
+ }
97
+
98
+ func onNewFcmToken(_ token: String) {
99
+ guard !token.isEmpty else {
100
+ PushLog.warning("An empty FCM token was ignored.")
101
+ return
102
+ }
103
+
104
+ queue.async { [self] in
105
+ if store.updateFcmToken(token), store.appKey != nil { syncNow() }
106
+ }
107
+ }
108
+
109
+ func send(identity: PendingIdentity) {
110
+ queue.async { [self] in
111
+ guard store.appKey != nil else {
112
+ PushLog.error("A call before initialize: nothing happened.")
113
+ return
114
+ }
115
+
116
+ warnIfATokenIsMissing(identity)
117
+
118
+ // Already accepted today for this install: skip the call, so an app that identifies at every launch makes one call a day.
119
+ // The listener gets the earlier result.
120
+ if let verified = store.repeatedAnswer(identity, day: sync.today()) {
121
+ onMain { self.listener?.onIdentityResult(DataTalksIdentityResult(verified: verified)) }
122
+ return
123
+ }
124
+
125
+ store.pendingIdentity = identity
126
+ syncNow()
127
+ }
128
+ }
129
+
130
+ func setMarketingOptIn(_ optIn: Bool) {
131
+ queue.async { [self] in
132
+ guard store.appKey != nil else {
133
+ PushLog.error("A call before initialize: nothing happened.")
134
+ return
135
+ }
136
+
137
+ store.pendingOptIn = optIn
138
+ syncNow()
139
+ }
140
+ }
141
+
142
+ func deleteLocalData() {
143
+ queue.async { [self] in
144
+ var pending = store.pendingDelete
145
+ if let key = store.appKey, let installId = store.installId, let secret = store.deviceSecret {
146
+ pending = PendingDelete(appKey: key, baseUrl: store.baseUrl, installId: installId, deviceSecret: secret)
147
+ }
148
+
149
+ store.wipe()
150
+ store.pendingDelete = pending
151
+ if pending != nil { syncNow() }
152
+ }
153
+ }
154
+
155
+ func requestPermission(provisional: Bool, completion: ((DataTalksPermission) -> Void)?) {
156
+ var options: UNAuthorizationOptions = [.alert, .sound, .badge]
157
+ if provisional { options.insert(.provisional) }
158
+
159
+ // Read the status, not `granted`: `granted` can't tell provisional from full authorization.
160
+ UNUserNotificationCenter.current().requestAuthorization(options: options) { [self] _, _ in
161
+ if let completion { permissionStatus(completion: completion) }
162
+ queue.async { [self] in syncIfDue() }
163
+ }
164
+ }
165
+
166
+ func permissionStatus(completion: @escaping (DataTalksPermission) -> Void) {
167
+ UNUserNotificationCenter.current().getNotificationSettings { settings in
168
+ let permission = DataTalksPermission(settings.authorizationStatus)
169
+ onMain { completion(permission) }
170
+ }
171
+ }
172
+
173
+ /// A tap on a Data Talks push: queues an open, plus a click when the push has a link, whether the SDK or the app opens it
174
+ /// (`openLinks`). Deliveries come from the notification service extension (`DataTalksPushExtension`); without one, the service
175
+ /// counts an open as a delivery.
176
+ func notificationOpened(userInfo: [AnyHashable: Any]) {
177
+ guard let message = PushMessage(userInfo: userInfo) else { return }
178
+
179
+ if let uid = message.uid {
180
+ let tappedAt = Date().timeIntervalSince1970
181
+ let link = message.link.flatMap { $0.isEmpty ? nil : $0 }
182
+ queue.async { [self] in
183
+ store.queueEvent(PushEvent.open, uid: uid, occurredAt: tappedAt)
184
+ if let link { store.queueEvent(PushEvent.click, uid: uid, occurredAt: tappedAt, link: link) }
185
+ syncIfDue()
186
+ }
187
+ }
188
+
189
+ // With `openLinks` false the app routes the link itself from `onNotificationOpened`.
190
+ let target = openLinks ? PushLinks.target(link: message.link, declaredSchemes: PushLinks.declaredSchemes()) : nil
191
+ let tapped = HeldOpen(deepLink: message.link, data: message.data)
192
+ onMain { [self] in
193
+ let current: DataTalksPushListener? = locked {
194
+ if currentListener == nil { heldOpen = tapped }
195
+ return currentListener
196
+ }
197
+
198
+ current?.onNotificationOpened(deepLink: tapped.deepLink, data: tapped.data)
199
+ if let target { openURL(target) }
200
+ }
201
+ }
202
+
203
+ func notifyMessage(_ message: DataTalksMessage) {
204
+ onMain { [self] in listener?.onMessageReceived(message) }
205
+ }
206
+
207
+ private func warnIfATokenIsMissing(_ identity: PendingIdentity) {
208
+ #if DEBUG
209
+ if store.requireVerifiedIdentity, case .identify(_, _, nil) = identity {
210
+ PushLog.warning("This app requires verified identity: identify without an identity token will be refused.")
211
+ }
212
+ #endif
213
+ }
214
+
215
+ /// Something changed: sync now and cancel any scheduled retry. A `Retry-After` still applies (`PushStore.notBefore`).
216
+ private func syncNow() {
217
+ retry?.cancel()
218
+ retry = nil
219
+ retryAt = nil
220
+ runSync()
221
+ }
222
+
223
+ /// Nothing changed: a scheduled retry keeps its time.
224
+ private func syncIfDue() {
225
+ if let retryAt, retryAt > Date() { return }
226
+ if sync.isDue() { syncNow() }
227
+ }
228
+
229
+ private func runSync() {
230
+ let endBackgroundWork = beginBackgroundWork()
231
+ defer { endBackgroundWork() }
232
+
233
+ switch sync.run() {
234
+ case .done:
235
+ store.failedAttempts = 0
236
+ case let .retryAfter(seconds):
237
+ scheduleRetry(after: seconds)
238
+ case .backoff:
239
+ let attempt = store.failedAttempts
240
+ store.failedAttempts = attempt + 1
241
+ scheduleRetry(after: PushSync.backoffSeconds(attempt: attempt))
242
+ }
243
+ }
244
+
245
+ // Retries run only while the app runs. Anything left stays in the store for the next launch: iOS can't run it later unless the
246
+ // app adds a background mode.
247
+ private func scheduleRetry(after seconds: Int) {
248
+ let work = DispatchWorkItem { [self] in
249
+ retry = nil
250
+ retryAt = nil
251
+ runSync()
252
+ }
253
+
254
+ retry = work
255
+ retryAt = Date().addingTimeInterval(TimeInterval(seconds))
256
+ queue.asyncAfter(deadline: .now() + .seconds(seconds), execute: work)
257
+ }
258
+
259
+ /// Syncs when the app becomes active: the permission can only change while the app is in the background, and the daily refresh
260
+ /// waits for the app to be used.
261
+ private func watchTheApp() {
262
+ #if canImport(UIKit)
263
+ queue.async { [self] in
264
+ guard !watchingTheApp else { return }
265
+ watchingTheApp = true
266
+ NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { [self] _ in
267
+ queue.async { [self] in syncIfDue() }
268
+ }
269
+ }
270
+ #endif
271
+ }
272
+
273
+ private func registerWithApns() {
274
+ #if canImport(UIKit)
275
+ onMain { UIApplication.shared.registerForRemoteNotifications() }
276
+ #endif
277
+ }
278
+
279
+ private func locked<T>(_ body: () -> T) -> T {
280
+ lock.lock()
281
+ defer { lock.unlock() }
282
+ return body()
283
+ }
284
+
285
+ private struct HeldOpen {
286
+ let deepLink: String?
287
+ let data: [String: Any]?
288
+ }
289
+
290
+ /// Lets a call in progress finish when the user leaves the app.
291
+ private func beginBackgroundWork() -> () -> Void {
292
+ #if canImport(UIKit)
293
+ let started = DispatchSemaphore(value: 0)
294
+ var task = UIBackgroundTaskIdentifier.invalid
295
+ onMain {
296
+ task = UIApplication.shared.beginBackgroundTask(withName: "DataTalksPush") {
297
+ UIApplication.shared.endBackgroundTask(task)
298
+ task = .invalid
299
+ }
300
+ started.signal()
301
+ }
302
+ started.wait()
303
+
304
+ return {
305
+ onMain {
306
+ if task != .invalid { UIApplication.shared.endBackgroundTask(task) }
307
+ task = .invalid
308
+ }
309
+ }
310
+ #else
311
+ return {}
312
+ #endif
313
+ }
314
+ }
315
+
316
+ private func onMain(_ work: @escaping () -> Void) {
317
+ if Thread.isMainThread {
318
+ work()
319
+ } else {
320
+ DispatchQueue.main.async(execute: work)
321
+ }
322
+ }
323
+
324
+ /// `DataTalksPush.useAsNotificationCenterDelegate`: handles Data Talks notifications and forwards the rest to the previous delegate.
325
+ final class NotificationCenterForwarder: NSObject, UNUserNotificationCenterDelegate {
326
+ private static var installed: NotificationCenterForwarder?
327
+
328
+ private let previous: UNUserNotificationCenterDelegate?
329
+
330
+ private init(previous: UNUserNotificationCenterDelegate?) {
331
+ self.previous = previous
332
+ }
333
+
334
+ static func install() {
335
+ let center = UNUserNotificationCenter.current()
336
+ guard installed == nil else { return }
337
+ let forwarder = NotificationCenterForwarder(previous: center.delegate)
338
+ installed = forwarder
339
+ center.delegate = forwarder
340
+ }
341
+
342
+ func userNotificationCenter(
343
+ _ center: UNUserNotificationCenter,
344
+ willPresent notification: UNNotification,
345
+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
346
+ ) {
347
+ if let options = DataTalksPush.handleWillPresent(notification) {
348
+ completionHandler(options)
349
+ } else if let handler = previous?.userNotificationCenter(_:willPresent:withCompletionHandler:) {
350
+ handler(center, notification, completionHandler)
351
+ } else {
352
+ completionHandler([])
353
+ }
354
+ }
355
+
356
+ func userNotificationCenter(
357
+ _ center: UNUserNotificationCenter,
358
+ didReceive response: UNNotificationResponse,
359
+ withCompletionHandler completionHandler: @escaping () -> Void
360
+ ) {
361
+ if DataTalksPush.handleNotificationResponse(response) {
362
+ completionHandler()
363
+ } else if let handler = previous?.userNotificationCenter(_:didReceive:withCompletionHandler:) {
364
+ handler(center, response, completionHandler)
365
+ } else {
366
+ completionHandler()
367
+ }
368
+ }
369
+ }