@anglerai/react-native-analytics 0.0.0-stage → 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AnglerAnalyticsRN.podspec +25 -0
- package/LICENSE +21 -0
- package/README.md +92 -2
- package/android/build.gradle +64 -0
- package/android/src/main/java/ai/getangler/analytics/reactnative/AnglerAnalyticsModule.kt +51 -0
- package/android/src/main/java/ai/getangler/analytics/reactnative/AnglerAnalyticsPackage.kt +25 -0
- package/android/src/main/java/ai/getangler/analytics/reactnative/ConfigParser.kt +58 -0
- package/android/src/test/java/ai/getangler/analytics/reactnative/ConfigParserTest.kt +51 -0
- package/ios/AnglerAnalyticsBridge.swift +58 -0
- package/ios/AnglerAnalyticsRN.mm +84 -0
- package/ios/vendor/AnglerAnalytics/Angler.swift +132 -0
- package/ios/vendor/AnglerAnalytics/AnglerCore.swift +398 -0
- package/ios/vendor/AnglerAnalytics/Attribution/AttributionStore.swift +109 -0
- package/ios/vendor/AnglerAnalytics/Attribution/ClickIdParser.swift +52 -0
- package/ios/vendor/AnglerAnalytics/Device/AdIdProvider.swift +36 -0
- package/ios/vendor/AnglerAnalytics/Device/DeviceContext.swift +111 -0
- package/ios/vendor/AnglerAnalytics/Device/FirebaseIdProvider.swift +35 -0
- package/ios/vendor/AnglerAnalytics/Lifecycle/LifecycleObserver.swift +77 -0
- package/ios/vendor/AnglerAnalytics/Lifecycle/SharedApplication.swift +15 -0
- package/ios/vendor/AnglerAnalytics/Log.swift +24 -0
- package/ios/vendor/AnglerAnalytics/Network/Flusher.swift +112 -0
- package/ios/vendor/AnglerAnalytics/Network/ResponsePolicy.swift +29 -0
- package/ios/vendor/AnglerAnalytics/Network/Scheduler.swift +13 -0
- package/ios/vendor/AnglerAnalytics/Network/Transport.swift +55 -0
- package/ios/vendor/AnglerAnalytics/Payload/JSONValue.swift +81 -0
- package/ios/vendor/AnglerAnalytics/Payload/Models.generated.swift +580 -0
- package/ios/vendor/AnglerAnalytics/Payload/PayloadBuilder.swift +148 -0
- package/ios/vendor/AnglerAnalytics/Payload/StandardEvent.swift +26 -0
- package/ios/vendor/AnglerAnalytics/Payload/TypedModels.swift +14 -0
- package/ios/vendor/AnglerAnalytics/Resources/PrivacyInfo.xcprivacy +77 -0
- package/ios/vendor/AnglerAnalytics/Storage/Clock.swift +14 -0
- package/ios/vendor/AnglerAnalytics/Storage/EventQueue.swift +85 -0
- package/ios/vendor/AnglerAnalytics/Storage/IdentityStore.swift +76 -0
- package/ios/vendor/AnglerAnalytics/Storage/KeyValueStore.swift +38 -0
- package/ios/vendor/AnglerAnalytics/Version.swift +4 -0
- package/package.json +46 -4
- package/src/NativeAnglerAnalytics.ts +21 -0
- package/src/index.ts +159 -0
- package/src/models.generated.ts +347 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(UIKit)
|
|
3
|
+
import UIKit
|
|
4
|
+
#endif
|
|
5
|
+
|
|
6
|
+
/// Keeps a background flush alive after the app leaves the foreground.
|
|
7
|
+
protocol BackgroundTasking {
|
|
8
|
+
func begin() -> Int?
|
|
9
|
+
func end(_ id: Int?)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
#if canImport(UIKit) && os(iOS)
|
|
13
|
+
/// `beginBackgroundTask` / `endBackgroundTask`, always called on the main thread.
|
|
14
|
+
struct UIKitBackgroundTasks: BackgroundTasking {
|
|
15
|
+
func begin() -> Int? {
|
|
16
|
+
guard Thread.isMainThread, let app = UIApplication.anglerShared else { return nil }
|
|
17
|
+
return MainActor.assumeIsolated {
|
|
18
|
+
let box = TaskIdBox()
|
|
19
|
+
box.id = app.beginBackgroundTask(withName: "ai.getangler.analytics.flush") {
|
|
20
|
+
app.endBackgroundTask(box.id)
|
|
21
|
+
}
|
|
22
|
+
return box.id == .invalid ? nil : box.id.rawValue
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// Only touched on the main thread.
|
|
27
|
+
private final class TaskIdBox: @unchecked Sendable {
|
|
28
|
+
var id: UIBackgroundTaskIdentifier = .invalid
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
func end(_ id: Int?) {
|
|
32
|
+
guard let id else { return }
|
|
33
|
+
DispatchQueue.main.async {
|
|
34
|
+
MainActor.assumeIsolated {
|
|
35
|
+
UIApplication.anglerShared?.endBackgroundTask(UIBackgroundTaskIdentifier(rawValue: id))
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
#endif
|
|
41
|
+
|
|
42
|
+
/// All SDK state lives here and is only touched on `queue` (design §3).
|
|
43
|
+
final class AnglerCore {
|
|
44
|
+
static let queueLabel = "ai.getangler.analytics"
|
|
45
|
+
static let batchSize = 100
|
|
46
|
+
static let src = "IOS"
|
|
47
|
+
|
|
48
|
+
let queue: DispatchQueue
|
|
49
|
+
private let queueKey = DispatchSpecificKey<Void>()
|
|
50
|
+
|
|
51
|
+
private let clock: Clock
|
|
52
|
+
private let queueDirectory: URL
|
|
53
|
+
private let transportFactory: (AnglerConfiguration) -> Transport
|
|
54
|
+
private let adIds: AdIdProviding
|
|
55
|
+
private let firebase: FirebaseIdProviding
|
|
56
|
+
private let device: (AnglerConfiguration, Bool, Bool) -> DeviceSnapshot
|
|
57
|
+
private let uuid: () -> String
|
|
58
|
+
private let scheduler: Scheduler
|
|
59
|
+
private let lifecycleNotifications: LifecycleNotifications?
|
|
60
|
+
private let backgroundTasks: BackgroundTasking?
|
|
61
|
+
private let protectedData: ProtectedDataGate?
|
|
62
|
+
private var deferredConfig: AnglerConfiguration?
|
|
63
|
+
private var protectedDataToken: NSObjectProtocol?
|
|
64
|
+
|
|
65
|
+
private let store: KeyValueStore
|
|
66
|
+
private let identity: IdentityStore
|
|
67
|
+
private let attribution: AttributionStore
|
|
68
|
+
/// Set once this process has seen the app in the foreground (its cold-start launch).
|
|
69
|
+
private var sawFirstForeground = false
|
|
70
|
+
private static let lastBackgroundKey = "last_background_ms"
|
|
71
|
+
|
|
72
|
+
private(set) var configuration: AnglerConfiguration?
|
|
73
|
+
private(set) var eventQueue: EventQueue?
|
|
74
|
+
private var flusher: Flusher?
|
|
75
|
+
private var lifecycleObserver: LifecycleObserver?
|
|
76
|
+
|
|
77
|
+
init(store: KeyValueStore,
|
|
78
|
+
clock: Clock,
|
|
79
|
+
queueDirectory: URL,
|
|
80
|
+
transportFactory: @escaping (AnglerConfiguration) -> Transport,
|
|
81
|
+
adIds: AdIdProviding,
|
|
82
|
+
device: @escaping (AnglerConfiguration, Bool, Bool) -> DeviceSnapshot,
|
|
83
|
+
uuid: @escaping () -> String,
|
|
84
|
+
scheduler: Scheduler,
|
|
85
|
+
lifecycle: LifecycleNotifications?,
|
|
86
|
+
backgroundTasks: BackgroundTasking?,
|
|
87
|
+
protectedData: ProtectedDataGate? = nil,
|
|
88
|
+
firebase: FirebaseIdProviding = NoFirebaseIdProvider(),
|
|
89
|
+
queue: DispatchQueue = DispatchQueue(label: AnglerCore.queueLabel)) {
|
|
90
|
+
self.clock = clock
|
|
91
|
+
self.queueDirectory = queueDirectory
|
|
92
|
+
self.transportFactory = transportFactory
|
|
93
|
+
self.adIds = adIds
|
|
94
|
+
self.firebase = firebase
|
|
95
|
+
self.device = device
|
|
96
|
+
self.uuid = uuid
|
|
97
|
+
self.scheduler = scheduler
|
|
98
|
+
self.lifecycleNotifications = lifecycle
|
|
99
|
+
self.backgroundTasks = backgroundTasks
|
|
100
|
+
self.protectedData = protectedData
|
|
101
|
+
self.queue = queue
|
|
102
|
+
self.store = store
|
|
103
|
+
identity = IdentityStore(store: store)
|
|
104
|
+
attribution = AttributionStore(store: store, clock: clock)
|
|
105
|
+
queue.setSpecific(key: queueKey, value: ())
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// MARK: - Public operations (any thread)
|
|
109
|
+
|
|
110
|
+
func configure(_ config: AnglerConfiguration) {
|
|
111
|
+
startObservingLifecycle()
|
|
112
|
+
if deferUntilProtectedDataAvailable(config) { return }
|
|
113
|
+
queue.async { self.doConfigure(config) }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// Before the first unlock after a reboot, UserDefaults reads as empty: configuring then
|
|
117
|
+
/// would mint a new install ID and send a duplicate app_installed. Waits for the unlock
|
|
118
|
+
/// instead. Returns true if configure was deferred.
|
|
119
|
+
private func deferUntilProtectedDataAvailable(_ config: AnglerConfiguration) -> Bool {
|
|
120
|
+
guard let gate = protectedData else { return false }
|
|
121
|
+
observerLock.lock()
|
|
122
|
+
defer { observerLock.unlock() }
|
|
123
|
+
if protectedDataToken == nil {
|
|
124
|
+
guard !gate.isAvailable() else { return false }
|
|
125
|
+
Log.debug("configure: waiting for the device to be unlocked")
|
|
126
|
+
deferredConfig = config
|
|
127
|
+
protectedDataToken = gate.center.addObserver(forName: gate.becameAvailable, object: nil, queue: nil) { [weak self] _ in
|
|
128
|
+
self?.protectedDataBecameAvailable()
|
|
129
|
+
}
|
|
130
|
+
// It may have become available between the check and the observer.
|
|
131
|
+
if gate.isAvailable() {
|
|
132
|
+
DispatchQueue.main.async { [weak self] in self?.protectedDataBecameAvailable() }
|
|
133
|
+
}
|
|
134
|
+
return true
|
|
135
|
+
}
|
|
136
|
+
if deferredConfig != nil { return true } // still waiting; the first config wins
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private func protectedDataBecameAvailable() {
|
|
141
|
+
observerLock.lock()
|
|
142
|
+
let config = deferredConfig
|
|
143
|
+
deferredConfig = nil
|
|
144
|
+
observerLock.unlock()
|
|
145
|
+
guard let config else { return }
|
|
146
|
+
queue.async { self.doConfigure(config) }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private let observerLock = NSLock()
|
|
150
|
+
|
|
151
|
+
/// Observes the lifecycle from the first configure call, on the caller's thread, so a
|
|
152
|
+
/// didBecomeActive posted before the queued configure work runs isn't missed (handlers
|
|
153
|
+
/// queue behind it). The cold-start app_launched is recorded on the first foreground, not
|
|
154
|
+
/// at configure: configure also runs for background launches (silent push, background
|
|
155
|
+
/// fetch), and the URL that opened the app is delivered after configure.
|
|
156
|
+
private func startObservingLifecycle() {
|
|
157
|
+
observerLock.lock()
|
|
158
|
+
defer { observerLock.unlock() }
|
|
159
|
+
guard lifecycleObserver == nil, let notifications = lifecycleNotifications else { return }
|
|
160
|
+
lifecycleObserver = LifecycleObserver(
|
|
161
|
+
notifications: notifications,
|
|
162
|
+
onForeground: { [weak self] in self?.didBecomeActive() },
|
|
163
|
+
onBackground: { [weak self] in self?.didEnterBackground() }
|
|
164
|
+
)
|
|
165
|
+
if let isActive = notifications.isActive {
|
|
166
|
+
// Wrappers configure after the app is already active, so that first didBecomeActive
|
|
167
|
+
// has passed. A duplicate is ignored (see handleForeground).
|
|
168
|
+
DispatchQueue.main.async { [weak self] in
|
|
169
|
+
if isActive() { self?.didBecomeActive() }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
func track(_ name: String, data: [String: Any]? = nil, properties: [String: String]? = nil, eventId: String? = nil) {
|
|
175
|
+
// Everything time- or consent-dependent is read at call time (design §5 snapshot rule).
|
|
176
|
+
let now = clock.now()
|
|
177
|
+
let generatedId = uuid()
|
|
178
|
+
let ad = adIds.current()
|
|
179
|
+
var json: [String: JSONValue]?
|
|
180
|
+
if let data {
|
|
181
|
+
json = [:]
|
|
182
|
+
for (k, v) in data {
|
|
183
|
+
if let j = JSONValue.from(v) { json?[k] = j } else { Log.debug("dropping data['\(k)']: not representable as JSON") }
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
let call = TrackCall(name: name, data: json, properties: properties, eventId: eventId)
|
|
187
|
+
queue.async { self.record(call, at: now, generatedId: generatedId, idfa: ad.idfa, authorized: ad.authorized) }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
func track(_ event: AnglerEvent, data: AnglerData? = nil, properties: [String: String]? = nil, eventId: String? = nil) {
|
|
191
|
+
track(event.name, data: data?.jsonObject, properties: properties, eventId: eventId)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
func handleDeepLink(urlString: String) {
|
|
195
|
+
queue.async {
|
|
196
|
+
guard self.identity.isEnabled else { return }
|
|
197
|
+
self.attribution.capture(clickIds: ClickIdParser.parse(url: urlString), url: urlString)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
func setUserId(_ userId: String?) {
|
|
202
|
+
queue.async { self.identity.customerId = (userId?.isEmpty ?? true) ? nil : userId }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
func setIdentifier(_ name: String, value: String?) {
|
|
206
|
+
queue.async {
|
|
207
|
+
if !self.identity.setIdentifier(name, value: value) {
|
|
208
|
+
Log.warning("setIdentifier('\(name)') ignored: reserved or empty identifier name")
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
func setApplicationTrackingEnabled(_ enabled: Bool) {
|
|
214
|
+
queue.async { self.identity.applicationTrackingEnabled = enabled }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
func setEnabled(_ enabled: Bool) {
|
|
218
|
+
queue.async {
|
|
219
|
+
self.identity.isEnabled = enabled
|
|
220
|
+
if !enabled { self.eventQueue?.removeAll() }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
func flush() {
|
|
225
|
+
queue.async { self.flusher?.flush(completion: nil) }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
func reset() {
|
|
229
|
+
queue.async {
|
|
230
|
+
self.identity.reset()
|
|
231
|
+
self.attribution.clear()
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// MARK: - On queue
|
|
236
|
+
|
|
237
|
+
private func doConfigure(_ config: AnglerConfiguration) {
|
|
238
|
+
if let current = configuration {
|
|
239
|
+
if current.workspaceId == config.workspaceId {
|
|
240
|
+
Log.debug("configure: already configured; ignoring repeat call")
|
|
241
|
+
} else {
|
|
242
|
+
Log.warning("configure: already configured for workspace '\(current.workspaceId)'; ignoring '\(config.workspaceId)'")
|
|
243
|
+
}
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
guard !config.workspaceId.isEmpty, !config.token.isEmpty else {
|
|
247
|
+
Log.warning("configure: workspaceId and token are required")
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
guard URLSessionTransport.endpoint(domain: config.domain, workspaceId: config.workspaceId) != nil else {
|
|
251
|
+
Log.error("configure: invalid domain '\(config.domain)'; expected a host such as data.getangler.ai")
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
Log.debugEnabled = config.debugLogging
|
|
255
|
+
configuration = config
|
|
256
|
+
|
|
257
|
+
let file = queueDirectory.appendingPathComponent("queue-\(Self.fileSafe(config.workspaceId)).json")
|
|
258
|
+
let events = EventQueue(fileURL: file, maxSize: config.maxQueueSize)
|
|
259
|
+
eventQueue = events
|
|
260
|
+
flusher = Flusher(queue: events,
|
|
261
|
+
transport: QueueHoppingTransport(base: transportFactory(config), core: self),
|
|
262
|
+
src: Self.src,
|
|
263
|
+
batchSize: Self.batchSize,
|
|
264
|
+
scheduler: QueueHoppingScheduler(base: scheduler, queue: queue),
|
|
265
|
+
random: { Double.random(in: 0..<1) })
|
|
266
|
+
|
|
267
|
+
let isNewInstall = identity.ensureAid().isNew
|
|
268
|
+
if !identity.isEnabled {
|
|
269
|
+
events.removeAll()
|
|
270
|
+
} else if config.trackLifecycleEvents && isNewInstall {
|
|
271
|
+
let ad = adIds.current()
|
|
272
|
+
record(TrackCall(name: "app_installed"), at: clock.now(), generatedId: uuid(), idfa: ad.idfa, authorized: ad.authorized)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
scheduleFlushTimer(interval: config.flushInterval)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private func record(_ call: TrackCall, at date: Date, generatedId: String, idfa: String?, authorized: Bool) {
|
|
279
|
+
guard let config = configuration, let events = eventQueue else {
|
|
280
|
+
Log.warning("track('\(call.name)') dropped: call Angler.configure first")
|
|
281
|
+
return
|
|
282
|
+
}
|
|
283
|
+
guard identity.isEnabled else { return }
|
|
284
|
+
guard !call.name.isEmpty else {
|
|
285
|
+
Log.warning("track: event name is empty; dropped")
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
let event = PayloadBuilder.buildEvent(
|
|
289
|
+
call: call,
|
|
290
|
+
generatedEventId: generatedId,
|
|
291
|
+
timestamp: PayloadBuilder.timestamp(date),
|
|
292
|
+
clientIdOverride: config.clientId,
|
|
293
|
+
identity: IdentitySnapshot(aid: identity.ensureAid().aid, customerId: identity.customerId,
|
|
294
|
+
adIdName: "idfa", adId: idfa, custom: customIdentifiers()),
|
|
295
|
+
attribution: attribution.snapshot(),
|
|
296
|
+
device: device(config, authorized, identity.applicationTrackingEnabled),
|
|
297
|
+
referrer: nil
|
|
298
|
+
)
|
|
299
|
+
events.append(event)
|
|
300
|
+
Log.debug("queued \(call.name) (\(events.count) in queue)")
|
|
301
|
+
if events.count >= config.flushAt { flusher?.flush(completion: nil) }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/// The host's custom identifiers plus the Firebase app instance ID, unless the host set one.
|
|
305
|
+
private func customIdentifiers() -> [String: String] {
|
|
306
|
+
var ids = identity.customIdentifiers
|
|
307
|
+
if ids[Self.firebaseIdName] == nil, let id = firebase.appInstanceId() { ids[Self.firebaseIdName] = id }
|
|
308
|
+
return ids
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
static let firebaseIdName = "firebase_app_instance_id"
|
|
312
|
+
|
|
313
|
+
private func scheduleFlushTimer(interval: TimeInterval) {
|
|
314
|
+
guard interval > 0 else { return }
|
|
315
|
+
QueueHoppingScheduler(base: scheduler, queue: queue).schedule(after: interval) { [weak self] in
|
|
316
|
+
guard let self else { return }
|
|
317
|
+
if (self.eventQueue?.count ?? 0) > 0 { self.flusher?.flush(completion: nil) }
|
|
318
|
+
self.scheduleFlushTimer(interval: interval)
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/// Called on the posting thread (main for UIKit).
|
|
323
|
+
private func didEnterBackground() {
|
|
324
|
+
let now = clock.now()
|
|
325
|
+
let task = backgroundTasks?.begin()
|
|
326
|
+
queue.async {
|
|
327
|
+
// Persisted, so a later process can tell how long the app was away.
|
|
328
|
+
self.store.set(String(now.epochMillis), for: Self.lastBackgroundKey)
|
|
329
|
+
guard let flusher = self.flusher, (self.eventQueue?.count ?? 0) > 0 else {
|
|
330
|
+
self.backgroundTasks?.end(task)
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
flusher.flush { self.backgroundTasks?.end(task) }
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
private func didBecomeActive() {
|
|
338
|
+
let now = clock.now()
|
|
339
|
+
let ad = adIds.current()
|
|
340
|
+
let launchId = uuid()
|
|
341
|
+
queue.async { self.handleForeground(at: now, launchId: launchId, idfa: ad.idfa, authorized: ad.authorized) }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/// A cold start's first foreground, or a return after 30+ minutes in the background, is a
|
|
345
|
+
/// new session (design §6.3, §9): `app_launched`, and a session URL from before that
|
|
346
|
+
/// background is cleared. Becoming active without a background in between is ignored.
|
|
347
|
+
private func handleForeground(at now: Date, launchId: String, idfa: String?, authorized: Bool) {
|
|
348
|
+
guard let config = configuration else { return }
|
|
349
|
+
let lastBackground = store.string(Self.lastBackgroundKey).flatMap(Int64.init)
|
|
350
|
+
let coldStart = !sawFirstForeground
|
|
351
|
+
guard coldStart || lastBackground != nil else { return }
|
|
352
|
+
sawFirstForeground = true
|
|
353
|
+
store.set(nil, for: Self.lastBackgroundKey)
|
|
354
|
+
|
|
355
|
+
var newSession = coldStart
|
|
356
|
+
if let lastBackground,
|
|
357
|
+
LifecycleObserver.isNewSession(backgroundedFor: TimeInterval(now.epochMillis - lastBackground) / 1000) {
|
|
358
|
+
attribution.clearSessionURL(capturedAtOrBefore: lastBackground)
|
|
359
|
+
newSession = true
|
|
360
|
+
}
|
|
361
|
+
if newSession && config.trackLifecycleEvents && identity.isEnabled {
|
|
362
|
+
record(TrackCall(name: "app_launched"), at: now, generatedId: launchId, idfa: idfa, authorized: authorized)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
fileprivate var isOnQueue: Bool { DispatchQueue.getSpecific(key: queueKey) != nil }
|
|
367
|
+
|
|
368
|
+
private static func fileSafe(_ s: String) -> String {
|
|
369
|
+
String(s.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) || $0 == "-" || $0 == "_" ? Character($0) : "_" })
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
extension TrackCall {
|
|
374
|
+
init(name: String) { self.init(name: name, data: nil, properties: nil, eventId: nil) }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/// Delivers transport callbacks on the core queue (directly if already there).
|
|
378
|
+
private struct QueueHoppingTransport: Transport {
|
|
379
|
+
let base: Transport
|
|
380
|
+
weak var core: AnglerCore?
|
|
381
|
+
|
|
382
|
+
func send(_ body: Data, completion: @escaping (Int?) -> Void) {
|
|
383
|
+
base.send(body) { status in
|
|
384
|
+
guard let core else { return }
|
|
385
|
+
if core.isOnQueue { completion(status) } else { core.queue.async { completion(status) } }
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/// Runs scheduled work on the core queue.
|
|
391
|
+
private struct QueueHoppingScheduler: Scheduler {
|
|
392
|
+
let base: Scheduler
|
|
393
|
+
let queue: DispatchQueue
|
|
394
|
+
|
|
395
|
+
func schedule(after delay: TimeInterval, _ work: @escaping () -> Void) {
|
|
396
|
+
base.schedule(after: delay) { [queue] in queue.async(execute: work) }
|
|
397
|
+
}
|
|
398
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
struct AttributionSnapshot: Equatable {
|
|
4
|
+
var clickIds: [String: String]
|
|
5
|
+
var fbc: String?
|
|
6
|
+
var url: String?
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/// Persists click IDs, `fbc` and the session URL (design §6.2, §6.3).
|
|
10
|
+
final class AttributionStore {
|
|
11
|
+
static let clickIdTTLMillis: Int64 = 400 * 86_400 * 1000
|
|
12
|
+
|
|
13
|
+
private enum Key {
|
|
14
|
+
static let clickIds = "click_ids"
|
|
15
|
+
static let fbc = "fbc"
|
|
16
|
+
static let sessionURL = "session_url"
|
|
17
|
+
static let sessionURLAt = "session_url_at"
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
private struct Entry: Codable {
|
|
21
|
+
var value: String
|
|
22
|
+
var capturedAtMs: Int64
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private struct FbcEntry: Codable {
|
|
26
|
+
var value: String
|
|
27
|
+
var fbclid: String
|
|
28
|
+
var capturedAtMs: Int64
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private let store: KeyValueStore
|
|
32
|
+
private let clock: Clock
|
|
33
|
+
|
|
34
|
+
init(store: KeyValueStore, clock: Clock) {
|
|
35
|
+
self.store = store
|
|
36
|
+
self.clock = clock
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Stores each non-empty click ID with a fresh 400-day expiry, derives `fbc` from
|
|
40
|
+
/// `fbclid`, and sets the session URL when `url` is non-nil.
|
|
41
|
+
func capture(clickIds: [String: String], url: String?) {
|
|
42
|
+
let now = clock.now().epochMillis
|
|
43
|
+
var entries = liveEntries(now: now)
|
|
44
|
+
for (name, value) in clickIds where !value.isEmpty {
|
|
45
|
+
entries[name] = Entry(value: value, capturedAtMs: now)
|
|
46
|
+
}
|
|
47
|
+
write(entries)
|
|
48
|
+
if let fbclid = clickIds["fbclid"], !fbclid.isEmpty, readFbc()?.fbclid != fbclid {
|
|
49
|
+
writeFbc(FbcEntry(value: "fb.1.\(now).\(fbclid)", fbclid: fbclid, capturedAtMs: now))
|
|
50
|
+
}
|
|
51
|
+
if let url, !url.isEmpty {
|
|
52
|
+
store.set(url, for: Key.sessionURL)
|
|
53
|
+
store.set(String(now), for: Key.sessionURLAt)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
func snapshot() -> AttributionSnapshot {
|
|
58
|
+
let entries = liveEntries(now: clock.now().epochMillis)
|
|
59
|
+
var fbc: String?
|
|
60
|
+
if let f = readFbc(), entries["fbclid"]?.value == f.fbclid { fbc = f.value }
|
|
61
|
+
return AttributionSnapshot(
|
|
62
|
+
clickIds: entries.mapValues(\.value),
|
|
63
|
+
fbc: fbc,
|
|
64
|
+
url: store.string(Key.sessionURL)
|
|
65
|
+
)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
func clearSessionURL() {
|
|
69
|
+
store.set(nil, for: Key.sessionURL)
|
|
70
|
+
store.set(nil, for: Key.sessionURLAt)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Ends the session URL if it was captured at or before `cutoffMs` (the start of a long
|
|
74
|
+
/// background), so a link that opened the app after that background is kept.
|
|
75
|
+
func clearSessionURL(capturedAtOrBefore cutoffMs: Int64) {
|
|
76
|
+
guard store.string(Key.sessionURL) != nil else { return }
|
|
77
|
+
let capturedAt = store.string(Key.sessionURLAt).flatMap(Int64.init) ?? Int64.min
|
|
78
|
+
if capturedAt <= cutoffMs { clearSessionURL() }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
func clear() {
|
|
82
|
+
store.set(nil, for: Key.clickIds)
|
|
83
|
+
store.set(nil, for: Key.fbc)
|
|
84
|
+
clearSessionURL()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private func liveEntries(now: Int64) -> [String: Entry] {
|
|
88
|
+
guard let raw = store.string(Key.clickIds),
|
|
89
|
+
let all = try? JSONDecoder().decode([String: Entry].self, from: Data(raw.utf8))
|
|
90
|
+
else { return [:] }
|
|
91
|
+
return all.filter { now - $0.value.capturedAtMs < Self.clickIdTTLMillis }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private func write(_ entries: [String: Entry]) {
|
|
95
|
+
if entries.isEmpty { store.set(nil, for: Key.clickIds); return }
|
|
96
|
+
let data = (try? JSONEncoder().encode(entries)) ?? Data("{}".utf8)
|
|
97
|
+
store.set(String(decoding: data, as: UTF8.self), for: Key.clickIds)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private func readFbc() -> FbcEntry? {
|
|
101
|
+
guard let raw = store.string(Key.fbc) else { return nil }
|
|
102
|
+
return try? JSONDecoder().decode(FbcEntry.self, from: Data(raw.utf8))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private func writeFbc(_ entry: FbcEntry) {
|
|
106
|
+
let data = (try? JSONEncoder().encode(entry)) ?? Data()
|
|
107
|
+
store.set(String(decoding: data, as: UTF8.self), for: Key.fbc)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// URL or query string → click-ID map (design §6.1). Takes strings rather than `URL`
|
|
4
|
+
/// because Foundation may reject or rewrite invalid percent-encoding.
|
|
5
|
+
enum ClickIdParser {
|
|
6
|
+
/// Query parameter (case-sensitive) → identifier name.
|
|
7
|
+
static let identifierByParameter: [String: String] = [
|
|
8
|
+
"gclid": "gclid",
|
|
9
|
+
"gbraid": "gbraid",
|
|
10
|
+
"wbraid": "wbraid",
|
|
11
|
+
"gad_source": "gad_source",
|
|
12
|
+
"fbclid": "fbclid",
|
|
13
|
+
"ttclid": "ttclid",
|
|
14
|
+
"ScCid": "sccid",
|
|
15
|
+
"rdt_cid": "rdt_cid",
|
|
16
|
+
"epik": "epik",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
/// The query is the text after the first `?` and before any `#`. Any scheme works.
|
|
20
|
+
static func parse(url: String) -> [String: String] {
|
|
21
|
+
guard let q = url.firstIndex(of: "?") else { return [:] }
|
|
22
|
+
var query = url[url.index(after: q)...]
|
|
23
|
+
if let hash = query.firstIndex(of: "#") { query = query[..<hash] }
|
|
24
|
+
return parse(query: String(query))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// Splits on `&`, then each pair at the first `=`. Percent-decodes name and value
|
|
28
|
+
/// (`+` stays `+`). Empty values and invalid encodings are skipped; the first
|
|
29
|
+
/// remaining occurrence of a parameter wins.
|
|
30
|
+
static func parse(query: String) -> [String: String] {
|
|
31
|
+
var result: [String: String] = [:]
|
|
32
|
+
for pair in query.split(separator: "&", omittingEmptySubsequences: true) {
|
|
33
|
+
let rawName: Substring
|
|
34
|
+
let rawValue: Substring
|
|
35
|
+
if let eq = pair.firstIndex(of: "=") {
|
|
36
|
+
rawName = pair[..<eq]
|
|
37
|
+
rawValue = pair[pair.index(after: eq)...]
|
|
38
|
+
} else {
|
|
39
|
+
rawName = pair
|
|
40
|
+
rawValue = ""
|
|
41
|
+
}
|
|
42
|
+
guard let name = rawName.removingPercentEncoding,
|
|
43
|
+
let id = identifierByParameter[name],
|
|
44
|
+
result[id] == nil,
|
|
45
|
+
let value = rawValue.removingPercentEncoding,
|
|
46
|
+
!value.isEmpty
|
|
47
|
+
else { continue }
|
|
48
|
+
result[id] = value
|
|
49
|
+
}
|
|
50
|
+
return result
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(AppTrackingTransparency)
|
|
3
|
+
import AppTrackingTransparency
|
|
4
|
+
#endif
|
|
5
|
+
#if canImport(AdSupport)
|
|
6
|
+
import AdSupport
|
|
7
|
+
#endif
|
|
8
|
+
|
|
9
|
+
protocol AdIdProviding {
|
|
10
|
+
/// The IDFA (only when ATT is authorized) and whether ATT is authorized.
|
|
11
|
+
func current() -> (idfa: String?, authorized: Bool)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/// Reads ATT status and the IDFA. Never requests ATT authorization; the host app owns the prompt.
|
|
15
|
+
struct SystemAdIdProvider: AdIdProviding {
|
|
16
|
+
func current() -> (idfa: String?, authorized: Bool) {
|
|
17
|
+
#if canImport(AppTrackingTransparency) && canImport(AdSupport)
|
|
18
|
+
let authorized = ATTrackingManager.trackingAuthorizationStatus == .authorized
|
|
19
|
+
guard authorized else { return (nil, false) }
|
|
20
|
+
let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
|
|
21
|
+
return (AdIdProvider.normalize(idfa: idfa, authorized: true), true)
|
|
22
|
+
#else
|
|
23
|
+
return (nil, false)
|
|
24
|
+
#endif
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
enum AdIdProvider {
|
|
29
|
+
private static let zeros = "00000000-0000-0000-0000-000000000000"
|
|
30
|
+
|
|
31
|
+
/// The IDFA to send, or nil when ATT isn't authorized or the IDFA is empty or all zeros.
|
|
32
|
+
static func normalize(idfa: String?, authorized: Bool) -> String? {
|
|
33
|
+
guard authorized, let idfa, !idfa.isEmpty, idfa != zeros else { return nil }
|
|
34
|
+
return idfa
|
|
35
|
+
}
|
|
36
|
+
}
|