@datatalks-ab/push-capacitor 0.0.0-stage → 0.5.0-beta.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/0.5.0-beta.1/push-android-0.5.0-beta.1-sources.jar +0 -0
  7. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1-sources.jar.md5 +1 -0
  8. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1-sources.jar.sha1 +1 -0
  9. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1-sources.jar.sha256 +1 -0
  10. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1-sources.jar.sha512 +1 -0
  11. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.aar +0 -0
  12. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.aar.md5 +1 -0
  13. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.aar.sha1 +1 -0
  14. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.aar.sha256 +1 -0
  15. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.aar.sha512 +1 -0
  16. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.module +144 -0
  17. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.module.md5 +1 -0
  18. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.module.sha1 +1 -0
  19. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.module.sha256 +1 -0
  20. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.module.sha512 +1 -0
  21. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.pom +63 -0
  22. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.pom.md5 +1 -0
  23. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.pom.sha1 +1 -0
  24. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.1.pom.sha256 +1 -0
  25. package/android/maven/se/datatalks/push-android/0.5.0-beta.1/push-android-0.5.0-beta.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 +34 -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,50 @@
1
+ import Foundation
2
+
3
+ /// The extension's only call: `POST /devices/{install_id}/events` with the delivery (contract 1.1.0), as the app sends its events. Only a
4
+ /// response with `results` completes the delivery; anything else (a refusal, a busy service, no network, a timeout) leaves it in the
5
+ /// inbox for the app, which handles each response. Nothing here logs: the key and the secret pass through it.
6
+ struct DeliveryReporter {
7
+ /// Idle timeout per request; the session caps each call at 10 seconds in total, well within the extension's 30.
8
+ static let requestTimeout: TimeInterval = 5
9
+
10
+ /// Same value as the app's `SdkInfo.header`: the service doesn't need to tell them apart.
11
+ static let sdkHeader = "datatalks-push-ios/0.5.0-beta.1"
12
+
13
+ private static let timestamps: ISO8601DateFormatter = {
14
+ let format = ISO8601DateFormatter()
15
+ format.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
16
+ return format
17
+ }()
18
+
19
+ let session: URLSession
20
+
21
+ /// Calls `completion` on a background queue, with true if the service acknowledged the delivery.
22
+ func report(_ event: DeliveryEvent, state: ExtensionState, completion: @escaping (Bool) -> Void) {
23
+ guard let url = URL(string: "\(state.baseUrl)/devices/\(state.installId)/events") else {
24
+ completion(false)
25
+ return
26
+ }
27
+
28
+ let delivery: [String: Any] = [
29
+ "event_id": event.eventId,
30
+ "type": DeliveryEvent.type,
31
+ "uid": event.uid,
32
+ "occurred_at": Self.timestamps.string(from: Date(timeIntervalSince1970: event.occurredAt)),
33
+ ]
34
+
35
+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: Self.requestTimeout)
36
+ request.httpMethod = "POST"
37
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
38
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
39
+ request.setValue(state.appKey, forHTTPHeaderField: "X-DataTalks-App-Key")
40
+ request.setValue(state.deviceSecret, forHTTPHeaderField: "X-DataTalks-Device-Secret")
41
+ request.setValue(Self.sdkHeader, forHTTPHeaderField: "X-DataTalks-SDK")
42
+ request.httpBody = try? JSONSerialization.data(withJSONObject: ["events": [delivery]])
43
+
44
+ session.dataTask(with: request) { data, response, _ in
45
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
46
+ let json = data.flatMap { (try? JSONSerialization.jsonObject(with: $0)) as? [String: Any] }
47
+ completion((200 ..< 300).contains(status) && json?["results"] is [Any])
48
+ }.resume()
49
+ }
50
+ }
@@ -0,0 +1,101 @@
1
+ import Foundation
2
+
3
+ /// The extension's side of the App Group it shares with the app (`DataTalksAppGroup` in both Info.plists): it reads the app's
4
+ /// `state.json` and writes `inbox/`, one file per delivery, which the app sends when the extension's own call fails. The app's side is
5
+ /// `SharedContainer` in DataTalksPush: change both together, along with the tests that read each side's files with the other's code.
6
+ struct ExtensionShared {
7
+ static let appGroupInfoKey = "DataTalksAppGroup"
8
+ static let folderName = "DataTalksPush"
9
+ static let stateFileName = "state.json"
10
+ static let inboxFolderName = "inbox"
11
+ /// Matches the app's queue limit. An app that names no group never empties the inbox, so beyond this limit a delivery is
12
+ /// reported but not kept.
13
+ static let inboxLimit = 200
14
+
15
+ let directory: URL
16
+ var fileManager: FileManager = .default
17
+
18
+ /// The extension's group container, or nil when its Info.plist names no group or it isn't entitled to the one it names.
19
+ static func forExtension(bundle: Bundle = .main) -> ExtensionShared? {
20
+ guard let group = bundle.object(forInfoDictionaryKey: appGroupInfoKey) as? String, !group.isEmpty,
21
+ let root = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)
22
+ else { return nil }
23
+
24
+ return ExtensionShared(directory: root.appendingPathComponent(folderName, isDirectory: true))
25
+ }
26
+
27
+ private var inbox: URL { directory.appendingPathComponent(Self.inboxFolderName, isDirectory: true) }
28
+
29
+ /// What the extension needs to send a delivery, as the app last wrote it; nil before the app has an install.
30
+ func state() -> ExtensionState? {
31
+ let file = directory.appendingPathComponent(Self.stateFileName)
32
+ guard let data = try? Data(contentsOf: file),
33
+ let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: String],
34
+ let appKey = json["app_key"], let baseUrl = json["base_url"], let installId = json["install_id"],
35
+ let deviceSecret = json["device_secret"]
36
+ else { return nil }
37
+
38
+ return ExtensionState(appKey: appKey, baseUrl: baseUrl, installId: installId, deviceSecret: deviceSecret)
39
+ }
40
+
41
+ /// Saves a delivery for the app first, since the extension can be stopped at any time. It records the app's current install id, if
42
+ /// any, so the app never sends it for another install. Returns nil if it can't be written; with the inbox full, returns the event
43
+ /// without saving it.
44
+ func recordDelivery(uid: String, at occurredAt: TimeInterval, installId: String?) -> DeliveryEvent? {
45
+ let event = DeliveryEvent(eventId: UUID().uuidString.lowercased(), uid: uid, occurredAt: occurredAt)
46
+ if inboxCount() >= Self.inboxLimit { return event }
47
+
48
+ var entry: [String: Any] = ["event_id": event.eventId, "type": DeliveryEvent.type, "uid": uid, "occurred_at": occurredAt]
49
+ entry["install_id"] = installId
50
+
51
+ do {
52
+ try fileManager.createDirectory(at: inbox, withIntermediateDirectories: true)
53
+ excludeFromBackup()
54
+ let data = try JSONSerialization.data(withJSONObject: entry)
55
+ try data.write(to: file(of: event), options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
56
+ return event
57
+ } catch {
58
+ return nil
59
+ }
60
+ }
61
+
62
+ /// The service acknowledged the delivery: the app doesn't need to send it.
63
+ func forget(_ event: DeliveryEvent) {
64
+ try? fileManager.removeItem(at: file(of: event))
65
+ }
66
+
67
+ // Another device is another install, so nothing here goes into a backup. The app does the same when it writes its state.
68
+ private func excludeFromBackup() {
69
+ var folder = directory
70
+ var values = URLResourceValues()
71
+ values.isExcludedFromBackup = true
72
+ try? folder.setResourceValues(values)
73
+ }
74
+
75
+ private func inboxCount() -> Int {
76
+ let files = (try? fileManager.contentsOfDirectory(at: inbox, includingPropertiesForKeys: nil)) ?? []
77
+ return files.filter { $0.pathExtension == "json" }.count
78
+ }
79
+
80
+ private func file(of event: DeliveryEvent) -> URL {
81
+ inbox.appendingPathComponent("\(event.eventId).json")
82
+ }
83
+ }
84
+
85
+ /// The app's key, host, install and secret, as `state.json` has them.
86
+ struct ExtensionState: Equatable {
87
+ let appKey: String
88
+ let baseUrl: String
89
+ let installId: String
90
+ let deviceSecret: String
91
+ }
92
+
93
+ /// A delivery the extension reports (contract 1.1.0 `PushEvent`). Created once, so the extension's call and a later one from the app send
94
+ /// the same event.
95
+ struct DeliveryEvent: Equatable {
96
+ static let type = "delivery"
97
+
98
+ let eventId: String
99
+ let uid: String
100
+ let occurredAt: TimeInterval
101
+ }
@@ -0,0 +1,27 @@
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
+ </array>
24
+ <key>NSPrivacyAccessedAPITypes</key>
25
+ <array/>
26
+ </dict>
27
+ </plist>
@@ -0,0 +1,90 @@
1
+ import Foundation
2
+ import UserNotifications
3
+
4
+ /// A push's picture (`dt_image`) as a notification attachment: an https JPEG, PNG or GIF of at most 5 MB (as on Android), downloaded
5
+ /// within 10 seconds. It downloads to a file, not into memory, which the extension has little of. Otherwise the push shows without it.
6
+ enum PushAttachment {
7
+ static let maxBytes = 5 * 1024 * 1024
8
+ static let downloadTimeout: TimeInterval = 10
9
+
10
+ /// The picture's URL if it's an https URL to download; otherwise nil.
11
+ static func url(_ text: String?) -> URL? {
12
+ guard let text, let url = URL(string: text), url.scheme?.lowercased() == "https", url.host != nil else { return nil }
13
+ return url
14
+ }
15
+
16
+ /// Calls `completion` with the attachment, or nil, on a background queue.
17
+ static func download(_ url: URL, session: URLSession, fileManager: FileManager = .default, completion: @escaping (UNNotificationAttachment?) -> Void) {
18
+ let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout)
19
+ session.downloadTask(with: request) { location, response, _ in
20
+ guard let location, let response = response as? HTTPURLResponse, (200 ..< 300).contains(response.statusCode) else {
21
+ completion(nil)
22
+ return
23
+ }
24
+
25
+ completion(attachment(at: location, fileManager: fileManager))
26
+ }.resume()
27
+ }
28
+
29
+ // The type comes from the file's first bytes: a server's Content-Type can be wrong, and the system needs the type up front.
30
+ static func attachment(at location: URL, fileManager: FileManager = .default) -> UNNotificationAttachment? {
31
+ // A resource value, not the file's attributes: those count as a file timestamp API, which needs a declared privacy reason.
32
+ guard let size = (try? location.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, accepts(size: size),
33
+ let kind = ImageKind(header: firstBytes(of: location))
34
+ else { return nil }
35
+
36
+ // The downloaded file is deleted when the task ends: the attachment needs its own file, with the type's extension.
37
+ let file = fileManager.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).\(kind.fileExtension)")
38
+ do {
39
+ try fileManager.moveItem(at: location, to: file)
40
+ return try UNNotificationAttachment(identifier: "dt_image", url: file, options: [UNNotificationAttachmentOptionsTypeHintKey: kind.typeIdentifier])
41
+ } catch {
42
+ try? fileManager.removeItem(at: file)
43
+ return nil
44
+ }
45
+ }
46
+
47
+ /// Whether a picture of this many bytes may be shown.
48
+ static func accepts(size: Int) -> Bool {
49
+ size > 0 && size <= maxBytes
50
+ }
51
+
52
+ private static func firstBytes(of file: URL) -> Data {
53
+ guard let handle = try? FileHandle(forReadingFrom: file) else { return Data() }
54
+ defer { try? handle.close() }
55
+ return handle.readData(ofLength: 8)
56
+ }
57
+
58
+ private enum ImageKind {
59
+ case jpeg, png, gif
60
+
61
+ init?(header: Data) {
62
+ let bytes = [UInt8](header)
63
+ if bytes.starts(with: [0xFF, 0xD8, 0xFF]) {
64
+ self = .jpeg
65
+ } else if bytes.starts(with: [0x89, 0x50, 0x4E, 0x47]) {
66
+ self = .png
67
+ } else if bytes.starts(with: Array("GIF8".utf8)) {
68
+ self = .gif
69
+ } else {
70
+ return nil
71
+ }
72
+ }
73
+
74
+ var fileExtension: String {
75
+ switch self {
76
+ case .jpeg: return "jpg"
77
+ case .png: return "png"
78
+ case .gif: return "gif"
79
+ }
80
+ }
81
+
82
+ var typeIdentifier: String {
83
+ switch self {
84
+ case .jpeg: return "public.jpeg"
85
+ case .png: return "public.png"
86
+ case .gif: return "com.compuserve.gif"
87
+ }
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,34 @@
1
+ import Foundation
2
+ import os
3
+
4
+ enum AppKeys {
5
+ private static let shape = try! NSRegularExpression(pattern: "^dtpk_(stg|prd)_(live|test)_[0-9A-Za-z]{32}$")
6
+
7
+ /// The base URL of the key's environment, or nil for a malformed key.
8
+ static func baseUrl(_ appKey: String) -> String? {
9
+ let whole = NSRange(appKey.startIndex..., in: appKey)
10
+ guard let match = shape.firstMatch(in: appKey, range: whole), let environment = Range(match.range(at: 1), in: appKey) else {
11
+ return nil
12
+ }
13
+
14
+ return appKey[environment] == "prd" ? "https://push.datatalks.se/v1" : "https://push.staging.datatalks.se/v1"
15
+ }
16
+ }
17
+
18
+ enum SdkInfo {
19
+ static let version = "0.5.0-beta.1"
20
+ static let header = "datatalks-push-ios/\(version)"
21
+ }
22
+
23
+ /// Never pass keys, secrets, tokens or identity values: messages are logged as public.
24
+ enum PushLog {
25
+ private static let log = Logger(subsystem: "se.datatalks.push", category: "DataTalksPush")
26
+
27
+ static func warning(_ message: String) {
28
+ log.warning("\(message, privacy: .public)")
29
+ }
30
+
31
+ static func error(_ message: String) {
32
+ log.error("\(message, privacy: .public)")
33
+ }
34
+ }
@@ -0,0 +1,110 @@
1
+ import Foundation
2
+ import UserNotifications
3
+
4
+ /// The Data Talks push SDK. Call `initialize` from `application(_:didFinishLaunchingWithOptions:)`.
5
+ ///
6
+ /// Calls return immediately and never throw for a service error. Work runs on the SDK's own serial queue, and work left when the
7
+ /// app stops resumes at the next launch. Results go to `listener`.
8
+ public enum DataTalksPush {
9
+ /// Receives opens, messages and identify results. Set it before `initialize`; it is held strongly. The latest tap that arrived
10
+ /// while no listener was set goes to the next listener set.
11
+ public static var listener: DataTalksPushListener? {
12
+ get { PushRuntime.shared.listener }
13
+ set { PushRuntime.shared.listener = newValue }
14
+ }
15
+
16
+ /// Starts the SDK with the app's publishable key and requests an APNs token. The key selects the host.
17
+ public static func initialize(appKey: String, options: DataTalksPushOptions = DataTalksPushOptions()) {
18
+ guard AppKeys.baseUrl(appKey) != nil else {
19
+ PushLog.error("The app key is malformed: the SDK stays off. Copy the key from the portal.")
20
+ return
21
+ }
22
+
23
+ PushRuntime.shared.start(appKey: appKey, baseUrl: options.baseUrl, openLinks: options.openLinks)
24
+ }
25
+
26
+ /// Forward `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` here.
27
+ public static func didRegisterForRemoteNotifications(deviceToken: Data) {
28
+ PushRuntime.shared.onNewToken(deviceToken.map { String(format: "%02x", $0) }.joined())
29
+ }
30
+
31
+ /// For apps whose iOS pushes go through their own Firebase project (transport FCM in the portal): pass the registration token
32
+ /// from `MessagingDelegate.messaging(_:didReceiveRegistrationToken:)` here, each time it arrives. Not needed with APNs.
33
+ public static func setFcmToken(_ token: String) {
34
+ PushRuntime.shared.onNewFcmToken(token)
35
+ }
36
+
37
+ /// Forward `application(_:didFailToRegisterForRemoteNotificationsWithError:)` here. The install registers once a token arrives.
38
+ public static func didFailToRegisterForRemoteNotifications(error: Error) {
39
+ PushLog.warning("APNs gave no token: \(error.localizedDescription)")
40
+ }
41
+
42
+ /// Requests the notification permission (alert, sound and badge). A `provisional` request shows no prompt and delivers quietly.
43
+ /// `completion` receives the resulting status on the main thread.
44
+ public static func requestPermission(provisional: Bool = false, completion: ((DataTalksPermission) -> Void)? = nil) {
45
+ PushRuntime.shared.requestPermission(provisional: provisional, completion: completion)
46
+ }
47
+
48
+ /// The current notification permission, passed to `completion` on the main thread.
49
+ public static func permissionStatus(completion: @escaping (DataTalksPermission) -> Void) {
50
+ PushRuntime.shared.permissionStatus(completion: completion)
51
+ }
52
+
53
+ /// Links this install to the signed-in user. Pass the `identityToken` your backend signed for this user; an app that requires
54
+ /// verified identity refuses a call without one. The result goes to `DataTalksPushListener.onIdentityResult`. A refused identify
55
+ /// isn't retried: call it again at the next sign-in.
56
+ ///
57
+ /// Repeating the same external id and email (with or without a token, as before) on the same UTC day makes no call: the listener
58
+ /// gets the earlier result, which says nothing about the token passed this time. An identify with only a token is always sent.
59
+ public static func identify(externalId: String? = nil, email: String? = nil, identityToken: String? = nil) {
60
+ guard [externalId, email, identityToken].contains(where: { !($0 ?? "").isEmpty }) else {
61
+ PushLog.warning("identify needs an external id, an email or an identity token.")
62
+ return
63
+ }
64
+
65
+ PushRuntime.shared.send(identity: .identify(externalId: externalId, email: email, identityToken: identityToken))
66
+ }
67
+
68
+ /// Unlinks this install from its user. The install stays registered.
69
+ public static func logout() {
70
+ PushRuntime.shared.send(identity: .logout)
71
+ }
72
+
73
+ /// Records the user's in-app marketing choice on this device. Transactional pushes aren't affected.
74
+ public static func setMarketingOptIn(_ optIn: Bool) {
75
+ PushRuntime.shared.setMarketingOptIn(optIn)
76
+ }
77
+
78
+ /// Deletes this install on the service and all SDK data on the device. The SDK stays off until the next `initialize`,
79
+ /// which creates a new install.
80
+ public static func deleteLocalData() {
81
+ PushRuntime.shared.deleteLocalData()
82
+ }
83
+
84
+ /// Makes the SDK the notification center's delegate. Other notifications go to the previous delegate. Call it before
85
+ /// `application(_:didFinishLaunchingWithOptions:)` returns, or a tap that launched the app is missed.
86
+ public static func useAsNotificationCenterDelegate() {
87
+ NotificationCenterForwarder.install()
88
+ }
89
+
90
+ /// For an app with its own `UNUserNotificationCenterDelegate`: forward `didReceive` here. Returns true for a Data Talks
91
+ /// push, which the SDK has handled, and false for any other notification, which the app handles.
92
+ @discardableResult
93
+ public static func handleNotificationResponse(_ response: UNNotificationResponse) -> Bool {
94
+ let userInfo = response.notification.request.content.userInfo
95
+ guard PushMessage(userInfo: userInfo) != nil else { return false }
96
+ if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
97
+ PushRuntime.shared.notificationOpened(userInfo: userInfo)
98
+ }
99
+
100
+ return true
101
+ }
102
+
103
+ /// For an app with its own `UNUserNotificationCenterDelegate`: forward `willPresent` here. Returns the presentation options
104
+ /// for a Data Talks push while the app is open, or nil for any other notification, which the app handles.
105
+ public static func handleWillPresent(_ notification: UNNotification) -> UNNotificationPresentationOptions? {
106
+ guard let message = PushMessage(userInfo: notification.request.content.userInfo) else { return nil }
107
+ PushRuntime.shared.notifyMessage(message.toPublic())
108
+ return [.banner, .list, .sound]
109
+ }
110
+ }
@@ -0,0 +1,72 @@
1
+ import Foundation
2
+
3
+ /// Callbacks from the SDK, on the main thread. Every method has an empty default: implement the ones you need.
4
+ public protocol DataTalksPushListener: AnyObject {
5
+ /// The user tapped a notification. The SDK opens `deepLink`, if any, unless `DataTalksPushOptions.openLinks` is false.
6
+ /// A tap that arrived while no listener was set, such as the one that launched the app, goes to the next listener set.
7
+ func onNotificationOpened(deepLink: String?, data: [String: Any]?)
8
+
9
+ /// A Data Talks push arrived while the app was in the foreground. Pushes to a closed app go only to the system.
10
+ func onMessageReceived(_ message: DataTalksMessage)
11
+
12
+ /// The service answered a `DataTalksPush.identify`.
13
+ func onIdentityResult(_ result: DataTalksIdentityResult)
14
+ }
15
+
16
+ public extension DataTalksPushListener {
17
+ func onNotificationOpened(deepLink: String?, data: [String: Any]?) {}
18
+
19
+ func onMessageReceived(_ message: DataTalksMessage) {}
20
+
21
+ func onIdentityResult(_ result: DataTalksIdentityResult) {}
22
+ }
23
+
24
+ /// A Data Talks push, read from its `dt_*` keys. The fields match the Android SDK's.
25
+ public struct DataTalksMessage {
26
+ public let uid: String?
27
+ public let title: String?
28
+ public let body: String?
29
+ /// The picture's `https` URL. iOS shows it only with a notification service extension (`DataTalksNotificationService`).
30
+ public let imageUrl: String?
31
+ public let deepLink: String?
32
+ public let data: [String: Any]?
33
+ }
34
+
35
+ /// The result of an identify. A non-nil `errorCode` means it was refused and won't be retried; `errorDetail` says why an identity
36
+ /// token failed. It never reveals whether a profile was found.
37
+ public struct DataTalksIdentityResult {
38
+ public let verified: Bool
39
+ public let errorCode: String?
40
+ public let errorDetail: String?
41
+
42
+ init(verified: Bool, errorCode: String? = nil, errorDetail: String? = nil) {
43
+ self.verified = verified
44
+ self.errorCode = errorCode
45
+ self.errorDetail = errorDetail
46
+ }
47
+ }
48
+
49
+ /// Whether this app may show notifications. The raw value is the name the service and the other SDKs use.
50
+ public enum DataTalksPermission: String {
51
+ case authorized
52
+ case denied
53
+ case notDetermined = "not_determined"
54
+ /// Pushes arrive quietly, in the notification center only.
55
+ case provisional
56
+ /// An App Clip's temporary permission.
57
+ case ephemeral
58
+ }
59
+
60
+ public struct DataTalksPushOptions {
61
+ /// Replaces the host the key selects. Only for testing against a local ingress.
62
+ public var baseUrl: String?
63
+
64
+ /// Set to false for an app that routes links itself: a tap then opens nothing and only passes the link to
65
+ /// `onNotificationOpened`.
66
+ public var openLinks: Bool
67
+
68
+ public init(baseUrl: String? = nil, openLinks: Bool = true) {
69
+ self.baseUrl = baseUrl
70
+ self.openLinks = openLinks
71
+ }
72
+ }
@@ -0,0 +1,128 @@
1
+ import Foundation
2
+ import UserNotifications
3
+
4
+ /// What a registration reports about the device.
5
+ protocol DeviceFacts {
6
+ func metadata() -> [String: String]
7
+
8
+ /// Blocks. Call it off the main thread.
9
+ func permission() -> String
10
+
11
+ var environment: String { get }
12
+ }
13
+
14
+ /// This device's facts, cut to the contract's lengths: the ingress refuses a longer value, and a 4xx is never retried.
15
+ struct SystemFacts: DeviceFacts {
16
+ func metadata() -> [String: String] {
17
+ let info = Bundle.main.infoDictionary
18
+ let os = ProcessInfo.processInfo.operatingSystemVersion
19
+ let facts: [(String, String?, Int)] = [
20
+ ("app_version", info?["CFBundleShortVersionString"] as? String, 64),
21
+ ("app_build", info?["CFBundleVersion"] as? String, 64),
22
+ ("os_version", "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)", 64),
23
+ ("device_manufacturer", "Apple", 128),
24
+ ("device_model", Self.modelIdentifier(), 128),
25
+ ("locale", Locale.current.identifier.replacingOccurrences(of: "_", with: "-"), 35),
26
+ ("time_zone", TimeZone.current.identifier, 64),
27
+ ]
28
+
29
+ var metadata: [String: String] = [:]
30
+ for (name, value, maxLength) in facts {
31
+ if let value, !value.isEmpty {
32
+ metadata[name] = Self.cut(value, maxLength: maxLength)
33
+ }
34
+ }
35
+
36
+ return metadata
37
+ }
38
+
39
+ func permission() -> String {
40
+ let answered = DispatchSemaphore(value: 0)
41
+ var status = UNAuthorizationStatus.notDetermined
42
+ UNUserNotificationCenter.current().getNotificationSettings { settings in
43
+ status = settings.authorizationStatus
44
+ answered.signal()
45
+ }
46
+ answered.wait()
47
+ return Self.name(of: status)
48
+ }
49
+
50
+ var environment: String {
51
+ #if targetEnvironment(simulator)
52
+ return ApsEnvironment.sandbox
53
+ #else
54
+ return ApsEnvironment.current()
55
+ #endif
56
+ }
57
+
58
+ static func name(of status: UNAuthorizationStatus) -> String {
59
+ DataTalksPermission(status).rawValue
60
+ }
61
+
62
+ /// Cuts in UTF-16 units, as the ingress counts them, and never splits a character.
63
+ static func cut(_ value: String, maxLength: Int) -> String {
64
+ guard value.utf16.count > maxLength else { return value }
65
+
66
+ var result = ""
67
+ var length = 0
68
+ for character in value {
69
+ length += character.utf16.count
70
+ if length > maxLength { break }
71
+ result.append(character)
72
+ }
73
+
74
+ return result
75
+ }
76
+
77
+ private static func modelIdentifier() -> String? {
78
+ if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulated }
79
+
80
+ var size = 0
81
+ guard sysctlbyname("hw.machine", nil, &size, nil, 0) == 0, size > 0 else { return nil }
82
+ var machine = [CChar](repeating: 0, count: size)
83
+ guard sysctlbyname("hw.machine", &machine, &size, nil, 0) == 0 else { return nil }
84
+ return String(cString: machine)
85
+ }
86
+ }
87
+
88
+ extension DataTalksPermission {
89
+ init(_ status: UNAuthorizationStatus) {
90
+ switch status {
91
+ case .authorized: self = .authorized
92
+ case .denied: self = .denied
93
+ case .provisional: self = .provisional
94
+ case .ephemeral: self = .ephemeral
95
+ default: self = .notDetermined
96
+ }
97
+ }
98
+ }
99
+
100
+ /// The APNs environment of this build, from the provisioning profile embedded in the app.
101
+ enum ApsEnvironment {
102
+ static let production = "production"
103
+ static let sandbox = "sandbox"
104
+
105
+ static func current(bundle: Bundle = .main) -> String {
106
+ guard let path = bundle.path(forResource: "embedded", ofType: "mobileprovision"), let profile = FileManager.default.contents(atPath: path) else {
107
+ // App Store builds have no profile.
108
+ return production
109
+ }
110
+
111
+ return read(profile: profile)
112
+ }
113
+
114
+ /// A profile is a plist in a signed envelope. `aps-environment` is `development` in development builds; any other value, or none,
115
+ /// means production.
116
+ static func read(profile: Data) -> String {
117
+ guard
118
+ let start = profile.range(of: Data("<plist".utf8)),
119
+ let end = profile.range(of: Data("</plist>".utf8), in: start.upperBound ..< profile.endIndex),
120
+ let plist = try? PropertyListSerialization.propertyList(from: profile[start.lowerBound ..< end.upperBound], format: nil) as? [String: Any],
121
+ let entitlements = plist["Entitlements"] as? [String: Any]
122
+ else {
123
+ return production
124
+ }
125
+
126
+ return entitlements["aps-environment"] as? String == "development" ? sandbox : production
127
+ }
128
+ }