@zapiack/react-native 0.0.0-stage → 0.1.0
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/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +81 -2
- package/android/build.gradle +48 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/zapiack/reactnative/ZapiackPushModule.kt +110 -0
- package/android/src/main/java/com/zapiack/reactnative/ZapiackPushPackage.kt +12 -0
- package/dist/index.d.mts +53 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +107 -0
- package/dist/index.mjs +81 -0
- package/ios/Zapiack/Api.swift +130 -0
- package/ios/Zapiack/EventQueue.swift +95 -0
- package/ios/Zapiack/ImageFile.swift +22 -0
- package/ios/Zapiack/Models.swift +151 -0
- package/ios/Zapiack/Processing.swift +59 -0
- package/ios/Zapiack/PushClient.swift +132 -0
- package/ios/Zapiack/Storage.swift +86 -0
- package/ios/Zapiack/ZapiackPush.swift +119 -0
- package/ios/ZapiackPushModule.m +18 -0
- package/ios/ZapiackPushModule.swift +121 -0
- package/package.json +70 -4
- package/zapiack-react-native.podspec +17 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
public protocol HTTPTransport {
|
|
4
|
+
func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
public struct URLSessionTransport: HTTPTransport {
|
|
8
|
+
private let session: URLSession
|
|
9
|
+
|
|
10
|
+
public init(session: URLSession = .shared) {
|
|
11
|
+
self.session = session
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
|
|
15
|
+
let (data, response) = try await session.data(for: request)
|
|
16
|
+
guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
|
|
17
|
+
return (data, http)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
public struct EventsResult: Decodable, Equatable {
|
|
22
|
+
public struct Rejection: Decodable, Equatable {
|
|
23
|
+
public var index: Int
|
|
24
|
+
public var reason: String
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
public var accepted: Int
|
|
28
|
+
public var ignored: Int
|
|
29
|
+
public var rejected: [Rejection]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
public enum SendOutcome: Equatable {
|
|
33
|
+
case sent(EventsResult)
|
|
34
|
+
/// The request did not get through, or the service was busy: keep the events and try again.
|
|
35
|
+
case retry
|
|
36
|
+
/// The request was refused for good: repeating it will be refused again.
|
|
37
|
+
case refused(status: Int)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public struct DeviceRegistration: Encodable {
|
|
41
|
+
public var installationId: String
|
|
42
|
+
public var platform: String
|
|
43
|
+
public var token: String
|
|
44
|
+
public var externalUserId: String??
|
|
45
|
+
public var tags: [String: JSONValue]?
|
|
46
|
+
public var permission: String?
|
|
47
|
+
public var environment: String?
|
|
48
|
+
public var appVersion: String?
|
|
49
|
+
|
|
50
|
+
public init(installationId: String, platform: String = "ios", token: String, externalUserId: String?? = nil, tags: [String: JSONValue]? = nil, permission: String? = nil, environment: String? = nil, appVersion: String? = nil) {
|
|
51
|
+
self.installationId = installationId
|
|
52
|
+
self.platform = platform
|
|
53
|
+
self.token = token
|
|
54
|
+
self.externalUserId = externalUserId
|
|
55
|
+
self.tags = tags
|
|
56
|
+
self.permission = permission
|
|
57
|
+
self.environment = environment
|
|
58
|
+
self.appVersion = appVersion
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private enum CodingKeys: String, CodingKey {
|
|
62
|
+
case installationId, platform, token, externalUserId, tags, permission, environment, appVersion
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// An absent user leaves the link alone, a string links it, and an explicit null unlinks it, so all three are kept apart.
|
|
66
|
+
public func encode(to encoder: Encoder) throws {
|
|
67
|
+
var c = encoder.container(keyedBy: CodingKeys.self)
|
|
68
|
+
try c.encode(installationId, forKey: .installationId)
|
|
69
|
+
try c.encode(platform, forKey: .platform)
|
|
70
|
+
try c.encode(token, forKey: .token)
|
|
71
|
+
switch externalUserId {
|
|
72
|
+
case .none: break
|
|
73
|
+
case .some(.none): try c.encodeNil(forKey: .externalUserId)
|
|
74
|
+
case .some(.some(let id)): try c.encode(id, forKey: .externalUserId)
|
|
75
|
+
}
|
|
76
|
+
try c.encodeIfPresent(tags, forKey: .tags)
|
|
77
|
+
try c.encodeIfPresent(permission, forKey: .permission)
|
|
78
|
+
try c.encodeIfPresent(environment, forKey: .environment)
|
|
79
|
+
try c.encodeIfPresent(appVersion, forKey: .appVersion)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
public struct SdkApi {
|
|
84
|
+
private let config: ZapiackConfig
|
|
85
|
+
private let transport: HTTPTransport
|
|
86
|
+
|
|
87
|
+
public init(config: ZapiackConfig, transport: HTTPTransport = URLSessionTransport()) {
|
|
88
|
+
self.config = config
|
|
89
|
+
self.transport = transport
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
func request(_ path: String, method: String, body: Data?) -> URLRequest {
|
|
93
|
+
var url = config.baseUrl
|
|
94
|
+
for part in ["push", "sdk", path] { url.appendPathComponent(part) }
|
|
95
|
+
var request = URLRequest(url: url)
|
|
96
|
+
request.httpMethod = method
|
|
97
|
+
request.httpBody = body
|
|
98
|
+
request.timeoutInterval = 20
|
|
99
|
+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
100
|
+
request.setValue(config.appKey, forHTTPHeaderField: "X-Zapiack-App-Key")
|
|
101
|
+
return request
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
public func register(_ registration: DeviceRegistration) async throws {
|
|
105
|
+
let body = try JSONEncoder().encode(registration)
|
|
106
|
+
let (_, response) = try await transport.send(request("devices", method: "PUT", body: body))
|
|
107
|
+
guard (200..<300).contains(response.statusCode) else { throw ZapiackError.registrationFailed(status: response.statusCode) }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
public func sendEvents(_ events: [SdkEvent]) async -> SendOutcome {
|
|
111
|
+
guard let body = try? JSONEncoder().encode(["events": events]) else { return .refused(status: 0) }
|
|
112
|
+
do {
|
|
113
|
+
let (data, response) = try await transport.send(request("events", method: "POST", body: body))
|
|
114
|
+
if (200..<300).contains(response.statusCode) {
|
|
115
|
+
let result = (try? JSONDecoder().decode(EventsResult.self, from: data)) ?? EventsResult(accepted: events.count, ignored: 0, rejected: [])
|
|
116
|
+
return .sent(result)
|
|
117
|
+
}
|
|
118
|
+
// Busy or down: try again. Anything else (a wrong key, a bad request) will not improve by repeating it.
|
|
119
|
+
if response.statusCode == 429 || response.statusCode == 408 || response.statusCode >= 500 { return .retry }
|
|
120
|
+
return .refused(status: response.statusCode)
|
|
121
|
+
} catch {
|
|
122
|
+
return .retry
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
public enum ZapiackError: Error, Equatable {
|
|
128
|
+
case notConfigured
|
|
129
|
+
case registrationFailed(status: Int)
|
|
130
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Events waiting to be sent, one file each. The app and its extension both write here, and a file is only ever created whole
|
|
4
|
+
/// and removed whole, so neither can overwrite the other's events the way a shared list would.
|
|
5
|
+
public final class EventQueue {
|
|
6
|
+
public static let maxEvents = 500
|
|
7
|
+
public static let batchSize = 100
|
|
8
|
+
private static let maxAge: TimeInterval = 6 * 24 * 3600
|
|
9
|
+
|
|
10
|
+
private let directory: URL
|
|
11
|
+
private let fileManager = FileManager.default
|
|
12
|
+
private let lock = NSLock()
|
|
13
|
+
private var sequence = 0
|
|
14
|
+
|
|
15
|
+
public init(directory: URL) {
|
|
16
|
+
self.directory = directory
|
|
17
|
+
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
@discardableResult
|
|
21
|
+
public func add(_ event: SdkEvent, now: Date = Date()) -> Bool {
|
|
22
|
+
guard let data = try? JSONEncoder().encode(event) else { return false }
|
|
23
|
+
lock.lock()
|
|
24
|
+
sequence += 1
|
|
25
|
+
let seq = sequence
|
|
26
|
+
lock.unlock()
|
|
27
|
+
// The time first so files list in the order events happened, then a counter for events in the same millisecond.
|
|
28
|
+
let name = String(format: "%015ld-%06ld-%@.json", Int(now.timeIntervalSince1970 * 1000), seq, event.clientEventId)
|
|
29
|
+
do {
|
|
30
|
+
try data.write(to: directory.appendingPathComponent(name), options: .atomic)
|
|
31
|
+
} catch {
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
trim()
|
|
35
|
+
return true
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
public func pending() -> [(url: URL, event: SdkEvent)] {
|
|
39
|
+
let urls = (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []
|
|
40
|
+
return urls
|
|
41
|
+
.filter { $0.pathExtension == "json" }
|
|
42
|
+
.sorted { $0.lastPathComponent < $1.lastPathComponent }
|
|
43
|
+
.compactMap { url in
|
|
44
|
+
guard let data = try? Data(contentsOf: url), let event = try? JSONDecoder().decode(SdkEvent.self, from: data) else {
|
|
45
|
+
// A file nothing can read is never going to be sent.
|
|
46
|
+
try? fileManager.removeItem(at: url)
|
|
47
|
+
return nil
|
|
48
|
+
}
|
|
49
|
+
return (url, event)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
public var count: Int { pending().count }
|
|
54
|
+
|
|
55
|
+
/// Sends what is waiting, a batch at a time. Stops at the first batch that has to be retried, leaving it in place.
|
|
56
|
+
@discardableResult
|
|
57
|
+
public func flush(using api: SdkApi, now: Date = Date()) async -> Bool {
|
|
58
|
+
discardExpired(now: now)
|
|
59
|
+
while true {
|
|
60
|
+
let batch = Array(pending().prefix(Self.batchSize))
|
|
61
|
+
if batch.isEmpty { return true }
|
|
62
|
+
switch await api.sendEvents(batch.map(\.event)) {
|
|
63
|
+
case .retry:
|
|
64
|
+
return false
|
|
65
|
+
case .refused, .sent:
|
|
66
|
+
// Sent, or refused for good: either way these events are finished with. Rejected ones are malformed, so dropped too.
|
|
67
|
+
for item in batch { try? fileManager.removeItem(at: item.url) }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private func discardExpired(now: Date) {
|
|
73
|
+
for item in pending() {
|
|
74
|
+
guard let at = ISO8601DateFormatter.withFraction.date(from: item.event.at) else {
|
|
75
|
+
try? fileManager.removeItem(at: item.url)
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
if now.timeIntervalSince(at) > Self.maxAge { try? fileManager.removeItem(at: item.url) }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private func trim() {
|
|
83
|
+
let all = pending()
|
|
84
|
+
guard all.count > Self.maxEvents else { return }
|
|
85
|
+
for item in all.prefix(all.count - Self.maxEvents) { try? fileManager.removeItem(at: item.url) }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
extension ISO8601DateFormatter {
|
|
90
|
+
static let withFraction: ISO8601DateFormatter = {
|
|
91
|
+
let f = ISO8601DateFormatter()
|
|
92
|
+
f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
93
|
+
return f
|
|
94
|
+
}()
|
|
95
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Picks the file type a downloaded picture is shown as; the system decides from the extension.
|
|
4
|
+
public struct ImageFile: Equatable {
|
|
5
|
+
public var fileExtension: String
|
|
6
|
+
|
|
7
|
+
public static func kind(mimeType: String?, url: URL) -> ImageFile? {
|
|
8
|
+
switch mimeType?.lowercased() {
|
|
9
|
+
case "image/jpeg", "image/jpg": return ImageFile(fileExtension: "jpg")
|
|
10
|
+
case "image/png": return ImageFile(fileExtension: "png")
|
|
11
|
+
case "image/gif": return ImageFile(fileExtension: "gif")
|
|
12
|
+
case "image/webp": return nil
|
|
13
|
+
default:
|
|
14
|
+
switch url.pathExtension.lowercased() {
|
|
15
|
+
case "jpg", "jpeg": return ImageFile(fileExtension: "jpg")
|
|
16
|
+
case "png": return ImageFile(fileExtension: "png")
|
|
17
|
+
case "gif": return ImageFile(fileExtension: "gif")
|
|
18
|
+
default: return nil
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// What every push carries so a tap can be reported and followed.
|
|
4
|
+
public struct PushBlock: Codable, Equatable {
|
|
5
|
+
public struct Tracking: Codable, Equatable {
|
|
6
|
+
public var w: Int?
|
|
7
|
+
public var s: Bool?
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
public struct Action: Codable, Equatable {
|
|
11
|
+
public var id: String
|
|
12
|
+
public var title: String
|
|
13
|
+
public var event: String?
|
|
14
|
+
public var link: String?
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
public var m: String
|
|
18
|
+
public var d: String
|
|
19
|
+
public var l: String?
|
|
20
|
+
public var i: String?
|
|
21
|
+
public var e: String?
|
|
22
|
+
public var t: Tracking?
|
|
23
|
+
public var a: [Action]?
|
|
24
|
+
|
|
25
|
+
public init(m: String, d: String, l: String? = nil, i: String? = nil, e: String? = nil, t: Tracking? = nil, a: [Action]? = nil) {
|
|
26
|
+
self.m = m
|
|
27
|
+
self.d = d
|
|
28
|
+
self.l = l
|
|
29
|
+
self.i = i
|
|
30
|
+
self.e = e
|
|
31
|
+
self.t = t
|
|
32
|
+
self.a = a
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Reads the block from a notification's `userInfo`, or returns nil when the push is not from Zapiack.
|
|
36
|
+
public init?(userInfo: [AnyHashable: Any]) {
|
|
37
|
+
guard let raw = userInfo["zapiack"], JSONSerialization.isValidJSONObject(raw),
|
|
38
|
+
let data = try? JSONSerialization.data(withJSONObject: raw),
|
|
39
|
+
let block = try? JSONDecoder().decode(PushBlock.self, from: data),
|
|
40
|
+
!block.m.isEmpty, !block.d.isEmpty
|
|
41
|
+
else { return nil }
|
|
42
|
+
self = block
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/// A value of the app's own, sent along with an event.
|
|
47
|
+
public enum JSONValue: Codable, Equatable {
|
|
48
|
+
case string(String)
|
|
49
|
+
case number(Double)
|
|
50
|
+
case bool(Bool)
|
|
51
|
+
case null
|
|
52
|
+
case array([JSONValue])
|
|
53
|
+
case object([String: JSONValue])
|
|
54
|
+
|
|
55
|
+
public init(from decoder: Decoder) throws {
|
|
56
|
+
let c = try decoder.singleValueContainer()
|
|
57
|
+
if c.decodeNil() { self = .null }
|
|
58
|
+
else if let v = try? c.decode(Bool.self) { self = .bool(v) }
|
|
59
|
+
else if let v = try? c.decode(Double.self) { self = .number(v) }
|
|
60
|
+
else if let v = try? c.decode(String.self) { self = .string(v) }
|
|
61
|
+
else if let v = try? c.decode([JSONValue].self) { self = .array(v) }
|
|
62
|
+
else { self = .object(try c.decode([String: JSONValue].self)) }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
public func encode(to encoder: Encoder) throws {
|
|
66
|
+
var c = encoder.singleValueContainer()
|
|
67
|
+
switch self {
|
|
68
|
+
case .string(let v): try c.encode(v)
|
|
69
|
+
case .number(let v): try c.encode(v)
|
|
70
|
+
case .bool(let v): try c.encode(v)
|
|
71
|
+
case .null: try c.encodeNil()
|
|
72
|
+
case .array(let v): try c.encode(v)
|
|
73
|
+
case .object(let v): try c.encode(v)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
public enum EventType: String, Codable {
|
|
79
|
+
case clicked, action, screen, custom, received
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
public struct SdkEvent: Codable, Equatable {
|
|
83
|
+
public var clientEventId: String
|
|
84
|
+
public var type: EventType
|
|
85
|
+
public var deliveryId: String
|
|
86
|
+
public var sessionId: String?
|
|
87
|
+
public var name: String?
|
|
88
|
+
public var actionId: String?
|
|
89
|
+
public var properties: [String: JSONValue]?
|
|
90
|
+
public var previousScreen: String?
|
|
91
|
+
public var at: String
|
|
92
|
+
|
|
93
|
+
public init(type: EventType, deliveryId: String, sessionId: String? = nil, name: String? = nil, actionId: String? = nil, properties: [String: JSONValue]? = nil, previousScreen: String? = nil, at: Date = Date()) {
|
|
94
|
+
self.clientEventId = UUID().uuidString.lowercased()
|
|
95
|
+
self.type = type
|
|
96
|
+
self.deliveryId = deliveryId
|
|
97
|
+
self.sessionId = sessionId
|
|
98
|
+
self.name = name
|
|
99
|
+
self.actionId = actionId
|
|
100
|
+
self.properties = properties
|
|
101
|
+
self.previousScreen = previousScreen
|
|
102
|
+
self.at = Timestamps.string(from: at)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// The window after a tap in which screens and events are credited to the push.
|
|
107
|
+
public struct ActiveSession: Codable, Equatable {
|
|
108
|
+
public var sessionId: String
|
|
109
|
+
public var deliveryId: String
|
|
110
|
+
public var messageId: String
|
|
111
|
+
public var startedAt: Date
|
|
112
|
+
public var windowMinutes: Int
|
|
113
|
+
public var screens: Bool
|
|
114
|
+
|
|
115
|
+
public init(sessionId: String, deliveryId: String, messageId: String, startedAt: Date, windowMinutes: Int, screens: Bool) {
|
|
116
|
+
self.sessionId = sessionId
|
|
117
|
+
self.deliveryId = deliveryId
|
|
118
|
+
self.messageId = messageId
|
|
119
|
+
self.startedAt = startedAt
|
|
120
|
+
self.windowMinutes = windowMinutes
|
|
121
|
+
self.screens = screens
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public func isOpen(at now: Date) -> Bool {
|
|
125
|
+
now <= startedAt.addingTimeInterval(TimeInterval(windowMinutes) * 60)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/// What was tapped, handed to the app so it can route.
|
|
130
|
+
public struct Tap: Equatable {
|
|
131
|
+
public var messageId: String
|
|
132
|
+
public var deliveryId: String
|
|
133
|
+
public var sessionId: String
|
|
134
|
+
/// The button that was tapped, when it was a button.
|
|
135
|
+
public var actionId: String?
|
|
136
|
+
/// The event name set on the notification or the button.
|
|
137
|
+
public var event: String?
|
|
138
|
+
public var link: URL?
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
public enum Timestamps {
|
|
142
|
+
private static let formatter: ISO8601DateFormatter = {
|
|
143
|
+
let f = ISO8601DateFormatter()
|
|
144
|
+
f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
145
|
+
return f
|
|
146
|
+
}()
|
|
147
|
+
|
|
148
|
+
public static func string(from date: Date) -> String {
|
|
149
|
+
formatter.string(from: date)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The decisions the app and the extension share, kept apart from UIKit so they can be tested.
|
|
4
|
+
public enum Processing {
|
|
5
|
+
/// The actions in a notification response that mean "the user did not choose anything".
|
|
6
|
+
public static let dismissIdentifier = "com.apple.UNNotificationDismissActionIdentifier"
|
|
7
|
+
public static let defaultIdentifier = "com.apple.UNNotificationDefaultActionIdentifier"
|
|
8
|
+
|
|
9
|
+
/// A picture is only fetched from a secure address.
|
|
10
|
+
public static func imageURL(from block: PushBlock) -> URL? {
|
|
11
|
+
guard let raw = block.i, let url = URL(string: raw), url.scheme?.lowercased() == "https", let host = url.host, !host.isEmpty else { return nil }
|
|
12
|
+
return url
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/// Only links the app can route are handed over; a script address is never one.
|
|
16
|
+
public static func link(from raw: String?) -> URL? {
|
|
17
|
+
guard let raw, let url = URL(string: raw), let scheme = url.scheme?.lowercased() else { return nil }
|
|
18
|
+
if ["javascript", "data", "file", "vbscript"].contains(scheme) { return nil }
|
|
19
|
+
return url
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
public static func receivedEvent(for block: PushBlock, at date: Date = Date()) -> SdkEvent {
|
|
23
|
+
SdkEvent(type: .received, deliveryId: block.d, at: date)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Turns a tap into the events to report and the session it opens. `actionIdentifier` is the system's, or a button's id.
|
|
27
|
+
public static func tap(block: PushBlock, actionIdentifier: String, at date: Date = Date()) -> (tap: Tap, session: ActiveSession, events: [SdkEvent])? {
|
|
28
|
+
if actionIdentifier == dismissIdentifier { return nil }
|
|
29
|
+
let sessionId = UUID().uuidString.lowercased()
|
|
30
|
+
let isDefault = actionIdentifier == defaultIdentifier
|
|
31
|
+
let action = isDefault ? nil : block.a?.first { $0.id == actionIdentifier }
|
|
32
|
+
// A button this push did not declare is not reported as one.
|
|
33
|
+
if !isDefault && action == nil { return nil }
|
|
34
|
+
|
|
35
|
+
let event: SdkEvent
|
|
36
|
+
if let action {
|
|
37
|
+
event = SdkEvent(type: .action, deliveryId: block.d, sessionId: sessionId, name: action.event, actionId: action.id, at: date)
|
|
38
|
+
} else {
|
|
39
|
+
event = SdkEvent(type: .clicked, deliveryId: block.d, sessionId: sessionId, name: block.e, at: date)
|
|
40
|
+
}
|
|
41
|
+
let session = ActiveSession(
|
|
42
|
+
sessionId: sessionId,
|
|
43
|
+
deliveryId: block.d,
|
|
44
|
+
messageId: block.m,
|
|
45
|
+
startedAt: date,
|
|
46
|
+
windowMinutes: block.t?.w ?? 30,
|
|
47
|
+
screens: block.t?.s ?? false
|
|
48
|
+
)
|
|
49
|
+
let tap = Tap(
|
|
50
|
+
messageId: block.m,
|
|
51
|
+
deliveryId: block.d,
|
|
52
|
+
sessionId: sessionId,
|
|
53
|
+
actionId: action?.id,
|
|
54
|
+
event: action?.event ?? block.e,
|
|
55
|
+
link: link(from: action?.link ?? block.l)
|
|
56
|
+
)
|
|
57
|
+
return (tap, session, [event])
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The state and rules behind the app-side SDK, without anything that needs a running app.
|
|
4
|
+
public final class PushClient {
|
|
5
|
+
public let config: ZapiackConfig
|
|
6
|
+
public let queue: EventQueue
|
|
7
|
+
private let storage: KeyValueStorage
|
|
8
|
+
private let api: SdkApi
|
|
9
|
+
private let now: () -> Date
|
|
10
|
+
private let lock = NSLock()
|
|
11
|
+
private var previousScreen: String?
|
|
12
|
+
|
|
13
|
+
public init(config: ZapiackConfig, storage: KeyValueStorage, queue: EventQueue, transport: HTTPTransport = URLSessionTransport(), now: @escaping () -> Date = Date.init) {
|
|
14
|
+
self.config = config
|
|
15
|
+
self.storage = storage
|
|
16
|
+
self.queue = queue
|
|
17
|
+
self.api = SdkApi(config: config, transport: transport)
|
|
18
|
+
self.now = now
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// MARK: Device
|
|
22
|
+
|
|
23
|
+
public var deviceToken: String? { storage.string(forKey: "zapiack.token") }
|
|
24
|
+
|
|
25
|
+
public func setDeviceToken(_ data: Data) {
|
|
26
|
+
storage.set(data.map { String(format: "%02x", $0) }.joined(), forKey: "zapiack.token")
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
private var tags: [String: JSONValue] {
|
|
30
|
+
get {
|
|
31
|
+
guard let raw = storage.string(forKey: SharedState.Key.tags), let data = raw.data(using: .utf8),
|
|
32
|
+
let value = try? JSONDecoder().decode([String: JSONValue].self, from: data) else { return [:] }
|
|
33
|
+
return value
|
|
34
|
+
}
|
|
35
|
+
set {
|
|
36
|
+
let data = try? JSONEncoder().encode(newValue)
|
|
37
|
+
storage.set(data.flatMap { String(data: $0, encoding: .utf8) }, forKey: SharedState.Key.tags)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// "set:<id>" or "clear": a change of user that has not reached the service yet.
|
|
42
|
+
private var pendingUser: String? {
|
|
43
|
+
get { storage.string(forKey: SharedState.Key.user) }
|
|
44
|
+
set { storage.set(newValue, forKey: SharedState.Key.user) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
public func login(_ userId: String) { pendingUser = "set:\(userId)" }
|
|
48
|
+
public func logout() { pendingUser = "clear" }
|
|
49
|
+
|
|
50
|
+
public func addTags(_ new: [String: JSONValue]) {
|
|
51
|
+
var current = tags
|
|
52
|
+
for (key, value) in new { current[key] = value }
|
|
53
|
+
tags = current
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public func removeTags(_ keys: [String]) {
|
|
57
|
+
var current = tags
|
|
58
|
+
for key in keys { current.removeValue(forKey: key) }
|
|
59
|
+
tags = current
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// Tells the service about this install. Sent on every start; a change of user goes once and is then forgotten.
|
|
63
|
+
public func register(permission: String?, environment: String, appVersion: String?) async throws {
|
|
64
|
+
guard let token = deviceToken else { return }
|
|
65
|
+
let user = pendingUser
|
|
66
|
+
var external: String?? = nil
|
|
67
|
+
if let user {
|
|
68
|
+
external = user == "clear" ? .some(nil) : .some(String(user.dropFirst(4)))
|
|
69
|
+
}
|
|
70
|
+
let registration = DeviceRegistration(
|
|
71
|
+
installationId: config.installationId,
|
|
72
|
+
token: token,
|
|
73
|
+
externalUserId: external,
|
|
74
|
+
tags: tags.isEmpty ? nil : tags,
|
|
75
|
+
permission: permission,
|
|
76
|
+
environment: environment,
|
|
77
|
+
appVersion: appVersion
|
|
78
|
+
)
|
|
79
|
+
try await api.register(registration)
|
|
80
|
+
// Only forget the change if it is still the one that was sent.
|
|
81
|
+
if pendingUser == user { pendingUser = nil }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// MARK: Taps and what follows
|
|
85
|
+
|
|
86
|
+
public var activeSession: ActiveSession? {
|
|
87
|
+
get {
|
|
88
|
+
guard let raw = storage.string(forKey: SharedState.Key.session), let data = raw.data(using: .utf8),
|
|
89
|
+
let session = try? JSONDecoder().decode(ActiveSession.self, from: data) else { return nil }
|
|
90
|
+
return session.isOpen(at: now()) ? session : nil
|
|
91
|
+
}
|
|
92
|
+
set {
|
|
93
|
+
let data = newValue.flatMap { try? JSONEncoder().encode($0) }
|
|
94
|
+
storage.set(data.flatMap { String(data: $0, encoding: .utf8) }, forKey: SharedState.Key.session)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// Reports a tap and opens its window. Returns what the app needs to route, or nil when it was a dismissal or not ours.
|
|
99
|
+
public func handleResponse(userInfo: [AnyHashable: Any], actionIdentifier: String) -> Tap? {
|
|
100
|
+
guard let block = PushBlock(userInfo: userInfo),
|
|
101
|
+
let result = Processing.tap(block: block, actionIdentifier: actionIdentifier, at: now()) else { return nil }
|
|
102
|
+
// Last tap wins: a new tap replaces the window of the one before it.
|
|
103
|
+
activeSession = result.session
|
|
104
|
+
lock.lock(); previousScreen = nil; lock.unlock()
|
|
105
|
+
for event in result.events { queue.add(event, now: now()) }
|
|
106
|
+
return result.tap
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// A screen the user reached. Only recorded while a tapped push's window is open and the push asked for screens.
|
|
110
|
+
public func screen(_ name: String) {
|
|
111
|
+
guard let session = activeSession, session.screens else { return }
|
|
112
|
+
lock.lock()
|
|
113
|
+
let from = previousScreen
|
|
114
|
+
previousScreen = name
|
|
115
|
+
lock.unlock()
|
|
116
|
+
queue.add(SdkEvent(type: .screen, deliveryId: session.deliveryId, sessionId: session.sessionId, name: name, previousScreen: from, at: now()), now: now())
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/// A named thing the user did. Credited to the tapped push while its window is open; otherwise there is nothing to credit.
|
|
120
|
+
/// Returns whether there was a tapped push to credit it to.
|
|
121
|
+
@discardableResult
|
|
122
|
+
public func track(_ name: String, properties: [String: JSONValue]? = nil) -> Bool {
|
|
123
|
+
guard let session = activeSession else { return false }
|
|
124
|
+
queue.add(SdkEvent(type: .custom, deliveryId: session.deliveryId, sessionId: session.sessionId, name: name, properties: properties, at: now()), now: now())
|
|
125
|
+
return true
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@discardableResult
|
|
129
|
+
public func flush() async -> Bool {
|
|
130
|
+
await queue.flush(using: api, now: now())
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Where the app and its notification extension keep what they share.
|
|
4
|
+
public protocol KeyValueStorage: AnyObject {
|
|
5
|
+
func string(forKey key: String) -> String?
|
|
6
|
+
func set(_ value: String?, forKey key: String)
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
public final class MemoryStorage: KeyValueStorage {
|
|
10
|
+
private var values: [String: String] = [:]
|
|
11
|
+
private let lock = NSLock()
|
|
12
|
+
|
|
13
|
+
public init() {}
|
|
14
|
+
|
|
15
|
+
public func string(forKey key: String) -> String? {
|
|
16
|
+
lock.lock(); defer { lock.unlock() }
|
|
17
|
+
return values[key]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
public func set(_ value: String?, forKey key: String) {
|
|
21
|
+
lock.lock(); defer { lock.unlock() }
|
|
22
|
+
values[key] = value
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Backed by an App Group, which is what lets the app and its extension see the same values.
|
|
27
|
+
public final class SharedDefaultsStorage: KeyValueStorage {
|
|
28
|
+
private let defaults: UserDefaults
|
|
29
|
+
|
|
30
|
+
public init?(appGroup: String) {
|
|
31
|
+
guard let defaults = UserDefaults(suiteName: appGroup) else { return nil }
|
|
32
|
+
self.defaults = defaults
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
public func string(forKey key: String) -> String? { defaults.string(forKey: key) }
|
|
36
|
+
|
|
37
|
+
public func set(_ value: String?, forKey key: String) {
|
|
38
|
+
if let value { defaults.set(value, forKey: key) } else { defaults.removeObject(forKey: key) }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public struct ZapiackConfig: Equatable {
|
|
43
|
+
public var appKey: String
|
|
44
|
+
public var baseUrl: URL
|
|
45
|
+
public var installationId: String
|
|
46
|
+
|
|
47
|
+
public init(appKey: String, baseUrl: URL, installationId: String) {
|
|
48
|
+
self.appKey = appKey
|
|
49
|
+
self.baseUrl = baseUrl
|
|
50
|
+
self.installationId = installationId
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// What the app writes at start-up and the extension reads when a push arrives.
|
|
55
|
+
public enum SharedState {
|
|
56
|
+
public static let defaultBaseUrl = URL(string: "https://api.zapiack.com/v1")!
|
|
57
|
+
|
|
58
|
+
enum Key {
|
|
59
|
+
static let appKey = "zapiack.appKey"
|
|
60
|
+
static let baseUrl = "zapiack.baseUrl"
|
|
61
|
+
static let installationId = "zapiack.installationId"
|
|
62
|
+
static let session = "zapiack.session"
|
|
63
|
+
static let user = "zapiack.user"
|
|
64
|
+
static let tags = "zapiack.tags"
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// A UUID made on first use and kept: it identifies this install even when its push address changes.
|
|
68
|
+
public static func installationId(in storage: KeyValueStorage) -> String {
|
|
69
|
+
if let existing = storage.string(forKey: Key.installationId), !existing.isEmpty { return existing }
|
|
70
|
+
let created = UUID().uuidString.lowercased()
|
|
71
|
+
storage.set(created, forKey: Key.installationId)
|
|
72
|
+
return created
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
public static func save(appKey: String, baseUrl: URL, in storage: KeyValueStorage) {
|
|
76
|
+
storage.set(appKey, forKey: Key.appKey)
|
|
77
|
+
storage.set(baseUrl.absoluteString, forKey: Key.baseUrl)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
public static func load(from storage: KeyValueStorage) -> ZapiackConfig? {
|
|
81
|
+
guard let appKey = storage.string(forKey: Key.appKey), appKey.hasPrefix("pk_"),
|
|
82
|
+
let base = storage.string(forKey: Key.baseUrl), let baseUrl = URL(string: base)
|
|
83
|
+
else { return nil }
|
|
84
|
+
return ZapiackConfig(appKey: appKey, baseUrl: baseUrl, installationId: installationId(in: storage))
|
|
85
|
+
}
|
|
86
|
+
}
|