@zapiack/react-native 0.0.0-stage → 0.2.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 +14 -0
- package/LICENSE +21 -0
- package/README.md +171 -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 +113 -0
- package/android/src/main/java/com/zapiack/reactnative/ZapiackPushPackage.kt +12 -0
- package/dist/calls.d.mts +198 -0
- package/dist/calls.d.ts +198 -0
- package/dist/calls.js +793 -0
- package/dist/calls.mjs +406 -0
- package/dist/chunk-CCLICX3L.mjs +371 -0
- package/dist/index.d.mts +61 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +490 -0
- package/dist/index.mjs +100 -0
- package/dist/realtime-BAcafCSr.d.mts +173 -0
- package/dist/realtime-BAcafCSr.d.ts +173 -0
- package/ios/Zapiack/Api.swift +134 -0
- package/ios/Zapiack/EventQueue.swift +95 -0
- package/ios/Zapiack/ImageFile.swift +22 -0
- package/ios/Zapiack/LayoutModel.swift +128 -0
- package/ios/Zapiack/LayoutView.swift +206 -0
- package/ios/Zapiack/Models.swift +151 -0
- package/ios/Zapiack/Processing.swift +59 -0
- package/ios/Zapiack/PushClient.swift +140 -0
- package/ios/Zapiack/Storage.swift +86 -0
- package/ios/Zapiack/ZapiackLiveActivityWidget.swift +170 -0
- package/ios/Zapiack/ZapiackLiveAttributes.swift +78 -0
- package/ios/Zapiack/ZapiackPush.swift +146 -0
- package/ios/ZapiackPushModule.m +19 -0
- package/ios/ZapiackPushModule.swift +126 -0
- package/package.json +97 -4
- package/zapiack-react-native.podspec +17 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// A push template's grid layout, as Zapiack sends it in `zp_layout`: rows and stacks that share their space by weight, cut from a
|
|
4
|
+
/// 24-column grid on the server so every platform draws the same thing.
|
|
5
|
+
///
|
|
6
|
+
/// Elements are named by short references: `t` the title, `b` the body, `i` the small picture, `p` the big picture, `l<n>` the
|
|
7
|
+
/// n-th live element (`zp_live`) and `a<n>` the n-th button.
|
|
8
|
+
public struct ZapiackLayoutNode: Decodable, Hashable {
|
|
9
|
+
public let row: Bool
|
|
10
|
+
public let children: [Child]
|
|
11
|
+
|
|
12
|
+
public enum Child: Hashable {
|
|
13
|
+
case sub(weight: Int, node: ZapiackLayoutNode)
|
|
14
|
+
case element(weight: Int, ref: String, rows: Int)
|
|
15
|
+
case space(weight: Int)
|
|
16
|
+
|
|
17
|
+
public var weight: Int {
|
|
18
|
+
switch self {
|
|
19
|
+
case let .sub(w, _), let .element(w, _, _), let .space(w): return w
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// How tall one grid row is drawn, in points.
|
|
25
|
+
public static let rowPoints: CGFloat = 8
|
|
26
|
+
|
|
27
|
+
private enum Keys: String, CodingKey { case d, c }
|
|
28
|
+
private enum ChildKeys: String, CodingKey { case w, n, e, h, s }
|
|
29
|
+
|
|
30
|
+
public init(from decoder: Decoder) throws {
|
|
31
|
+
let c = try decoder.container(keyedBy: Keys.self)
|
|
32
|
+
row = (try c.decode(String.self, forKey: .d)) == "r"
|
|
33
|
+
var list = try c.nestedUnkeyedContainer(forKey: .c)
|
|
34
|
+
var out: [Child] = []
|
|
35
|
+
while !list.isAtEnd {
|
|
36
|
+
let item = try list.nestedContainer(keyedBy: ChildKeys.self)
|
|
37
|
+
let w = min(max(try item.decodeIfPresent(Int.self, forKey: .w) ?? 0, 0), 80)
|
|
38
|
+
guard w > 0 else { continue }
|
|
39
|
+
if let n = try item.decodeIfPresent(ZapiackLayoutNode.self, forKey: .n) {
|
|
40
|
+
out.append(.sub(weight: w, node: n))
|
|
41
|
+
} else if let e = try item.decodeIfPresent(String.self, forKey: .e), e.range(of: "^(t|b|i|p|l[0-9]{1,2}|a[0-9])$", options: .regularExpression) != nil {
|
|
42
|
+
out.append(.element(weight: w, ref: e, rows: min(max(try item.decodeIfPresent(Int.self, forKey: .h) ?? 1, 1), 80)))
|
|
43
|
+
} else {
|
|
44
|
+
out.append(.space(weight: w))
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
children = out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// Reads the tree from the JSON text Zapiack sends, or nil.
|
|
51
|
+
public static func parse(_ json: String?) -> ZapiackLayoutNode? {
|
|
52
|
+
guard let json, let data = json.data(using: .utf8) else { return nil }
|
|
53
|
+
return try? JSONDecoder().decode(ZapiackLayoutNode.self, from: data)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/// How tall it draws, in grid rows: a stack adds its parts up, a row is as tall as its tallest part.
|
|
57
|
+
public var rows: Int {
|
|
58
|
+
row ? children.map(Self.rows(of:)).max() ?? 0 : children.map(Self.rows(of:)).reduce(0, +)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private static func rows(of child: Child) -> Int {
|
|
62
|
+
switch child {
|
|
63
|
+
case let .sub(_, n): return n.rows
|
|
64
|
+
case let .element(_, _, r): return r
|
|
65
|
+
case let .space(w): return w
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// One live element (`zp_live`): a timer, progress, counter, date or badge, as the server filled it in.
|
|
71
|
+
public struct ZapiackLiveItem: Decodable, Hashable {
|
|
72
|
+
public let type: String
|
|
73
|
+
public let mode: String?
|
|
74
|
+
public let source: String?
|
|
75
|
+
public let format: String?
|
|
76
|
+
public let look: String?
|
|
77
|
+
public let color: String?
|
|
78
|
+
public let label: String?
|
|
79
|
+
public let onEnd: String?
|
|
80
|
+
public let expiredText: String?
|
|
81
|
+
public let steps: [String]?
|
|
82
|
+
public let current: Int?
|
|
83
|
+
public let value: String?
|
|
84
|
+
public let style: String?
|
|
85
|
+
public let text: String?
|
|
86
|
+
|
|
87
|
+
private enum Keys: String, CodingKey { case type, mode, source, format, look, color, label, onEnd, expiredText, steps, current, value, style, text }
|
|
88
|
+
|
|
89
|
+
public init(from decoder: Decoder) throws {
|
|
90
|
+
let c = try decoder.container(keyedBy: Keys.self)
|
|
91
|
+
type = try c.decode(String.self, forKey: .type)
|
|
92
|
+
mode = try c.decodeIfPresent(String.self, forKey: .mode)
|
|
93
|
+
source = try c.decodeIfPresent(String.self, forKey: .source)
|
|
94
|
+
format = try c.decodeIfPresent(String.self, forKey: .format)
|
|
95
|
+
look = try c.decodeIfPresent(String.self, forKey: .look)
|
|
96
|
+
color = try c.decodeIfPresent(String.self, forKey: .color)
|
|
97
|
+
label = try c.decodeIfPresent(String.self, forKey: .label)
|
|
98
|
+
onEnd = try c.decodeIfPresent(String.self, forKey: .onEnd)
|
|
99
|
+
expiredText = try c.decodeIfPresent(String.self, forKey: .expiredText)
|
|
100
|
+
steps = try c.decodeIfPresent([String].self, forKey: .steps)
|
|
101
|
+
current = (try? c.decodeIfPresent(Int.self, forKey: .current)) ?? (try? c.decodeIfPresent(Double.self, forKey: .current)).flatMap { $0.map(Int.init) }
|
|
102
|
+
// A counter's value is a number; a date's is text. Both are kept as text to show.
|
|
103
|
+
if let n = try? c.decodeIfPresent(Double.self, forKey: .value) {
|
|
104
|
+
value = n.rounded() == n ? String(Int(n)) : String(n)
|
|
105
|
+
} else {
|
|
106
|
+
value = try c.decodeIfPresent(String.self, forKey: .value)
|
|
107
|
+
}
|
|
108
|
+
style = try c.decodeIfPresent(String.self, forKey: .style)
|
|
109
|
+
text = try c.decodeIfPresent(String.self, forKey: .text)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
public static func parse(_ json: String?) -> [ZapiackLiveItem] {
|
|
113
|
+
guard let json, let data = json.data(using: .utf8) else { return [] }
|
|
114
|
+
return (try? JSONDecoder().decode([ZapiackLiveItem].self, from: data)) ?? []
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// When a timer ends: its date for a fixed timer, its minutes after `received` for the others.
|
|
118
|
+
public func timerEnd(received: Date) -> Date? {
|
|
119
|
+
guard type == "timer", let source else { return nil }
|
|
120
|
+
if mode == "fixed" {
|
|
121
|
+
let f = ISO8601DateFormatter()
|
|
122
|
+
f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
123
|
+
return f.date(from: source) ?? ISO8601DateFormatter().date(from: source)
|
|
124
|
+
}
|
|
125
|
+
guard let minutes = Double(source), minutes > 0 else { return nil }
|
|
126
|
+
return received.addingTimeInterval(minutes * 60)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
#if canImport(SwiftUI) && canImport(UIKit)
|
|
2
|
+
import SwiftUI
|
|
3
|
+
import UIKit
|
|
4
|
+
|
|
5
|
+
/// Everything a layout's references point at.
|
|
6
|
+
public struct ZapiackLayoutContent {
|
|
7
|
+
public var title: String
|
|
8
|
+
public var body: String?
|
|
9
|
+
public var live: [ZapiackLiveItem]
|
|
10
|
+
public var actions: [String]
|
|
11
|
+
public var background: String?
|
|
12
|
+
public var thumbnail: UIImage?
|
|
13
|
+
public var picture: UIImage?
|
|
14
|
+
/// When the push arrived: per-user timers count from here.
|
|
15
|
+
public var received: Date
|
|
16
|
+
/// Set by a Live Activity, which knows the timer's end exactly.
|
|
17
|
+
public var timerEnd: Date?
|
|
18
|
+
/// Leaves buttons out, where the system draws them itself (the notification content extension).
|
|
19
|
+
public var hideActions: Bool
|
|
20
|
+
|
|
21
|
+
public init(title: String, body: String? = nil, live: [ZapiackLiveItem] = [], actions: [String] = [], background: String? = nil, thumbnail: UIImage? = nil, picture: UIImage? = nil, received: Date = Date(), timerEnd: Date? = nil, hideActions: Bool = false) {
|
|
22
|
+
self.title = title
|
|
23
|
+
self.body = body
|
|
24
|
+
self.live = live
|
|
25
|
+
self.actions = actions
|
|
26
|
+
self.background = background
|
|
27
|
+
self.thumbnail = thumbnail
|
|
28
|
+
self.picture = picture
|
|
29
|
+
self.received = received
|
|
30
|
+
self.timerEnd = timerEnd
|
|
31
|
+
self.hideActions = hideActions
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
var dark: Bool {
|
|
35
|
+
guard let bg = background.flatMap(Color.zapiackRGB) else { return true }
|
|
36
|
+
return (bg.r * 299 + bg.g * 587 + bg.b * 114) / 1000 < 140
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Draws a Zapiack grid layout: rows share their width by weight, stacks take each element's height in grid rows. It is the same
|
|
41
|
+
/// tree Android and the dashboard draw, so a design looks the same everywhere.
|
|
42
|
+
@available(iOS 16.0, *)
|
|
43
|
+
public struct ZapiackLayoutView: View {
|
|
44
|
+
let node: ZapiackLayoutNode
|
|
45
|
+
let content: ZapiackLayoutContent
|
|
46
|
+
|
|
47
|
+
public init(node: ZapiackLayoutNode, content: ZapiackLayoutContent) {
|
|
48
|
+
self.node = node
|
|
49
|
+
self.content = content
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public var body: some View {
|
|
53
|
+
GeometryReader { g in
|
|
54
|
+
NodeView(node: node, width: g.size.width, content: content)
|
|
55
|
+
}
|
|
56
|
+
.frame(minHeight: CGFloat(node.rows) * ZapiackLayoutNode.rowPoints, alignment: .topLeading)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
@available(iOS 16.0, *)
|
|
61
|
+
struct NodeView: View {
|
|
62
|
+
let node: ZapiackLayoutNode
|
|
63
|
+
let width: CGFloat
|
|
64
|
+
let content: ZapiackLayoutContent
|
|
65
|
+
|
|
66
|
+
var body: some View {
|
|
67
|
+
let total = max(1, node.children.map(\.weight).reduce(0, +))
|
|
68
|
+
if node.row {
|
|
69
|
+
HStack(alignment: .top, spacing: 0) {
|
|
70
|
+
ForEach(Array(node.children.enumerated()), id: \.offset) { _, child in
|
|
71
|
+
cell(child, width: width * CGFloat(child.weight) / CGFloat(total))
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
VStack(alignment: .leading, spacing: 0) {
|
|
76
|
+
ForEach(Array(node.children.enumerated()), id: \.offset) { _, child in
|
|
77
|
+
cell(child, width: width)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
@ViewBuilder
|
|
84
|
+
func cell(_ child: ZapiackLayoutNode.Child, width: CGFloat) -> some View {
|
|
85
|
+
switch child {
|
|
86
|
+
case let .sub(_, n):
|
|
87
|
+
NodeView(node: n, width: width, content: content).frame(width: width, alignment: .topLeading)
|
|
88
|
+
case let .space(w):
|
|
89
|
+
Color.clear.frame(width: width, height: node.row ? 1 : CGFloat(w) * ZapiackLayoutNode.rowPoints)
|
|
90
|
+
case let .element(_, ref, rows):
|
|
91
|
+
ElementView(ref: ref, content: content)
|
|
92
|
+
.padding(2)
|
|
93
|
+
.frame(width: width, alignment: .topLeading)
|
|
94
|
+
.frame(minHeight: CGFloat(rows) * ZapiackLayoutNode.rowPoints, alignment: .topLeading)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
@available(iOS 16.0, *)
|
|
100
|
+
struct ElementView: View {
|
|
101
|
+
let ref: String
|
|
102
|
+
let content: ZapiackLayoutContent
|
|
103
|
+
|
|
104
|
+
private var ink: Color { content.dark ? .white : Color(red: 0.07, green: 0.07, blue: 0.07) }
|
|
105
|
+
private var muted: Color { ink.opacity(0.7) }
|
|
106
|
+
|
|
107
|
+
var body: some View {
|
|
108
|
+
switch ref.first {
|
|
109
|
+
case "t":
|
|
110
|
+
Text(content.title).font(.headline).foregroundStyle(ink).lineLimit(2)
|
|
111
|
+
case "b":
|
|
112
|
+
Text(content.body ?? "").font(.subheadline).foregroundStyle(muted).lineLimit(4)
|
|
113
|
+
case "i", "p":
|
|
114
|
+
if let image = ref == "i" ? content.thumbnail : content.picture {
|
|
115
|
+
Image(uiImage: image).resizable().scaledToFill().frame(maxWidth: .infinity, maxHeight: .infinity).clipped().clipShape(RoundedRectangle(cornerRadius: 10))
|
|
116
|
+
}
|
|
117
|
+
case "a":
|
|
118
|
+
if !content.hideActions, let i = Int(ref.dropFirst()), i < content.actions.count {
|
|
119
|
+
Text(content.actions[i])
|
|
120
|
+
.font(.footnote.weight(.semibold))
|
|
121
|
+
.lineLimit(1)
|
|
122
|
+
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
123
|
+
.padding(.vertical, 8)
|
|
124
|
+
.foregroundStyle(i == 0 ? (content.dark ? Color.black : Color.white) : ink)
|
|
125
|
+
.background(RoundedRectangle(cornerRadius: 10).fill(i == 0 ? ink : ink.opacity(0.14)))
|
|
126
|
+
}
|
|
127
|
+
case "l":
|
|
128
|
+
if let i = Int(ref.dropFirst()), i < content.live.count {
|
|
129
|
+
LiveItemView(item: content.live[i], content: content, ink: ink, muted: muted)
|
|
130
|
+
}
|
|
131
|
+
default:
|
|
132
|
+
EmptyView()
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
@available(iOS 16.0, *)
|
|
138
|
+
struct LiveItemView: View {
|
|
139
|
+
let item: ZapiackLiveItem
|
|
140
|
+
let content: ZapiackLayoutContent
|
|
141
|
+
let ink: Color
|
|
142
|
+
let muted: Color
|
|
143
|
+
|
|
144
|
+
var body: some View {
|
|
145
|
+
let color = item.color.flatMap(Color.init(zapiackHex:)) ?? ink
|
|
146
|
+
switch item.type {
|
|
147
|
+
case "timer":
|
|
148
|
+
if let end = content.timerEnd ?? item.timerEnd(received: content.received) {
|
|
149
|
+
VStack(alignment: .leading, spacing: 2) {
|
|
150
|
+
if end <= Date() {
|
|
151
|
+
switch item.onEnd {
|
|
152
|
+
case "hide": EmptyView()
|
|
153
|
+
case "expired": Text(item.expiredText ?? "").font(.subheadline.weight(.semibold)).foregroundStyle(color)
|
|
154
|
+
default: Text(item.format == "mmss" ? "00:00" : "0:00:00").font(.title.bold()).monospacedDigit().foregroundStyle(color)
|
|
155
|
+
}
|
|
156
|
+
} else if item.format == "dhm" {
|
|
157
|
+
Text(end, style: .relative).font(.title3.bold()).foregroundStyle(color)
|
|
158
|
+
} else {
|
|
159
|
+
Text(timerInterval: Date()...end, countsDown: true).font(.title.bold()).monospacedDigit().foregroundStyle(color)
|
|
160
|
+
}
|
|
161
|
+
if let label = item.label, !label.isEmpty { Text(label).font(.caption.weight(.medium)).foregroundStyle(item.look == "pills" ? muted : color).lineLimit(2) }
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
case "progress":
|
|
165
|
+
if let steps = item.steps, steps.count >= 2 {
|
|
166
|
+
let done = min(max(item.current ?? 0, 0), steps.count)
|
|
167
|
+
VStack(alignment: .leading, spacing: 4) {
|
|
168
|
+
HStack(spacing: 4) {
|
|
169
|
+
ForEach(0..<steps.count, id: \.self) { i in Capsule().fill(i < done ? color : ink.opacity(0.18)).frame(height: 4) }
|
|
170
|
+
}
|
|
171
|
+
HStack(spacing: 4) {
|
|
172
|
+
ForEach(0..<steps.count, id: \.self) { i in
|
|
173
|
+
Text(steps[i]).font(.caption2).foregroundStyle(muted).lineLimit(1).frame(maxWidth: .infinity, alignment: i == 0 ? .leading : i == steps.count - 1 ? .trailing : .center)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
case "counter":
|
|
179
|
+
HStack(alignment: .firstTextBaseline, spacing: 4) {
|
|
180
|
+
Text(item.value ?? "").font(.title3.bold()).foregroundStyle(color)
|
|
181
|
+
Text(item.label ?? "").font(.footnote).foregroundStyle(muted)
|
|
182
|
+
}
|
|
183
|
+
case "badge":
|
|
184
|
+
Text(item.text ?? "").font(.caption2.weight(.semibold)).padding(.horizontal, 8).padding(.vertical, 2).background(Capsule().fill(color)).foregroundStyle(.white)
|
|
185
|
+
case "date":
|
|
186
|
+
Text(item.value ?? "").font(.footnote).foregroundStyle(muted)
|
|
187
|
+
default:
|
|
188
|
+
EmptyView()
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
extension Color {
|
|
194
|
+
/// A #RRGGBB colour, or nil.
|
|
195
|
+
public init?(zapiackHex hex: String) {
|
|
196
|
+
guard let rgb = Color.zapiackRGB(hex) else { return nil }
|
|
197
|
+
self.init(red: rgb.r / 255, green: rgb.g / 255, blue: rgb.b / 255)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
static func zapiackRGB(_ hex: String) -> (r: Double, g: Double, b: Double)? {
|
|
201
|
+
let s = hex.trimmingCharacters(in: .whitespaces)
|
|
202
|
+
guard s.count == 7, s.hasPrefix("#"), let n = UInt32(s.dropFirst(), radix: 16) else { return nil }
|
|
203
|
+
return (Double((n >> 16) & 0xFF), Double((n >> 8) & 0xFF), Double(n & 0xFF))
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
#endif
|
|
@@ -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, Sendable {
|
|
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,140 @@
|
|
|
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
|
+
/// The push-to-start token for Live Activities, when the app turned them on (iOS 17.2+).
|
|
26
|
+
public var liveActivityToken: String? { storage.string(forKey: "zapiack.live-token") }
|
|
27
|
+
|
|
28
|
+
public func setLiveActivityToken(_ data: Data) {
|
|
29
|
+
storage.set(data.map { String(format: "%02x", $0) }.joined(), forKey: "zapiack.live-token")
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
public func setDeviceToken(_ data: Data) {
|
|
33
|
+
storage.set(data.map { String(format: "%02x", $0) }.joined(), forKey: "zapiack.token")
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private var tags: [String: JSONValue] {
|
|
37
|
+
get {
|
|
38
|
+
guard let raw = storage.string(forKey: SharedState.Key.tags), let data = raw.data(using: .utf8),
|
|
39
|
+
let value = try? JSONDecoder().decode([String: JSONValue].self, from: data) else { return [:] }
|
|
40
|
+
return value
|
|
41
|
+
}
|
|
42
|
+
set {
|
|
43
|
+
let data = try? JSONEncoder().encode(newValue)
|
|
44
|
+
storage.set(data.flatMap { String(data: $0, encoding: .utf8) }, forKey: SharedState.Key.tags)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// "set:<id>" or "clear": a change of user that has not reached the service yet.
|
|
49
|
+
private var pendingUser: String? {
|
|
50
|
+
get { storage.string(forKey: SharedState.Key.user) }
|
|
51
|
+
set { storage.set(newValue, forKey: SharedState.Key.user) }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
public func login(_ userId: String) { pendingUser = "set:\(userId)" }
|
|
55
|
+
public func logout() { pendingUser = "clear" }
|
|
56
|
+
|
|
57
|
+
public func addTags(_ new: [String: JSONValue]) {
|
|
58
|
+
var current = tags
|
|
59
|
+
for (key, value) in new { current[key] = value }
|
|
60
|
+
tags = current
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public func removeTags(_ keys: [String]) {
|
|
64
|
+
var current = tags
|
|
65
|
+
for key in keys { current.removeValue(forKey: key) }
|
|
66
|
+
tags = current
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// Tells the service about this install. Sent on every start; a change of user goes once and is then forgotten.
|
|
70
|
+
public func register(permission: String?, environment: String, appVersion: String?) async throws {
|
|
71
|
+
guard let token = deviceToken else { return }
|
|
72
|
+
let user = pendingUser
|
|
73
|
+
var external: String?? = nil
|
|
74
|
+
if let user {
|
|
75
|
+
external = user == "clear" ? .some(nil) : .some(String(user.dropFirst(4)))
|
|
76
|
+
}
|
|
77
|
+
let registration = DeviceRegistration(
|
|
78
|
+
installationId: config.installationId,
|
|
79
|
+
token: token,
|
|
80
|
+
externalUserId: external,
|
|
81
|
+
tags: tags.isEmpty ? nil : tags,
|
|
82
|
+
permission: permission,
|
|
83
|
+
environment: environment,
|
|
84
|
+
appVersion: appVersion,
|
|
85
|
+
liveActivityToken: liveActivityToken
|
|
86
|
+
)
|
|
87
|
+
try await api.register(registration)
|
|
88
|
+
// Only forget the change if it is still the one that was sent.
|
|
89
|
+
if pendingUser == user { pendingUser = nil }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// MARK: Taps and what follows
|
|
93
|
+
|
|
94
|
+
public var activeSession: ActiveSession? {
|
|
95
|
+
get {
|
|
96
|
+
guard let raw = storage.string(forKey: SharedState.Key.session), let data = raw.data(using: .utf8),
|
|
97
|
+
let session = try? JSONDecoder().decode(ActiveSession.self, from: data) else { return nil }
|
|
98
|
+
return session.isOpen(at: now()) ? session : nil
|
|
99
|
+
}
|
|
100
|
+
set {
|
|
101
|
+
let data = newValue.flatMap { try? JSONEncoder().encode($0) }
|
|
102
|
+
storage.set(data.flatMap { String(data: $0, encoding: .utf8) }, forKey: SharedState.Key.session)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// Reports a tap and opens its window. Returns what the app needs to route, or nil when it was a dismissal or not ours.
|
|
107
|
+
public func handleResponse(userInfo: [AnyHashable: Any], actionIdentifier: String) -> Tap? {
|
|
108
|
+
guard let block = PushBlock(userInfo: userInfo),
|
|
109
|
+
let result = Processing.tap(block: block, actionIdentifier: actionIdentifier, at: now()) else { return nil }
|
|
110
|
+
// Last tap wins: a new tap replaces the window of the one before it.
|
|
111
|
+
activeSession = result.session
|
|
112
|
+
lock.lock(); previousScreen = nil; lock.unlock()
|
|
113
|
+
for event in result.events { queue.add(event, now: now()) }
|
|
114
|
+
return result.tap
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// A screen the user reached. Only recorded while a tapped push's window is open and the push asked for screens.
|
|
118
|
+
public func screen(_ name: String) {
|
|
119
|
+
guard let session = activeSession, session.screens else { return }
|
|
120
|
+
lock.lock()
|
|
121
|
+
let from = previousScreen
|
|
122
|
+
previousScreen = name
|
|
123
|
+
lock.unlock()
|
|
124
|
+
queue.add(SdkEvent(type: .screen, deliveryId: session.deliveryId, sessionId: session.sessionId, name: name, previousScreen: from, at: now()), now: now())
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// A named thing the user did. Credited to the tapped push while its window is open; otherwise there is nothing to credit.
|
|
128
|
+
/// Returns whether there was a tapped push to credit it to.
|
|
129
|
+
@discardableResult
|
|
130
|
+
public func track(_ name: String, properties: [String: JSONValue]? = nil) -> Bool {
|
|
131
|
+
guard let session = activeSession else { return false }
|
|
132
|
+
queue.add(SdkEvent(type: .custom, deliveryId: session.deliveryId, sessionId: session.sessionId, name: name, properties: properties, at: now()), now: now())
|
|
133
|
+
return true
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
@discardableResult
|
|
137
|
+
public func flush() async -> Bool {
|
|
138
|
+
await queue.flush(using: api, now: now())
|
|
139
|
+
}
|
|
140
|
+
}
|