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,86 @@
package de.fojadrachi.playtube
import org.json.JSONArray
import org.json.JSONObject
/**
* Reine Logik fuer Diagnoseberichte (ohne Android, mit Unit-Tests): Logzeilen filtern und
* den Bericht fuer `POST /api/diag` (playtube-jam) bauen. Versand und Log-Datei: [Diagnostics].
*
* Nicht gesendet werden Cookies, Tokens, Anmeldedaten, Suchanfragen, Songtitel, Video-IDs,
* E-Mail-Adressen und URL-Parameter.
*/
object DiagReport {
const val MAX_LINES = 300
const val MAX_LINE_CHARS = 480
private val COOKIE = Regex("(?i)\\b(cookie|set-cookie|authorization)\\b.*")
private val BEARER = Regex("(?i)\\bbearer\\s+\\S+")
private val SECRET = Regex("(?i)\\b(\\w*token|\\w*key|secret|password|passwort|sapisid)(\\s*[\"']?\\s*[:=]\\s*[\"']?)[^\\s\"'&,;]+")
private val EMAIL = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
private val URL_QUERY = Regex("(?i)(https?://[^\\s?#\"']+)[?#][^\\s\"']*")
private val WORD = Regex("[A-Za-z0-9_-]+")
private val CONTROL = Regex("[\\u0000-\\u0008\\u000b-\\u001f\\u007f\\u202a-\\u202e\\u2066-\\u2069]")
/** YouTube-Video-ID: 11 Zeichen, Gross- und Kleinbuchstaben gemischt plus Ziffer, `_` oder `-`. */
fun looksLikeVideoId(word: String): Boolean =
word.length == 11 &&
word.all { it.isLetterOrDigit() && it.code < 128 || it == '_' || it == '-' } &&
word.any { it in 'A'..'Z' } && word.any { it in 'a'..'z' } &&
word.any { it.isDigit() || it == '_' || it == '-' }
private fun looksLikeSecret(word: String): Boolean =
word.length >= 20 && word.any { it.isDigit() } && word.any { it.isLetter() }
fun sanitize(line: String): String {
var text = CONTROL.replace(line, " ")
text = COOKIE.replace(text) { "${it.groupValues[1].lowercase()} [entfernt]" }
text = BEARER.replace(text, "Bearer [entfernt]")
text = SECRET.replace(text) { "${it.groupValues[1]}${it.groupValues[2]}[entfernt]" }
text = EMAIL.replace(text, "[e-mail]")
text = URL_QUERY.replace(text) { "${it.groupValues[1]}?[…]" }
text = WORD.replace(text) {
when {
looksLikeVideoId(it.value) -> "[video]"
looksLikeSecret(it.value) -> "[id]"
else -> it.value
}
}
return text.trim().take(MAX_LINE_CHARS)
}
data class Collected(val lines: List<String>, val latest: Long)
/** Zeilen `[secs] text` nach `since` (Unix-Sekunden), gefiltert, hoechstens [MAX_LINES] neueste. */
fun collect(logText: String, since: Long): Collected {
var latest = since
val lines = ArrayList<String>()
for (raw in logText.lineSequence()) {
if (!raw.startsWith("[")) continue
val end = raw.indexOf("] ")
if (end < 0) continue
val secs = raw.substring(1, end).toLongOrNull() ?: continue
if (secs <= since) continue
latest = maxOf(latest, secs)
lines += "[$secs] ${sanitize(raw.substring(end + 2))}"
}
return Collected(lines.takeLast(MAX_LINES), latest)
}
fun isError(line: String): Boolean {
val lower = line.lowercase()
return listOf("absturz", "exception", "error", "fehler", "fehlgeschlagen", "failed").any { it in lower }
}
fun build(installId: String, version: String, androidVersion: String, device: String, lines: List<String>, note: String = ""): JSONObject =
JSONObject()
.put("app", "android")
.put("version", version)
.put("platform", "android-$androidVersion")
.put("os", device)
.put("installId", installId)
.put("lines", JSONArray(lines))
.put("errors", JSONArray(lines.filter(::isError)))
.put("note", note)
.put("includesTitles", false)
}
@@ -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
}
}
@@ -104,9 +104,15 @@ object JamHub {
val body = JSONObject().put("name", displayName).put("client", "android").toString()
val request = Request.Builder().url("$server/api/jam").post(body.toRequestBody("application/json".toMediaType())).build()
http.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) { main.post { setStatus(str(R.string.jam_status_failed)) } }
override fun onFailure(call: Call, e: IOException) {
Diagnostics.line("jam: Anlegen fehlgeschlagen: $e")
main.post { setStatus(str(R.string.jam_status_failed)) }
}
override fun onResponse(call: Call, response: Response) {
val text = response.use { if (it.isSuccessful) it.body?.string() else null }
val text = response.use {
if (!it.isSuccessful) Diagnostics.line("jam: Anlegen fehlgeschlagen: HTTP ${it.code}")
if (it.isSuccessful) it.body?.string() else null
}
main.post {
val json = text?.let { runCatching { JSONObject(it) }.getOrNull() }
if (json == null) {
@@ -134,9 +140,13 @@ object JamHub {
setStatus(str(R.string.jam_status_joining))
val request = Request.Builder().url("$server/api/jam/$joinCode").build()
http.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) { main.post { setStatus(str(R.string.jam_status_failed)) } }
override fun onFailure(call: Call, e: IOException) {
Diagnostics.line("jam: Beitreten fehlgeschlagen: $e")
main.post { setStatus(str(R.string.jam_status_failed)) }
}
override fun onResponse(call: Call, response: Response) {
val status = response.use { it.code }
if (status != 200 && status != 404) Diagnostics.line("jam: Beitreten fehlgeschlagen: HTTP $status")
main.post {
when (status) {
200 -> {
@@ -195,6 +205,7 @@ object JamHub {
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
Diagnostics.line("jam: Verbindung fehlgeschlagen: $t")
main.post { if (socket === webSocket) lost() }
}
@@ -240,7 +251,10 @@ object JamHub {
"ended" -> close(endedText(msg.optString("reason")), forget = true)
"error" -> when (val error = msg.optString("error")) {
"not_found", "kicked", "full" -> close(endedText(error), forget = true)
else -> setStatus(errorText(error))
else -> {
Diagnostics.line("jam: Server meldet Fehler $error")
setStatus(errorText(error))
}
}
}
}
@@ -11,6 +11,10 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import android.webkit.CookieManager
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
@@ -58,12 +62,14 @@ class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Diagnostics.init(this)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.webView)
progress = findViewById(R.id.progress)
keepContentBetweenSystemBars()
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
findViewById<View>(R.id.jamButton).setOnClickListener { JamActivity.start(this) }
findViewById<View>(R.id.settingsButton).setOnClickListener { showSettings() }
JamHub.init(this)
configureWebView()
@@ -91,6 +97,9 @@ class MainActivity : AppCompatActivity() {
handler.post(probeLoop)
handler.post(jamLoop)
checkForUpdate()
showDiagnosticsNotice()
// Kurz nach dem Start: Absturz vom letzten Mal o. ä. senden (höchstens alle 6 Stunden).
handler.postDelayed({ Diagnostics.sendIfDue(this) }, DIAG_DELAY_MS)
}
override fun onNewIntent(intent: Intent) {
@@ -227,6 +236,58 @@ class MainActivity : AppCompatActivity() {
}.start()
}
// ------------------------------------------------------------------ Einstellungen / Diagnose
/** Einmaliger Hinweis: Diagnosedaten sind an (Opt-out) und lassen sich hier abschalten. */
private fun showDiagnosticsNotice() {
if (!Diagnostics.needsNotice(this)) return
AlertDialog.Builder(this)
.setTitle(R.string.diag_notice_title)
.setMessage(R.string.diag_notice_message)
.setPositiveButton(R.string.diag_notice_ok) { _, _ -> Diagnostics.noticeShown(this) }
.setNegativeButton(R.string.diag_notice_off) { _, _ ->
Diagnostics.setEnabled(this, false)
Diagnostics.noticeShown(this)
}
.setOnCancelListener { Diagnostics.noticeShown(this) }
.show()
}
private fun showSettings() {
val pad = (20 * resources.displayMetrics.density).toInt()
val box = CheckBox(this).apply {
setText(R.string.diag_enabled)
isChecked = Diagnostics.isEnabled(this@MainActivity)
setOnCheckedChangeListener { _, checked -> Diagnostics.setEnabled(this@MainActivity, checked) }
}
val hint = TextView(this).apply {
text = getString(R.string.diag_hint) + "\n\n" + getString(R.string.diag_install_id, Diagnostics.installId(this@MainActivity))
setTextIsSelectable(true)
alpha = 0.75f
}
val content = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(pad, pad / 2, pad, 0)
addView(box)
addView(hint)
}
AlertDialog.Builder(this)
.setTitle(R.string.settings_title)
.setView(content)
.setPositiveButton(R.string.diag_done, null)
.setNeutralButton(R.string.diag_send_now) { _, _ ->
Diagnostics.send(this) { ok ->
val text = when (ok) {
null -> R.string.diag_nothing
true -> R.string.diag_sent
false -> R.string.diag_failed
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
}
.show()
}
private fun showUpdateDialog(release: UpdateChecker.Release) {
val prefs = getSharedPreferences(PREFS, MODE_PRIVATE)
if (prefs.getString(KEY_DISMISSED_UPDATE, null) == release.tag) return
@@ -251,6 +312,7 @@ class MainActivity : AppCompatActivity() {
private const val HOME_URL = "https://music.youtube.com/"
private const val PROBE_INTERVAL_MS = 1500L
private const val JAM_INTERVAL_MS = 700L
private const val DIAG_DELAY_MS = 30_000L
private const val PREFS = "playtube"
private const val KEY_DISMISSED_UPDATE = "dismissed_update"
@@ -134,6 +134,7 @@ object PcSession {
}
}
} catch (e: IOException) {
Diagnostics.line("pc: Verbinden fehlgeschlagen: $e")
main.post {
if (gen != generation) return@post
reset()
@@ -293,6 +294,7 @@ object PcSession {
} catch (e: PcRemote.RemoteException) {
main.post { done(Result.failure(e)) } // Befehl abgelehnt - Verbindung bleibt
} catch (e: IOException) {
Diagnostics.line("pc: Verbindung verloren: $e")
closeConnection()
main.post {
if (gen == generation) onConnectionLost()