Implement bug reporter

This commit is contained in:
Suphon Thanakornpakapong committed 2021-10-26 15:34:48 +07:00
1 parent 1ed6429fb6
commit 5d1054338c
16 files changed
+559 -1

No files matched your search

+3 -1
View File
@@ -69,11 +69,12 @@ def ciBuild = System.getenv("CI") == "true"
def ciRef = System.getenv("GITHUB_REF") ?: ""
def ciRunNumber = System.getenv("GITHUB_RUN_NUMBER") ?: ""
def isReleaseBuild = ciBuild && ciRef.contains("alpha")
def buildCommit = commitHash()
def devReleaseName
if (ciBuild) {
devReleaseName = "Dev (#${ciRunNumber})"
} else {
devReleaseName = "Dev (${commitHash()})"
devReleaseName = "Dev (${buildCommit})"
}
def version = "12.0"
@@ -96,6 +97,7 @@ android {
versionName "${versionDisplayName}"
buildConfigField "String", "VERSION_DISPLAY_NAME", "\"${versionDisplayName}\""
buildConfigField "String", "MAJOR_VERSION", "\"${majorVersion}\""
buildConfigField "String", "COMMIT_HASH", "\"${buildCommit}\""
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
+27
View File
@@ -19,6 +19,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<permission
android:name="${packageName}.permission.READ_SETTINGS"
@@ -70,6 +71,32 @@
</intent-filter>
</service>
<provider
android:authorities="${applicationId}.bugreport.provider"
android:exported="false"
android:grantUriPermissions="true"
android:name="app.lawnchair.bugreport.FileProvider">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
<receiver
android:name="app.lawnchair.bugreport.BugReportReceiver"
android:exported="false">
<intent-filter>
<action android:name="${applicationId}.bugreport.COPY" />
<action android:name="${applicationId}.bugreport.UPLOAD" />
<action android:name="${applicationId}.bugreport.UPLOAD_COMPLETE" />
</intent-filter>
</receiver>
<service
android:enabled="true"
android:exported="false"
android:name="app.lawnchair.bugreport.UploaderService"
android:process=":bugReport" />
<meta-data
android:name="xyz.paphonb.quickstepswitcher.minSdk"
android:value="30" />
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ This file is part of Lawnchair Launcher.
~
~ Lawnchair Launcher 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.
~
~ Lawnchair Launcher 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 Lawnchair Launcher. If not, see <https://www.gnu.org/licenses/>.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="#000" android:pathData="M14,12H10V10H14M14,16H10V14H14M20,8H17.19C16.74,7.22 16.12,6.55 15.37,6.04L17,4.41L15.59,3L13.42,5.17C12.96,5.06 12.5,5 12,5C11.5,5 11.04,5.06 10.59,5.17L8.41,3L7,4.41L8.62,6.04C7.88,6.55 7.26,7.22 6.81,8H4V10H6.09C6.04,10.33 6,10.66 6,11V12H4V14H6V15C6,15.34 6.04,15.67 6.09,16H4V18H6.81C7.85,19.79 9.78,21 12,21C14.22,21 16.15,19.79 17.19,18H20V16H17.91C17.96,15.67 18,15.34 18,15V14H20V12H18V11C18,10.66 17.96,10.33 17.91,10H20V8Z" />
</vector>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ This file is part of Lawnchair Launcher.
~
~ Lawnchair Launcher 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.
~
~ Lawnchair Launcher 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 Lawnchair Launcher. If not, see <https://www.gnu.org/licenses/>.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="?android:textColorSecondary" android:pathData="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z" />
</vector>
+25
View File
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ This file is part of Lawnchair Launcher.
~
~ Lawnchair Launcher 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.
~
~ Lawnchair Launcher 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 Lawnchair Launcher. If not, see <https://www.gnu.org/licenses/>.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="?android:textColorSecondary" android:pathData="M9,16V10H5L12,3L19,10H15V16H9M5,20V18H19V20H5Z" />
</vector>
+2
View File
@@ -32,4 +32,6 @@
<color name="black_800">#121212</color>
<color name="black_900">#000000</color>
<color name="bugNotificationColor">#ff4caf50</color>
</resources>
+18
View File
@@ -168,4 +168,22 @@
<string name="dynamic">Dynamic</string>
<string name="all_apps_search_market_message">Search for More Apps</string>
<string name="show_app_search_bar">Show Search Bar</string>
<string name="lawnchair_bug_report">Lawnchair Bug Report</string>
<string name="crash_report_notif_title">%1$s Crashed</string>
<string name="action_upload">Upload to Dogbin</string>
<string name="action_copy_link">Copy Link</string>
<string name="action_copy">Copy</string>
<string name="copied_toast">Copied to clipboard.</string>
<string name="action_share">Share</string>
<string name="action_upload_error">Upload failed</string>
<string name="dogbin_uploading">Uploading…</string>
<string name="bugreport_channel_name">Bug Reports</string>
<string name="status_channel_name">Upload Status</string>
<string name="bugreport_group_summary">%d new reports.</string>
<string name="bugreport_group_summary_multiple">Multiple new reports.</string>
</resources>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="log_files" path="logs"/>
</paths>
@@ -25,6 +25,7 @@ import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import app.lawnchair.bugreport.LawnchairBugReporter
import app.lawnchair.preferences.PreferenceManager
import app.lawnchair.util.restartLauncher
import com.android.launcher3.InvariantDeviceProfile
@@ -42,6 +43,8 @@ class LawnchairApp : Application() {
super.onCreate()
instance = this
QuickStepContract.sRecentsDisabled = !recentsEnabled
LawnchairBugReporter.INSTANCE.get(this)
}
fun onLauncherAppStateCreated() {
@@ -0,0 +1,86 @@
package app.lawnchair.bugreport
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import androidx.core.content.FileProvider
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
import java.io.File
data class BugReport(val timestamp: Long, val id: Int, val type: String, val description: String, val contents: String,
var link: String?, var uploadError: Boolean = false, val file: File?) : Parcelable {
constructor(id: Int, type: String, description: String, contents: String, file: File?) : this(
System.currentTimeMillis(), id, type, description, contents, null, false, file)
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readInt(),
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString(),
parcel.readByte() != 0.toByte(),
parcel.readString()?.let { File(it) })
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(timestamp)
parcel.writeInt(id)
parcel.writeString(type)
parcel.writeString(description)
parcel.writeString(contents)
parcel.writeString(link)
parcel.writeByte(if (uploadError) 1 else 0)
parcel.writeString(file?.absolutePath)
}
override fun describeContents(): Int {
return 0
}
fun getTitle(context: Context): String {
return if (type == TYPE_UNCAUGHT_EXCEPTION) {
context.getString(R.string.crash_report_notif_title,
context.getString(R.string.derived_app_name))
} else type
}
fun getFileUri(context: Context): Uri? {
return file?.let {
FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.bugreport.provider", it)
}
}
fun createShareIntent(context: Context): Intent {
val sendIntent: Intent = Intent(Intent.ACTION_SEND).apply {
val fileUri = getFileUri(context)
if (fileUri != null) {
putExtra(Intent.EXTRA_STREAM, fileUri)
} else {
putExtra(Intent.EXTRA_TEXT, link ?: contents)
}
type = "text/plain"
}
return Intent.createChooser(sendIntent, context.getText(R.string.lawnchair_bug_report))
}
val notificationId = id
companion object CREATOR : Parcelable.Creator<BugReport> {
const val TYPE_UNCAUGHT_EXCEPTION = "Uncaught exception"
const val TYPE_STRICT_MODE_VIOLATION = "Strict mode violation"
override fun createFromParcel(parcel: Parcel): BugReport {
return BugReport(parcel)
}
override fun newArray(size: Int): Array<BugReport?> {
return arrayOfNulls(size)
}
}
}
@@ -0,0 +1,136 @@
package app.lawnchair.bugreport
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.*
import android.graphics.drawable.Icon
import android.net.Uri
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
class BugReportReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val report = intent.getParcelableExtra<BugReport>("report")!!
when (intent.action) {
COPY_ACTION -> copyReport(context, report)
UPLOAD_ACTION -> startUpload(context, report)
UPLOAD_COMPLETE_ACTION -> notify(context, report)
}
}
private fun copyReport(context: Context, report: BugReport) {
val clipData = ClipData.newPlainText(context.getString(R.string.lawnchair_bug_report), report.link ?: report.contents)
context.getSystemService<ClipboardManager>()!!.setPrimaryClip(clipData)
Toast.makeText(context, R.string.copied_toast, Toast.LENGTH_LONG).show()
}
private fun startUpload(context: Context, report: BugReport) {
notify(context, report, true)
context.startService(Intent(context, UploaderService::class.java)
.putExtra("report", report))
}
companion object {
const val notificationChannelId = "${BuildConfig.APPLICATION_ID}.BugReport"
const val statusChannelId = "${BuildConfig.APPLICATION_ID}.status"
private const val GROUP_KEY = "${BuildConfig.APPLICATION_ID}.crashes"
private const val GROUP_ID = 0
private const val COPY_ACTION = "${BuildConfig.APPLICATION_ID}.bugreport.COPY"
private const val UPLOAD_ACTION = "${BuildConfig.APPLICATION_ID}.bugreport.UPLOAD"
const val UPLOAD_COMPLETE_ACTION = "${BuildConfig.APPLICATION_ID}.bugreport.UPLOAD_COMPLETE"
fun notify(context: Context, report: BugReport, uploading: Boolean = false) {
val manager = context.getSystemService<NotificationManager>()!!
val notificationId = report.notificationId
val builder = Notification.Builder(context, notificationChannelId)
.setContentTitle(report.getTitle(context))
.setContentText(report.description)
.setSmallIcon(R.drawable.ic_bug_notification)
.setColor(ContextCompat.getColor(context, R.color.bugNotificationColor))
.setOnlyAlertOnce(true)
.setGroup(GROUP_KEY)
.setShowWhen(true)
.setWhen(report.timestamp)
val count = manager.activeNotifications.filter { it.groupKey == GROUP_KEY }.count()
val summary = if (count > 99 || count < 0) {
context.getString(R.string.bugreport_group_summary_multiple)
} else {
context.getString(R.string.bugreport_group_summary, count)
}
val groupBuilder = Notification.Builder(context, notificationChannelId)
.setContentTitle(context.getString(R.string.bugreport_channel_name))
.setContentText(summary)
.setSmallIcon(R.drawable.ic_bug_notification)
.setColor(ContextCompat.getColor(context, R.color.bugNotificationColor))
.setStyle(Notification.InboxStyle()
.setBigContentTitle(summary)
.setSummaryText(context.getString(R.string.bugreport_channel_name)))
.setGroupSummary(true)
.setGroup(GROUP_KEY)
val fileUri = report.getFileUri(context)
if (report.link != null) {
val openIntent = Intent(Intent.ACTION_VIEW, Uri.parse(report.link))
val pendingOpenIntent = PendingIntent.getActivity(
context, notificationId, openIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
builder.setContentIntent(pendingOpenIntent)
} else if (fileUri != null) {
val openIntent = Intent(Intent.ACTION_VIEW)
.setDataAndType(fileUri, "text/plain")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val pendingOpenIntent = PendingIntent.getActivity(
context, notificationId, openIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
builder.setContentIntent(pendingOpenIntent)
}
val pendingShareIntent = PendingIntent.getActivity(
context, notificationId, report.createShareIntent(context), FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
val icon = Icon.createWithResource(context, R.drawable.ic_share)
val shareActionBuilder = Notification.Action.Builder(
icon, context.getString(R.string.action_share), pendingShareIntent)
builder.addAction(shareActionBuilder.build())
if (report.link != null || fileUri == null) {
val copyIntent = Intent(COPY_ACTION)
.setPackage(BuildConfig.APPLICATION_ID)
.putExtra("report", report)
val pendingCopyIntent = PendingIntent.getBroadcast(
context, notificationId, copyIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
val copyText = if (report.link != null) R.string.action_copy_link else R.string.action_copy
val copyIcon = Icon.createWithResource(context, R.drawable.ic_copy)
val copyActionBuilder = Notification.Action.Builder(
copyIcon, context.getString(copyText), pendingCopyIntent)
builder.addAction(copyActionBuilder.build())
}
if (uploading) {
builder.setOngoing(true)
builder.setProgress(0, 0, true)
} else if (report.link == null && UploaderUtils.isAvailable) {
val uploadIntent = Intent(UPLOAD_ACTION)
.setPackage(BuildConfig.APPLICATION_ID)
.putExtra("report", report)
val pendingUploadIntent = PendingIntent.getBroadcast(
context, notificationId, uploadIntent, FLAG_UPDATE_CURRENT or FLAG_IMMUTABLE)
val uploadText = if (report.uploadError) R.string.action_upload_error else R.string.action_upload
val uploadIcon = Icon.createWithResource(context, R.drawable.ic_upload)
val uploadActionBuilder = Notification.Action.Builder(
uploadIcon, context.getString(uploadText), pendingUploadIntent)
builder.addAction(uploadActionBuilder.build())
}
manager.notify(notificationId, builder.build())
manager.notify(GROUP_ID, groupBuilder.build())
}
}
}
@@ -0,0 +1,5 @@
package app.lawnchair.bugreport
import androidx.core.content.FileProvider
class FileProvider : FileProvider()
@@ -0,0 +1,119 @@
package app.lawnchair.bugreport
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.core.content.getSystemService
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
import com.android.launcher3.util.MainThreadInitializedObject
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class LawnchairBugReporter(private val context: Context) {
private val notificationManager = context.getSystemService<NotificationManager>()!!
private val cacheFolder by lazy { File(context.cacheDir, "logs").apply {
deleteRecursively()
mkdirs()
} }
private val appName by lazy { context.getString(R.string.derived_app_name) }
init {
notificationManager.createNotificationChannel(
NotificationChannel(
BugReportReceiver.notificationChannelId,
context.getString(R.string.bugreport_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
)
notificationManager.createNotificationChannel(
NotificationChannel(
BugReportReceiver.statusChannelId,
context.getString(R.string.status_channel_name),
NotificationManager.IMPORTANCE_NONE
)
)
val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
sendNotification(throwable)
defaultHandler?.uncaughtException(thread, throwable)
}
}
private fun sendNotification(throwable: Throwable) {
val bugReport = Report(BugReport.TYPE_UNCAUGHT_EXCEPTION, throwable)
.generateBugReport() ?: return
val notifications = notificationManager.activeNotifications
val hasNotification = notifications.any { it.id == bugReport.notificationId }
if (hasNotification || notifications.size > 3) {
return
}
BugReportReceiver.notify(context, bugReport)
}
inner class Report(val error: String, val throwable: Throwable? = null) {
private val fileName = "$appName bug report ${SimpleDateFormat.getDateTimeInstance().format(Date())}"
fun generateBugReport(): BugReport? {
val contents = writeContents()
val contentsWithHeader = "$fileName\n$contents"
val reportFile = save(contentsWithHeader)
val id = contents.hashCode()
return BugReport(id, error, getDescription(throwable ?: return null), contentsWithHeader, reportFile)
}
private fun getDescription(throwable: Throwable): String {
return "${throwable::class.java.name}: ${throwable.message}"
}
private fun save(contents: String): File? {
val dest = cacheFolder
val file = File(dest, "$fileName.txt")
if (!file.createNewFile()) return null
file.writeText(contents)
return file
}
private fun writeContents() = StringBuilder()
.appendLine("version: ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
.appendLine("commit: ${BuildConfig.COMMIT_HASH}")
.appendLine("build.brand: ${Build.BRAND}")
.appendLine("build.device: ${Build.DEVICE}")
.appendLine("build.display: ${Build.DISPLAY}")
.appendLine("build.fingerprint: ${Build.FINGERPRINT}")
.appendLine("build.hardware: ${Build.HARDWARE}")
.appendLine("build.id: ${Build.ID}")
.appendLine("build.manufacturer: ${Build.MANUFACTURER}")
.appendLine("build.model: ${Build.MODEL}")
.appendLine("build.product: ${Build.PRODUCT}")
.appendLine("build.type: ${Build.TYPE}")
.appendLine("version.codename: ${Build.VERSION.CODENAME}")
.appendLine("version.incremental: ${Build.VERSION.INCREMENTAL}")
.appendLine("version.release: ${Build.VERSION.RELEASE}")
.appendLine("version.sdk_int: ${Build.VERSION.SDK_INT}")
.appendLine("display.density_dpi: ${context.resources.displayMetrics.densityDpi}")
.appendLine()
.appendLine("error: $error")
.also {
if (throwable != null) {
it
.appendLine()
.appendLine(Log.getStackTraceString(throwable))
}
}
.toString()
}
companion object {
val INSTANCE = MainThreadInitializedObject(::LawnchairBugReporter)
}
}
@@ -0,0 +1,67 @@
package app.lawnchair.bugreport
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.android.launcher3.R
import kotlinx.coroutines.*
import java.util.*
class UploaderService : Service() {
private var job: Job? = null
private val scope = CoroutineScope(Dispatchers.IO) + CoroutineName("UploaderService")
private val uploadQueue: Queue<BugReport> = LinkedList()
override fun onBind(intent: Intent): IBinder {
TODO("not implemented")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return START_REDELIVER_INTENT
uploadQueue.offer(intent.getParcelableExtra("report"))
if (job == null) {
job = scope.launch {
startUpload()
stopSelf()
}
}
return START_STICKY
}
private suspend fun startUpload() {
while (uploadQueue.isNotEmpty()) {
val report = uploadQueue.poll()!!
try {
report.link = UploaderUtils.upload(report.contents)
} catch (e: Throwable) {
report.uploadError = true
} finally {
sendBroadcast(Intent(this, BugReportReceiver::class.java)
.setAction(BugReportReceiver.UPLOAD_COMPLETE_ACTION)
.putExtra("report", report))
}
}
}
override fun onCreate() {
super.onCreate()
Log.d("DUS", "onCreate")
startForeground(101, NotificationCompat.Builder(this, BugReportReceiver.statusChannelId)
.setSmallIcon(R.drawable.ic_bug_notification)
.setContentTitle(getString(R.string.dogbin_uploading))
.setColor(ContextCompat.getColor(this, R.color.bugNotificationColor))
.setPriority(NotificationCompat.PRIORITY_MIN)
.build())
}
override fun onDestroy() {
super.onDestroy()
job?.cancel()
}
}
@@ -0,0 +1,11 @@
package app.lawnchair.bugreport
object UploaderUtils {
const val isAvailable = false
@Suppress("BlockingMethodInNonBlockingContext")
suspend fun upload(content: String): String {
TODO("find an uploader service")
}
}
@@ -37,6 +37,9 @@ fun DebugMenuPreferences() {
context.startActivity(intent)
})
IconShapePreference()
ClickablePreference(label = "Crash launcher", onClick = {
throw RuntimeException("User triggered crash")
})
}
}
}