feat: Diagnosedaten senden (Opt-out, Zahnrad-Knopf, einmaliger Hinweis)

Eigenes kleines Log (Abstuerze per UncaughtExceptionHandler, Jam- und
PC-Verbindungsfehler), gefiltert an POST /api/diag des Playtube-Dienstes,
kurz nach dem Start hoechstens alle 6 Stunden. Einstellungsdialog mit
Schalter, "Jetzt senden" und Installations-Kennung. Unit-Tests DiagReportTest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-12 22:34:30 +01:00
co-authored by Claude Opus 5.5
parent d8d6ef4196
commit 9bab0d6a24
10 changed files with 421 additions and 4 deletions
@@ -0,0 +1,134 @@
package de.fojadrachi.playtube
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.security.SecureRandom
/**
* Diagnosedaten: kleines eigenes Log (Abstuerze, Verbindungsfehler) in `files/diag.log`, das
* Playtube kurz nach dem Start und hoechstens alle 6 Stunden an den Playtube-Server schickt
* (`POST /api/diag`). Standardmaessig an, abschaltbar im Einstellungsdialog.
*/
object Diagnostics {
private const val PREFS = "playtube"
private const val KEY_ENABLED = "diag_enabled"
private const val KEY_INSTALL_ID = "diag_install_id"
private const val KEY_LAST_SENT = "diag_last_sent"
private const val KEY_LAST_TRY = "diag_last_try"
private const val KEY_NOTICE = "diag_notice_shown"
private const val MAX_LOG_BYTES = 256 * 1024
private const val INTERVAL_MS = 6 * 3600 * 1000L
private const val TIMEOUT_MS = 10_000
private var appContext: Context? = null
private val main = Handler(Looper.getMainLooper())
fun init(context: Context) {
if (appContext != null) return
appContext = context.applicationContext
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
// Absturz sofort ins Log - gesendet wird beim naechsten Start.
line("Absturz in ${thread.name}: ${error.stackTraceToString().take(3000)}")
previous?.uncaughtException(thread, error)
}
}
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
fun isEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_ENABLED, true)
fun setEnabled(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean(KEY_ENABLED, enabled).apply()
}
/** Einmaliger Hinweis, dass Diagnosedaten gesendet werden (Opt-out). */
fun needsNotice(context: Context): Boolean = !prefs(context).getBoolean(KEY_NOTICE, false)
fun noticeShown(context: Context) {
prefs(context).edit().putBoolean(KEY_NOTICE, true).apply()
}
fun installId(context: Context): String {
val prefs = prefs(context)
prefs.getString(KEY_INSTALL_ID, null)?.takeIf { it.isNotBlank() }?.let { return it }
val bytes = ByteArray(12).also { SecureRandom().nextBytes(it) }
val id = bytes.joinToString("") { "%02x".format(it) }
prefs.edit().putString(KEY_INSTALL_ID, id).apply()
return id
}
private fun logFile(context: Context) = File(context.filesDir, "diag.log")
/** Zeile ins Diagnose-Log schreiben (thread-sicher, auch ohne Versand-Erlaubnis lokal). */
@Synchronized
fun line(text: String) {
val context = appContext ?: return
runCatching {
val file = logFile(context)
if (file.length() > MAX_LOG_BYTES) {
// Aeltere Haelfte verwerfen.
val keep = file.readText().takeLast(MAX_LOG_BYTES / 2)
file.writeText(keep.substring(keep.indexOf('\n') + 1))
}
file.appendText("[${System.currentTimeMillis() / 1000}] ${text.replace('\n', ' ')}\n")
}
}
/** Automatisch senden (Start): nur wenn an, neue Zeilen da und der letzte Versuch >= 6 h her ist. */
fun sendIfDue(context: Context) {
if (!isEnabled(context)) return
val now = System.currentTimeMillis()
if (now - prefs(context).getLong(KEY_LAST_TRY, 0) < INTERVAL_MS) return
send(context) { }
}
/** Senden; [done] bekommt (null = nichts Neues, true/false = Erfolg) auf dem Hauptthread. */
fun send(context: Context, done: (Boolean?) -> Unit) {
val ctx = context.applicationContext
Thread {
val prefs = prefs(ctx)
val text = runCatching { logFile(ctx).readText() }.getOrDefault("")
val collected = DiagReport.collect(text, prefs.getLong(KEY_LAST_SENT, 0))
if (collected.lines.isEmpty()) {
main.post { done(null) }
return@Thread
}
prefs.edit().putLong(KEY_LAST_TRY, System.currentTimeMillis()).apply()
val body = DiagReport.build(
installId(ctx),
BuildConfig.VERSION_NAME,
Build.VERSION.RELEASE ?: "?",
"${Build.MANUFACTURER} ${Build.MODEL}".take(80),
collected.lines,
)
val ok = post("${BuildConfig.JAM_SERVER}/api/diag", body.toString())
if (ok) prefs.edit().putLong(KEY_LAST_SENT, collected.latest).apply()
main.post { done(ok) }
}.start()
}
private fun post(url: String, json: String): Boolean =
try {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connectTimeout = TIMEOUT_MS
connection.readTimeout = TIMEOUT_MS
connection.requestMethod = "POST"
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("User-Agent", "Playtube-Android/${BuildConfig.VERSION_NAME}")
try {
connection.outputStream.use { it.write(json.toByteArray()) }
connection.responseCode == HttpURLConnection.HTTP_OK
} finally {
connection.disconnect()
}
} catch (_: Exception) {
false
}
}