diff --git a/app/build.gradle b/app/build.gradle index 6d1819f..484ccdf 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -45,8 +45,8 @@ android { applicationId 'com.gorios.lanvoice' minSdk 26 targetSdk 34 - versionCode 4 - versionName '0.3.0' + versionCode 5 + versionName '0.3.1' ndk { abiFilters 'arm64-v8a' } } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } diff --git a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt index 918ed50..8ae8410 100644 --- a/app/src/main/java/com/gorios/lanvoice/MainActivity.kt +++ b/app/src/main/java/com/gorios/lanvoice/MainActivity.kt @@ -2,6 +2,7 @@ package com.gorios.lanvoice import android.Manifest import android.content.pm.PackageManager +import android.os.Build import android.os.Bundle import android.security.NetworkSecurityPolicy import androidx.activity.ComponentActivity @@ -11,15 +12,21 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState @@ -35,6 +42,8 @@ import com.gorios.lanvoice.audio.AecAvailability import com.gorios.lanvoice.audio.VoicePhase import com.gorios.lanvoice.audio.VoiceSession import com.gorios.lanvoice.audio.VoiceUiState +import com.gorios.lanvoice.diag.DiagnosticReportInfo +import com.gorios.lanvoice.diag.DiagnosticReportUpload import com.gorios.lanvoice.net.ConnectionStatus import com.gorios.lanvoice.net.DebugLogUpload import com.gorios.lanvoice.expression.ExpressionController @@ -46,6 +55,9 @@ import kotlinx.coroutines.delay class MainActivity : ComponentActivity() { private var state by mutableStateOf(VoiceUiState()) private var connectionLogs by mutableStateOf>(emptyList()) + private var reportSending by mutableStateOf(false) + private var reportResult by mutableStateOf(null) + private var appVersion = "unknown" private lateinit var session: VoiceSession private var pendingStart = false private var expressionState by mutableStateOf(ExpressionUiState()) @@ -69,17 +81,48 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + appVersion = packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown" DebugLogUpload.appLaunch( - packageManager.getPackageInfo(packageName, 0).versionName ?: "unknown", + appVersion, NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted("192.168.31.61"), ) session = VoiceSession( getString(R.string.voice_server_host), resources.getInteger(R.integer.voice_server_port), onState = { state = it; startPendingVoice() }, - onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(3) }, + onConnectionLog = { connectionLogs = (connectionLogs + it).takeLast(10) }, ) expressions = ExpressionController(this, this) { expressionState = it } - setContent { Home(state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions, connectionLogs) } + setContent { + Home( + state, ::toggleVoice, session::interrupt, expressionState, ::toggleExpressions, + connectionLogs, ::sendDiagnosticReport, reportSending, reportResult, + ) + } + } + + private fun sendDiagnosticReport() { + if (reportSending) return + reportSending = true + reportResult = null + DebugLogUpload.log("connect", "send_report started") + DiagnosticReportUpload.send( + DiagnosticReportInfo( + appVersion = appVersion, + device = "${Build.MANUFACTURER} ${Build.MODEL}", + androidApi = Build.VERSION.SDK_INT, + connection = state.connection.name, + voiceActive = state.voiceActive, + phase = state.phase.name, + aec = state.aec.name, + ), + ) { success -> + runOnUiThread { + if (!isDestroyed) { + reportSending = false + reportResult = if (success) "已发送" else "发送失败" + } + } + } } private fun toggleExpressions() { @@ -121,7 +164,6 @@ class MainActivity : ComponentActivity() { super.onStart() inForeground = true DebugLogUpload.log("connect", "activity onStart") - connectionLogs = emptyList() session.foreground() startPendingVoice() } @@ -153,10 +195,13 @@ fun Home( state: VoiceUiState, onToggleVoice: () -> Unit, onInterrupt: () -> Unit, expressionState: ExpressionUiState, onToggleExpressions: () -> Unit, connectionLogs: List = emptyList(), + onSendReport: () -> Unit = {}, reportSending: Boolean = false, reportResult: String? = null, ) { val gold = Color(0xFFE8C884) val muted = Color(0xFF9CA3AF) val connected = state.connection == ConnectionStatus.CONNECTED + val logScroll = rememberScrollState() + LaunchedEffect(connectionLogs, logScroll.maxValue) { logScroll.scrollTo(logScroll.maxValue) } val uploadResult by produceState(initialValue = DebugLogUpload.lastResult) { while (true) { value = DebugLogUpload.lastResult @@ -189,10 +234,10 @@ fun Home( Text("调试日志已开启 · $uploadResult", color = muted, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp)) if (connectionLogs.isNotEmpty()) { Text( - text = connectionLogs.takeLast(3).joinToString("\n"), + text = connectionLogs.takeLast(10).joinToString("\n"), color = muted, fontSize = 12.sp, textAlign = TextAlign.Center, - maxLines = 3, softWrap = false, overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(top = 6.dp), + lineHeight = 18.sp, softWrap = false, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 6.dp).heightIn(max = 54.dp).verticalScroll(logScroll), ) } ExpressionControls(expressionState, onToggleExpressions) @@ -224,6 +269,12 @@ fun Home( Button(onClick = onInterrupt, enabled = connected && state.voiceActive) { Text("打断") } + Row(verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = onSendReport, enabled = !reportSending) { + Text(if (reportSending) "发送中…" else "发送诊断报告", color = muted, fontSize = 12.sp) + } + reportResult?.let { Text(it, color = muted, fontSize = 12.sp) } + } Text( "AEC:" + when (state.aec) { AecAvailability.AVAILABLE -> "可用" diff --git a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt new file mode 100644 index 0000000..066dc93 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticLog.kt @@ -0,0 +1,41 @@ +package com.gorios.lanvoice.diag + +import java.util.ArrayDeque + +/** Process-local metadata only; never store voice, chat, images or authentication payloads. */ +object DiagnosticLog { + enum class Level { INFO, WARN, ERROR } + + data class Entry( + internal val id: Long, + val ts: Long, + val tag: String, + val msg: String, + val level: Level, + ) + + private const val CAPACITY = 500 + private val lock = Any() + private val entries = ArrayDeque() + private var nextId = 0L + + fun record( + tag: String, message: String, + level: Level = if (tag == "error") Level.ERROR else Level.INFO, + ): Entry = synchronized(lock) { + val bounded = message.replace('\r', ' ').replace('\n', ' ').take(500) + .let { if (it.lastOrNull()?.isHighSurrogate() == true) it.dropLast(1) else it } + val entry = Entry(++nextId, System.currentTimeMillis(), tag, bounded, level) + if (entries.size == CAPACITY) entries.removeFirst() + entries.addLast(entry) + entry + } + + fun snapshot(): List = synchronized(lock) { entries.toList() } + + /** Clear only entries included in a successful report; retain logs added during upload. */ + internal fun acknowledge(snapshot: List) = synchronized(lock) { + val through = snapshot.lastOrNull()?.id ?: return@synchronized + while (entries.isNotEmpty() && entries.first.id <= through) entries.removeFirst() + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt new file mode 100644 index 0000000..79f3512 --- /dev/null +++ b/app/src/main/java/com/gorios/lanvoice/diag/DiagnosticReportUpload.kt @@ -0,0 +1,96 @@ +package com.gorios.lanvoice.diag + +import okhttp3.Call +import okhttp3.Callback +import okhttp3.ConnectionPool +import okhttp3.ConnectionSpec +import okhttp3.Dispatcher +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import org.json.JSONArray +import org.json.JSONObject +import java.io.IOException +import java.net.Proxy +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +data class DiagnosticReportInfo( + val appVersion: String, + val device: String, + val androidApi: Int, + val connection: String, + val voiceActive: Boolean, + val phase: String, + val aec: String, +) + +/** Explicit user submission, isolated from both voice traffic and per-entry debug uploads. */ +object DiagnosticReportUpload { + private const val ENDPOINT = "https://192.168.31.61:5011/debug/report" + private val sending = AtomicBoolean() + private val json = "application/json; charset=utf-8".toMediaType() + private val client by lazy { + OkHttpClient.Builder() + .connectionSpecs(listOf(ConnectionSpec.MODERN_TLS)) + .proxy(Proxy.NO_PROXY) + .connectionPool(ConnectionPool(1, 30, TimeUnit.SECONDS)) + .dispatcher(Dispatcher().apply { maxRequests = 1; maxRequestsPerHost = 1 }) + .connectTimeout(3, TimeUnit.SECONDS) + .readTimeout(5, TimeUnit.SECONDS) + .writeTimeout(5, TimeUnit.SECONDS) + .callTimeout(10, TimeUnit.SECONDS) + .followRedirects(false) + .followSslRedirects(false) + .retryOnConnectionFailure(false) + .build() + } + + /** Result arrives on an OkHttp worker (or immediately if setup fails). */ + fun send(info: DiagnosticReportInfo, onResult: (Boolean) -> Unit) { + if (!sending.compareAndSet(false, true)) { + onResult(false) + return + } + val snapshot = DiagnosticLog.snapshot() + try { + val logs = JSONArray() + snapshot.forEach { entry -> + logs.put(JSONObject() + .put("ts", entry.ts).put("tag", entry.tag).put("msg", entry.msg) + .put("level", entry.level.name)) + } + val body = JSONObject() + .put("type", "diagnostic_report") + .put("timestamp", System.currentTimeMillis()) + .put("app_version", info.appVersion) + .put("device", info.device) + .put("android_api", info.androidApi) + .put("connection", info.connection) + .put("voice_active", info.voiceActive) + .put("phase", info.phase) + .put("aec", info.aec) + .put("logs", logs) + .toString().toRequestBody(json) + client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback { + override fun onFailure(call: Call, error: IOException) { + sending.set(false) + onResult(false) + } + + override fun onResponse(call: Call, response: Response) { + val success = response.isSuccessful + try { response.close() } catch (_: Exception) { } + if (success) DiagnosticLog.acknowledge(snapshot) + sending.set(false) + onResult(success) + } + }) + } catch (_: Exception) { + sending.set(false) + onResult(false) + } + } +} diff --git a/app/src/main/java/com/gorios/lanvoice/net/DebugLogUpload.kt b/app/src/main/java/com/gorios/lanvoice/net/DebugLogUpload.kt index d2ad4a1..66779c7 100644 --- a/app/src/main/java/com/gorios/lanvoice/net/DebugLogUpload.kt +++ b/app/src/main/java/com/gorios/lanvoice/net/DebugLogUpload.kt @@ -1,5 +1,6 @@ package com.gorios.lanvoice.net +import com.gorios.lanvoice.diag.DiagnosticLog import okhttp3.Call import okhttp3.Callback import okhttp3.ConnectionPool @@ -57,17 +58,18 @@ object DebugLogUpload { fun log(tag: String, message: String) { if (tag !in tags) return + // Record before the upload queue limit: offline/overloaded uploads must not + // lose the local diagnostics needed by a later user-submitted report. + val entry = DiagnosticLog.record(tag, message) if (pending.incrementAndGet() > MAX_PENDING) { pending.decrementAndGet() return } try { - val bounded = message.replace('\r', ' ').replace('\n', ' ').take(500) - .let { if (it.lastOrNull()?.isHighSurrogate() == true) it.dropLast(1) else it } val body = JSONObject() - .put("timestamp_ms", System.currentTimeMillis()) - .put("tag", tag) - .put("message", bounded) + .put("timestamp_ms", entry.ts) + .put("tag", entry.tag) + .put("message", entry.msg) .toString().toRequestBody(json) client.newCall(Request.Builder().url(ENDPOINT).post(body).build()).enqueue(object : Callback { override fun onFailure(call: Call, error: IOException) {