2 Commits
Author SHA1 Message Date
TapTap e6c1dae3c3 docs: explain how to retry diagnostics after a server update
CI / build (push) Successful in 4m5s
CI / play (push) Successful in 3m33s
2026-11-20 13:50:36 +00:00
TapTap b1ccfc9ee1 feat: upload diagnostics with redaction and crash capture
CI / build (push) Successful in 2m44s
CI / play (push) Skipped
- 500-entry local ring buffer, immediate flush for warnings/errors
- batch upload to POST /logs with device id, platform, version and session
- redact tokens, Authorization headers and secrets before storage/upload
- Android/desktop uncaught handlers persist a crash entry for the next launch
- Settings diagnostics card with pending count, send now and clear
- fall back cleanly when the server predates /logs
- include X-Request-Id in API failure diagnostics; version 0.4.3
2026-11-20 13:43:10 +00:00
20 changed files with 821 additions and 21 deletions

No files matched your search

+5 -1
View File
@@ -62,6 +62,10 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
**Keep this mood offline** switch, and Delete at the bottom.
- **Downloads** screen for device-side copies: play, delete, clear, storage
usage.
- **Diagnostics**: warnings, errors and crashes are kept in a 500-entry local
ring buffer and uploaded in batches (tokens and passwords are redacted). The
full-screen Settings screen shows the queue, last upload and a Send now action;
`scripts/logs.sh` on the server prints or clears stored entries.
- **Sleep timer** (15/30/45/60/90 minutes or **finish this track**) that pauses
playback. On Android the
pause is scheduled inside the media service, so it still fires when the app is
@@ -208,7 +212,7 @@ Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
| `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
Then `git tag v0.4.2 && git push --tags` builds, signs and uploads the bundle.
Then `git tag v0.4.3 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
+2 -1
View File
@@ -41,7 +41,7 @@ val hasUploadKey = uploadKeyStore?.exists() == true &&
val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
val appVersionName = System.getenv("VERSION_NAME")
?: localProperties.getProperty("VERSION_NAME")
?: "0.4.2"
?: "0.4.3"
kotlin {
androidTarget {
@@ -78,6 +78,7 @@ kotlin {
implementation("io.ktor:ktor-client-content-negotiation:3.1.2")
implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.2")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
}
@@ -9,6 +9,7 @@
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:name=".AudioManagerApplication"
android:allowBackup="true"
android:label="AudioManager"
android:supportsRtl="true"
@@ -0,0 +1,26 @@
package win.taptap.musicmanager.client
import android.app.Application
import win.taptap.musicmanager.client.logging.AppLog
/**
* Initializes diagnostics before the activity exists and records the one case
* the in-app logger cannot: an uncaught exception. The line is persisted
* synchronously and uploaded on the next launch.
*/
class AudioManagerApplication : Application() {
override fun onCreate() {
super.onCreate()
AndroidContextHolder.context = applicationContext
AppLog.init(platformStorage())
val previous = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
runCatching {
AppLog.error("crash", "Uncaught exception on ${thread.name}", error)
AppLog.flushNow()
}
previous?.uncaughtException(thread, error)
}
}
}
@@ -135,3 +135,7 @@ class AndroidStorage(context: Context) : AppStorage {
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
private val LOG_LOCK = Any()
internal actual fun <T> withLogLock(block: () -> T): T = synchronized(LOG_LOCK) { block() }
@@ -0,0 +1,4 @@
package win.taptap.musicmanager.client
/** One place for the version shown in Settings and sent with diagnostics. */
const val APP_VERSION = "0.4.3"
@@ -22,3 +22,9 @@ expect fun decodeImage(bytes: ByteArray): ImageBitmap?
* desktop and web have no metered flag and return true.
*/
expect fun isUnmeteredNetwork(): Boolean
/**
* Serializes the shared log buffer. Android and desktop have real threads;
* Wasm is single-threaded and runs the block directly.
*/
internal expect fun <T> withLogLock(block: () -> T): T
@@ -0,0 +1,6 @@
package win.taptap.musicmanager.client
import kotlinx.datetime.Clock
/** Epoch milliseconds, shared by the log buffer, settings and the uploader. */
fun currentTimeMillis(): Long = Clock.System.now().toEpochMilliseconds()
@@ -25,6 +25,7 @@ import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
import io.ktor.utils.io.ByteReadChannel
import kotlinx.serialization.json.Json
import win.taptap.musicmanager.client.logging.AppLog
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
expectSuccess = false
@@ -186,6 +187,16 @@ class ApiClient(private val http: HttpClient) {
suspend fun info(): ServerInfo = get("/info")
/** Uploads a diagnostics batch; returns how many entries the server kept. */
suspend fun uploadLogs(batch: ClientLogBatch): Int =
parse<ClientLogsAccepted>(
http.post(url("/logs")) {
auth()
contentType(ContentType.Application.Json)
setBody(batch)
},
).accepted
suspend fun search(
query: String,
limit: Int = 10,
@@ -345,11 +356,24 @@ class ApiClient(private val http: HttpClient) {
}
private suspend fun error(response: HttpResponse): ApiException {
val status = response.status.value
val requestId = response.headers["X-Request-Id"]
// Path only: query strings can carry the media token.
val method = response.call.request.method.value
val path = response.call.request.url.encodedPath
if (status >= 500) {
AppLog.warn(
"api",
"$method $path failed with $status" +
(requestId?.let { " (request $it)" } ?: ""),
)
}
val body = runCatching { response.body<ApiErrorBody>() }.getOrNull()
return ApiException(
status = response.status.value,
code = body?.error?.code ?: "http_${response.status.value}",
message = body?.error?.message ?: "Request failed (${response.status.value})",
status = status,
code = body?.error?.code ?: "http_$status",
message = body?.error?.message ?: "Request failed ($status)",
requestId = requestId,
)
}
@@ -8,8 +8,13 @@ data class ApiErrorBody(val error: ApiError)
@Serializable
data class ApiError(val code: String, val message: String)
class ApiException(val status: Int, val code: String, override val message: String) :
RuntimeException(message)
class ApiException(
val status: Int,
val code: String,
override val message: String,
/** Server request id from `X-Request-Id`, when the response carried one. */
val requestId: String? = null,
) : RuntimeException(message)
@Serializable
data class LoginRequest(
@@ -52,12 +57,34 @@ data class Song(
val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
}
@Serializable
data class ClientLogEntry(
val timestamp: Long = 0,
val level: String,
val tag: String,
val message: String,
val detail: String? = null,
val sessionId: String? = null,
)
@Serializable
data class ClientLogBatch(
val deviceId: String,
val platform: String,
val appVersion: String,
val entries: List<ClientLogEntry>,
)
@Serializable
data class ClientLogsAccepted(val accepted: Int)
@Serializable
data class ServerInfo(
val defaultSource: String = "deezer",
val deezerQuality: Int = 0,
val loudnessEnabled: Boolean = false,
val loudnessTargetLufs: Double = -16.0,
val clientLogRetentionDays: Int = 14,
)
@Serializable
@@ -40,6 +40,10 @@ data class ClientSettings(
val normalizationEnabled: Boolean = true,
/** 0 = gapless; other values are fade lengths in seconds. */
val crossfadeSeconds: Int = 0,
/** Upload warnings and errors to the server for later debugging. */
val diagnosticsEnabled: Boolean = true,
/** Stable random id so the server can group one device's batches. */
val deviceId: String = "",
)
/** The queue survives a restart so the next launch can resume where it stopped. */
@@ -0,0 +1,233 @@
package win.taptap.musicmanager.client.logging
import kotlin.random.Random
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import win.taptap.musicmanager.client.APP_VERSION
import win.taptap.musicmanager.client.currentTimeMillis
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.withLogLock
enum class LogLevel(val label: String, val severity: Int) {
DEBUG("debug", 0),
INFO("info", 1),
WARN("warn", 2),
ERROR("error", 3),
}
@Serializable
data class LogRecord(
val id: Long,
val timestamp: Long,
val level: String,
val tag: String,
val message: String,
val detail: String? = null,
val sessionId: String,
)
@Serializable
private data class StoredLogs(
val nextId: Long = 1,
val owner: String? = null,
val entries: List<LogRecord> = emptyList(),
)
/**
* Small, persistent diagnostics buffer.
*
* The buffer is a ring: info and above (debug is opt-in) is kept up to
* [MAX_ENTRIES], persisted after a short debounce, and flushed immediately for
* warnings and errors so a crash cannot lose the line that explains it. Bearing
* tokens, passwords and ARLs are redacted before anything is written or sent.
*
* Logging must never break playback: every storage operation is best-effort.
*/
object AppLog {
const val FILE = "logs.json"
const val MAX_ENTRIES = 500
private const val MAX_MESSAGE = 2_000
private const val MAX_DETAIL = 8_000
private const val MAX_TAG = 48
private const val FLUSH_DELAY_MS = 1_500L
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
}
private val bearer = Regex("""(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}""")
private val authorization = Regex("""(?i)\b(authorization\s*:\s*)[^\r\n]+""")
private val querySecret = Regex(
"""(?i)(\b(?:token|access_token|password|passwd|arl|key)=)[^&\s"'<>]+""",
)
private val jsonSecret = Regex(
"""(?i)("(?:token|access_token|password|arl|key)"\s*:\s*")[^"]*(")""",
)
private var storage: AppStorage? = null
private var scope: CoroutineScope? = null
private var flushJob: Job? = null
private var entries = mutableListOf<LogRecord>()
private var nextId = 1L
private var owner: String? = null
private var collecting = true
private var minimum = LogLevel.INFO
private var sessionId = newSessionId()
/** Safe to call more than once; the first storage wins. */
fun attach(storage: AppStorage, scope: CoroutineScope) {
if (this.storage == null) {
init(storage)
}
this.scope = scope
}
fun init(storage: AppStorage) {
withLogLock {
this.storage = storage
val stored = runCatching {
storage.read(FILE)?.let { json.decodeFromString<StoredLogs>(it) }
}.getOrNull()
entries = stored?.entries?.toMutableList() ?: mutableListOf()
nextId = maxOf(
stored?.nextId ?: 1L,
(entries.maxOfOrNull { it.id } ?: 0L) + 1,
)
owner = stored?.owner
}
info("app", "Started AudioManager $APP_VERSION on $platformName")
}
fun setCollecting(enabled: Boolean) {
collecting = enabled
}
fun setMinimumLevel(level: LogLevel) {
minimum = level
}
/** Clears the buffer when a different account signs in on this device. */
fun setOwner(name: String?) {
val clear = withLogLock {
val changed = owner != null && name != null && owner != name
if (changed) {
entries.clear()
nextId = 1
}
owner = name
changed
}
if (clear) flushNow()
}
fun ownerName(): String? = withLogLock { owner }
fun debug(tag: String, message: String, error: Throwable? = null) =
log(LogLevel.DEBUG, tag, message, error)
fun info(tag: String, message: String, error: Throwable? = null) =
log(LogLevel.INFO, tag, message, error)
fun warn(tag: String, message: String, error: Throwable? = null) =
log(LogLevel.WARN, tag, message, error)
fun error(tag: String, message: String, error: Throwable? = null) =
log(LogLevel.ERROR, tag, message, error)
/** Oldest entries first; the uploader takes a prefix and removes it on success. */
fun pending(limit: Int = 100): List<LogRecord> =
withLogLock { entries.take(limit.coerceAtLeast(1)) }
fun pendingCount(): Int = withLogLock { entries.size }
fun markUploaded(ids: Set<Long>) {
if (ids.isEmpty()) return
withLogLock { entries.removeAll { it.id in ids } }
flushNow()
}
fun clear() {
withLogLock {
entries.clear()
nextId = 1
owner = null
}
runCatching { storage?.delete(FILE) }
}
fun flushNow() {
val target = storage ?: return
val snapshot = withLogLock {
StoredLogs(nextId = nextId, owner = owner, entries = entries.toList())
}
runCatching { target.write(FILE, json.encodeToString(snapshot)) }
}
/** Removes tokens and passwords from a line; also used by tests. */
fun redact(value: String): String = value
.replace(bearer) { match -> match.groupValues[1] + "***" }
.replace(authorization) { match -> match.groupValues[1] + "***" }
.replace(querySecret) { match -> match.groupValues[1] + "***" }
.replace(jsonSecret) { match -> match.groupValues[1] + "***" + match.groupValues[2] }
private fun log(level: LogLevel, tag: String, message: String, error: Throwable?) {
if (!collecting || level.severity < minimum.severity) return
val cleanTag = redact(tag).trim().take(MAX_TAG).ifBlank { "app" }
val cleanMessage = redact(message).trim().take(MAX_MESSAGE).ifBlank { "(empty)" }
val cleanDetail = error
?.let { redact(it.stackTraceToString()).take(MAX_DETAIL) }
?.takeIf { it.isNotBlank() }
withLogLock {
entries += LogRecord(
id = nextId++,
timestamp = currentTimeMillis(),
level = level.label,
tag = cleanTag,
message = cleanMessage,
detail = cleanDetail,
sessionId = sessionId,
)
while (entries.size > MAX_ENTRIES) entries.removeAt(0)
}
// Console output is redacted too: logcat and desktop stderr are just as
// readable as the uploaded copy.
println("${level.label.uppercase()}/$cleanTag: $cleanMessage")
if (level.severity >= LogLevel.WARN.severity) {
flushNow()
} else {
scheduleFlush()
}
}
private fun scheduleFlush() {
val parent = scope
if (parent == null) {
flushNow()
return
}
if (flushJob?.isActive == true) return
flushJob = parent.launch {
delay(FLUSH_DELAY_MS)
flushJob = null
flushNow()
}
}
private fun newSessionId(): String = buildString {
append("run-")
repeat(2) { append(Random.nextInt().toUInt().toString(16).padStart(8, '0')) }
}
}
@@ -13,6 +13,8 @@ import kotlinx.coroutines.flow.update
import kotlin.random.Random
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.ClientLogBatch
import win.taptap.musicmanager.client.api.ClientLogEntry
import win.taptap.musicmanager.client.api.CreateMoodRequest
import win.taptap.musicmanager.client.api.DownloadStatus
import win.taptap.musicmanager.client.api.Mood
@@ -24,8 +26,11 @@ import win.taptap.musicmanager.client.api.Session
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.UpdateMoodRequest
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.APP_VERSION
import win.taptap.musicmanager.client.createAudioPlayer
import win.taptap.musicmanager.client.currentTimeMillis
import win.taptap.musicmanager.client.isUnmeteredNetwork
import win.taptap.musicmanager.client.logging.AppLog
import win.taptap.musicmanager.client.data.AppCache
import win.taptap.musicmanager.client.data.ClientSettings
import win.taptap.musicmanager.client.data.CachedState
@@ -66,6 +71,13 @@ data class AppState(
/** 0 = gapless, otherwise the fade length in seconds. */
val crossfadeSeconds: Int = 0,
val serverInfo: ServerInfo? = null,
/** Upload diagnostics to the server. Local collection stays on either way. */
val diagnosticsEnabled: Boolean = true,
val pendingLogCount: Int = 0,
val logUploading: Boolean = false,
/** False when the server is too old to have POST /logs. */
val logUploadSupported: Boolean = true,
val lastLogUploadAt: Long? = null,
/** Where the full-screen player returns when it is closed. */
val nowPlayingReturn: Screen = Screen.Moods,
/** Where the search screen returns when it is closed. */
@@ -117,11 +129,18 @@ class AppStore(
private var moodRequestGeneration = 0
private var searchTargetGeneration = 0
private var loggingOut = false
private var logUploadJob: Job? = null
private var logUploadInFlight = false
private var logUploadFailures = 0
private var logUploadUnsupported = false
private var lastLogUploadAt = 0L
private var settings = ClientSettings()
/** Tracks whose last offline download failed; retried on the next mood open. */
private val offlineFailed = mutableSetOf<String>()
init {
AppLog.attach(storage, scope)
startLogUploader()
bootstrap()
}
@@ -131,8 +150,12 @@ class AppStore(
val cached = cache.load()
val playback = cache.loadPlayback()
val loadedSettings = cache.loadSettings()
settings = loadedSettings
player.setCrossfadeSeconds(loadedSettings.crossfadeSeconds)
settings = if (loadedSettings.deviceId.isBlank()) {
loadedSettings.copy(deviceId = newDeviceId()).also { cache.saveSettings(it) }
} else {
loadedSettings
}
player.setCrossfadeSeconds(settings.crossfadeSeconds)
val restoredSong = playback?.current
val restoredTimeline = playback?.let { snapshot ->
@@ -154,8 +177,10 @@ class AppStore(
positionSeconds = playback?.positionSeconds ?: 0.0,
durationSeconds = restoredSong?.duration?.toDouble() ?: 0.0,
offlineMoods = loadedSettings.offlineMoods,
normalizationEnabled = loadedSettings.normalizationEnabled,
crossfadeSeconds = loadedSettings.crossfadeSeconds,
normalizationEnabled = settings.normalizationEnabled,
crossfadeSeconds = settings.crossfadeSeconds,
diagnosticsEnabled = settings.diagnosticsEnabled,
pendingLogCount = AppLog.pendingCount(),
)
}
@@ -189,13 +214,16 @@ class AppStore(
if (session == null) return@launch
api.restore(session.serverUrl, session.token)
AppLog.setOwner(session.user.name)
_state.update {
it.copy(
authenticated = true,
user = session.user,
serverUrl = session.serverUrl,
pendingLogCount = AppLog.pendingCount(),
)
}
scope.launch { uploadLogs() }
refreshAll(silent = true)
}
}
@@ -216,6 +244,9 @@ class AppStore(
cache.saveSession(SessionState(api.baseUrl, response.token, response.user))
}
loggingOut = false
logUploadUnsupported = false
AppLog.setOwner(response.user.name)
AppLog.info("auth", "Signed in on $platformName")
_state.update {
it.copy(
authenticated = true,
@@ -223,16 +254,22 @@ class AppStore(
serverUrl = api.baseUrl,
loading = false,
message = null,
diagnosticsEnabled = settings.diagnosticsEnabled,
logUploadSupported = true,
pendingLogCount = AppLog.pendingCount(),
)
}
scope.launch { uploadLogs(force = true) }
refreshAll()
} catch (t: Throwable) {
AppLog.warn("auth", "Login failed: ${t.friendlyMessage()}", t)
_state.update {
it.copy(
loading = false,
message = t.friendlyMessage(),
messageIsError = true,
messageId = it.messageId + 1,
pendingLogCount = AppLog.pendingCount(),
)
}
}
@@ -246,6 +283,8 @@ class AppStore(
searchJob?.cancel()
refreshJob?.cancel()
stopPlayback()
runCatching { uploadLogs(force = true) }
AppLog.clear()
runCatching { api.logout() }
api.clear()
cache.saveSession(null)
@@ -255,6 +294,7 @@ class AppStore(
serverUrl = _state.value.serverUrl,
downloads = storage.listDownloads().keys,
)
logUploadJob?.cancel()
}
}
@@ -309,6 +349,7 @@ class AppStore(
)
}
syncOfflineMoods()
uploadLogs()
} catch (t: Throwable) {
if (t is ApiException && t.status == 401) {
logout()
@@ -404,7 +445,9 @@ class AppStore(
}
fun openSettings() {
_state.update { it.copy(screen = Screen.Settings) }
_state.update {
it.copy(screen = Screen.Settings, pendingLogCount = AppLog.pendingCount())
}
}
fun openMoodSettings() {
@@ -491,6 +534,171 @@ class AppStore(
_state.update { it.copy(crossfadeSeconds = value) }
}
/** Turns server upload on or off; local collection stays enabled either way. */
fun setDiagnosticsEnabled(enabled: Boolean) {
settings = settings.copy(diagnosticsEnabled = enabled)
cache.saveSettings(settings)
_state.update {
it.copy(
diagnosticsEnabled = enabled,
pendingLogCount = AppLog.pendingCount(),
)
}
if (enabled) {
logUploadUnsupported = false
_state.update { it.copy(logUploadSupported = true) }
scope.launch { uploadLogs(force = true) }
}
}
fun sendLogsNow() {
scope.launch { uploadLogs(force = true) }
}
fun clearLocalLogs() {
AppLog.clear()
_state.update {
it.copy(
pendingLogCount = 0,
message = "Local diagnostics cleared",
messageIsError = false,
messageId = it.messageId + 1,
)
}
}
private fun startLogUploader() {
logUploadJob?.cancel()
logUploadJob = scope.launch {
while (isActive) {
delay(LOG_UPLOAD_INTERVAL_MS)
uploadLogs()
}
}
}
private fun refreshLogState() {
_state.update {
it.copy(
pendingLogCount = AppLog.pendingCount(),
diagnosticsEnabled = settings.diagnosticsEnabled,
)
}
}
/**
* Sends one batch of local warnings/errors. A failed upload keeps the
* entries for the next attempt; a rejected batch is dropped so one bad
* entry cannot block diagnostics forever.
*/
private suspend fun uploadLogs(force: Boolean = false) {
val state = _state.value
if (!state.authenticated || state.user == null) return
if (logUploadUnsupported) return
if (!settings.diagnosticsEnabled) return
if (api.token == null) return
if (logUploadInFlight) return
val now = currentTimeMillis()
if (!force && now - lastLogUploadAt < LOG_MIN_UPLOAD_GAP_MS) return
val pending = AppLog.pending(LOG_BATCH_SIZE)
if (pending.isEmpty()) {
refreshLogState()
return
}
val user = state.user
if (AppLog.ownerName() == null) AppLog.setOwner(user.name)
if (AppLog.ownerName() != user.name) {
// Should not happen after setOwner, but never upload another
// account's lines under the current token.
AppLog.clear()
refreshLogState()
return
}
logUploadInFlight = true
_state.update { it.copy(logUploading = true) }
try {
val accepted = api.uploadLogs(
ClientLogBatch(
deviceId = settings.deviceId,
platform = platformName,
appVersion = APP_VERSION,
entries = pending.map { record ->
ClientLogEntry(
timestamp = record.timestamp,
level = record.level,
tag = record.tag,
message = record.message,
detail = record.detail,
sessionId = record.sessionId,
)
},
),
)
AppLog.markUploaded(pending.map { it.id }.toSet())
logUploadFailures = 0
lastLogUploadAt = currentTimeMillis()
_state.update {
it.copy(
logUploading = false,
pendingLogCount = AppLog.pendingCount(),
lastLogUploadAt = lastLogUploadAt,
message = if (force) "Diagnostics sent ($accepted entries)" else it.message,
messageIsError = if (force) false else it.messageIsError,
messageId = if (force) it.messageId + 1 else it.messageId,
)
}
} catch (t: Throwable) {
if (t is ApiException && t.status == 404) {
// An older server without the diagnostics endpoint. Keep the
// entries locally and stop retrying until the next sign-in.
logUploadUnsupported = true
_state.update {
it.copy(
logUploading = false,
logUploadSupported = false,
pendingLogCount = AppLog.pendingCount(),
message = if (force) {
"This server does not accept diagnostics yet"
} else {
it.message
},
messageIsError = if (force) true else it.messageIsError,
messageId = if (force) it.messageId + 1 else it.messageId,
)
}
return
}
val rejected = t is ApiException && t.status in REJECTED_LOG_STATUSES
if (rejected) {
// The server will never accept this batch; keep the queue moving.
AppLog.markUploaded(pending.map { it.id }.toSet())
}
logUploadFailures += 1
if (logUploadFailures == 1 || force) {
AppLog.warn("logs", "Diagnostics upload failed: ${t.friendlyMessage()}", t)
}
lastLogUploadAt = currentTimeMillis()
_state.update {
it.copy(
logUploading = false,
pendingLogCount = AppLog.pendingCount(),
message = if (force) {
"Diagnostics upload failed: ${t.friendlyMessage()}"
} else {
it.message
},
messageIsError = if (force) true else it.messageIsError,
messageId = if (force) it.messageId + 1 else it.messageId,
)
}
} finally {
logUploadInFlight = false
}
}
fun selectSearchMood(moodId: String) {
_state.update { it.copy(searchTargetMoodId = moodId) }
loadSearchTarget(moodId)
@@ -1267,7 +1475,10 @@ class AppStore(
downloads = storage.listDownloads().keys,
)
}
lastError?.let { offlineFailed += song.id }
lastError?.let { error ->
offlineFailed += song.id
AppLog.warn("download", "Download failed: ${error.friendlyMessage()}", error)
}
if (announce) {
message(lastError ?: IllegalStateException("Download failed"))
} else {
@@ -1341,6 +1552,8 @@ class AppStore(
}
fun release() {
logUploadJob?.cancel()
AppLog.flushNow()
persistPlayback()
pollJob?.cancel()
refreshJob?.cancel()
@@ -1367,12 +1580,14 @@ class AppStore(
try {
player.setQueue(tracks, trackIndex, startAtSeconds)
} catch (t: Throwable) {
AppLog.error("playback", "Timeline failed: ${t.message ?: "unknown error"}", t)
_state.update {
it.copy(
playing = false,
message = "Playback failed: ${t.message ?: "unknown error"}",
messageIsError = true,
messageId = it.messageId + 1,
pendingLogCount = AppLog.pendingCount(),
)
}
return
@@ -1745,13 +1960,17 @@ class AppStore(
if (current == null) history else (history + current).takeLast(MAX_HISTORY)
private fun message(t: Throwable) {
val request = (t as? ApiException)?.requestId?.let { " [request $it]" }.orEmpty()
AppLog.warn("app", t.friendlyMessage() + request, t)
_state.update {
it.copy(
message = t.friendlyMessage(),
messageIsError = true,
messageId = it.messageId + 1,
pendingLogCount = AppLog.pendingCount(),
)
}
scope.launch { uploadLogs() }
}
}
@@ -1777,6 +1996,15 @@ private const val DOWNLOAD_ATTEMPTS = 3
private const val PROGRESS_POLL_TICKS = 12
private const val MAX_HISTORY = 50
private const val OFFLINE_PARALLEL = 3
private const val LOG_BATCH_SIZE = 100
private const val LOG_UPLOAD_INTERVAL_MS = 60_000L
private const val LOG_MIN_UPLOAD_GAP_MS = 45_000L
private val REJECTED_LOG_STATUSES = setOf(400, 413, 422)
/** Random, stable per install; not a hardware identifier. */
private fun newDeviceId(): String = buildString {
repeat(4) { append(Random.nextInt().toUInt().toString(16).padStart(8, '0')) }
}
private const val SEARCH_DEBOUNCE_MS = 300L
private const val SEARCH_LIMIT = 10
private const val DEFAULT_SOURCE = "deezer"
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -16,6 +17,7 @@ import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.Logout
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
@@ -30,6 +32,8 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.APP_VERSION
import win.taptap.musicmanager.client.currentTimeMillis
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@@ -184,6 +188,79 @@ fun SettingsScreen(state: AppState, store: AppStore) {
}
}
item {
val retention = state.serverInfo?.clientLogRetentionDays ?: 14
val lastUpload = state.lastLogUploadAt
val uploadedText = when {
lastUpload == null -> "never"
currentTimeMillis() - lastUpload < 60_000 -> "just now"
currentTimeMillis() - lastUpload < 3_600_000 ->
"${(currentTimeMillis() - lastUpload) / 60_000} min ago"
else -> "${(currentTimeMillis() - lastUpload) / 3_600_000} h ago"
}
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Diagnostics", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Send logs to this server", style = MaterialTheme.typography.bodyMedium)
Text(
"Warnings, errors and crashes so a bug can be fixed later.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = state.diagnosticsEnabled,
onCheckedChange = { store.setDiagnosticsEnabled(it) },
)
}
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
FilledTonalButton(
onClick = { store.sendLogsNow() },
enabled = state.pendingLogCount > 0 && !state.logUploading &&
state.diagnosticsEnabled && state.logUploadSupported,
) {
if (state.logUploading) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
}
Text("Send now")
}
OutlinedButton(
onClick = { store.clearLocalLogs() },
enabled = state.pendingLogCount > 0,
) {
Text("Clear local")
}
}
Text(
"${state.pendingLogCount} entries waiting · last sent $uploadedText",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
if (state.logUploadSupported) {
"Authorization headers, tokens and passwords are removed before upload. " +
"The server keeps diagnostics for $retention days."
} else {
"This server does not accept diagnostics yet; entries stay on this device. " +
"Restart or toggle this switch after updating the server."
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
Surface(
shape = RoundedCornerShape(16.dp),
@@ -193,7 +270,7 @@ fun SettingsScreen(state: AppState, store: AppStore) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"AudioManager 0.4.2 · $platformName",
"AudioManager $APP_VERSION · $platformName",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -0,0 +1,62 @@
package win.taptap.musicmanager.client
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import win.taptap.musicmanager.client.logging.AppLog
class AppLogTest {
@AfterTest
fun cleanUp() {
AppLog.clear()
}
@Test
fun `redacts bearer tokens query parameters and json secrets`() {
assertFalse(AppLog.redact("Authorization: Bearer abcdefgh123").contains("abcdefgh123"))
assertTrue(AppLog.redact("Authorization: Bearer abcdefgh123").contains("***"))
val query = AppLog.redact("GET https://music/stream?token=abc123&size=320 failed")
assertFalse(query.contains("abc123"))
assertTrue(query.contains("token=***"))
assertTrue(query.contains("size=320"))
val json = AppLog.redact("""{"password":"hunter2","keep":"me"}""")
assertFalse(json.contains("hunter2"))
assertTrue(json.contains("\"keep\":\"me\""))
}
@Test
fun `keeps only the newest entries and persists across a reload`() {
val storage = MemoryStorage()
AppLog.init(storage)
AppLog.clear()
repeat(AppLog.MAX_ENTRIES + 10) { index ->
AppLog.warn("test", "line-$index")
}
assertEquals(AppLog.MAX_ENTRIES, AppLog.pendingCount())
assertEquals("line-10", AppLog.pending(1).single().message)
AppLog.init(storage)
assertTrue(AppLog.pending(AppLog.MAX_ENTRIES).any { it.message == "line-509" })
}
@Test
fun `uploaded entries are removed and the rest stays queued`() {
AppLog.init(MemoryStorage())
AppLog.clear()
AppLog.warn("test", "first")
AppLog.warn("test", "second")
val first = AppLog.pending(1)
AppLog.markUploaded(first.map { it.id }.toSet())
assertEquals(1, AppLog.pendingCount())
assertEquals("second", AppLog.pending().single().message)
}
}
@@ -5,6 +5,7 @@ import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.content.TextContent
import io.ktor.http.headersOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -29,6 +30,7 @@ import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.PlaybackSnapshot
import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.logging.AppLog
import win.taptap.musicmanager.client.playback.PlaybackTrack
import win.taptap.musicmanager.client.store.AppStore
@@ -508,6 +510,79 @@ class AppStoreTest {
store.release()
}
@Test
fun `diagnostics upload after authentication and are removed locally`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
AppLog.clear()
AppLog.init(storage)
AppLog.clear()
AppLog.warn("test", "playback stalled", RuntimeException("Bearer super-secret-token"))
var uploads = 0
var body: String? = null
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/info" -> respond(
"""{"defaultSource":"deezer","deezerQuality":0,"loudnessEnabled":true,
"loudnessTargetLufs":-16.0,"clientLogRetentionDays":14}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/logs" -> {
uploads += 1
body = (request.body as TextContent).text
respond("""{"accepted":1}""", HttpStatusCode.OK, jsonHeaders)
}
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
awaitState("diagnostics upload") { uploads == 1 }
awaitState("log queue drained") { store.state.value.pendingLogCount == 0 }
assertTrue(body!!.contains("playback stalled"))
assertFalse(body!!.contains("super-secret-token"))
assertTrue(body!!.contains("***"))
assertEquals(0, AppLog.pendingCount())
store.release()
AppLog.clear()
}
@Test
fun `an older server disables uploads but keeps the local entries`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
AppLog.clear()
AppLog.init(storage)
AppLog.clear()
AppLog.warn("test", "keep this line")
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/info" -> respond(
"""{"defaultSource":"deezer","deezerQuality":0,"loudnessEnabled":true,"loudnessTargetLufs":-16.0}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
awaitState("diagnostics unsupported") { !store.state.value.logUploadSupported }
assertTrue(store.state.value.pendingLogCount > 0)
assertTrue(AppLog.pending().any { it.message == "keep this line" })
store.release()
AppLog.clear()
}
@Test
fun `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage()
@@ -6,15 +6,25 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import win.taptap.musicmanager.client.logging.AppLog
import win.taptap.musicmanager.client.ui.App
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "AudioManager",
state = rememberWindowState(size = DpSize(1100.dp, 820.dp)),
) {
App()
fun main() {
AppLog.init(platformStorage())
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
runCatching {
AppLog.error("crash", "Uncaught exception on ${thread.name}", error)
AppLog.flushNow()
}
}
application {
Window(
onCloseRequest = ::exitApplication,
title = "AudioManager",
state = rememberWindowState(size = DpSize(1100.dp, 820.dp)),
) {
App()
}
}
}
@@ -126,3 +126,7 @@ actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
private val LOG_LOCK = Any()
internal actual fun <T> withLogLock(block: () -> T): T = synchronized(LOG_LOCK) { block() }
@@ -49,3 +49,5 @@ actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
internal actual fun <T> withLogLock(block: () -> T): T = block()
@@ -3,10 +3,12 @@ package win.taptap.musicmanager.client
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.ComposeViewport
import kotlinx.browser.document
import win.taptap.musicmanager.client.logging.AppLog
import win.taptap.musicmanager.client.ui.App
@OptIn(ExperimentalComposeUiApi::class)
fun main() {
AppLog.init(platformStorage())
ComposeViewport(document.body!!) {
App()
}