Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
A call to the Spotify page that cannot reach it (a page that is not the player, a renderer that died, a script the WebView refused) fails at once with its reason instead of waiting 20 s for its timeout, and every call is run only by the page it was made for: one made for a page that went away is neither kept waiting nor run by the next page [skip ci]
kota-zod37f9c41ec5e
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.ktindex d39bf50a..9c19f457 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt@@ -2,7 +2,9 @@ package app.myspoti.spotify.bridgeimport kotlinx.coroutines.channels.BufferOverflowimport kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.SharedFlow@@ -134,7 +136,9 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {// injection into the SAME page must not announce "ready" again, or every ready// collector (state refresh, web token, audio quality, volume) runs twice. The page// re-announces only when the host is not ready (a page it thought it had lost).- host.evaluate("window.__mspReannounce = ${!_ready.value}; ${BridgeScript.source}")+ // The page's generation goes in with it: a call made for a page that went away is refused+ // by the next one (see [call]) instead of running there.+ host.evaluate("window.__mspPage = $pagesGone; window.__mspReannounce = ${!_ready.value}; ${BridgeScript.source}")}/**@@ -170,21 +174,38 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {/** [label]: who sends it, written in its log line (a play's origin). */suspend fun call(method: String, args: JsonObject = JsonObject(emptyMap()), timeoutMs: Long = 20_000, quiet: Boolean = false, label: String? = null): JsonElement {// The page is reloading: nothing would answer, the call would only wait for its timeout.+ val page = pagesGoneif (gone) throw BridgeException("not ready")val id = ids.incrementAndGet()val waiter = CompletableDeferred<JsonElement>()pending[id] = waitertry {+ // The page went away between the check above and the waiter's registration: pageGone+ // did not see this call, and nothing of that page will answer it.+ if (gone || pagesGone != page) throw BridgeException("page reloaded")val started = System.currentTimeMillis()if (!quiet) logger?.invoke("call #$id $method${label?.let { " ($it)" }.orEmpty()} ${args.toString().take(200)}")- host.evaluate("window.Myspoti && window.Myspoti.call($id, ${json.encodeToString(JsonElement.serializer(), kotlinx.serialization.json.JsonPrimitive(method))}, $args).catch(() => {})")+ // Run only by the page it was made for (the generation set by inject), which says so.+ val script = "(window.Myspoti && window.__mspPage === $page) ? (window.Myspoti.call($id, ${json.encodeToString(JsonElement.serializer(), kotlinx.serialization.json.JsonPrimitive(method))}, $args).catch(() => {}), true) : false"return try {// withTimeoutOrNull, not withTimeout: a timeout must surface as a// BridgeException, not as a CancellationException — callers in plain// launch {} blocks would otherwise end silently, indistinguishable// from the caller itself being cancelled (which still throws).- val result = withTimeoutOrNull(timeoutMs) { waiter.await() }- ?: throw BridgeException("timeout after $timeoutMs ms: $method")+ val result = withTimeoutOrNull(timeoutMs) {+ coroutineScope {+ // A script the host could not run, or one that found no bridge of this+ // page, fails the call now instead of after its timeout.+ val sent = launch {+ val value = try { host.evaluateValue(script) } catch (e: CancellationException) { throw e } catch (e: Exception) {+ waiter.completeExceptionally(e as? BridgeException ?: BridgeException("not sent: ${e.message}"))+ return@launch+ }+ if (value == "false") waiter.completeExceptionally(BridgeException("the bridge is not in this page"))+ }+ try { waiter.await() } finally { sent.cancel() }+ }+ } ?: throw BridgeException("timeout after $timeoutMs ms: $method")result.also {if (quiet) return@alsoval shown = if (method == "token.get") "(token hidden)" else it.toString().take(200)diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.ktindex 588cd875..4d1caced 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt@@ -20,6 +20,13 @@ interface BridgeHost {/** Runs [script] in the page. Fire and forget: answers come back through [messages]. */suspend fun evaluate(script: String)+ /**+ * Runs [script] like [evaluate] and returns the JSON of its value once the page ran it, or+ * null when this host cannot tell. Throws when the script could not be handed to the page,+ * so a call fails at once instead of waiting for an answer that cannot come.+ */+ suspend fun evaluateValue(script: String): String? { evaluate(script); return null }+/** JSON strings posted by the bridge (`MyspotiHost.postMessage` / `__mspHostPost`). */val messages: Flow<String>}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.ktindex 5b761a8a..701b05e7 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt@@ -68,4 +68,34 @@ class BridgeMessagesTest {bridge.ready.first { it }assertEquals(JsonPrimitive(1), bridge.call("bridge.version", timeoutMs = 2_000))}++ /** A host that tells what the page made of each script: [value], or a failure to run it. */+ private class TellingHost(val value: () -> String?) : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ val scripts = mutableListOf<String>()+ override suspend fun evaluate(script: String) { scripts += script }+ override suspend fun evaluateValue(script: String): String? { scripts += script; return value() }+ }++ @Test fun `a call that cannot reach the page fails at once, not after its timeout`() = runBlocking {+ for (host in listOf(TellingHost { "false" }, TellingHost { throw IllegalStateException("view destroyed") })) {+ val bridge = Bridge(host, scope)+ val started = System.currentTimeMillis()+ assertThrows(BridgeException::class.java) { runBlocking { bridge.call("bridge.version", timeoutMs = 5_000) } }+ assertEquals(true, System.currentTimeMillis() - started < 1_000)+ }+ }++ @Test fun `a call is made for the page of its generation`() = runBlocking {+ val host = TellingHost { "true" }+ val bridge = Bridge(host, scope)+ host.messages.subscriptionCount.first { it > 0 }+ bridge.pageGone()+ bridge.inject()+ host.messages.emit("""{"type":"ready","version":1}""")+ bridge.ready.first { it }+ runCatching { bridge.call("bridge.version", timeoutMs = 50) }+ assertEquals(true, host.scripts.first().startsWith("window.__mspPage = 1;"))+ assertEquals(true, "window.__mspPage === 1)" in host.scripts.last())+ }}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.ktindex aac20dce..25644b50 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt@@ -360,6 +360,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {// that was already replaced must not tear down the healthy new one.if (gone !== [email protected]) return trueLogbook.log("renderer gone (crashed=${detail.didCrash()}): rebuilding the page")+ // The page is gone with it: the calls it had fail now, not each after its timeout.+ onPageStarting?.invoke()rebuild()return true}@@ -631,11 +633,22 @@ class WebPlayerHost(private val context: Context) : BridgeHost {val done = CompletableDeferred<Unit>()main.post {runCatching { view.evaluateJavascript(script, null) }+ .onFailure { Logbook.log("script not run in the page: ${it.message}") }done.complete(Unit)}done.await()}+ /** The page's own answer: a call that never reached the bridge fails now, not after its timeout. */+ override suspend fun evaluateValue(script: String): String? {+ val done = CompletableDeferred<String?>()+ main.post {+ runCatching { view.evaluateJavascript(script) { value -> done.complete(value) } }+ .onFailure { done.completeExceptionally(app.myspoti.spotify.bridge.BridgeException("page not reachable: ${it.message}")) }+ }+ return done.await()+ }+/*** Keeps the page attached to a window, a tiny non-interactive view in [container] while the* player is hidden.