@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.
- package/DatatalksAbPushCapacitor.podspec +21 -0
- package/DatatalksPushExtension.podspec +21 -0
- package/Package.swift +35 -0
- package/README.md +212 -2
- package/android/build.gradle +48 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar +0 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.md5 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.sha1 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.sha256 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1-sources.jar.sha512 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar +0 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.md5 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.sha1 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.sha256 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.aar.sha512 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module +144 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.md5 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.sha1 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.sha256 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.module.sha512 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom +63 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.md5 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.sha1 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.sha256 +1 -0
- package/android/maven/se/datatalks/push-android/1.0.0-rc.1/push-android-1.0.0-rc.1.pom.sha512 +1 -0
- package/android/maven/se/datatalks/push-android/maven-metadata.xml +13 -0
- package/android/maven/se/datatalks/push-android/maven-metadata.xml.md5 +1 -0
- package/android/maven/se/datatalks/push-android/maven-metadata.xml.sha1 +1 -0
- package/android/maven/se/datatalks/push-android/maven-metadata.xml.sha256 +1 -0
- package/android/maven/se/datatalks/push-android/maven-metadata.xml.sha512 +1 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/se/datatalks/push/capacitor/DataTalksPushPlugin.java +255 -0
- package/dist/esm/definitions.d.ts +92 -0
- package/dist/esm/definitions.js +3 -0
- package/dist/esm/definitions.js.map +1 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/web.d.ts +12 -0
- package/dist/esm/web.js +26 -0
- package/dist/esm/web.js.map +1 -0
- package/dist/plugin.cjs.js +40 -0
- package/dist/plugin.cjs.js.map +1 -0
- package/dist/plugin.js +43 -0
- package/dist/plugin.js.map +1 -0
- package/ios/Extension/DataTalksNotificationService.swift +120 -0
- package/ios/Extension/DeliveryReporter.swift +50 -0
- package/ios/Extension/ExtensionShared.swift +101 -0
- package/ios/Extension/PrivacyInfo.xcprivacy +27 -0
- package/ios/Extension/PushAttachment.swift +90 -0
- package/ios/Sources/DataTalksPushPlugin/Core/AppKeys.swift +35 -0
- package/ios/Sources/DataTalksPushPlugin/Core/DataTalksPush.swift +110 -0
- package/ios/Sources/DataTalksPushPlugin/Core/DataTalksPushListener.swift +72 -0
- package/ios/Sources/DataTalksPushPlugin/Core/DeviceFacts.swift +128 -0
- package/ios/Sources/DataTalksPushPlugin/Core/PrivacyInfo.xcprivacy +60 -0
- package/ios/Sources/DataTalksPushPlugin/Core/PushApi.swift +64 -0
- package/ios/Sources/DataTalksPushPlugin/Core/PushMessage.swift +47 -0
- package/ios/Sources/DataTalksPushPlugin/Core/PushRuntime.swift +369 -0
- package/ios/Sources/DataTalksPushPlugin/Core/PushStore.swift +465 -0
- package/ios/Sources/DataTalksPushPlugin/Core/PushSync.swift +381 -0
- package/ios/Sources/DataTalksPushPlugin/Core/SharedContainer.swift +104 -0
- package/ios/Sources/DataTalksPushPlugin/DataTalksPushPlugin.swift +197 -0
- package/package.json +55 -4
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
enum SyncOutcome: Equatable {
|
|
4
|
+
case done
|
|
5
|
+
|
|
6
|
+
/// The service asked to wait (429, 503).
|
|
7
|
+
case retryAfter(Int)
|
|
8
|
+
|
|
9
|
+
/// Another 5xx or a network error: exponential backoff, at most an hour.
|
|
10
|
+
case backoff
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/// RFC 3339 timestamps in UTC, the format of the contract's `occurred_at`.
|
|
14
|
+
enum Timestamps {
|
|
15
|
+
private static let format: ISO8601DateFormatter = {
|
|
16
|
+
let format = ISO8601DateFormatter()
|
|
17
|
+
format.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
18
|
+
return format
|
|
19
|
+
}()
|
|
20
|
+
|
|
21
|
+
static func utc(_ secondsSinceEpoch: TimeInterval) -> String {
|
|
22
|
+
format.string(from: Date(timeIntervalSince1970: secondsSinceEpoch))
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Brings the service up to date with the store, in order: the pending delete, the config, the registration, the identity call, the
|
|
27
|
+
/// consent and the push events. Each step reads what is still pending, so a second run is safe and the next run resumes a failed one.
|
|
28
|
+
/// The rules are the contract's (`info.description` in `spec/openapi/push-v1.yaml`). Used on the runtime's queue only.
|
|
29
|
+
final class PushSync {
|
|
30
|
+
private enum Step: Equatable {
|
|
31
|
+
case next
|
|
32
|
+
|
|
33
|
+
/// The install changed: start over with the new one.
|
|
34
|
+
case restart
|
|
35
|
+
|
|
36
|
+
case stop(SyncOutcome)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
private enum Code {
|
|
40
|
+
static let appDisabled = "app_disabled"
|
|
41
|
+
static let keyInvalid = "key_invalid"
|
|
42
|
+
static let keyWrongEnvironment = "key_wrong_environment"
|
|
43
|
+
static let installIdConflict = "install_id_conflict"
|
|
44
|
+
static let deviceAuthFailed = "device_auth_failed"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private static let secondsPerDay: TimeInterval = 86400
|
|
48
|
+
private static let maxRestarts = 3
|
|
49
|
+
private static let defaultRetryAfterSeconds = 60
|
|
50
|
+
private static let defaultConfigSeconds: TimeInterval = 3600
|
|
51
|
+
private static let backoffBaseSeconds = 30
|
|
52
|
+
private static let backoffMaxSeconds = 3600
|
|
53
|
+
private static let maxEventsPerCall = 50
|
|
54
|
+
private static let maxEventCallsPerRun = 4
|
|
55
|
+
|
|
56
|
+
// The device routes accept 8 KB (8192 bytes). Each event is measured as encoded, so 50 opens fit. The envelope is {"events":[]}.
|
|
57
|
+
private static let maxEventsBodyBytes = 8000
|
|
58
|
+
private static let eventsEnvelopeBytes = 13
|
|
59
|
+
|
|
60
|
+
private let store: PushStore
|
|
61
|
+
private let facts: DeviceFacts
|
|
62
|
+
private let session: URLSession
|
|
63
|
+
private let onIdentityResult: (DataTalksIdentityResult) -> Void
|
|
64
|
+
private let clock: () -> TimeInterval
|
|
65
|
+
|
|
66
|
+
/// Set until the next app start when the app is disabled or the key refused: the same call would get the same answer.
|
|
67
|
+
var stopped = false
|
|
68
|
+
|
|
69
|
+
// Warned once per launch that the app sends through Firebase but hasn't passed its FCM token.
|
|
70
|
+
private var warnedNoFcmToken = false
|
|
71
|
+
|
|
72
|
+
init(
|
|
73
|
+
store: PushStore,
|
|
74
|
+
facts: DeviceFacts,
|
|
75
|
+
session: URLSession,
|
|
76
|
+
onIdentityResult: @escaping (DataTalksIdentityResult) -> Void,
|
|
77
|
+
clock: @escaping () -> TimeInterval = { Date().timeIntervalSince1970 }
|
|
78
|
+
) {
|
|
79
|
+
self.store = store
|
|
80
|
+
self.facts = facts
|
|
81
|
+
self.session = session
|
|
82
|
+
self.onIdentityResult = onIdentityResult
|
|
83
|
+
self.clock = clock
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// The delay after `attempt` failed tries, with jitter so that devices don't all retry at once after an outage.
|
|
87
|
+
static func backoffSeconds(attempt: Int, spread: Double = Double.random(in: 0 ... 1)) -> Int {
|
|
88
|
+
let full = min(backoffBaseSeconds << min(max(attempt, 0), 10), backoffMaxSeconds)
|
|
89
|
+
return Int(Double(full) * (0.8 + 0.2 * spread))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
func isDue() -> Bool {
|
|
93
|
+
if stopped { return false }
|
|
94
|
+
store.mergeInbox()
|
|
95
|
+
if store.pendingDelete != nil { return true }
|
|
96
|
+
if store.appKey == nil { return false }
|
|
97
|
+
return store.pendingIdentity != nil
|
|
98
|
+
|| store.pendingOptIn != nil
|
|
99
|
+
|| (store.installId != nil && store.deviceSecret != nil && store.hasEvents)
|
|
100
|
+
|| registrationIsDue(permission: facts.permission())
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
func run() -> SyncOutcome {
|
|
104
|
+
do {
|
|
105
|
+
return try runSteps()
|
|
106
|
+
} catch {
|
|
107
|
+
PushLog.warning("The service can't be reached: \(type(of: error))")
|
|
108
|
+
return .backoff
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private func runSteps() throws -> SyncOutcome {
|
|
113
|
+
if stopped { return .done }
|
|
114
|
+
store.mergeInbox()
|
|
115
|
+
|
|
116
|
+
let wait = store.notBefore - clock()
|
|
117
|
+
if wait > 0 { return .retryAfter(Int(wait) + 1) }
|
|
118
|
+
|
|
119
|
+
if case let .stop(outcome) = try sendPendingDelete() { return outcome }
|
|
120
|
+
|
|
121
|
+
guard let key = store.appKey, let baseUrl = store.baseUrl ?? AppKeys.baseUrl(key) else { return .done }
|
|
122
|
+
let api = PushApi(baseUrl: baseUrl, appKey: key, session: session)
|
|
123
|
+
|
|
124
|
+
if case let .stop(outcome) = try readConfig(api) { return outcome }
|
|
125
|
+
|
|
126
|
+
for _ in 0 ..< Self.maxRestarts {
|
|
127
|
+
var step = try register(api)
|
|
128
|
+
if step == .next { step = try sendIdentity(api) }
|
|
129
|
+
if step == .next { step = try sendConsent(api) }
|
|
130
|
+
if step == .next { step = try sendEvents(api) }
|
|
131
|
+
switch step {
|
|
132
|
+
case .next: return .done
|
|
133
|
+
case .restart: continue
|
|
134
|
+
case let .stop(outcome): return outcome
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return .backoff
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private func sendPendingDelete() throws -> Step {
|
|
142
|
+
guard let pending = store.pendingDelete else { return .next }
|
|
143
|
+
guard let baseUrl = pending.baseUrl ?? AppKeys.baseUrl(pending.appKey) else { return .next }
|
|
144
|
+
|
|
145
|
+
let api = PushApi(baseUrl: baseUrl, appKey: pending.appKey, session: session)
|
|
146
|
+
let response = try api.call("DELETE", "/devices/\(pending.installId)", deviceSecret: pending.deviceSecret)
|
|
147
|
+
if !response.isSuccess, let stop = stopFor(response) { return stop }
|
|
148
|
+
store.pendingDelete = nil
|
|
149
|
+
return .next
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private func readConfig(_ api: PushApi) throws -> Step {
|
|
153
|
+
if clock() < store.configExpiresAt { return .next }
|
|
154
|
+
|
|
155
|
+
let response = try api.call("GET", "/config")
|
|
156
|
+
guard response.isSuccess else {
|
|
157
|
+
if let stop = stopFor(response) { return stop }
|
|
158
|
+
PushLog.warning("The app's settings were refused: \(response.code ?? "no code")")
|
|
159
|
+
return .next
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
guard let config = response.json else { return .stop(.backoff) }
|
|
163
|
+
store.requireVerifiedIdentity = config["require_verified_identity"] as? Bool ?? false
|
|
164
|
+
store.configExpiresAt = clock() + ((config["refresh_after_seconds"] as? TimeInterval) ?? Self.defaultConfigSeconds)
|
|
165
|
+
|
|
166
|
+
let ios = (config["platforms"] as? [String: Any])?["ios"] as? [String: Any]
|
|
167
|
+
guard let transport = ios?["transport"] as? String, transport == Transport.apns || transport == Transport.fcm else {
|
|
168
|
+
PushLog.warning("The app isn't set up for iOS in the portal.")
|
|
169
|
+
stopped = true
|
|
170
|
+
return .stop(.done)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
store.iosTransport = transport
|
|
174
|
+
return .next
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private func register(_ api: PushApi) throws -> Step {
|
|
178
|
+
let permission = facts.permission()
|
|
179
|
+
if !registrationIsDue(permission: permission) { return .next }
|
|
180
|
+
|
|
181
|
+
// Nothing to register until there's a token for the transport, whose arrival starts a new sync. The later steps wait too.
|
|
182
|
+
let throughFcm = store.iosTransport == Transport.fcm
|
|
183
|
+
guard let token = store.registrationToken else {
|
|
184
|
+
if throughFcm, !warnedNoFcmToken {
|
|
185
|
+
warnedNoFcmToken = true
|
|
186
|
+
PushLog.warning("The app sends through Firebase: pass its FCM registration token to DataTalksPush.setFcmToken.")
|
|
187
|
+
}
|
|
188
|
+
return .stop(.done)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let installId = store.installId ?? UUID().uuidString.lowercased()
|
|
192
|
+
store.installId = installId
|
|
193
|
+
|
|
194
|
+
var body: [String: Any] = facts.metadata()
|
|
195
|
+
body["install_id"] = installId
|
|
196
|
+
body["platform"] = "ios"
|
|
197
|
+
body["environment"] = facts.environment
|
|
198
|
+
if throughFcm {
|
|
199
|
+
body["fcm_token"] = token
|
|
200
|
+
body["fcm_token_type"] = "fcm_token"
|
|
201
|
+
} else {
|
|
202
|
+
body["apns_token"] = token
|
|
203
|
+
}
|
|
204
|
+
body["os_permission"] = permission
|
|
205
|
+
|
|
206
|
+
let response = try api.call("POST", "/devices", deviceSecret: store.deviceSecret, body: body)
|
|
207
|
+
if response.isSuccess {
|
|
208
|
+
if let secret = response.json?["device_secret"] as? String, !secret.isEmpty {
|
|
209
|
+
store.deviceSecret = secret
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
store.markRegistered(day: today(), permission: permission)
|
|
213
|
+
return .next
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if let stop = stopFor(response) { return stop }
|
|
217
|
+
if response.code == Code.installIdConflict || response.code == Code.deviceAuthFailed {
|
|
218
|
+
store.dropInstall()
|
|
219
|
+
return .restart
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Never retried unchanged: a new token, a permission change or the next daily refresh sends it again.
|
|
223
|
+
PushLog.warning("The registration was refused: \(response.code ?? "no code")")
|
|
224
|
+
store.markRegistered(day: today(), permission: permission)
|
|
225
|
+
return .next
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private func sendIdentity(_ api: PushApi) throws -> Step {
|
|
229
|
+
guard let pending = store.pendingIdentity, let installId = store.installId, let secret = store.deviceSecret else { return .next }
|
|
230
|
+
|
|
231
|
+
let response: ApiResponse
|
|
232
|
+
// The identity's fingerprint, for an identify; nil for a logout.
|
|
233
|
+
var fingerprint: String?
|
|
234
|
+
switch pending {
|
|
235
|
+
case .logout:
|
|
236
|
+
response = try api.call("POST", "/devices/\(installId)/logout", deviceSecret: secret)
|
|
237
|
+
case let .identify(externalId, email, identityToken):
|
|
238
|
+
fingerprint = PushStore.identityFingerprint(installId: installId, externalId: externalId, email: email, hasToken: identityToken != nil)
|
|
239
|
+
let body = ["external_id": externalId, "email": email, "identity_token": identityToken].compactMapValues { $0 }
|
|
240
|
+
response = try api.call("POST", "/devices/\(installId)/identify", deviceSecret: secret, body: body)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if !response.isSuccess, let stop = stopFor(response) { return stop }
|
|
244
|
+
|
|
245
|
+
// A 2xx without `identity_verified` (a captive portal page, for example) doesn't prove the identity arrived.
|
|
246
|
+
let verified = response.json?["identity_verified"] as? Bool
|
|
247
|
+
|
|
248
|
+
// Record what the service now holds: the accepted identity, or none after a logout or a refusal, so the next identify is sent.
|
|
249
|
+
if response.isSuccess, let fingerprint, let verified {
|
|
250
|
+
store.acceptedIdentity = AcceptedIdentity(fingerprint: fingerprint, day: today(), verified: verified)
|
|
251
|
+
} else {
|
|
252
|
+
store.acceptedIdentity = nil
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Finished or refused: never replay an identify after a 401 (spec). App calls wait on this queue, so the pending call is still
|
|
256
|
+
// the one sent; the check mirrors Android, where a new call can arrive in between.
|
|
257
|
+
if store.pendingIdentity == pending { store.pendingIdentity = nil }
|
|
258
|
+
|
|
259
|
+
if fingerprint != nil {
|
|
260
|
+
onIdentityResult(
|
|
261
|
+
response.isSuccess
|
|
262
|
+
? DataTalksIdentityResult(verified: verified ?? false)
|
|
263
|
+
: DataTalksIdentityResult(verified: false, errorCode: response.code, errorDetail: response.detail)
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if response.code == Code.deviceAuthFailed {
|
|
268
|
+
store.dropInstall()
|
|
269
|
+
return .restart
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return .next
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private func sendConsent(_ api: PushApi) throws -> Step {
|
|
276
|
+
guard let optIn = store.pendingOptIn, let installId = store.installId, let secret = store.deviceSecret else { return .next }
|
|
277
|
+
|
|
278
|
+
let response = try api.call("PUT", "/devices/\(installId)/consent", deviceSecret: secret, body: ["marketing_opt_in": optIn])
|
|
279
|
+
if !response.isSuccess, let stop = stopFor(response) { return stop }
|
|
280
|
+
|
|
281
|
+
if response.code == Code.deviceAuthFailed {
|
|
282
|
+
// Keep the choice for the new install.
|
|
283
|
+
store.dropInstall()
|
|
284
|
+
return .restart
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
store.pendingOptIn = nil
|
|
288
|
+
return .next
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/// Sends the queued events oldest first, at most `maxEventsPerCall` per call and within the device routes' body limit. Any result
|
|
292
|
+
/// for an event (accepted, duplicate or skipped) removes it; a 429, a 5xx, a network error, a 404 or a 2xx without `results` keeps
|
|
293
|
+
/// them all for the next run.
|
|
294
|
+
private func sendEvents(_ api: PushApi) throws -> Step {
|
|
295
|
+
guard let installId = store.installId, let secret = store.deviceSecret else { return .next }
|
|
296
|
+
|
|
297
|
+
for _ in 0 ..< Self.maxEventCallsPerRun {
|
|
298
|
+
let batch = eventBatch(store.pendingEvents(now: clock()))
|
|
299
|
+
if batch.isEmpty { return .next }
|
|
300
|
+
|
|
301
|
+
let response = try api.call("POST", "/devices/\(installId)/events", deviceSecret: secret, body: ["events": batch.map(Self.eventJson)])
|
|
302
|
+
if response.isSuccess && !(response.json?["results"] is [Any]) {
|
|
303
|
+
// Not a service response (a captive portal page, for example): nothing proves the events arrived.
|
|
304
|
+
PushLog.warning("The events answer has no results.")
|
|
305
|
+
return .stop(.backoff)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if !response.isSuccess {
|
|
309
|
+
if let stop = stopFor(response) { return stop }
|
|
310
|
+
if response.code == Code.deviceAuthFailed {
|
|
311
|
+
// The events belong to the old install: the service matches them to pushes sent to it.
|
|
312
|
+
store.dropInstall()
|
|
313
|
+
return .restart
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if response.status == 404 {
|
|
317
|
+
// The route is missing (an unknown install gets a 401, not a 404): the ingress predates contract 1.1.0.
|
|
318
|
+
// Keep the events until it accepts them.
|
|
319
|
+
PushLog.warning("The service doesn't take events yet.")
|
|
320
|
+
return .stop(.backoff)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Any other refusal would repeat: the contract forbids resending an unchanged request after a 4xx.
|
|
324
|
+
PushLog.warning("Events were refused: \(response.code ?? String(response.status))")
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
store.removeEvents(Set(batch.map(\.eventId)))
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// More events than one run sends: the rest go with the next run, within the install's rate limit.
|
|
331
|
+
return .next
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private func eventBatch(_ events: [PushEvent]) -> [PushEvent] {
|
|
335
|
+
var batch: [PushEvent] = []
|
|
336
|
+
var bytes = Self.eventsEnvelopeBytes
|
|
337
|
+
for event in events {
|
|
338
|
+
// Measured as encoded, plus the separating comma.
|
|
339
|
+
let size = ((try? JSONSerialization.data(withJSONObject: Self.eventJson(event)))?.count ?? 0) + 1
|
|
340
|
+
if batch.count == Self.maxEventsPerCall || (!batch.isEmpty && bytes + size > Self.maxEventsBodyBytes) { break }
|
|
341
|
+
batch.append(event)
|
|
342
|
+
bytes += size
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return batch
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private static func eventJson(_ event: PushEvent) -> [String: Any] {
|
|
349
|
+
var json: [String: Any] = ["event_id": event.eventId, "type": event.type, "uid": event.uid, "occurred_at": Timestamps.utc(event.occurredAt)]
|
|
350
|
+
json["link"] = event.link
|
|
351
|
+
return json
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
private func registrationIsDue(permission: String) -> Bool {
|
|
355
|
+
store.tokenChanged || store.installId == nil || store.registeredOn != today() || store.reportedPermission != permission
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/// The responses that end this run; nil for those the step handles itself.
|
|
359
|
+
private func stopFor(_ response: ApiResponse) -> Step? {
|
|
360
|
+
if response.status == 429 || response.status == 503 {
|
|
361
|
+
let seconds = response.retryAfterSeconds ?? Self.defaultRetryAfterSeconds
|
|
362
|
+
store.notBefore = clock() + TimeInterval(seconds)
|
|
363
|
+
return .stop(.retryAfter(seconds))
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if response.status >= 500 { return .stop(.backoff) }
|
|
367
|
+
|
|
368
|
+
if [Code.appDisabled, Code.keyInvalid, Code.keyWrongEnvironment].contains(response.code) {
|
|
369
|
+
PushLog.warning("The service stopped this app: \(response.code ?? "no code")")
|
|
370
|
+
stopped = true
|
|
371
|
+
return .stop(.done)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
return nil
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/// Days since the epoch, in UTC: the unit of the daily refresh and of `AcceptedIdentity.day`.
|
|
378
|
+
func today() -> Int {
|
|
379
|
+
Int(clock() / Self.secondsPerDay)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The App Group folder the app shares with its notification service extension (`DataTalksPushExtension`), when its Info.plist names
|
|
4
|
+
/// one (`DataTalksAppGroup`). The app writes what the extension needs to report a delivery (`state.json`); the extension leaves each
|
|
5
|
+
/// delivery in `inbox/` until its own call succeeds, and the app sends the rest. The app's own store stays out of it, and the folder is
|
|
6
|
+
/// excluded from backups: another device is another install.
|
|
7
|
+
///
|
|
8
|
+
/// The extension reads and writes the same files with its own code (`ExtensionShared`). Change both together, along with the tests
|
|
9
|
+
/// that read each side's files with the other side's code.
|
|
10
|
+
final class SharedContainer {
|
|
11
|
+
static let appGroupInfoKey = "DataTalksAppGroup"
|
|
12
|
+
static let folderName = "DataTalksPush"
|
|
13
|
+
static let stateFileName = "state.json"
|
|
14
|
+
static let inboxFolderName = "inbox"
|
|
15
|
+
|
|
16
|
+
private let directory: URL
|
|
17
|
+
private let fileManager: FileManager
|
|
18
|
+
|
|
19
|
+
init(directory: URL, fileManager: FileManager = .default) {
|
|
20
|
+
self.directory = directory
|
|
21
|
+
self.fileManager = fileManager
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// The app's group container, or nil when the app names no group or isn't entitled to the one it names.
|
|
25
|
+
static func forApp(bundle: Bundle = .main) -> SharedContainer? {
|
|
26
|
+
guard let group = bundle.object(forInfoDictionaryKey: appGroupInfoKey) as? String, !group.isEmpty else { return nil }
|
|
27
|
+
guard let root = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) else {
|
|
28
|
+
PushLog.warning("The App Group \(group) isn't one of the app's: the extension can't report deliveries.")
|
|
29
|
+
return nil
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return SharedContainer(directory: root.appendingPathComponent(folderName, isDirectory: true))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
private var stateFile: URL { directory.appendingPathComponent(Self.stateFileName) }
|
|
36
|
+
|
|
37
|
+
private var inbox: URL { directory.appendingPathComponent(Self.inboxFolderName, isDirectory: true) }
|
|
38
|
+
|
|
39
|
+
/// Writes what the extension needs to send a delivery. If a value is missing or the write fails (also when the folder can't be
|
|
40
|
+
/// excluded from backups), the file is removed and deliveries wait for the app. Readable after the first unlock following a restart,
|
|
41
|
+
/// like the Keychain items.
|
|
42
|
+
func writeState(appKey: String?, baseUrl: String?, installId: String?, deviceSecret: String?) {
|
|
43
|
+
guard let appKey, let baseUrl, let installId, let deviceSecret else {
|
|
44
|
+
try? fileManager.removeItem(at: stateFile)
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let state = ["app_key": appKey, "base_url": baseUrl, "install_id": installId, "device_secret": deviceSecret]
|
|
49
|
+
do {
|
|
50
|
+
try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
51
|
+
try excludeFromBackup()
|
|
52
|
+
let data = try JSONSerialization.data(withJSONObject: state, options: [.sortedKeys])
|
|
53
|
+
try data.write(to: stateFile, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
|
|
54
|
+
} catch {
|
|
55
|
+
try? fileManager.removeItem(at: stateFile)
|
|
56
|
+
PushLog.warning("The state for the notification service extension can't be written: \(type(of: error))")
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// Returns and removes the deliveries the extension left; the app's queue owns them from here on. Unreadable files are removed too.
|
|
61
|
+
func takeInbox() -> [InboxDelivery] {
|
|
62
|
+
guard let files = try? fileManager.contentsOfDirectory(at: inbox, includingPropertiesForKeys: nil) else { return [] }
|
|
63
|
+
|
|
64
|
+
var deliveries: [InboxDelivery] = []
|
|
65
|
+
for file in files where file.pathExtension == "json" {
|
|
66
|
+
if let data = try? Data(contentsOf: file), let delivery = Self.parse(data) {
|
|
67
|
+
deliveries.append(delivery)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try? fileManager.removeItem(at: file)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return deliveries
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// The install is gone: drop what the extension left for it.
|
|
77
|
+
func clearInbox() {
|
|
78
|
+
try? fileManager.removeItem(at: inbox)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The folder rather than each file, so the extension's inbox is covered too.
|
|
82
|
+
private func excludeFromBackup() throws {
|
|
83
|
+
var folder = directory
|
|
84
|
+
var values = URLResourceValues()
|
|
85
|
+
values.isExcludedFromBackup = true
|
|
86
|
+
try folder.setResourceValues(values)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private static func parse(_ data: Data) -> InboxDelivery? {
|
|
90
|
+
guard let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
|
91
|
+
let id = json["event_id"] as? String, let type = json["type"] as? String, let uid = json["uid"] as? String,
|
|
92
|
+
let occurredAt = json["occurred_at"] as? TimeInterval
|
|
93
|
+
else { return nil }
|
|
94
|
+
|
|
95
|
+
let event = PushEvent(eventId: id, type: type, uid: uid, occurredAt: occurredAt, link: json["link"] as? String)
|
|
96
|
+
return InboxDelivery(event: event, installId: json["install_id"] as? String)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// A delivery the extension left, with the install id the push went to if the app had one at the time.
|
|
101
|
+
struct InboxDelivery: Equatable {
|
|
102
|
+
let event: PushEvent
|
|
103
|
+
let installId: String?
|
|
104
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import Capacitor
|
|
2
|
+
import Foundation
|
|
3
|
+
import UserNotifications
|
|
4
|
+
|
|
5
|
+
/// Capacitor bridge to the Data Talks iOS SDK, whose sources this target compiles (`Core/`, copied in by
|
|
6
|
+
/// `scripts/vendor-native.mjs`). It has no logic of its own: each call forwards to `DataTalksPush`, and the SDK's listener
|
|
7
|
+
/// callbacks become plugin events.
|
|
8
|
+
@objc(DataTalksPushPlugin)
|
|
9
|
+
public class DataTalksPushPlugin: CAPPlugin, CAPBridgedPlugin {
|
|
10
|
+
public let identifier = "DataTalksPushPlugin"
|
|
11
|
+
public let jsName = "DataTalksPush"
|
|
12
|
+
public let pluginMethods: [CAPPluginMethod] = [
|
|
13
|
+
CAPPluginMethod(name: "checkPermissions", returnType: CAPPluginReturnPromise),
|
|
14
|
+
CAPPluginMethod(name: "requestPermissions", returnType: CAPPluginReturnPromise),
|
|
15
|
+
CAPPluginMethod(name: "identify", returnType: CAPPluginReturnPromise),
|
|
16
|
+
CAPPluginMethod(name: "logout", returnType: CAPPluginReturnPromise),
|
|
17
|
+
CAPPluginMethod(name: "setFcmToken", returnType: CAPPluginReturnPromise),
|
|
18
|
+
CAPPluginMethod(name: "setMarketingOptIn", returnType: CAPPluginReturnPromise),
|
|
19
|
+
CAPPluginMethod(name: "deleteLocalData", returnType: CAPPluginReturnPromise),
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
// The router holds its handler weakly.
|
|
23
|
+
private let notificationHandler = NotificationHandler()
|
|
24
|
+
private let events = PluginEvents()
|
|
25
|
+
|
|
26
|
+
override public func load() {
|
|
27
|
+
// Capacitor's router owns the notification center's delegate and forwards notifications to a single push handler, so
|
|
28
|
+
// this plugin replaces any other push plugin.
|
|
29
|
+
if let other = bridge?.notificationRouter.pushNotificationHandler {
|
|
30
|
+
Self.warn("another plugin was the push handler (\(type(of: other))) and is replaced, so it gets no notifications. Remove it, such as @capacitor/push-notifications.")
|
|
31
|
+
}
|
|
32
|
+
bridge?.notificationRouter.pushNotificationHandler = notificationHandler
|
|
33
|
+
// Check once every plugin has loaded: a later plugin can take the handler back, and another SDK the center's delegate.
|
|
34
|
+
DispatchQueue.main.async { [weak self] in self?.warnAboutOtherPushPlugins() }
|
|
35
|
+
|
|
36
|
+
// Posted by the app delegate, with the two lines every Capacitor push plugin requires.
|
|
37
|
+
NotificationCenter.default.addObserver(self, selector: #selector(didRegister(_:)), name: .capacitorDidRegisterForRemoteNotifications, object: nil)
|
|
38
|
+
NotificationCenter.default.addObserver(self, selector: #selector(didFailToRegister(_:)), name: .capacitorDidFailToRegisterForRemoteNotifications, object: nil)
|
|
39
|
+
|
|
40
|
+
// Listener first: a tap the SDK is holding is delivered now and retained in the plugin until the web app listens.
|
|
41
|
+
events.plugin = self
|
|
42
|
+
DataTalksPush.listener = events
|
|
43
|
+
|
|
44
|
+
guard let appKey = getConfig().getString("appKey"), !appKey.isEmpty else {
|
|
45
|
+
Self.warn("capacitor.config has no plugins.DataTalksPush.appKey: the SDK stays off.")
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let options = DataTalksPushOptions(baseUrl: getConfig().getString("baseUrl"), openLinks: getConfig().getBoolean("openLinks", true))
|
|
50
|
+
DataTalksPush.initialize(appKey: appKey, options: options)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
deinit {
|
|
54
|
+
NotificationCenter.default.removeObserver(self)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private func warnAboutOtherPushPlugins() {
|
|
58
|
+
guard let router = bridge?.notificationRouter else { return }
|
|
59
|
+
|
|
60
|
+
if let handler = router.pushNotificationHandler, (handler as AnyObject) !== notificationHandler {
|
|
61
|
+
Self.warn("another plugin is the push handler (\(type(of: handler))), so taps on pushes from Data Talks don't reach the SDK. Remove it, such as @capacitor/push-notifications.")
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let delegate = UNUserNotificationCenter.current().delegate
|
|
65
|
+
if (delegate as AnyObject?) !== router {
|
|
66
|
+
let owner = delegate.map { "\(type(of: $0))" } ?? "none"
|
|
67
|
+
Self.warn("the notification center's delegate isn't Capacitor's (\(owner)), so taps and pushes in the foreground don't reach the SDK. Remove the SDK that took it, and keep ios.handleApplicationNotifications on.")
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private static func warn(_ message: String) {
|
|
72
|
+
CAPLog.print("⚡️ DataTalksPush: \(message)")
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
@objc private func didRegister(_ notification: Notification) {
|
|
76
|
+
// Data is the APNs token. A String is the FCM token, posted by an AppDelegate set up for Firebase.
|
|
77
|
+
if let token = notification.object as? Data {
|
|
78
|
+
DataTalksPush.didRegisterForRemoteNotifications(deviceToken: token)
|
|
79
|
+
} else if let token = notification.object as? String {
|
|
80
|
+
DataTalksPush.setFcmToken(token)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
@objc private func didFailToRegister(_ notification: Notification) {
|
|
85
|
+
guard let error = notification.object as? Error else { return }
|
|
86
|
+
DataTalksPush.didFailToRegisterForRemoteNotifications(error: error)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
@objc override public func checkPermissions(_ call: CAPPluginCall) {
|
|
90
|
+
DataTalksPush.permissionStatus { call.resolve(Self.permissionResult($0)) }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
@objc override public func requestPermissions(_ call: CAPPluginCall) {
|
|
94
|
+
DataTalksPush.requestPermission(provisional: call.getBool("provisional") ?? false) { call.resolve(Self.permissionResult($0)) }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
@objc func identify(_ call: CAPPluginCall) {
|
|
98
|
+
let externalId = call.getString("externalId")
|
|
99
|
+
let email = call.getString("email")
|
|
100
|
+
let identityToken = call.getString("identityToken")
|
|
101
|
+
guard [externalId, email, identityToken].contains(where: { !($0 ?? "").isEmpty }) else {
|
|
102
|
+
call.reject("identify needs an externalId, an email or an identityToken.")
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
DataTalksPush.identify(externalId: externalId, email: email, identityToken: identityToken)
|
|
107
|
+
call.resolve()
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
@objc func logout(_ call: CAPPluginCall) {
|
|
111
|
+
DataTalksPush.logout()
|
|
112
|
+
call.resolve()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
@objc func setFcmToken(_ call: CAPPluginCall) {
|
|
116
|
+
guard let token = call.getString("token"), !token.isEmpty else {
|
|
117
|
+
call.reject("setFcmToken needs a token.")
|
|
118
|
+
return
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
DataTalksPush.setFcmToken(token)
|
|
122
|
+
call.resolve()
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@objc func setMarketingOptIn(_ call: CAPPluginCall) {
|
|
126
|
+
guard let optIn = call.getBool("optIn") else {
|
|
127
|
+
call.reject("setMarketingOptIn needs optIn.")
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
DataTalksPush.setMarketingOptIn(optIn)
|
|
132
|
+
call.resolve()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
@objc func deleteLocalData(_ call: CAPPluginCall) {
|
|
136
|
+
DataTalksPush.deleteLocalData()
|
|
137
|
+
call.resolve()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// Capacitor's states, as `@capacitor/push-notifications` reports them: provisional and App Clip (ephemeral) count as granted.
|
|
141
|
+
private static func permissionResult(_ permission: DataTalksPermission) -> [String: Any] {
|
|
142
|
+
let state: String
|
|
143
|
+
switch permission {
|
|
144
|
+
case .authorized, .provisional, .ephemeral:
|
|
145
|
+
state = "granted"
|
|
146
|
+
case .denied:
|
|
147
|
+
state = "denied"
|
|
148
|
+
case .notDetermined:
|
|
149
|
+
state = "prompt"
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return ["receive": state]
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// Receives notifications from Capacitor's router. A push from another sender gets no banner while the app is open, and its
|
|
157
|
+
/// tap goes nowhere: this plugin replaces any other push plugin.
|
|
158
|
+
private final class NotificationHandler: NSObject, NotificationHandlerProtocol {
|
|
159
|
+
func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions {
|
|
160
|
+
DataTalksPush.handleWillPresent(notification) ?? []
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
func didReceive(response: UNNotificationResponse) {
|
|
164
|
+
DataTalksPush.handleNotificationResponse(response)
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/// Turns the SDK's listener callbacks into plugin events. A separate object because the SDK holds its listener strongly.
|
|
169
|
+
private final class PluginEvents: DataTalksPushListener {
|
|
170
|
+
weak var plugin: CAPPlugin?
|
|
171
|
+
|
|
172
|
+
func onNotificationOpened(deepLink: String?, data: [String: Any]?) {
|
|
173
|
+
var event: [String: Any] = [:]
|
|
174
|
+
if let deepLink { event["deepLink"] = deepLink }
|
|
175
|
+
if let data { event["data"] = data }
|
|
176
|
+
// Retained until the web app listens: a tap that launches the app arrives before its JavaScript runs.
|
|
177
|
+
plugin?.notifyListeners("notificationOpened", data: event, retainUntilConsumed: true)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
func onMessageReceived(_ message: DataTalksMessage) {
|
|
181
|
+
var event: [String: Any] = [:]
|
|
182
|
+
if let uid = message.uid { event["uid"] = uid }
|
|
183
|
+
if let title = message.title { event["title"] = title }
|
|
184
|
+
if let body = message.body { event["body"] = body }
|
|
185
|
+
if let imageUrl = message.imageUrl { event["imageUrl"] = imageUrl }
|
|
186
|
+
if let deepLink = message.deepLink { event["deepLink"] = deepLink }
|
|
187
|
+
if let data = message.data { event["data"] = data }
|
|
188
|
+
plugin?.notifyListeners("messageReceived", data: event)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
func onIdentityResult(_ result: DataTalksIdentityResult) {
|
|
192
|
+
var event: [String: Any] = ["verified": result.verified]
|
|
193
|
+
if let errorCode = result.errorCode { event["errorCode"] = errorCode }
|
|
194
|
+
if let errorDetail = result.errorDetail { event["errorDetail"] = errorDetail }
|
|
195
|
+
plugin?.notifyListeners("identityResult", data: event)
|
|
196
|
+
}
|
|
197
|
+
}
|