-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSentryDebug.kt
351 lines (314 loc) · 14.5 KB
/
SentryDebug.kt
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
/*
* Infomaniak Mail - Android
* Copyright (C) 2023-2024 Infomaniak Network SA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.infomaniak.mail.utils
import android.os.Bundle
import androidx.navigation.NavController
import com.infomaniak.mail.BuildConfig
import com.infomaniak.mail.data.cache.mailboxContent.MessageController
import com.infomaniak.mail.data.cache.mailboxContent.ThreadController
import com.infomaniak.mail.data.models.Folder
import com.infomaniak.mail.data.models.draft.Draft
import com.infomaniak.mail.data.models.mailbox.Mailbox
import com.infomaniak.mail.data.models.message.Message
import com.infomaniak.mail.data.models.thread.Thread
import com.infomaniak.mail.utils.extensions.toLongUid
import io.realm.kotlin.TypedRealm
import io.realm.kotlin.migration.AutomaticSchemaMigration.MigrationContext
import io.realm.kotlin.query.RealmResults
import io.sentry.Breadcrumb
import io.sentry.Sentry
import io.sentry.SentryLevel
object SentryDebug {
//region Add Breadcrumb
private var previousDestinationName: String = ""
fun addNavigationBreadcrumb(name: String, arguments: Bundle?) {
// This function comes from `io.sentry.android.navigation.SentryNavigationListener`
fun Bundle?.refined(): Map<String, Any?> = this?.let { args ->
args.keySet()
.filter { it != NavController.KEY_DEEP_LINK_INTENT } // there's a lot of unrelated stuff
.associateWith { args[it] }
} ?: emptyMap()
val newDestinationName = name.substringAfter("${BuildConfig.APPLICATION_ID}:id/")
addInfoBreadcrumb(
category = "Navigation",
data = mapOf(
"1_from" to previousDestinationName,
"2_to" to newDestinationName,
"3_args" to arguments.refined(),
),
)
previousDestinationName = newDestinationName
}
fun addUrlBreadcrumb(url: String, requestContextId: String) {
addInfoBreadcrumb(
category = "API",
data = mapOf(
"url" to url,
"requestContextId" to requestContextId,
),
)
}
fun addNotificationBreadcrumb(notification: String) {
addInfoBreadcrumb("Notification", notification)
}
fun addThreadsAlgoBreadcrumb(message: String, data: Map<String, Any>) {
addInfoBreadcrumb("ThreadsAlgo", message, data)
}
fun addCursorBreadcrumb(message: String, folder: Folder, cursor: String?) {
addInfoBreadcrumb(
category = "Cursor",
message = message,
data = mapOf(
"folderName" to folder.name,
"previousFolderCursor" to "${folder.cursor}",
"newFolderCursor" to "$cursor",
),
)
}
fun addMigrationBreadcrumb(migrationContext: MigrationContext) = with(migrationContext) {
addInfoBreadcrumb(
category = "Migration",
data = mapOf(
"realmName" to oldRealm.configuration.name,
"oldVersion" to oldRealm.version().version,
"newVersion" to newRealm.version().version,
),
)
}
fun addAttachmentsBreadcrumb(draft: Draft, step: String) = with(draft) {
var count = 1
val data = mutableMapOf<String, Any>()
fun String.keyPad(): String = padStart(length = 15)
fun Int.countPad(): String = toString().padStart(length = 2, '0')
fun count(): String = "${count.countPad().also { count++ }}."
fun format(index: Int): String = (index + 1).countPad()
data[count() + "step".keyPad()] = step
data[count() + "email".keyPad()] = AccountUtils.currentMailboxEmail.toString()
data[count() + "draft".keyPad() + " - localUuid"] = localUuid
data[count() + "draft".keyPad() + " - remoteUuid"] = remoteUuid.toString()
data[count() + "draft".keyPad() + " - action"] = action?.name.toString()
data[count() + "draft".keyPad() + " - mode"] = when {
inReplyToUid != null -> "REPLY or REPLY_ALL"
forwardedUid != null -> "FORWARD"
else -> "NEW_MAIL"
}
data[count() + "attachments".keyPad() + " - count"] = attachments.count()
attachments.forEachIndexed { index, it ->
data[count() + "attachment #${format(index)}".keyPad()] =
"localUuid: ${it.localUuid} | uuid: ${it.uuid} | uploadLocalUri: ${it.uploadLocalUri}"
data[count() + "attachment #${format(index)}".keyPad()] = "uploadStatus: ${it.uploadStatus.name} | size: ${it.size}"
}
addInfoBreadcrumb(category = "Attachments_Situation", data = data)
}
private fun addInfoBreadcrumb(category: String, message: String? = null, data: Map<String, Any>? = null) {
Breadcrumb().apply {
this.category = category
this.message = message
data?.let { it.forEach { (key, value) -> this.setData(key, value) } }
this.level = SentryLevel.INFO
}.also(Sentry::addBreadcrumb)
}
//endregion
//region Send Sentry
// TODO: Added the 04/09/23. It's not supposed to be possible, but we never know…
// If this doesn't trigger after a certain amount of time, you can remove it.
//
// Also added in ThreadListAdapter & ThreadController the 04/06/24.
fun sendEmptyThread(thread: Thread, message: String) = with(thread) {
Sentry.withScope { scope ->
scope.setExtra("currentUserId", "${AccountUtils.currentUserId}")
scope.setExtra("currentMailboxEmail", AccountUtils.currentMailboxEmail.toString())
scope.setExtra("folderId", folderId)
scope.setExtra("folder.id", folder.id)
scope.setExtra("folder.role", folder.role?.name.toString())
scope.setExtra("uid", uid)
scope.setExtra("messages.count", "${messages.count()}")
scope.setExtra("duplicates.count", "${duplicates.count()}")
scope.setExtra("isFromSearch", "$isFromSearch")
scope.setExtra("hasDrafts", "$hasDrafts")
Sentry.captureMessage(message, SentryLevel.ERROR)
}
}
fun sendFailedNotification(
reason: String,
sentryLevel: SentryLevel,
userId: Int? = null,
mailboxId: Int? = null,
messageUid: String? = null,
mailbox: Mailbox? = null,
throwable: Throwable? = null,
) {
Sentry.withScope { scope ->
scope.level = sentryLevel
scope.setExtra("userId", "${userId?.toString()}")
scope.setExtra("currentUserId", "[${AccountUtils.currentUserId}]")
scope.setExtra("mailboxId", "${mailboxId?.toString()}")
scope.setExtra("mailbox.email", "[${mailbox?.email}]")
scope.setExtra("currentMailboxEmail", "[${AccountUtils.currentMailboxEmail}]")
scope.setExtra("messageUid", "$messageUid")
throwable?.let { scope.setExtra("throwable", it.stackTraceToString()) }
Sentry.captureMessage("Failed Notif : $reason")
}
}
fun sendMissingMessages(
sentUids: List<Int>,
receivedMessages: List<Message>,
folder: Folder,
newCursor: String,
) {
if (receivedMessages.count() != sentUids.count()) {
val receivedUids = mutableSetOf<Int>().apply {
receivedMessages.forEach { add(it.shortUid) }
}
val missingUids = sentUids.filterNot(receivedUids::contains)
if (missingUids.isNotEmpty()) {
Sentry.withScope { scope ->
scope.setExtra("1. newCursor", newCursor)
scope.setExtra("2. previousCursor", "${folder.cursor}")
scope.setExtra("3. input", "${sentUids.map { it }}")
scope.setExtra("4. output", "${receivedMessages.map { it.shortUid }}")
scope.setExtra("5. missing", "${missingUids.map { it.toString().toLongUid(folder.id) }}")
Sentry.captureMessage(
"We tried to download some Messages, but they were nowhere to be found.",
SentryLevel.ERROR,
)
}
}
}
}
fun sendMessageInWrongFolder(remoteMessage: Message, folder: Folder, realm: TypedRealm) {
val localMessage = MessageController.getMessage(remoteMessage.uid, realm)
Sentry.withScope { scope ->
scope.setExtra(
"localMessageFolders",
"${localMessage?.foldersForSentry?.joinToString { "${it.role?.name} | ${it.id}" }}",
)
scope.setExtra("remoteMessageUid", remoteMessage.uid)
scope.setExtra("folderRole", "${folder.role?.name}")
scope.setExtra("folderId", folder.id)
Sentry.captureMessage(
"Message is in wrong Folder (related to 'Message has multiple parent folders'",
SentryLevel.ERROR,
)
}
}
fun sendOrphanMessages(previousCursor: String?, folder: Folder): List<Message> {
val orphanMessages = folder.messages.filter { it.isOrphan() }
if (orphanMessages.isNotEmpty()) {
Sentry.withScope { scope ->
scope.setExtra("orphanMessages", "${orphanMessages.map { it.uid }}")
scope.setExtra("number of Messages", "${orphanMessages.count()}")
scope.setExtra("previousCursor", "$previousCursor")
scope.setExtra("newCursor", "${folder.cursor}")
scope.setExtra("folder", folder.displayForSentry())
Sentry.captureMessage("We found some orphan Messages.", SentryLevel.ERROR)
}
}
return orphanMessages
}
fun sendOrphanThreads(previousCursor: String?, folder: Folder, realm: TypedRealm): RealmResults<Thread> {
val orphanThreads = ThreadController.getOrphanThreads(realm)
if (orphanThreads.isNotEmpty()) {
Sentry.withScope { scope ->
scope.setExtra("orphanThreads", "${orphanThreads.map { it.uid }}")
scope.setExtra("number of Threads", "${orphanThreads.count()}")
scope.setExtra("number of Messages", "${orphanThreads.map { it.messages.count() }}")
scope.setExtra("previousCursor", "$previousCursor")
scope.setExtra("newCursor", "${folder.cursor}")
scope.setExtra("folder", folder.displayForSentry())
Sentry.captureMessage("We found some orphan Threads.", SentryLevel.ERROR)
}
}
return orphanThreads
}
fun sendOrphanDrafts(orphans: List<Draft>) {
if (orphans.isNotEmpty()) {
Sentry.withScope { scope ->
scope.setExtra(
"orphanDrafts",
orphans.joinToString {
if (it.messageUid == null) {
"${Draft::localUuid.name}: [${it.localUuid}]"
} else {
"${Draft::messageUid.name}: ${it.messageUid}"
}
},
)
Sentry.captureMessage("We found some orphan Drafts.", SentryLevel.ERROR)
}
}
}
fun sendOverScrolledMessage(clientWidth: Int, scrollWidth: Int, messageUid: String) {
Sentry.withScope { scope ->
scope.setTag("messageUid", messageUid)
scope.setExtra("clientWidth", "$clientWidth")
scope.setExtra("scrollWidth", "$scrollWidth")
Sentry.captureMessage("When resizing the mail with js, after zooming, it can still scroll.", SentryLevel.ERROR)
}
}
fun sendJavaScriptError(errorName: String, errorMessage: String, errorStack: String, messageUid: String) {
Sentry.withScope { scope ->
scope.setTag("messageUid", messageUid)
scope.setExtra("errorName", errorName)
scope.setExtra("errorMessage", errorMessage)
scope.setExtra("errorStack", errorStack)
Sentry.captureMessage("JavaScript returned an error when displaying an email.", SentryLevel.ERROR)
}
}
fun sendSubBodiesTrigger(messageUid: String) {
Sentry.withScope { scope ->
scope.setExtra("email", "${AccountUtils.currentMailboxEmail}")
scope.setExtra("messageUid", messageUid)
Sentry.captureMessage("Received an email with SubBodies!!", SentryLevel.INFO)
}
}
fun sendCredentialsIssue(infomaniakLogin: String?, infomaniakPassword: String) {
Sentry.withScope { scope ->
scope.setExtra("email", "${AccountUtils.currentUser?.email}")
val loginStatus = when {
infomaniakLogin == null -> "is null"
infomaniakLogin.isEmpty() -> "is empty"
infomaniakLogin.isBlank() -> "is blank"
else -> "is ok"
}
scope.setExtra("infomaniakLogin status", loginStatus)
val passwordStatus = when {
infomaniakPassword.isEmpty() -> "is empty"
infomaniakPassword.isBlank() -> "is blank"
else -> "is ok"
}
scope.setExtra("infomaniakPassword status", passwordStatus)
Sentry.captureMessage("Credentials issue when trying to auto-sync user", SentryLevel.ERROR)
}
}
fun sendWebViewVersionName(webViewPackageName: String?, webViewVersionName: String?, majorVersion: Int) {
Sentry.withScope { scope ->
scope.setTag("webViewPackageName", "$webViewPackageName")
scope.setTag("webViewVersionName", "$webViewVersionName")
scope.setTag("majorVersion", "$majorVersion")
Sentry.captureMessage(
"WebView version name might be null on some devices. Checking that the version name is ok.",
SentryLevel.INFO,
)
}
}
//endregion
//region Utils
fun Folder.displayForSentry() = role?.name ?: id
//endregion
}