SmokeScreen.kt 8.71 KB
Newer Older
1
2
3
package com.frostnerd.smokescreen

import android.app.Application
4
5
6
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
7
import android.content.Intent
8
import androidx.core.app.NotificationCompat
9
import com.frostnerd.smokescreen.activity.ErrorDialogActivity
10
import com.frostnerd.smokescreen.activity.LoggingDialogActivity
11
import com.frostnerd.smokescreen.activity.PinActivity
12
import com.frostnerd.smokescreen.database.AppDatabase
13
import com.frostnerd.smokescreen.util.Notifications
14
import com.frostnerd.smokescreen.util.RequestCodes
Daniel Wolf's avatar
Daniel Wolf committed
15
import com.frostnerd.smokescreen.util.crashhelpers.DatasavingSentryEventHelper
Daniel Wolf's avatar
Daniel Wolf committed
16
import com.frostnerd.smokescreen.util.preferences.AppSettings
17
import com.frostnerd.smokescreen.util.preferences.Crashreporting
Daniel Wolf's avatar
Daniel Wolf committed
18
19
import io.sentry.Sentry
import io.sentry.android.AndroidSentryClientFactory
20
import io.sentry.event.User
21
22
23
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
Daniel Wolf's avatar
Daniel Wolf committed
24
import leakcanary.LeakSentry
25
import java.util.*
26
27
import kotlin.system.exitProcess

Daniel Wolf's avatar
Daniel Wolf committed
28
29
/*
 * Copyright (C) 2019 Daniel Wolf (Ch4t4r)
30
 *
Daniel Wolf's avatar
Daniel Wolf committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 * 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/>.
 *
 * You can contact the developer at daniel.wolf@frostnerd.com.
45
46
 */
