@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,465 @@
|
|
|
1
|
+
import CryptoKit
|
|
2
|
+
import Foundation
|
|
3
|
+
import Security
|
|
4
|
+
|
|
5
|
+
protocol SecureValues {
|
|
6
|
+
func read(_ name: String) -> String?
|
|
7
|
+
|
|
8
|
+
/// False when the value couldn't be stored.
|
|
9
|
+
func write(_ name: String, _ value: String?) -> Bool
|
|
10
|
+
|
|
11
|
+
func removeAll()
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/// Device-only Keychain items: a backup restored to another device doesn't include them, so that device registers as a new install.
|
|
15
|
+
final class KeychainValues: SecureValues {
|
|
16
|
+
private let service = "se.datatalks.push"
|
|
17
|
+
|
|
18
|
+
func read(_ name: String) -> String? {
|
|
19
|
+
var query = item(name)
|
|
20
|
+
query[kSecReturnData as String] = true
|
|
21
|
+
query[kSecMatchLimit as String] = kSecMatchLimitOne
|
|
22
|
+
|
|
23
|
+
var result: CFTypeRef?
|
|
24
|
+
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
|
|
25
|
+
return String(data: data, encoding: .utf8)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
func write(_ name: String, _ value: String?) -> Bool {
|
|
29
|
+
SecItemDelete(item(name) as CFDictionary)
|
|
30
|
+
guard let value else { return true }
|
|
31
|
+
|
|
32
|
+
var attributes = item(name)
|
|
33
|
+
attributes[kSecValueData as String] = Data(value.utf8)
|
|
34
|
+
attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
|
35
|
+
return SecItemAdd(attributes as CFDictionary, nil) == errSecSuccess
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
func removeAll() {
|
|
39
|
+
SecItemDelete([kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service] as CFDictionary)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private func item(_ name: String) -> [String: Any] {
|
|
43
|
+
[kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: name]
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// The identity call waiting to be sent. A later identify or logout replaces it.
|
|
48
|
+
enum PendingIdentity: Equatable {
|
|
49
|
+
case logout
|
|
50
|
+
case identify(externalId: String?, email: String?, identityToken: String?)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// The last identity the service accepted for this install: a fingerprint (no id or email in the clear), the day (in days since the
|
|
54
|
+
/// epoch) and whether it was verified. A repeat identify on the same day is skipped and gets this result.
|
|
55
|
+
struct AcceptedIdentity: Equatable {
|
|
56
|
+
let fingerprint: String
|
|
57
|
+
let day: Int
|
|
58
|
+
let verified: Bool
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// What deleting an install needs after the store is wiped.
|
|
62
|
+
struct PendingDelete: Equatable {
|
|
63
|
+
let appKey: String
|
|
64
|
+
let baseUrl: String?
|
|
65
|
+
let installId: String
|
|
66
|
+
let deviceSecret: String
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// A push event waiting for `POST /devices/{install_id}/events` (contract 1.1.0). `eventId` is generated once, so a retry after a lost
|
|
70
|
+
/// response sends the same events. `occurredAt` is in seconds since the epoch.
|
|
71
|
+
struct PushEvent: Equatable {
|
|
72
|
+
static let delivery = "delivery"
|
|
73
|
+
static let open = "open"
|
|
74
|
+
static let click = "click"
|
|
75
|
+
|
|
76
|
+
let eventId: String
|
|
77
|
+
let type: String
|
|
78
|
+
let uid: String
|
|
79
|
+
let occurredAt: TimeInterval
|
|
80
|
+
let link: String?
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
enum Transport {
|
|
84
|
+
static let apns = "apns"
|
|
85
|
+
static let fcm = "fcm"
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// What the SDK keeps on the device: the key, install id, secret, token and identity values in the Keychain, the rest in user
|
|
89
|
+
/// defaults. Used on the runtime's queue only.
|
|
90
|
+
final class PushStore {
|
|
91
|
+
private enum Key {
|
|
92
|
+
static let appKey = "app_key"
|
|
93
|
+
static let installId = "install_id"
|
|
94
|
+
static let deviceSecret = "device_secret"
|
|
95
|
+
static let apnsToken = "apns_token"
|
|
96
|
+
static let fcmToken = "fcm_token"
|
|
97
|
+
static let pendingIdentity = "pending_identity"
|
|
98
|
+
static let acceptedIdentity = "accepted_identity"
|
|
99
|
+
static let pendingDelete = "pending_delete"
|
|
100
|
+
|
|
101
|
+
static let installed = "installed"
|
|
102
|
+
static let baseUrl = "base_url"
|
|
103
|
+
static let iosTransport = "ios_transport"
|
|
104
|
+
static let tokenChanged = "token_changed"
|
|
105
|
+
static let registeredOn = "registered_on"
|
|
106
|
+
static let reportedPermission = "reported_permission"
|
|
107
|
+
static let pendingOptIn = "pending_opt_in"
|
|
108
|
+
static let notBefore = "not_before"
|
|
109
|
+
static let failedAttempts = "failed_attempts"
|
|
110
|
+
static let configExpiresAt = "config_expires_at"
|
|
111
|
+
static let requireVerifiedIdentity = "require_verified_identity"
|
|
112
|
+
static let events = "events"
|
|
113
|
+
|
|
114
|
+
// Legacy format from before contract 1.1.0: opens only, as {uid, opened_at} in seconds.
|
|
115
|
+
static let legacyOpenEvents = "open_events"
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private static let maxEvents = 200
|
|
119
|
+
private static let maxEventAge: TimeInterval = 30 * 86400
|
|
120
|
+
|
|
121
|
+
private let values: SecureValues
|
|
122
|
+
private let defaults: UserDefaults
|
|
123
|
+
private let shared: SharedContainer?
|
|
124
|
+
|
|
125
|
+
// Values already read. Also the only copy of a value the Keychain refused, in which case the next launch registers a new install.
|
|
126
|
+
private var cache: [String: String] = [:]
|
|
127
|
+
|
|
128
|
+
init(values: SecureValues, defaults: UserDefaults, shared: SharedContainer? = nil) {
|
|
129
|
+
self.values = values
|
|
130
|
+
self.defaults = defaults
|
|
131
|
+
self.shared = shared
|
|
132
|
+
|
|
133
|
+
// The Keychain survives an uninstall and the defaults don't, so a reinstall clears the Keychain and starts a new install, as on
|
|
134
|
+
// Android. Otherwise the reinstalled app would keep receiving the previous user's pushes.
|
|
135
|
+
if !defaults.bool(forKey: Key.installed) {
|
|
136
|
+
values.removeAll()
|
|
137
|
+
defaults.set(true, forKey: Key.installed)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
var appKey: String? {
|
|
142
|
+
get { readSecure(Key.appKey) }
|
|
143
|
+
set {
|
|
144
|
+
writeSecure(Key.appKey, newValue)
|
|
145
|
+
publishSharedState()
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
var installId: String? {
|
|
150
|
+
get { readSecure(Key.installId) }
|
|
151
|
+
set {
|
|
152
|
+
writeSecure(Key.installId, newValue)
|
|
153
|
+
publishSharedState()
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
var deviceSecret: String? {
|
|
158
|
+
get { readSecure(Key.deviceSecret) }
|
|
159
|
+
set {
|
|
160
|
+
writeSecure(Key.deviceSecret, newValue)
|
|
161
|
+
publishSharedState()
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
var apnsToken: String? {
|
|
166
|
+
readSecure(Key.apnsToken)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/// The registration token the app passed from Firebase Messaging, for apps that send through their own Firebase project.
|
|
170
|
+
var fcmToken: String? {
|
|
171
|
+
readSecure(Key.fcmToken)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/// The transport the portal sets for iOS: `apns`, or `fcm` for apps that send through their own Firebase project. `apns` until
|
|
175
|
+
/// the settings are read. A change registers again with the other token.
|
|
176
|
+
var iosTransport: String {
|
|
177
|
+
get { defaults.string(forKey: Key.iosTransport) ?? Transport.apns }
|
|
178
|
+
set {
|
|
179
|
+
if newValue != iosTransport { tokenChanged = true }
|
|
180
|
+
defaults.set(newValue, forKey: Key.iosTransport)
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/// The token for the transport in use.
|
|
185
|
+
var registrationToken: String? {
|
|
186
|
+
iosTransport == Transport.fcm ? fcmToken : apnsToken
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
var baseUrl: String? {
|
|
190
|
+
get { defaults.string(forKey: Key.baseUrl) }
|
|
191
|
+
set {
|
|
192
|
+
defaults.set(newValue, forKey: Key.baseUrl)
|
|
193
|
+
publishSharedState()
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
var tokenChanged: Bool {
|
|
198
|
+
get { defaults.bool(forKey: Key.tokenChanged) }
|
|
199
|
+
set { defaults.set(newValue, forKey: Key.tokenChanged) }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/// The day of the last answer to a registration, in days since the epoch.
|
|
203
|
+
var registeredOn: Int? {
|
|
204
|
+
defaults.object(forKey: Key.registeredOn) as? Int
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
var reportedPermission: String? {
|
|
208
|
+
defaults.string(forKey: Key.reportedPermission)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
var pendingIdentity: PendingIdentity? {
|
|
212
|
+
get { readSecure(Key.pendingIdentity).flatMap(Self.parseIdentity) }
|
|
213
|
+
set { writeSecure(Key.pendingIdentity, newValue.map(Self.format)) }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/// See `AcceptedIdentity`. Cleared by a logout, a refused identify, a new install or a new app key.
|
|
217
|
+
var acceptedIdentity: AcceptedIdentity? {
|
|
218
|
+
get { readSecure(Key.acceptedIdentity).flatMap(Self.parseAccepted) }
|
|
219
|
+
set { writeSecure(Key.acceptedIdentity, newValue.map { "\($0.day)|\($0.verified ? 1 : 0)|\($0.fingerprint)" }) }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// Today's answer for `identity` on this install when nothing else is queued, so the identify can be skipped; nil when it must be
|
|
223
|
+
/// sent. Token-only identifies are never skipped: different users' tokens look the same here.
|
|
224
|
+
func repeatedAnswer(_ identity: PendingIdentity, day: Int) -> Bool? {
|
|
225
|
+
guard case let .identify(externalId, email, identityToken) = identity, pendingIdentity == nil,
|
|
226
|
+
!(externalId ?? "").isEmpty || !(email ?? "").isEmpty,
|
|
227
|
+
let installId, let accepted = acceptedIdentity, accepted.day == day,
|
|
228
|
+
accepted.fingerprint == Self.identityFingerprint(installId: installId, externalId: externalId, email: email, hasToken: identityToken != nil)
|
|
229
|
+
else { return nil }
|
|
230
|
+
return accepted.verified
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// A SHA-256 fingerprint of the identity for one install: the ids, and whether a signed token came with them.
|
|
234
|
+
static func identityFingerprint(installId: String, externalId: String?, email: String?, hasToken: Bool) -> String {
|
|
235
|
+
let text = [installId, externalId ?? "", email ?? "", hasToken ? "1" : "0"].joined(separator: "\u{0}")
|
|
236
|
+
return SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined()
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
var pendingOptIn: Bool? {
|
|
240
|
+
get { defaults.object(forKey: Key.pendingOptIn) as? Bool }
|
|
241
|
+
set { defaults.set(newValue, forKey: Key.pendingOptIn) }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
var pendingDelete: PendingDelete? {
|
|
245
|
+
get { readSecure(Key.pendingDelete).flatMap(Self.parseDelete) }
|
|
246
|
+
set { writeSecure(Key.pendingDelete, newValue.map(Self.format)) }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/// No call before this time (seconds since the epoch), set from the service's `Retry-After`.
|
|
250
|
+
var notBefore: TimeInterval {
|
|
251
|
+
get { defaults.double(forKey: Key.notBefore) }
|
|
252
|
+
set { defaults.set(newValue, forKey: Key.notBefore) }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
var failedAttempts: Int {
|
|
256
|
+
get { defaults.integer(forKey: Key.failedAttempts) }
|
|
257
|
+
set { defaults.set(newValue, forKey: Key.failedAttempts) }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
var configExpiresAt: TimeInterval {
|
|
261
|
+
get { defaults.double(forKey: Key.configExpiresAt) }
|
|
262
|
+
set { defaults.set(newValue, forKey: Key.configExpiresAt) }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/// A change clears the accepted identity: an identify accepted before may now be refused.
|
|
266
|
+
var requireVerifiedIdentity: Bool {
|
|
267
|
+
get { defaults.bool(forKey: Key.requireVerifiedIdentity) }
|
|
268
|
+
set {
|
|
269
|
+
if newValue != requireVerifiedIdentity { acceptedIdentity = nil }
|
|
270
|
+
defaults.set(newValue, forKey: Key.requireVerifiedIdentity)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
var hasEvents: Bool {
|
|
275
|
+
!readEvents().isEmpty
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/// Stores the APNs `token` if it differs from the stored one, and returns whether it did.
|
|
279
|
+
func updateToken(_ token: String) -> Bool {
|
|
280
|
+
guard apnsToken != token else { return false }
|
|
281
|
+
writeSecure(Key.apnsToken, token)
|
|
282
|
+
if iosTransport == Transport.apns { tokenChanged = true }
|
|
283
|
+
return true
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/// Stores the FCM `token` if it differs from the stored one, and returns whether it did.
|
|
287
|
+
func updateFcmToken(_ token: String) -> Bool {
|
|
288
|
+
guard fcmToken != token else { return false }
|
|
289
|
+
writeSecure(Key.fcmToken, token)
|
|
290
|
+
if iosTransport == Transport.fcm { tokenChanged = true }
|
|
291
|
+
return true
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/// The service accepted this registration or refused it for good: nothing to resend today.
|
|
295
|
+
func markRegistered(day: Int, permission: String) {
|
|
296
|
+
defaults.set(day, forKey: Key.registeredOn)
|
|
297
|
+
defaults.set(permission, forKey: Key.reportedPermission)
|
|
298
|
+
tokenChanged = false
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/// The install is unknown or its secret is lost: the next registration creates a new install. Its events are dropped too, since the
|
|
302
|
+
/// service matches each to a push sent to the old install.
|
|
303
|
+
func dropInstall() {
|
|
304
|
+
installId = nil
|
|
305
|
+
deviceSecret = nil
|
|
306
|
+
acceptedIdentity = nil
|
|
307
|
+
for key in [Key.registeredOn, Key.events, Key.legacyOpenEvents] {
|
|
308
|
+
defaults.removeObject(forKey: key)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
shared?.clearInbox()
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
func replaceAppKey(_ key: String) {
|
|
315
|
+
appKey = key
|
|
316
|
+
// Another key can mean another environment, which doesn't know the identity.
|
|
317
|
+
acceptedIdentity = nil
|
|
318
|
+
configExpiresAt = 0
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/// Queues an event until the service acknowledges it. Only the newest `maxEvents` are kept.
|
|
322
|
+
func queueEvent(_ type: String, uid: String, occurredAt: TimeInterval, link: String? = nil) {
|
|
323
|
+
var events = readEvents()
|
|
324
|
+
events.append(PushEvent(eventId: UUID().uuidString.lowercased(), type: type, uid: uid, occurredAt: occurredAt, link: link))
|
|
325
|
+
writeEvents(Array(events.suffix(Self.maxEvents)))
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/// The events still to send, oldest first. Events older than 30 days are dropped: the service no longer accepts them.
|
|
329
|
+
func pendingEvents(now: TimeInterval) -> [PushEvent] {
|
|
330
|
+
let events = readEvents()
|
|
331
|
+
let fresh = events.filter { now - $0.occurredAt <= Self.maxEventAge }
|
|
332
|
+
if fresh.count != events.count { writeEvents(fresh) }
|
|
333
|
+
return fresh
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/// Moves the deliveries the notification service extension left (`SharedContainer`) into the queue, oldest first, skipping events
|
|
337
|
+
/// already queued. Deliveries for another install are dropped: the service would match them to a push this install never got.
|
|
338
|
+
func mergeInbox() {
|
|
339
|
+
guard let shared else { return }
|
|
340
|
+
let current = installId
|
|
341
|
+
let arrived = shared.takeInbox().filter { $0.installId == nil || $0.installId == current }.map(\.event)
|
|
342
|
+
guard !arrived.isEmpty else { return }
|
|
343
|
+
|
|
344
|
+
var events = readEvents()
|
|
345
|
+
let known = Set(events.map(\.eventId))
|
|
346
|
+
events.append(contentsOf: arrived.filter { !known.contains($0.eventId) })
|
|
347
|
+
writeEvents(Array(events.sorted { $0.occurredAt < $1.occurredAt }.suffix(Self.maxEvents)))
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/// Writes what the notification service extension needs to report deliveries, or removes it once the install is gone. Called on
|
|
351
|
+
/// every change of key, host, install or secret, and at each start in case the app just added its App Group.
|
|
352
|
+
func publishSharedState() {
|
|
353
|
+
guard let shared else { return }
|
|
354
|
+
let key = appKey
|
|
355
|
+
shared.writeState(appKey: key, baseUrl: baseUrl ?? key.flatMap(AppKeys.baseUrl), installId: installId, deviceSecret: deviceSecret)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/// Removes the events the service acknowledged.
|
|
359
|
+
func removeEvents(_ eventIds: Set<String>) {
|
|
360
|
+
let events = readEvents()
|
|
361
|
+
let left = events.filter { !eventIds.contains($0.eventId) }
|
|
362
|
+
if left.count != events.count { writeEvents(left) }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
func wipe() {
|
|
366
|
+
cache.removeAll()
|
|
367
|
+
values.removeAll()
|
|
368
|
+
for key in [
|
|
369
|
+
Key.baseUrl, Key.iosTransport, Key.tokenChanged, Key.registeredOn, Key.reportedPermission, Key.pendingOptIn, Key.notBefore,
|
|
370
|
+
Key.failedAttempts, Key.configExpiresAt, Key.requireVerifiedIdentity, Key.events, Key.legacyOpenEvents,
|
|
371
|
+
] {
|
|
372
|
+
defaults.removeObject(forKey: key)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
shared?.clearInbox()
|
|
376
|
+
publishSharedState()
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Opens stored in the legacy format become open events on the first read. Every write removes them, so while they exist they
|
|
380
|
+
// are the oldest entries.
|
|
381
|
+
private func readEvents() -> [PushEvent] {
|
|
382
|
+
let events = (defaults.array(forKey: Key.events) as? [[String: Any]] ?? []).compactMap(Self.parseEvent)
|
|
383
|
+
guard let legacy = defaults.array(forKey: Key.legacyOpenEvents) as? [[String: Any]] else { return events }
|
|
384
|
+
|
|
385
|
+
let opens = legacy.compactMap { entry -> PushEvent? in
|
|
386
|
+
guard let uid = entry["uid"] as? String, let openedAt = entry["opened_at"] as? TimeInterval else { return nil }
|
|
387
|
+
return PushEvent(eventId: UUID().uuidString.lowercased(), type: PushEvent.open, uid: uid, occurredAt: openedAt, link: nil)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
let migrated = Array((opens + events).suffix(Self.maxEvents))
|
|
391
|
+
writeEvents(migrated)
|
|
392
|
+
return migrated
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private func writeEvents(_ events: [PushEvent]) {
|
|
396
|
+
let stored = events.map { event -> [String: Any] in
|
|
397
|
+
var entry: [String: Any] = ["event_id": event.eventId, "type": event.type, "uid": event.uid, "occurred_at": event.occurredAt]
|
|
398
|
+
entry["link"] = event.link
|
|
399
|
+
return entry
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
defaults.set(stored, forKey: Key.events)
|
|
403
|
+
defaults.removeObject(forKey: Key.legacyOpenEvents)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private static func parseEvent(_ entry: [String: Any]) -> PushEvent? {
|
|
407
|
+
guard let id = entry["event_id"] as? String, let type = entry["type"] as? String, let uid = entry["uid"] as? String,
|
|
408
|
+
let occurredAt = entry["occurred_at"] as? TimeInterval
|
|
409
|
+
else { return nil }
|
|
410
|
+
return PushEvent(eventId: id, type: type, uid: uid, occurredAt: occurredAt, link: entry["link"] as? String)
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private func readSecure(_ name: String) -> String? {
|
|
414
|
+
if let cached = cache[name] { return cached }
|
|
415
|
+
let value = values.read(name)
|
|
416
|
+
cache[name] = value
|
|
417
|
+
return value
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private func writeSecure(_ name: String, _ value: String?) {
|
|
421
|
+
cache[name] = value
|
|
422
|
+
if !values.write(name, value) {
|
|
423
|
+
PushLog.warning("A value can't be stored in the Keychain, so it stays in memory.")
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
private static func parseAccepted(_ text: String) -> AcceptedIdentity? {
|
|
428
|
+
let parts = text.split(separator: "|", maxSplits: 2, omittingEmptySubsequences: false)
|
|
429
|
+
guard parts.count == 3, let day = Int(parts[0]) else { return nil }
|
|
430
|
+
return AcceptedIdentity(fingerprint: String(parts[2]), day: day, verified: parts[1] == "1")
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private static func format(_ identity: PendingIdentity) -> String {
|
|
434
|
+
switch identity {
|
|
435
|
+
case .logout:
|
|
436
|
+
return encode(["op": "logout"])
|
|
437
|
+
case let .identify(externalId, email, identityToken):
|
|
438
|
+
return encode(["op": "identify", "external_id": externalId, "email": email, "identity_token": identityToken].compactMapValues { $0 })
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private static func parseIdentity(_ text: String) -> PendingIdentity? {
|
|
443
|
+
guard let json = decode(text) else { return nil }
|
|
444
|
+
if json["op"] == "logout" { return .logout }
|
|
445
|
+
return .identify(externalId: json["external_id"], email: json["email"], identityToken: json["identity_token"])
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
private static func format(_ delete: PendingDelete) -> String {
|
|
449
|
+
encode(["app_key": delete.appKey, "base_url": delete.baseUrl, "install_id": delete.installId, "device_secret": delete.deviceSecret].compactMapValues { $0 })
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
private static func parseDelete(_ text: String) -> PendingDelete? {
|
|
453
|
+
guard let json = decode(text), let key = json["app_key"], let install = json["install_id"], let secret = json["device_secret"] else { return nil }
|
|
454
|
+
return PendingDelete(appKey: key, baseUrl: json["base_url"], installId: install, deviceSecret: secret)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
private static func encode(_ values: [String: String]) -> String {
|
|
458
|
+
let data = (try? JSONSerialization.data(withJSONObject: values)) ?? Data()
|
|
459
|
+
return String(data: data, encoding: .utf8) ?? "{}"
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
private static func decode(_ text: String) -> [String: String]? {
|
|
463
|
+
(try? JSONSerialization.jsonObject(with: Data(text.utf8))) as? [String: String]
|
|
464
|
+
}
|
|
465
|
+
}
|