Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Crash fixes: foreground start while paused, malformed page messages
liliapk277c1214616c
diff --git a/base/api-spotify/README.md b/base/api-spotify/README.mdindex 40769e44..a8044970 100644--- a/base/api-spotify/README.md+++ b/base/api-spotify/README.md@@ -58,7 +58,7 @@ The same file runs in the Android WebView and in desktop Chrome over CDP.| Direction | Android | Desktop (CDP) ||---|---|---|| Host → page | `evaluateJavascript("Myspoti.call(id, method, args)")` | `Runtime.evaluate`, same call |-| Page → host | `@JavascriptInterface MyspotiHost.post(json)` | `Runtime.addBinding("__mspHostPost")` |+| Page → host | `MyspotiHost.postMessage(json)` (web message listener, open.spotify.com only) | `Runtime.addBinding("__mspHostPost")` |`Myspoti.call` also returns a Promise, but hosts should rely on the `result` message:Android's `evaluateJavascript` does not wait for Promises.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 775e8171..3f742e2e 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@@ -12,10 +12,10 @@ import kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.boolean-import kotlinx.serialization.json.int-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.intOrNullimport java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.atomic.AtomicInteger@@ -38,14 +38,20 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {init {scope.launch {- host.messages.collect { raw -> handle(raw) }+ // A message the bridge did not write (another script, a future page) must never+ // end this collector: it runs on the main thread, where a throw kills the app.+ host.messages.collect { raw ->+ runCatching { handle(raw) }.onFailure { logger?.invoke("page message dropped: ${it.message}") }+ }}}private fun handle(raw: String) {- val msg = runCatching { json.parseToJsonElement(raw).jsonObject }.getOrNull() ?: return+ val msg = runCatching { json.parseToJsonElement(raw) }.getOrNull() as? JsonObject ?: return+ // Lenient reads: a field of an unexpected type counts as missing.+ fun field(name: String) = msg[name] as? JsonPrimitive+ val type = field("type")?.contentOrNulllogger?.let { log ->- val type = msg["type"]?.jsonPrimitive?.contentif (type == "state") {val s = msg["state"] as? JsonObjectlog("page state: " + (s?.get("track") as? JsonObject)?.get("name") + " paused=" + s?.get("isPaused") + " buffering=" + s?.get("isBuffering"))@@ -53,13 +59,13 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {// Results are logged by call(); never write their values (tokens) here.} else if (type != "queue") log("page $type: " + raw.take(300))}- when (msg["type"]?.jsonPrimitive?.content) {+ when (type) {"ready" -> _ready.value = true"result" -> {- val id = msg["id"]?.jsonPrimitive?.int ?: return+ val id = field("id")?.intOrNull ?: returnval waiter = pending.remove(id) ?: return- if (msg["ok"]?.jsonPrimitive?.boolean == true) waiter.complete(msg["value"] ?: JsonNull)- else waiter.completeExceptionally(BridgeException(msg["error"]?.jsonPrimitive?.content ?: "bridge error"))+ if (field("ok")?.booleanOrNull == true) waiter.complete(msg["value"] ?: JsonNull)+ else waiter.completeExceptionally(BridgeException(field("error")?.contentOrNull ?: "bridge error"))}"state" -> _events.tryEmit("state" to (msg["state"] ?: JsonNull))"queue" -> _events.tryEmit("queue" to (msg["queue"] ?: JsonNull))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 dae8f296..dcf9cfb2 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@@ -19,7 +19,7 @@ interface BridgeHost {/** Runs [script] in the page. Fire and forget: answers come back through [messages]. */suspend fun evaluate(script: String)- /** JSON strings posted by the bridge (`MyspotiHost.post` / `__mspHostPost`). */+ /** JSON strings posted by the bridge (`MyspotiHost.postMessage` / `__mspHostPost`). */val messages: Flow<String>}diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex 14281428..f3ed6c72 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -7,8 +7,8 @@** Host -> page: window.Myspoti.call(id, method, args) (also returns a Promise)* Page -> host: one JSON string per message, sent to the first host channel found:- * - window.MyspotiHost.post(json) Android @JavascriptInterface- * - window.__mspHostPost(json) CDP Runtime.addBinding+ * - window.MyspotiHost.postMessage(json) Android web message listener (open.spotify.com only)+ * - window.__mspHostPost(json) CDP Runtime.addBinding* Messages: {type: "ready"} | {type: "state", state} | {type: "queue", queue}* | {type: "result", id, ok, value | error} | {type: "error", error}*@@ -27,7 +27,7 @@const post = msg => {const json = JSON.stringify(msg);try {- if (window.MyspotiHost && window.MyspotiHost.post) return window.MyspotiHost.post(json);+ if (window.MyspotiHost && typeof window.MyspotiHost.postMessage === 'function') return window.MyspotiHost.postMessage(json);if (typeof window.__mspHostPost === 'function') return window.__mspHostPost(json);} catch (e) { /* host gone: nothing to report to */ }};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.ktnew file mode 100644index 00000000..c06028cd--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt@@ -0,0 +1,57 @@+package app.myspoti.spotify.bridge++import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitive+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertThrows+import org.junit.jupiter.api.Test++/** Messages the bridge did not write must be dropped, never end the message loop. */+class BridgeMessagesTest {+ /** Answers each `Myspoti.call(id, …)` with [reply] for that id. */+ private class FakeHost(val reply: (Int) -> String) : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ override suspend fun evaluate(script: String) {+ val id = Regex("""Myspoti\.call\((\d+),""").find(script)?.groupValues?.get(1)?.toInt() ?: return+ messages.emit(reply(id))+ }+ }++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ @AfterEach fun stop() = scope.cancel()++ private val garbage = listOf(+ """{"type":"result","id":"x"}""",+ """{"type":{"nested":true}}""",+ """{"type":"result","id":1.5,"ok":"yes"}""",+ """{"type":"result","id":999,"ok":"maybe","error":{"m":1}}""",+ """[1,2,3]""",+ """not json""",+ )++ private fun bridgeAfterGarbage(reply: (Int) -> String): Bridge = runBlocking {+ val host = FakeHost(reply)+ val bridge = Bridge(host, scope)+ host.messages.subscriptionCount.first { it > 0 }+ garbage.forEach { host.messages.emit(it) }+ bridge+ }++ @Test fun `calls still answer after malformed messages`() = runBlocking {+ val bridge = bridgeAfterGarbage { id -> """{"type":"result","id":$id,"ok":true,"value":42}""" }+ assertEquals(JsonPrimitive(42), bridge.call("bridge.version", timeoutMs = 2_000))+ }++ @Test fun `a result with fields of the wrong type fails that call only`() {+ val bridge = bridgeAfterGarbage { id -> """{"type":"result","id":$id,"ok":"yes","error":{"m":1}}""" }+ assertThrows(BridgeException::class.java) { runBlocking { bridge.call("bridge.version", timeoutMs = 2_000) } }+ }+}diff --git a/base/app/proguard-rules.pro b/base/app/proguard-rules.proindex 6f344a5f..3f809456 100644--- a/base/app/proguard-rules.pro+++ b/base/app/proguard-rules.pro@@ -1,8 +1,6 @@-# The Web Player page calls the host through this @JavascriptInterface.--keepclassmembers class app.myspoti.host.android.WebPlayerHost$HostInterface {- @android.webkit.JavascriptInterface <methods>;-}--keepclassmembers class app.myspoti.host.android.ControlRelay {+# The Web Player page calls the host through this @JavascriptInterface on WebViews without+# web message listeners (PlayerChannel.kt).+-keepclassmembers class app.myspoti.host.android.PlayerChannel {@android.webkit.JavascriptInterface <methods>;}# Bundled resources read by name (bridge script, GraphQL operation table).diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.ktindex e5e65d55..a13a27ff 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt@@ -2,7 +2,6 @@ package app.myspoti.host.androidimport android.os.Handlerimport android.os.Looper-import android.webkit.JavascriptInterfaceimport android.webkit.WebViewimport okhttp3.Callimport okhttp3.Callback@@ -26,7 +25,7 @@ import java.util.concurrent.TimeUnit* reproduces the silence, and removing it restores playback.** The page's `fetch` is wrapped at document start. Matching requests go through- * [MyspotiNet.send], which repeats them with OkHttp using the page's own headers (its token,+ * `MyspotiNet.postMessage` ([exposeToPlayer]), which repeats them with OkHttp using the page's own headers (its token,* client token, connection id), then hands the response back to the page.*/internal class ControlRelay(private val view: WebView) {@@ -37,7 +36,7 @@ internal class ControlRelay(private val view: WebView) {.build()fun install() {- view.addJavascriptInterface(this, "MyspotiNet")+ view.exposeToPlayer("MyspotiNet", ::onMessage)val documentStart = androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT)if (documentStart) androidx.webkit.WebViewCompat.addDocumentStartJavaScript(view, SCRIPT, setOf("https://open.spotify.com"))android.util.Log.d(WebPlayerHost.LOG, "control relay installed (document start: $documentStart)")@@ -46,14 +45,20 @@ internal class ControlRelay(private val view: WebView) {/** Fallback for WebViews without document-start scripts; harmless when already installed. */fun injectNow() = view.evaluateJavascript(SCRIPT, null)- @JavascriptInterface- fun send(id: Int, url: String, method: String, headersJson: String, body: String?) {+ /** `{id, url, method, headers, body}` from the page's wrapped `fetch`. */+ private fun onMessage(json: String) {+ val m = runCatching { JSONObject(json) }.getOrNull() ?: return+ val id = m.optInt("id", -1).takeIf { it >= 0 } ?: return+ val body = if (m.isNull("body")) null else m.optString("body")+ send(id, m.optString("url"), m.optString("method", "GET"), m.optJSONObject("headers") ?: JSONObject(), body)+ }++ private fun send(id: Int, url: String, method: String, given: JSONObject, body: String?) {if (!isRelayed(url)) {reply(id, 0, "{}", "")return}val headers = Headers.Builder()- val given = runCatching { JSONObject(headersJson) }.getOrDefault(JSONObject())given.keys().forEach { key ->// OkHttp sets the transport headers itself.if (key.lowercase() !in setOf("host", "content-length", "connection", "accept-encoding", "x-requested-with"))@@ -126,7 +131,7 @@ internal class ControlRelay(private val view: WebView) {return new Promise((resolve, reject) => {const id = ++seq;pending.set(id, { resolve, reject });- window.MyspotiNet.send(id, url, method, JSON.stringify(headers), body == null ? null : body);+ window.MyspotiNet.postMessage(JSON.stringify({ id, url, method, headers, body: body == null ? null : body }));});};})();diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.ktindex 87e08080..07f9f025 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt@@ -91,12 +91,28 @@ class PlaybackService : MediaBrowserServiceCompat() {}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ // Every start may be a startForegroundService() (playback, a headset button or the+ // notification's dismissal through MediaButtonReceiver, another app): Android kills the+ // app unless startForeground() follows, paused or not. A paused player then leaves the+ // foreground after PAUSE_GRACE_MS, as after any pause.+ val info = current+ startForegroundSafely(build(info), always = true)MediaButtonReceiver.handleIntent(session, intent)- // Started for playback: Android needs the foreground notification right away.- current?.let { show(it) } ?: startForegroundSafely(build(null))+ if (info != null) show(info)+ // The paused notification was swiped away: leave the foreground with it.+ if (info?.playing != true && isStop(intent)) {+ handler.removeCallbacks(leaveForeground)+ ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)+ foreground = false+ }return START_NOT_STICKY}+ private fun isStop(intent: Intent?): Boolean =+ intent?.action == Intent.ACTION_MEDIA_BUTTON &&+ androidx.core.content.IntentCompat.getParcelableExtra(intent, Intent.EXTRA_KEY_EVENT, android.view.KeyEvent::class.java)+ ?.keyCode == android.view.KeyEvent.KEYCODE_MEDIA_STOP+override fun onDestroy() {instance = nullsession.release()@@ -201,8 +217,9 @@ class PlaybackService : MediaBrowserServiceCompat() {}}- private fun startForegroundSafely(notification: Notification) {- if (foreground) {+ /** [always]: call startForeground() even when already in the foreground (a new foreground start). */+ private fun startForegroundSafely(notification: Notification, always: Boolean = false) {+ if (foreground && !always) {runCatching { NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification) }return}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.ktnew file mode 100644index 00000000..960c8187--- /dev/null+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlayerChannel.kt@@ -0,0 +1,35 @@+package app.myspoti.host.android++import android.annotation.SuppressLint+import android.webkit.JavascriptInterface+import android.webkit.WebView+import androidx.webkit.WebViewCompat+import androidx.webkit.WebViewFeature++/**+ * Gives the Web Player page a `window.<name>.postMessage(string)` channel to the app.+ *+ * An `addJavascriptInterface` object is injected into every frame of the WebView, whatever its+ * origin: the player page embeds a google.com reCAPTCHA iframe, which could then post to the+ * app. A web message listener is only injected into frames of [PLAYER_ORIGIN], and only the+ * main frame's messages are taken. WebViews without the feature fall back to the interface;+ * the page calls the same `postMessage` either way.+ */+@SuppressLint("JavascriptInterface")+internal fun WebView.exposeToPlayer(name: String, onMessage: (String) -> Unit) {+ if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {+ WebViewCompat.addWebMessageListener(this, name, setOf(PLAYER_ORIGIN)) { _, message, _, isMainFrame, _ ->+ if (isMainFrame) message.data?.let(onMessage)+ }+ } else {+ addJavascriptInterface(PlayerChannel(onMessage), name)+ }+}++private const val PLAYER_ORIGIN = "https://open.spotify.com"++/** Fallback channel for WebViews without web message listeners. */+internal class PlayerChannel(private val onMessage: (String) -> Unit) {+ @JavascriptInterface+ fun postMessage(message: String) = onMessage(message)+}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 5c450597..5e6003d0 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@@ -8,7 +8,6 @@ import android.os.Looperimport android.view.Viewimport android.view.ViewGroupimport android.webkit.CookieManager-import android.webkit.JavascriptInterfaceimport android.webkit.PermissionRequestimport android.webkit.WebChromeClientimport android.webkit.WebResourceRequest@@ -98,7 +97,7 @@ class WebPlayerHost(context: Context) : BridgeHost {setAcceptCookie(true)setAcceptThirdPartyCookies(webView, true)}- addJavascriptInterface(HostInterface(), "MyspotiHost")+ exposeToPlayer("MyspotiHost") { json -> _messages.tryEmit(json) }webChromeClient = object : WebChromeClient() {override fun onConsoleMessage(message: android.webkit.ConsoleMessage): Boolean {if (message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.ERROR ||@@ -157,11 +156,6 @@ class WebPlayerHost(context: Context) : BridgeHost {private fun isLoginPage(url: String?) =url != null && (url.contains("accounts.spotify.com") || url.contains("/login") || url.contains("challenge.spotify.com"))- private inner class HostInterface {- @JavascriptInterface- fun post(json: String) { _messages.tryEmit(json) }- }-fun load() = main.post { view.loadUrl(PLAYER_URL) }fun reload() = main.post { view.reload() }