class SmokeScreen : Application() {
47

48
    private var defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null
49
    val customUncaughtExceptionHandler = EnrichableUncaughtExceptionHandler()
50
    private fun showCrashNotification() {
51
52
53
54
55
56
57
        val notification =
            NotificationCompat.Builder(this, Notifications.noConnectionNotificationChannelId(this))
                .setSmallIcon(R.drawable.ic_cloud_warn)
                .setOngoing(false)
                .setAutoCancel(true)
                .setContentIntent(
                    PendingIntent.getActivity(
58
                        this, RequestCodes.CRASH_NOTIFICATION,
59
                        PinActivity.openAppIntent(this), PendingIntent.FLAG_UPDATE_CURRENT
60
                    )
61
                )
62
                .setContentTitle(getString(R.string.notification_appcrash_title))
63
64
65
        if (getPreferences().loggingEnabled) {
            val pendingIntent = PendingIntent.getActivity(
                this,
66
                RequestCodes.CRASH_NOTIFICATION_SEND_LOGS,
67
68
69
70
                Intent(
                    this,
                    LoggingDialogActivity::class.java
                ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
71
72
                PendingIntent.FLAG_CANCEL_CURRENT
            )
73
74
75
76
77
            notification.addAction(
                R.drawable.ic_share,
                getString(R.string.title_send_logs),
                pendingIntent
            )
78
79
        }

80
81
        notification.setStyle(NotificationCompat.BigTextStyle(notification).bigText(getString(R.string.notification_appcrash_message)))
        (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(
Daniel Wolf's avatar
Daniel Wolf committed
82
            Notifications.ID_APP_CRASH,
83
84
85
86
            notification.build()
        )
    }

87
    override fun onCreate() {
88
        if(!BuildConfig.LEAK_DETECTION) LeakSentry.config = LeakSentry.config.copy(enabled = false)
89
        initSentry()
90
91
92
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(customUncaughtExceptionHandler)
        super.onCreate()
93
        log("Application created.")
94
        LeakSentry.watchIfEnabled(this)
95
96
    }

97
    fun initSentry(forceStatus: Status = Status.NONE) {
Daniel Wolf's avatar
Daniel Wolf committed
98
        if (!BuildConfig.DEBUG && BuildConfig.SENTRY_DSN != "dummy") {
Daniel Wolf's avatar
Daniel Wolf committed
99
100
101
102
103
104
105
            GlobalScope.launch(Dispatchers.IO) {
                val enabledType = getPreferences().crashreportingType
                if (forceStatus != Status.DATASAVING && (enabledType == Crashreporting.FULL || forceStatus == Status.ENABLED)) {
                    // Enable Sentry in full mode
                    // This passes some device-related data, but nothing which allows user actions to be tracked across the app
                    // Info: Some data is attached by the AndroidEventBuilderHelper class, which is present by default

106
                    Sentry.init(
Daniel Wolf's avatar
Daniel Wolf committed
107
                        BuildConfig.SENTRY_DSN,
108
                        AndroidSentryClientFactory(this@SmokeScreen)
109
                    )
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
                    Sentry.getContext().user =
                        User(getPreferences().crashReportingUUID, null, null, null)
                    Sentry.getStoredClient().apply {
                        addTag("user.language", Locale.getDefault().displayLanguage)
                        addTag("app.database_version", AppDatabase.currentVersion.toString())
                        addTag("app.dns_server_name", getPreferences().dnsServerConfig.name)
                        addTag(
                            "app.dns_server_primary",
                            getPreferences().dnsServerConfig.servers[0].address.formatToString()
                        )
                        addTag(
                            "app.dns_server_secondary",
                            getPreferences().dnsServerConfig.servers.getOrNull(1)?.address?.formatToString()
                        )
                        addTag(
                            "app.installer_package",
                            packageManager.getInstallerPackageName(packageName)
                        )
                        addTag("richdata", "true")
129
                        addTag("app.fromCi", BuildConfig.FROM_CI.toString())
130
                        addTag("app.commit", BuildConfig.COMMIT_HASH)
131
                    }
Daniel Wolf's avatar
Daniel Wolf committed
132
133
134
135
                } else if (enabledType == Crashreporting.MINIMAL || forceStatus == Status.DATASAVING) {
                    // Inits Sentry in datasaving mode
                    // Only data absolutely necessary is transmitted (Android version, app version).
                    // Only crashes will be reported, no regular events.
136
                    Sentry.init(
Daniel Wolf's avatar
Daniel Wolf committed
137
                        BuildConfig.SENTRY_DSN,
138
139
                        AndroidSentryClientFactory(this@SmokeScreen)
                    )
Daniel Wolf's avatar
Daniel Wolf committed
140
141
                    Sentry.getContext().user =
                        User("anon-" + BuildConfig.VERSION_CODE, null, null, null)
142
143
144
                    Sentry.getStoredClient().apply {
                        addTag("richdata", "false")
                        addTag("dist", BuildConfig.VERSION_CODE.toString())
145
                        addTag("app.commit", BuildConfig.COMMIT_HASH)
146
                        addTag("app.fromCi", BuildConfig.FROM_CI.toString())
Daniel Wolf's avatar
Daniel Wolf committed
147
                        addExtra("dist", BuildConfig.VERSION_CODE)
148
149
150
151
152
                        this.builderHelpers.forEach {
                            this.removeBuilderHelper(it)
                        }
                        this.addBuilderHelper(DatasavingSentryEventHelper())
                    }
153
                }
154
            }
155
        }
156
157
    }

158
159
160
161
162
163
164
165
166
    override fun onLowMemory() {
        super.onLowMemory()
        log("The system seems to have low memory")
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        log("Memory has been trimmed with level $level")
    }
167

168
    inner class EnrichableUncaughtExceptionHandler : Thread.UncaughtExceptionHandler {
169
170
171
172
173
174
        private val extras = mutableMapOf<String, String>()

        override fun uncaughtException(t: Thread, e: Throwable) {
            e.printStackTrace()
            log(e, extras)
            extras.clear()
Daniel Wolf's avatar
Daniel Wolf committed
175
            val isPrerelease = !AppSettings.isReleaseVersion
176
            if (isPrerelease && getPreferences().loggingEnabled && getPreferences().crashreportingType == Crashreporting.OFF) {
177
178
179
180
181
182
                startActivity(
                    Intent(
                        this@SmokeScreen,
                        ErrorDialogActivity::class.java
                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                )
183
            } else if (isPrerelease && getPreferences().crashreportingType != Crashreporting.OFF) {
184
185
186
187
188
189
190
                showCrashNotification()
            }
            closeLogger()
            defaultUncaughtExceptionHandler?.uncaughtException(t, e)
            exitProcess(0)
        }

191
        fun addExtra(key: String, value: String) {
192
193
194
195
            extras[key] = value
        }

    }
196
197
198
199
}

enum class Status {
    ENABLED, DATASAVING, NONE
200
}