AnalyticsAPIService.swift
3.02 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
//
// AnalyticsAPIService.swift
// VPNAnalytics
//
// Created by Mihail Konoplitskyi on 02.09.2022.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
class AnalyticsAPIService: NSObject {
private let api = AnalyticsNetworkHelper()
var applicationToken: String = ""
static var baseUrl: String = ""
func logEvent(eventType: VPNAnalyticsConstants.VPNAnalyticsEvent, eventParams: [String: String]? , success: @escaping () -> ()) {
guard !applicationToken.isEmpty else {
debugPrint("\(type(of: self)) - failed to log \(eventType.rawValue) event - application token is empty")
return
}
var params = self.preparePOSTParamsArray(eventType: eventType)
if let eventParams = eventParams {
params = params.merging(eventParams, uniquingKeysWith: {(first, _) in first})
}
self.api.post(apiRoute: .sendEvent, params: params, headers: [:]) { (logEventResponseModel: LogEventResponseModel) in
debugPrint("\(type(of: self)) - successfully sent \(eventType.rawValue) event")
if logEventResponseModel.success {
success()
}
} failure: { error in
debugPrint("\(type(of: self)) - failed to log \(eventType.rawValue) event - \(error.localizedDescription)")
}
}
private func getCurrentIPAddress(completion: @escaping (String) -> ()) {
api.get(apiRoute: .getMyIP, params: ["format":"json"]) { (ipResponseModel: IPResponseModel) in
completion(ipResponseModel.ip)
} failure: { error in
print(error.localizedDescription)
}
}
private func preparePOSTParamsArray(eventType: VPNAnalyticsConstants.VPNAnalyticsEvent) -> [String:String] {
#if os(macOS)
guard let width = NSScreen.main?.frame,
let height = NSScreen.main?.frame.height else {
return [:]
}
let screenWidth = String(describing: width)
let screenHeight = String(describing: height)
#else
let screenWidth = String(describing: Int(UIScreen.main.bounds.width))
let screenHeight = String(describing: Int(UIScreen.main.bounds.height))
#endif
let appVersionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "Unknown"
let appBuildVersionNumber = Bundle.main.infoDictionary?["CFBundleVersion"] ?? "Unknown"
let appVersion = "v\(appVersionNumber) b\(appBuildVersionNumber)"
#if os(macOS)
let device = "MacOS v\(ProcessInfo.processInfo.operatingSystemVersion)"
#else
let device = "iOS v\(UIDevice.current.systemVersion)"
#endif
return ["type": eventType.rawValue,
"app_token": applicationToken,
"screen_width": screenWidth,
"screen_height": screenHeight,
"device": device,
"app_version": appVersion]
}
}