Skip to content

Native Android client for Spotify, built with Jetpack Compose

The page says ready once per page load, and the web token is fetched once

kota-zo8e6f1375ac6f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b831832d..ce460cf0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@ Each release on GitHub shows its section below. The app shows it too when it off
## Unreleased
+- **Far fewer calls to the player page**: "ready" is announced once per page load (twice meant every listener of it ran twice: state, token, quality, volume), the web token is fetched once and shared, and the Connect device list is read at most every 6 s in the page instead of every 2 s.
- **Myspoti's icon in the notification** and in Samsung's Now Bar, instead of a generic music note.
- **Ads that get through are silent**: they are muted on the page itself, no longer through a Spotify Connect volume command that some accounts refuse (the ad was heard). The song after the ad no longer stays paused.
- **Previous no longer pauses**: "previous" in the middle of a song restarts it and keeps playing (the skip fade left the sound at zero, and Android's WebView pauses silent media in the background).
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
index 2d24e2db..fe0a0a84 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
@@ -73,7 +73,16 @@ class SpotifyApi(
scope.launch {
// Each page load may be another account (logout, then a new sign-in): the next
// direct call asks the page for its current token.
- ready.filter { it }.collect { [email protected](); runCatching { player.refresh() } }
+ ready.filter { it }.collect {
+ try {
+ player.refresh()
+ } catch (e: kotlinx.coroutines.CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ // No state now: the page's next state event brings it anyway.
+ }
+ }
}
}
@@ -82,5 +91,8 @@ class SpotifyApi(
/** The host calls this when a Web Player page load starts (reload, renderer back). */
fun onPageStarting() = bridge.pageGone()
+ /** True when the page's token belongs to a signed-in user (the cached one is reused). */
+ suspend fun isSignedIn(): Boolean = http.isSignedIn()
+
suspend fun awaitReady() { ready.first { it } }
}
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.kt
index e037119b..7ab33bb3 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
@@ -79,8 +79,11 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {
/** Injects the bridge into the current page. Hosts call this after each page load. */
suspend fun inject() {
- _ready.value = false
- host.evaluate(BridgeScript.source)
+ // onPageFinished can fire twice for one page load (a redirect settling): a second
+ // 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}")
}
/**
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
index 48340be6..5a20ded6 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
@@ -9,6 +9,7 @@ import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
@@ -70,7 +71,7 @@ class SpotifyHttp(
private val bridge: Bridge,
private val language: String = "en",
) {
- private data class WebToken(val access: String, val expiresAtMs: Long, val clientId: String, val appVersion: String)
+ private data class WebToken(val access: String, val expiresAtMs: Long, val clientId: String, val appVersion: String, val anonymous: Boolean)
private data class ClientToken(val value: String, val expiresAtMs: Long)
private val lock = Mutex()
@@ -81,6 +82,24 @@ class SpotifyHttp(
/** Drops the cached web token (it belongs to one account); the client token is kept. */
suspend fun forgetWebToken() = lock.withLock { web = null }
+ /** True when the page's token belongs to a signed-in user (the cached one is reused). */
+ suspend fun isSignedIn(): Boolean = lock.withLock { !webToken().anonymous }
+
+ /** The account's token, fetched again only when the cached one is missing or stale. */
+ private suspend fun webToken(): WebToken {
+ val now = System.currentTimeMillis()
+ return web?.takeIf { it.expiresAtMs - now > 60_000 } ?: run {
+ val t = bridge.call("token.get").jsonObject
+ WebToken(
+ access = t["accessToken"]!!.jsonPrimitive.content,
+ expiresAtMs = t["expiresAtMs"]!!.jsonPrimitive.long,
+ clientId = t["clientId"]!!.jsonPrimitive.content,
+ appVersion = t["appVersion"]!!.jsonPrimitive.content,
+ anonymous = t["isAnonymous"]?.jsonPrimitive?.contentOrNull == "true",
+ ).also { web = it }
+ }
+ }
+
/** Sends a request with browser headers. Returns the status and body text. */
suspend fun send(method: String, url: String, body: String? = null, contentType: String = JSON_TYPE, accept: String = "application/json"): Pair<Int, String> {
// The account's token only ever goes to Spotify itself.
@@ -116,15 +135,7 @@ class SpotifyHttp(
private suspend fun tokens(): Pair<WebToken, ClientToken> = lock.withLock {
val now = System.currentTimeMillis()
- val w = web?.takeIf { it.expiresAtMs - now > 60_000 } ?: run {
- val t = bridge.call("token.get").jsonObject
- WebToken(
- access = t["accessToken"]!!.jsonPrimitive.content,
- expiresAtMs = t["expiresAtMs"]!!.jsonPrimitive.long,
- clientId = t["clientId"]!!.jsonPrimitive.content,
- appVersion = t["appVersion"]!!.jsonPrimitive.content,
- ).also { web = it }
- }
+ val w = webToken()
val c = client?.takeIf { it.expiresAtMs - now > 3_600_000 } ?: mintClientToken(w).also { client = it }
w to c
}
diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.js
index ef36f975..6ca06f48 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -15,9 +15,15 @@
* The bridge only reads the page's own service registry; it patches nothing.
*/
(() => {
- // Injected again (each page load event): say ready again instead of staying silent.
+ // Injected again (a second page-finished event for the same page): say ready again only
+ // when the host asks for it (window.__mspReannounce, set when it is not ready). A second
+ // "ready" for one page load would run every ready collector twice (state refresh, web
+ // token, audio quality, volume).
if (window.Myspoti && window.Myspoti.version) {
- if (window.Myspoti.announce) window.Myspoti.announce();
+ if (window.Myspoti.announce && window.__mspReannounce) {
+ window.__mspReannounce = false;
+ window.Myspoti.announce();
+ }
return;
}
@@ -208,6 +214,21 @@
// Not heard, yet not "muted audio" to Chromium (see 'media.mute').
const SILENT = 0.001;
+ // "Is this page Spotify Connect's active device": a full device-list round trip, so it is
+ // read at most once every ACTIVE_CACHE_MS and reused (a transfer happens minutes apart).
+ const ACTIVE_CACHE_MS = 6000;
+ let activeValue = null, activeAt = 0;
+ const activeDevice = async () => {
+ const now = Date.now();
+ if (activeValue !== null && now - activeAt < ACTIVE_CACHE_MS) return activeValue;
+ try {
+ const me = (await need().resolve('ConnectDevicesAPI').getDevices()).find(d => d.isLocal);
+ activeValue = !!(me && me.isActive);
+ activeAt = now;
+ } catch (e) { /* unknown: the caller keeps the last answer */ }
+ return activeValue;
+ };
+
// The element volume the page player itself sets for its volume (cubic curve or not).
const ownLevel = player => {
const v = typeof player._playerVolume === 'number' ? player._playerVolume : 1;
@@ -312,15 +333,16 @@
// The page player's own media element now: what is really heard, whatever the state says.
// active: this page is Spotify Connect's active device (else the state is another device's).
// level: the element's volume (0..1), which local fades move; own: the level the page
- // player itself wants there.
- // -> {paused, muted, volume, level, own, time, readyState, ended, active} | null (no element yet)
+ // player itself wants there. playerVolume: what the page player itself is set to, read
+ // here too so the host's periodic volume check costs no second call.
+ // -> {paused, muted, volume, level, own, time, readyState, ended, playerVolume, active} | null (no element yet)
'media.state': async () => {
const player = await localPlayer();
const el = player && player._player;
if (!(el instanceof HTMLMediaElement)) return null;
- let active = null;
- try { const me = (await need().resolve('ConnectDevicesAPI').getDevices()).find(d => d.isLocal); active = !!(me && me.isActive); } catch (e) { /* unknown */ }
- return { paused: el.paused, muted: el.muted, volume: el.volume, level: el.volume, own: ownLevel(player), time: el.currentTime, readyState: el.readyState, ended: el.ended, active };
+ let playerVolume = null;
+ try { playerVolume = await need().playback.getVolume(); } catch (e) { /* unknown */ }
+ return { paused: el.paused, muted: el.muted, volume: el.volume, level: el.volume, own: ownLevel(player), time: el.currentTime, readyState: el.readyState, ended: el.ended, playerVolume, active: await activeDevice() };
},
// The media element's volume, on this phone only: no Spotify Connect command (refused on
// some accounts, slow on a busy network) and nothing reported to Spotify, as the player's
@@ -335,6 +357,21 @@
return el.volume;
},
+ // A whole fade in one call: the page applies the steps itself, so the host sends the play
+ // command while the sound goes down instead of waiting for every step (a round trip each).
+ // {steps: [level, ...], ms, restore: true?} -> true. Levels are never 0: see 'media.mute'.
+ 'media.fade': async a => {
+ const player = await localPlayer();
+ const el = player && player._player;
+ if (!(el instanceof HTMLMediaElement)) return null;
+ const steps = (Array.isArray(a.steps) ? a.steps : []).map(Number);
+ const per = Math.max(1, Number(a.ms) || 12);
+ const set = v => { el.volume = Math.min(1, Math.max(SILENT, v)); };
+ steps.forEach((v, i) => setTimeout(() => set(v), i * per));
+ if (a.restore) setTimeout(() => { el.volume = ownLevel(player); }, steps.length * per);
+ return true;
+ },
+
'volume.get': () => need().playback.getVolume(),
'volume.set': a => need().playback.setVolume(a.level),
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
index 9f476eac..95a5a42e 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
@@ -35,13 +35,19 @@ object MyspotiRuntime {
host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }
host.onPageStarting = { spotify.onPageStarting() }
spotify.player.reloadHost = { host.reload() }
- // Every 10 s: is the bridge ready, what does the player say (diagnostics in Logcat).
+ // The bridge, the page and the player in Logcat (diagnostics of a bug report): what
+ // changes is logged when it changes, not once every 10 s whether or not anything happened.
scope.launch {
+ var last = ""
while (true) {
kotlinx.coroutines.delay(10_000)
val s = spotify.player.state.value
- android.util.Log.d(WebPlayerHost.LOG, "status ready=${spotify.ready.value} login=${host.loginRequired.value} " +
- "track=${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering} url=${host.url.value.take(60)}")
+ val line = "status ready=${spotify.ready.value} login=${host.loginRequired.value} " +
+ "track=${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering} url=${host.url.value.take(60)}"
+ if (line != last) {
+ last = line
+ android.util.Log.d(WebPlayerHost.LOG, line)
+ }
}
}
if (!loadPage) return
@@ -53,12 +59,7 @@ object MyspotiRuntime {
}
/** True when the Web Player holds a signed-in user's token (not an anonymous one). */
- suspend fun isSignedIn(): Boolean {
- val token = spotify.bridge.call("token.get")
- return (token as? kotlinx.serialization.json.JsonObject)?.get("isAnonymous")?.let {
- (it as? kotlinx.serialization.json.JsonPrimitive)?.content == "false"
- } ?: false
- }
+ suspend fun isSignedIn(): Boolean = spotify.isSignedIn()
/** Data saver: frees the page; [resume] loads it again. */
fun suspendPlayer() = host.unload()