-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathSentryCapacitorPlugin.swift
More file actions
396 lines (320 loc) · 14 KB
/
SentryCapacitorPlugin.swift
File metadata and controls
396 lines (320 loc) · 14 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
import Foundation
import Capacitor
import Sentry
// Keep compatibility with CocoaPods.
#if SWIFT_PACKAGE
import Sentry._Hybrid
#endif
/**
* Please read the Capacitor iOS Plugin Development Guide
* here: https://capacitorjs.com/docs/plugins/ios
*/
@objc(SentryCapacitorPlugin)
public class SentryCapacitorPlugin: CAPPlugin, CAPBridgedPlugin {
public let identifier = "SentryCapacitorPlugin"
public let jsName = "SentryCapacitor"
public let pluginMethods: [CAPPluginMethod] = [
CAPPluginMethod(name: "initNativeSdk",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "captureEnvelope",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "fetchNativeRelease",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "fetchNativeSdkInfo",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "fetchNativeDeviceContexts",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "getStringBytesLength",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setTag",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setExtra",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setUser",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "addBreadcrumb",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "clearBreadcrumbs",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "closeNativeSdk",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setContext",returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "crash", returnType:CAPPluginReturnPromise),
CAPPluginMethod(name: "pauseAppHangTracking", returnType:CAPPluginReturnPromise),
CAPPluginMethod(name: "resumeAppHangTracking", returnType:CAPPluginReturnPromise),
]
private let nativeSdkName = "sentry.cocoa.capacitor";
private var sentryOptions: Options?
// The Cocoa SDK is init. after the notification didBecomeActiveNotification is registered.
// We need to be able to receive this notification and start a session when the SDK is fully operational.
private var didReceiveDidBecomeActiveNotification = false
public override func load() {
registerObserver()
}
private func registerObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
@objc private func applicationDidBecomeActive() {
didReceiveDidBecomeActiveNotification = true
// we only need to do that in the 1st time, so removing it
NotificationCenter.default.removeObserver(self,
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
@objc func initNativeSdk(_ call: CAPPluginCall) {
let _optionsDict = call.getObject("options")
guard let optionsDict = _optionsDict else {
return call.reject("options is null")
}
do {
let options = try SentryOptionsInternal.initWithDict(optionsDict)
let sdkVersion = PrivateSentrySDKOnly.getSdkVersionString()
PrivateSentrySDKOnly.setSdkName(nativeSdkName, andVersionString: sdkVersion)
if let sidecarUrl = optionsDict["sidecarUrl"] as? String {
options.enableSpotlight = true
options.spotlightUrl = sidecarUrl
}
// Note: For now, in sentry-cocoa, beforeSend is not called before captureEnvelope
options.beforeSend = { [weak self] event in
self?.setEventOriginTag(event: event)
return event
}
DispatchQueue.main.async { [] in
SentrySDK.start(options: options)
}
sentryOptions = options
// checking enableAutoSessionTracking is actually not necessary, but we'd spare the sent bits.
if didReceiveDidBecomeActiveNotification && sentryOptions?.enableAutoSessionTracking == true {
// we send a SentryHybridSdkDidBecomeActive to the Sentry Cocoa SDK, so the SDK will mimics
// the didBecomeActiveNotification notification and start a session if not yet.
NotificationCenter.default.post(name: Notification.Name("SentryHybridSdkDidBecomeActive"), object: nil)
// we reset the flag for the sake of correctness
didReceiveDidBecomeActiveNotification = false
}
call.resolve()
} catch {
call.reject("Failed to start native SDK")
}
}
@objc func captureEnvelope(_ call: CAPPluginCall) {
guard let base64Bytes = call.getString("envelope") else {
print("Cannot parse the envelope data")
call.reject("Envelope is null or empty")
return
}
guard let data = Data(base64Encoded: base64Bytes) else {
print("Cannot decode base64 envelope data")
call.reject("Failed to decode base64 envelope")
return
}
let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count)
data.copyBytes(to: pointer, count: data.count)
guard let envelope = PrivateSentrySDKOnly.envelope(with: data) else {
call.reject("SentryCapacitor", "Failed to parse envelope from byte array.", nil)
return
}
pointer.deallocate()
PrivateSentrySDKOnly.capture(envelope)
call.resolve()
}
@objc func getStringBytesLength(_ call: CAPPluginCall) {
if let payloadSize = call.getString("string")?.utf8.count {
call.resolve(["value": payloadSize])
} else {
call.reject("Coud not calculate string length.")
}
}
@objc func fetchNativeRelease(_ call: CAPPluginCall) {
let infoDict = Bundle.main.infoDictionary
call.resolve([
"id": infoDict?["CFBundleIdentifier"] ?? "",
"version": infoDict?["CFBundleShortVersionString"] ?? "",
"build": infoDict?["CFBundleVersion"] ?? ""
])
}
@objc func fetchNativeSdkInfo(_ call: CAPPluginCall) {
call.resolve([
"name": PrivateSentrySDKOnly.getSdkName(),
"version": PrivateSentrySDKOnly.getSdkVersionString()
])
}
@objc func fetchNativeDeviceContexts(_ call: CAPPluginCall) {
// Based on: https://github.com/getsentry/sentry-react-native/blob/a8d5ac86e3c53c90ef8e190cc082bdac440bd2a7/ios/RNSentry.m#L156-L188
// Updated with: https://github.com/getsentry/sentry-react-native/blob/241b7c2831f1bb5691c735058d8dc3de61c40fac/ios/RNSentry.mm#L190-L228
// Temp work around until sorted out this API in sentry-cocoa.
// TODO: If the callback isnt' executed the promise wouldn't be resolved.
SentrySDK.configureScope { [weak self] scope in
var contexts: [String : Any?] = [:]
let serializedScope = scope.serialize()
for (key, value) in serializedScope {
contexts[key] = value
}
if contexts["user"] == nil {
contexts["user"] = ["id" : PrivateSentrySDKOnly.installationID]
}
if self?.sentryOptions?.debug == true {
let data: Data? = try? JSONSerialization.data(withJSONObject: contexts, options: [])
if let data = data {
let debugContext = String(data: data, encoding: .utf8)
print("Contexts: \(debugContext ?? "")")
}
}
let extraContext = PrivateSentrySDKOnly.getExtraContext()
var context = contexts["contexts"] as? [String: Any] ?? [:]
if let deviceExtraContext = extraContext["device"] as? [String: Any] {
var deviceContext = context["device"] as? [String: Any] ?? [:]
for (key, value) in deviceExtraContext {
deviceContext[key] = value
}
context["device"] = deviceContext
}
if let appExtraContext = extraContext["app"] as? [String: Any] {
var appContext = context["app"] as? [String: Any] ?? [:]
for (key, value) in appExtraContext {
appContext[key] = value
}
context["app"] = appContext
}
// Remove capacitor breadcrumbs
if let breadcrumbs = contexts["breadcrumbs"] as? [[String: Any]] {
let filteredBreadcrumbs = breadcrumbs.filter { breadcrumb in
guard let origin = breadcrumb["origin"] as? String else {
return true
}
return origin != "capacitor"
}
contexts["breadcrumbs"] = filteredBreadcrumbs
}
contexts["contexts"] = context
call.resolve(contexts as PluginCallResultData)
}
}
@objc func setUser(_ call: CAPPluginCall) {
let defaultUserKeys = call.getObject("defaultUserKeys")
let otherUserKeys = call.getObject("otherUserKeys")
SentrySDK.configureScope { scope in
if (defaultUserKeys == nil && otherUserKeys == nil) {
scope.setUser(nil)
} else {
let user = User()
if let userId = defaultUserKeys?["id"] as? String {
user.userId = userId
}
user.email = defaultUserKeys?["email"] as! String?
user.username = defaultUserKeys?["username"] as! String?
user.ipAddress = defaultUserKeys?["ip_address"] as! String?
user.data = otherUserKeys
scope.setUser(user)
}
}
call.resolve()
}
@objc func setTag(_ call: CAPPluginCall) {
guard let key = call.getString("key") else {
return call.reject("Error deserializing tag")
}
guard let value = call.getString("value") else {
SentrySDK.configureScope { scope in
scope.removeTag(key: key)
}
return call.resolve()
}
SentrySDK.configureScope { scope in
scope.setTag(value: value, key: key)
}
call.resolve()
}
@objc func setExtra(_ call: CAPPluginCall) {
guard let key = call.getString("key") else {
return call.reject("Error deserializing extra")
}
let value = call.getString("value")
SentrySDK.configureScope { scope in
scope.setExtra(value: value, key: key)
}
call.resolve()
}
@objc func setContext(_ call: CAPPluginCall) {
guard let key = call.getString("key") else {
return call.reject("Error deserializing context")
}
SentrySDK.configureScope { scope in
scope.setContext(value: call.getObject("value") ?? [:], key: key)
}
}
@objc func addBreadcrumb(_ call: CAPPluginCall) {
SentrySDK.configureScope { [weak self] scope in
let breadcrumb = Breadcrumb()
if let timestamp = call.getDouble("timestamp") {
breadcrumb.timestamp = Date(timeIntervalSince1970: timestamp)
}
if let level = call.getString("level"), let processedLevel = self?.processLevel(level) {
breadcrumb.level = processedLevel
}
if let category = call.getString("category") {
breadcrumb.category = category
}
if let origin = call.getString("origin") {
breadcrumb.origin = origin
} else {
breadcrumb.origin = "capacitor"
}
breadcrumb.type = call.getString("type")
breadcrumb.message = call.getString("message")
breadcrumb.data = call.getObject("data")
scope.addBreadcrumb(breadcrumb)
}
call.resolve()
}
@objc func clearBreadcrumbs(_ call: CAPPluginCall) {
SentrySDK.configureScope { scope in
scope.clearBreadcrumbs()
}
call.resolve()
}
@objc func closeNativeSdk(_ call: CAPPluginCall ) {
SentrySDK.close()
call.resolve()
}
@objc func crash(_ call: CAPPluginCall) {
SentrySDK.crash()
}
@objc func pauseAppHangTracking(_ call: CAPPluginCall) {
SentrySDK.pauseAppHangTracking();
call.resolve();
}
@objc func resumeAppHangTracking(_ call: CAPPluginCall) {
SentrySDK.resumeAppHangTracking();
call.resolve();
}
private func processLevel(_ levelString: String) -> SentryLevel {
switch levelString {
case "fatal":
return SentryLevel.fatal
case "warning":
return SentryLevel.warning
case "debug":
return SentryLevel.debug
case "error":
return SentryLevel.error
case "info":
return SentryLevel.info
default:
return SentryLevel.info
}
}
private func setEventOriginTag(event: Event) {
guard let sdk = event.sdk, isValidSdk(sdk: sdk), let name = sdk["name"] as? String, name == nativeSdkName else {
return
}
setEventEnvironmentTag(event: event, environment: "native")
}
private func setEventEnvironmentTag(event: Event, environment: String) {
var newTags = [String: String]()
if let tags = event.tags, !tags.isEmpty {
newTags.merge(tags) { (_, new) in new }
}
newTags["event.origin"] = "ios"
if !environment.isEmpty {
newTags["event.environment"] = environment
}
event.tags = newTags
}
private func isValidSdk(sdk: [String: Any]) -> Bool {
guard let name = sdk["name"] as? String else {
return false
}
return !name.isEmpty
}
}