From 5d1054338c41ccc8385fe885e4ca9dc968b968fd Mon Sep 17 00:00:00 2001 From: Suphon Thanakornpakapong Date: Tue, 26 Oct 2021 15:34:48 +0700 Subject: [PATCH] Implement bug reporter --- build.gradle | 4 +- lawnchair/AndroidManifest.xml | 27 ++++ .../res/drawable/ic_bug_notification.xml | 25 ++++ lawnchair/res/drawable/ic_copy.xml | 25 ++++ lawnchair/res/drawable/ic_upload.xml | 25 ++++ lawnchair/res/values/color.xml | 2 + lawnchair/res/values/strings.xml | 18 +++ lawnchair/res/xml/provider_paths.xml | 4 + lawnchair/src/app/lawnchair/LawnchairApp.kt | 3 + .../src/app/lawnchair/bugreport/BugReport.kt | 86 +++++++++++ .../lawnchair/bugreport/BugReportReceiver.kt | 136 ++++++++++++++++++ .../app/lawnchair/bugreport/FileProvider.kt | 5 + .../bugreport/LawnchairBugReporter.kt | 119 +++++++++++++++ .../lawnchair/bugreport/UploaderService.kt | 67 +++++++++ .../app/lawnchair/bugreport/UploaderUtils.kt | 11 ++ .../ui/preferences/DebugMenuPreferences.kt | 3 + 16 files changed, 559 insertions(+), 1 deletion(-) create mode 100644 lawnchair/res/drawable/ic_bug_notification.xml create mode 100644 lawnchair/res/drawable/ic_copy.xml create mode 100644 lawnchair/res/drawable/ic_upload.xml create mode 100644 lawnchair/res/xml/provider_paths.xml create mode 100644 lawnchair/src/app/lawnchair/bugreport/BugReport.kt create mode 100644 lawnchair/src/app/lawnchair/bugreport/BugReportReceiver.kt create mode 100644 lawnchair/src/app/lawnchair/bugreport/FileProvider.kt create mode 100644 lawnchair/src/app/lawnchair/bugreport/LawnchairBugReporter.kt create mode 100644 lawnchair/src/app/lawnchair/bugreport/UploaderService.kt create mode 100644 lawnchair/src/app/lawnchair/bugreport/UploaderUtils.kt diff --git a/build.gradle b/build.gradle index fcf710af66..4ad268dbbc 100644 --- a/build.gradle +++ b/build.gradle @@ -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 diff --git a/lawnchair/AndroidManifest.xml b/lawnchair/AndroidManifest.xml index 33f268108d..ba3defee91 100644 --- a/lawnchair/AndroidManifest.xml +++ b/lawnchair/AndroidManifest.xml @@ -19,6 +19,7 @@ + + + + + + + + + + + + + + + diff --git a/lawnchair/res/drawable/ic_bug_notification.xml b/lawnchair/res/drawable/ic_bug_notification.xml new file mode 100644 index 0000000000..aadcec8ede --- /dev/null +++ b/lawnchair/res/drawable/ic_bug_notification.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/lawnchair/res/drawable/ic_copy.xml b/lawnchair/res/drawable/ic_copy.xml new file mode 100644 index 0000000000..09b81dfe5c --- /dev/null +++ b/lawnchair/res/drawable/ic_copy.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/lawnchair/res/drawable/ic_upload.xml b/lawnchair/res/drawable/ic_upload.xml new file mode 100644 index 0000000000..fd1cf428f2 --- /dev/null +++ b/lawnchair/res/drawable/ic_upload.xml @@ -0,0 +1,25 @@ + + + + + + diff --git a/lawnchair/res/values/color.xml b/lawnchair/res/values/color.xml index 4792860655..1c7f5606c0 100644 --- a/lawnchair/res/values/color.xml +++ b/lawnchair/res/values/color.xml @@ -32,4 +32,6 @@ #121212 #000000 + + #ff4caf50 \ No newline at end of file diff --git a/lawnchair/res/values/strings.xml b/lawnchair/res/values/strings.xml index 9570e97368..2d931a2d0d 100644 --- a/lawnchair/res/values/strings.xml +++ b/lawnchair/res/values/strings.xml @@ -168,4 +168,22 @@ Dynamic Search for More Apps Show Search Bar + + Lawnchair Bug Report + %1$s Crashed + Upload to Dogbin + + Copy Link + Copy + Copied to clipboard. + Share + + Upload failed + Uploading… + + Bug Reports + Upload Status + + %d new reports. + Multiple new reports. diff --git a/lawnchair/res/xml/provider_paths.xml b/lawnchair/res/xml/provider_paths.xml new file mode 100644 index 0000000000..0a2c179330 --- /dev/null +++ b/lawnchair/res/xml/provider_paths.xml @@ -0,0 +1,4 @@ + + + + diff --git a/lawnchair/src/app/lawnchair/LawnchairApp.kt b/lawnchair/src/app/lawnchair/LawnchairApp.kt index 474c3259e9..5c7dc3315b 100644 --- a/lawnchair/src/app/lawnchair/LawnchairApp.kt +++ b/lawnchair/src/app/lawnchair/LawnchairApp.kt @@ -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() { diff --git a/lawnchair/src/app/lawnchair/bugreport/BugReport.kt b/lawnchair/src/app/lawnchair/bugreport/BugReport.kt new file mode 100644 index 0000000000..3558af059c --- /dev/null +++ b/lawnchair/src/app/lawnchair/bugreport/BugReport.kt @@ -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 { + + 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 { + return arrayOfNulls(size) + } + } +} diff --git a/lawnchair/src/app/lawnchair/bugreport/BugReportReceiver.kt b/lawnchair/src/app/lawnchair/bugreport/BugReportReceiver.kt new file mode 100644 index 0000000000..47a326227d --- /dev/null +++ b/lawnchair/src/app/lawnchair/bugreport/BugReportReceiver.kt @@ -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("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()!!.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()!! + 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()) + } + } +} diff --git a/lawnchair/src/app/lawnchair/bugreport/FileProvider.kt b/lawnchair/src/app/lawnchair/bugreport/FileProvider.kt new file mode 100644 index 0000000000..c9cc879d9b --- /dev/null +++ b/lawnchair/src/app/lawnchair/bugreport/FileProvider.kt @@ -0,0 +1,5 @@ +package app.lawnchair.bugreport + +import androidx.core.content.FileProvider + +class FileProvider : FileProvider() diff --git a/lawnchair/src/app/lawnchair/bugreport/LawnchairBugReporter.kt b/lawnchair/src/app/lawnchair/bugreport/LawnchairBugReporter.kt new file mode 100644 index 0000000000..7fbf2eb886 --- /dev/null +++ b/lawnchair/src/app/lawnchair/bugreport/LawnchairBugReporter.kt @@ -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()!! + 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) + } +} diff --git a/lawnchair/src/app/lawnchair/bugreport/UploaderService.kt b/lawnchair/src/app/lawnchair/bugreport/UploaderService.kt new file mode 100644 index 0000000000..3144310bb5 --- /dev/null +++ b/lawnchair/src/app/lawnchair/bugreport/UploaderService.kt @@ -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 = 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() + } +} diff --git a/lawnchair/src/app/lawnchair/bugreport/UploaderUtils.kt b/lawnchair/src/app/lawnchair/bugreport/UploaderUtils.kt new file mode 100644 index 0000000000..5d837d0b7a --- /dev/null +++ b/lawnchair/src/app/lawnchair/bugreport/UploaderUtils.kt @@ -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") + } +} diff --git a/lawnchair/src/app/lawnchair/ui/preferences/DebugMenuPreferences.kt b/lawnchair/src/app/lawnchair/ui/preferences/DebugMenuPreferences.kt index d20608374a..c772e1db95 100644 --- a/lawnchair/src/app/lawnchair/ui/preferences/DebugMenuPreferences.kt +++ b/lawnchair/src/app/lawnchair/ui/preferences/DebugMenuPreferences.kt @@ -37,6 +37,9 @@ fun DebugMenuPreferences() { context.startActivity(intent) }) IconShapePreference() + ClickablePreference(label = "Crash launcher", onClick = { + throw RuntimeException("User triggered crash") + }) } } }