-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathAnalyticsManager.swift
More file actions
436 lines (380 loc) · 17.1 KB
/
Copy pathAnalyticsManager.swift
File metadata and controls
436 lines (380 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import Foundation
import Countly
import greenaddress
public enum AnalyticsConsent: Int {
case notDetermined
case denied
case authorized
}
public enum AnalyticsInvoiceType: String {
case bolt11
case bolt12
case lnurl
}
public enum AppStorageConstants: String {
case dontShowTorAlert = "dont_show_tor_alert"
case defaultTransactionPriority = "default_transaction_priority"
case userAnalyticsPreference = "user_analytics_preference"
case analyticsUUID = "analytics_uuid"
case countlyOffset = "countly_offset"
case alwaysAskPassphrase = "always_ask_passphrase"
case storeReviewDate = "store_review_date"
case hideBalance = "hide_balance"
case acceptedTerms = "accepted_terms"
case dismissedPromos = "dismissed_promos"
case walletsToBackup = "wallets_to_backuo"
case buyCountyCodeUserSelected = "buy_county_code_user_selected"
case v5Triggered = "v5_treiggered"
case firstInitialization = "FirstInitialization"
case lightningNodeId = "lightning_node_id"
}
public protocol AnalyticsManagerDelegate: AnyObject {
func remoteConfigIsReady()
}
public class AnalyticsManager {
public static let shared = AnalyticsManager()
public let host = (Bundle.main.infoDictionary?["COUNTLY_APP_HOST"] as? String ?? "")
.replacingOccurrences(of: "\\", with: "")
public let hostOnion = (Bundle.main.infoDictionary?["COUNTLY_APP_HOST_ONION"] as? String ?? "")
.replacingOccurrences(of: "\\", with: "")
public let appKey = (Bundle.main.infoDictionary?["COUNTLY_APP_KEY"] as? String ?? "")
public var maxCountlyOffset: Int {
if let offset = Bundle.main.infoDictionary?["COUNTLY_APP_MAX_OFFSET"] as? String,
let number = Int(offset) {
return number * 1000
}
return 1
}
public var eventSendThreshold: UInt? {
if let offset = Bundle.main.infoDictionary?["COUNTLY_APP_EVENT_SEND_THRESHOLD"] as? String {
return UInt(offset)
}
return nil
}
public var consent: AnalyticsConsent {
get {
return AnalyticsConsent(rawValue: UserDefaults.standard.integer(forKey: AppStorageConstants.userAnalyticsPreference.rawValue)) ?? .notDetermined
}
set {
let prev = AnalyticsConsent(rawValue: UserDefaults.standard.integer(forKey: AppStorageConstants.userAnalyticsPreference.rawValue)) ?? .notDetermined
UserDefaults.standard.set(newValue.rawValue, forKey: AppStorageConstants.userAnalyticsPreference.rawValue)
if newValue == .denied {
reset()
}
giveConsent()
}
}
public var hwData: (fwVersion: String?, model: String?) = (nil,nil)
public var analyticsUUID: String {
get {
if let uuid = UserDefaults.standard.string(forKey: AppStorageConstants.analyticsUUID.rawValue) {
logger.info("AnalyticsManager analyticsUUID \(uuid, privacy: .public)")
return uuid
} else {
let uuid = UUID().uuidString
logger.info("AnalyticsManager analyticsUUID \(uuid, privacy: .public)")
UserDefaults.standard.setValue(uuid, forKey: AppStorageConstants.analyticsUUID.rawValue)
return uuid
}
}
}
private var conf: URLSessionConfiguration?
public let authorizedGroup = [CLYConsent.sessions,
CLYConsent.events,
CLYConsent.crashReporting,
CLYConsent.viewTracking,
CLYConsent.userDetails,
CLYConsent.location,
CLYConsent.remoteConfig,
CLYConsent.metrics,
CLYConsent.performanceMonitoring,
CLYConsent.feedback]
public let deniedGroup = [CLYConsent.crashReporting,
CLYConsent.remoteConfig,
CLYConsent.metrics,
CLYConsent.feedback]
// list of ignorable common error messages
public let skipExceptionRecording = [
"id_invalid_amount",
"id_no_amount_specified",
"id_invalid_address",
"id_insufficient_funds",
"id_invalid_private_key",
"id_action_canceled",
"id_login_failed"
]
public var countlyFeedbackWidget: CountlyFeedbackWidget?
public func invalidateAnalyticsUUID() {
UserDefaults.standard.removeObject(forKey: AppStorageConstants.analyticsUUID.rawValue)
}
public func invalidateCountlyOffset() {
UserDefaults.standard.removeObject(forKey: AppStorageConstants.countlyOffset.rawValue)
}
public var countlyOffset: UInt {
get {
if let offset = UserDefaults.standard.object(forKey: AppStorageConstants.countlyOffset.rawValue) as? UInt {
logger.info("AnalyticsManager analyticsOFFSET \(offset)")
return offset
} else {
let offset = secureRandom(max: maxCountlyOffset)
logger.info("AnalyticsManager analyticsOFFSET \(offset)")
UserDefaults.standard.setValue(offset, forKey: AppStorageConstants.countlyOffset.rawValue)
return offset
}
}
}
public weak var delegate: AnalyticsManagerDelegate?
public var activeNetworks: Set<NetworkId>? {
WalletManager.current?.activeNetworkIds
}
public var analyticsNetworks: AnalyticsManager.NtwTypeDescriptor? {
if let activeNetworks = activeNetworks {
let bitcoinNtws = activeNetworks.filter { $0 == .electrumMainnet || $0 == .greenMainnet || $0.lightning }
let liquidNtws = activeNetworks.filter { $0 == .electrumLiquid || $0 == .greenLiquid }
let testnetNtws = activeNetworks.filter { $0 == .electrumTestnet || $0 == .greenTestnet }
let testnetLiquidNtws = activeNetworks.filter { $0 == .electrumTestnetLiquid || $0 == .greenTestnetLiquid }
if bitcoinNtws.count > 0 && liquidNtws.count > 0 { return AnalyticsManager.NtwTypeDescriptor.mainnetMixed }
if bitcoinNtws.count > 0 { return AnalyticsManager.NtwTypeDescriptor.mainnet }
if liquidNtws.count > 0 { return AnalyticsManager.NtwTypeDescriptor.liquid }
if testnetNtws.count > 0 && testnetLiquidNtws.count > 0 { return AnalyticsManager.NtwTypeDescriptor.testnetMixed }
if testnetNtws.count > 0 { return AnalyticsManager.NtwTypeDescriptor.testnet }
if testnetLiquidNtws.count > 0 { return AnalyticsManager.NtwTypeDescriptor.testnetLiquid }
}
return nil
}
public var analyticsSecurity: [SecTypeDescriptor]? {
if let activeNetworks = activeNetworks {
let hasSinglesig = activeNetworks.filter { [.electrumMainnet, .electrumLiquid, .electrumTestnet, .electrumTestnetLiquid].contains($0) }.count > 0
let hasMultisig = activeNetworks.filter { [.greenMainnet, .greenLiquid, .greenTestnet, .greenTestnetLiquid].contains($0) }.count > 0
let hasLightning = activeNetworks.filter { [.lightningMainnet].contains($0) }.count > 0
var security = [SecTypeDescriptor]()
if hasSinglesig {
security += [hasMultisig || hasLightning ? .single : .singlesig]
}
if hasMultisig {
security += [hasSinglesig || hasLightning ? .multi : .multisig]
}
if hasLightning {
security += [hasSinglesig || hasMultisig ? .light : .lightning]
}
return security
}
return nil
}
public func secureRandom(max: Int) -> UInt {
// SystemRandomNumberGenerator is automatically seeded, is safe to use in multiple threads
// and uses a cryptographically secure algorithm whenever possible.
var gen = SystemRandomNumberGenerator()
return UInt(Int.random(in: 1...max, using: &gen))
}
public func countlyStart() {
let config: CountlyConfig = CountlyConfig()
config.appKey = appKey
config.host = getHost()
config.offset = countlyOffset
config.deviceID = analyticsUUID
config.features = [.crashReporting]
config.enablePerformanceMonitoring = true
config.enableDebug = false
config.requiresConsent = true
config.enableRemoteConfig = true
if let threshold = eventSendThreshold {
config.eventSendThreshold = threshold
}
config.urlSessionConfiguration = getSessionConfiguration(session: nil)
if consent == .authorized {
config.consents = authorizedGroup
} else {
config.consents = deniedGroup
}
config.remoteConfigCompletionHandler = { error in
if error == nil {
logger.info("AnalyticsManager Remote Config is ready to use!")
self.delegate?.remoteConfigIsReady()
let notification = NSNotification.Name(rawValue: "remote_config_is_ready")
NotificationCenter.default.post(name: notification, object: nil, userInfo: nil)
} else {
logger.error("AnalyticsManager There was an error while fetching Remote Config:\n\(error!.localizedDescription)")
}
}
logger.info("AnalyticsManager start")
Countly.sharedInstance().start(with: config)
giveConsent()
}
private func reset() {
Countly.sharedInstance().cancelConsentForAllFeatures()
// change the deviceID
invalidateAnalyticsUUID()
invalidateCountlyOffset()
Countly.sharedInstance().changeDeviceIDWithoutMerge(analyticsUUID)
Countly.sharedInstance().setNewOffset(countlyOffset)
Countly.sharedInstance().disableLocationInfo()
}
private func giveConsent() {
logger.info("AnalyticsManager giving consent: \(self.consent.rawValue)")
switch consent {
case .notDetermined:
break
case .denied:
Countly.sharedInstance().giveConsent(forFeatures: deniedGroup)
updateUserProperties()
case .authorized:
Countly.sharedInstance().giveConsent(forFeatures: authorizedGroup)
updateUserProperties()
}
}
func isEqual(confA: URLSessionConfiguration?, confB: URLSessionConfiguration?) -> Bool {
guard let left = confA?.connectionProxyDictionary,
let right = confB?.connectionProxyDictionary else {
return confA?.connectionProxyDictionary == nil && confB?.connectionProxyDictionary == nil
}
guard left.count == right.count else { return false }
return (left as NSDictionary).isEqual(to: right)
}
public func setupSession(session: GDKSession?) {
logger.info("AnalyticsManager setup session")
let host = getHost()
let conf = getSessionConfiguration(session: session)
if !isEqual(confA: conf, confB: self.conf) {
Countly.sharedInstance().setNewHost(host)
Countly.sharedInstance().setNewURLSessionConfiguration(conf)
}
/*URLSession(configuration: conf).dataTask(with: URL(string: host+"/i")!) {
data, response, error in
print (data)
print (response)
print (error)
}.resume()*/
}
private func getHost() -> String {
GdkSettings.read()?.tor ?? false ? hostOnion : host
}
private func getSessionConfiguration(session: GDKSession?) -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.ephemeral
let settings = GdkSettings.read()
// set explicit proxy
if settings?.proxy ?? false {
configuration.connectionProxyDictionary = [
kCFStreamPropertySOCKSProxyHost: settings?.socks5Hostname ?? "",
kCFStreamPropertySOCKSProxyPort: settings?.socks5Port ?? ""
]
}
// set implicit tor proxy
if settings?.tor ?? false {
let proxySettings = try? session?.getProxySettings()
let proxy = proxySettings?["proxy"] as? String ?? ""
let parser = proxy.split(separator: ":").map { $0.replacingOccurrences(of: "/", with: "") }
if parser.first == "socks5" && parser.count == 3 {
configuration.connectionProxyDictionary = [
kCFStreamPropertySOCKSProxyHost: parser[1],
kCFStreamPropertySOCKSProxyPort: Int(parser[2]) ?? 0,
kCFProxyTypeKey: kCFProxyTypeSOCKS
]
}
}
return configuration
}
private func updateUserProperties() {
let accounts = WalletsStorage.shared.sws
let bitcoin_wallets = accounts.filter { !$0.gdkNetwork.liquid }
let liquid_wallets = accounts.filter { $0.gdkNetwork.liquid }
var props: [String: String] = [:]
props[AnalyticsManager.strUserPropertyTotalWallets] = "\((bitcoin_wallets + liquid_wallets).count)"
Countly.user().custom = props as CountlyUserDetailsNullableDictionary
Countly.user().save()
}
public func appLoadingFinished() {
guard consent != .notDetermined else { return }
Countly.sharedInstance().appLoadingFinished()
}
public func userPropertiesDidChange() {
guard consent != .notDetermined else { return }
updateUserProperties()
}
public func getSurvey(completion: @escaping (CountlyWidget?) -> Void) {
guard consent != .notDetermined else {
completion(nil)
return
}
Countly.sharedInstance().getFeedbackWidgets({ [weak self] widgets, error in
if error == nil, let widget = (widgets?.filter { $0.type == .NPS || $0.type == .survey })?.first {
widget.getData { wData, error in
if error == nil, let data = wData {
let w = CountlyWidget.build(data)
self?.countlyFeedbackWidget = widget
completion(w)
} else {
completion(nil)
}
}
} else {
completion(nil)
}
})
}
public func submitSurvey(_ result: [AnyHashable: Any]) {
guard let widget = countlyFeedbackWidget else { return }
widget.recordResult(result)
}
public func submitNPS(_ result: [AnyHashable: Any]) {
guard let widget = countlyFeedbackWidget else { return }
widget.recordResult(result)
}
public func submitExclude() {
guard let widget = countlyFeedbackWidget else { return }
widget.recordResult(nil)
}
public func recordEvent(_ key: AnalyticsEventName) {
guard consent == .authorized else { return }
Countly.sharedInstance().recordEvent(key.rawValue)
}
public func recordEvent(_ key: AnalyticsEventName, sgmt: [String: String]) {
guard consent == .authorized else { return }
Countly.sharedInstance().recordEvent(key.rawValue, segmentation: sgmt, count: 1, sum: 0.0)
}
public func cancelEvent(_ key: AnalyticsEventName) {
guard consent == .authorized else { return }
Countly.sharedInstance().cancelEvent(key.rawValue)
}
public func startEvent(_ key: AnalyticsEventName) {
guard consent == .authorized else { return }
Countly.sharedInstance().startEvent(key.rawValue)
}
public func endEvent(_ key: AnalyticsEventName, sgmt: [String: String]) {
guard consent == .authorized else { return }
Countly.sharedInstance().endEvent(key.rawValue, segmentation: sgmt, count: 1, sum: 0.0)
}
public func startTrace(_ key: AnalyticsEventName) {
guard consent == .authorized else { return }
Countly.sharedInstance().startCustomTrace(key.rawValue)
}
public func endTrace(_ key: AnalyticsEventName) {
guard consent == .authorized else { return }
Countly.sharedInstance().endCustomTrace(key.rawValue, metrics: [:])
}
public func cancelTrace(_ key: AnalyticsEventName) {
guard consent == .authorized else { return }
Countly.sharedInstance().cancelCustomTrace(key.rawValue)
}
public func recordView(_ name: AnalyticsViewName) {
guard consent == .authorized else { return }
Countly.sharedInstance().recordView(name.rawValue)
}
public func recordView(_ name: AnalyticsViewName, sgmt: [String: String]?) {
guard consent == .authorized else { return }
guard let s = sgmt else { return }
Countly.sharedInstance().recordView(name.rawValue, segmentation: s)
}
public func getRemoteConfigValue(key: String) -> Any? {
return Countly.sharedInstance().remoteConfigValue(forKey: key)
}
public func recordFeedback(rating: Int, email: String?, comment: String) {
Countly.sharedInstance()
.recordRatingWidget(withID: AnalyticsManager.ratingWidgetId,
rating: rating,
email: email,
comment: comment,
userCanBeContacted: true)
}
public var emptiedAccount: Account?
}