Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Fast skips that land and show the right song, a pick kept through an ad, playlist mosaics, a 402 report that can tell the causes apart
kota-zo8d7b018fb428
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2ca654a7..6159596e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,10 @@ Each release on GitHub shows its section below. The app shows it too when it off- **"Next" that does nothing**: when the player page answered "ok" to a skip but stayed on the song (the sound dipped, then nothing), the song after it is now asked for by name.- **Spotify refusing playback (402)**: after a refusal, the app now also tries taking playback to this phone first, then the list on shuffle, before telling you; the diagnostic report now says which kind of account plays and whether a refused command targeted this phone or another device.- **Smart shuffle from the player keeps the song playing**: on a long playlist the song was often not found and a random one started; the playing song now always stays first.+- **Fast taps on "next" in the player land where they should, and the screen follows**: each tap showed the same second song (held for seconds while the page went on to the fifth), and a first skip Spotify applied late could push the player one song past the target. The screen now shows the song the taps add up to, and where the skips landed is checked and corrected.+- **A song picked just before an ad plays after the ad** instead of the old queue going on (reported with a song picked in another playlist).+- **Profile playlists without a cover of their own show their mosaic** instead of a grey square.+- **"Restart the player" in Settings says it did.**- **Shuffle no longer flips back**: a state sent by the page before it took the tap could turn the button off again, and the list and the player then disagreed.## 2.0.0-beta.9diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.ktindex 44c1a85f..298bd7cd 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt@@ -79,6 +79,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop@Volatile private var wantedVolume: Double? = null/** The last [play] sent: (context, track, when), for a refused command's retry. */@Volatile private var lastPlay: Triple<Uri, Uri?, Long>? = null+ /** The play an ad came in place of (see [onState]), asked again when the ad is over. */+ @Volatile private var pickBeforeAd: Triple<Uri, Uri?, Long>? = null/** How far down [onRefused]'s steps the current play went (0: not refused). */@Volatile private var refusalStep = 0@Volatile private var refusalTransferring = false@@ -662,6 +664,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (!_adPlaying.value) {adSince = System.currentTimeMillis()adMuteTries = 0+ // A song picked a moment ago and not playing yet: the ad came in its place.+ val p = lastPlay+ pickBeforeAd = p?.takeIf {+ adSince - it.third < PICK_AD_MS && it.second != null && lastTrackState?.item?.uri != it.second+ }}adState = sadStateAt = System.currentTimeMillis()@@ -672,7 +679,18 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopshowIntent()return}+ val adJustEnded = _adPlaying.value_adPlaying.value = false+ val pick = pickBeforeAd+ if (adJustEnded && pick != null) {+ pickBeforeAd = null+ // Reported (beta.9): a song picked in another playlist, an ad, then the old queue went+ // on and the song had to be picked again. Not on it after the ad: asked for again.+ if (s?.item?.uri != pick.second && System.currentTimeMillis() - pick.third < PICK_REPLAY_MS && liveIntent() == null) {+ bridge.logger?.invoke("song picked before the ad not played: asked again")+ scope.launch { runCatching { play(pick.first, trackUri = pick.second) } }+ }+ }adsOffSent = falseadSkipped = falseadMuteTries = 0@@ -950,6 +968,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun seek(positionMs: Long) { endCrossfade(restore = true); command("player.seek", buildJsonObject { put("positionMs", positionMs) }) }override suspend fun next() {pausedByUser = false+ pickBeforeAd = nullif (skipsHeld) { stepIntent(1); return }// Remembered: should the page go into an ad break instead, this song comes after it.val base = lastWithSong()@@ -988,6 +1007,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun previous() {pausedByUser = false+ pickBeforeAd = nullif (skipsHeld) { stepIntent(-1); return }intent = nullwithFade {@@ -1168,6 +1188,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopconst val PLAY_TIMEOUT_MS = 10_000L/** A refusal that long after a play belongs to it. */const val REFUSED_WINDOW_MS = 5_000L+ /** An ad starting this soon after a song is picked came in its place. */+ const val PICK_AD_MS = 8_000L+ /** After this the user has moved on: a pick is no longer replayed after its ad. */+ const val PICK_REPLAY_MS = 120_000L/** A plain skip still on its song after this: the page lost it. */const val NEXT_LOST_MS = 2_500L/** After the refusal fallback's transfer, before the song is asked again. */diff --git a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.ktindex 307b3db0..1cc4b052 100644--- a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt+++ b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt@@ -40,6 +40,8 @@ class TestControlReceiver : BroadcastReceiver() {"resume" -> SongPlayer.play()"pause" -> SongPlayer.pause()"next" -> SongPlayer.next()+ // The player's own "next" button and the mini player's swipe.+ "swipenext" -> SongPlayer.swipeNext()"previous" -> SongPlayer.previous()"seek" -> SongPlayer.seekTo(intent.getLongExtra("ms", 0L))"screenon" -> context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.ktindex 65bce9bd..3a764565 100644--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt@@ -328,6 +328,7 @@ object SongPlayer {}val item = s.itemval uri = item?.uri.orEmpty()+ if (uri.isNotEmpty()) lastPageUri = urival id = trackIdOf(uri)val pending = pendingTrackIdif (pending != null) {@@ -661,6 +662,35 @@ object SongPlayer {// The song [burstTaps] after the one playing at the first tap.val target = burstUpcoming.getOrNull(burstTaps - 1)transport(waitReady = !stateSeen) { if (target == null) api.player.next() else api.player.skipTo(target) }+ if (target != null) {+ burstTarget = target+ burstContext = _nowPlaying.value.contextUri+ burstSeq+++ main.removeCallbacks(verifyBurst)+ main.postDelayed(verifyBurst, BURST_VERIFY_MS)+ }+ }++ /*+ * Measured on the test phone: the burst's first "next" is acknowledged by the page, applied+ * a second late, after the jump to the target — the page then lands one song past it (the+ * screen showed the target, the speaker the song after). Where the burst landed is checked,+ * and the target played by name when it is not there.+ */+ private var burstTarget: app.myspoti.api.NowPlaying? = null+ private var burstContext = ""+ private var burstSeq = 0+ private var lastPageUri = ""+ private const val BURST_VERIFY_MS = 2_500L+ private val verifyBurst = Runnable {+ val t = burstTarget ?: return@Runnable+ burstTarget = null+ val seq = burstSeq+ // A newer tap, pick or pause: the user moved on.+ if (SystemClock.elapsedRealtime() - burstAt < BURST_VERIFY_MS || !playing) return@Runnable+ if (lastPageUri == t.uri || burstContext.isBlank()) return@Runnable+ Log.d(TAG, "skips landed on $lastPageUri, not ${t.name}: playing it")+ transport { if (seq == burstSeq) api.player.play(burstContext, t.uri) }}fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); transport(waitReady = !stateSeen) { api.player.previous() } }@@ -844,13 +874,22 @@ object SongPlayer {/** Swipe to the next track: show it right away, then skip. */fun swipeNext() {if (LocalPlayer.active.value) { next(); return }- _nowPlaying.value.next?.let { n ->- markPending(n.spotifyTrackId)- boundState?.updateSongState(n.coverUri, n.title, n.singer, true, n.id, 0, n.album)- durationMs = n.durationMs.toLong()- pushNotification(n, false)- }next()+ // The song this tap lands on, the one [next]'s burst will skip to. Reported (beta.9): each+ // fast tap showed `nowPlaying.next` — the same second song every time, held as pending,+ // so the screen stayed on it for seconds while the page went on to the fifth.+ val n = if (burstTaps <= 1) _nowPlaying.value.next+ else burstUpcoming.getOrNull(burstTaps - 1)?.let(::songOf)+ if (n == null) {+ // Unknown target: the page's own states show where it lands.+ pendingTrackId = null+ pendingItemUri = null+ return+ }+ markPending(n.spotifyTrackId)+ boundState?.updateSongState(n.coverUri, n.title, n.singer, true, n.id, 0, n.album)+ durationMs = n.durationMs.toLong()+ pushNotification(n, false)}fun seekTo(ms: Long) {diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.kt b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.ktindex e1556a4f..71069f96 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.kt@@ -11,5 +11,8 @@ package com.music.spotui.ui.componentsfun spotifyImageUrl(url: String?): String? = when {url.isNullOrBlank() -> nullurl.startsWith("spotify:image:") -> "https://i.scdn.co/image/" + url.removePrefix("spotify:image:")+ // A playlist without a cover of its own: the 2x2 mosaic of its first albums, which the+ // profile endpoints also hand out as a URI (reported: profile playlists left grey).+ url.startsWith("spotify:mosaic:") -> "https://mosaic.scdn.co/640/" + url.removePrefix("spotify:mosaic:").split(':').joinToString("")else -> url}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex 07d46cf9..e3442e6d 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -161,7 +161,11 @@ fun SettingsScreen(navController: NavController) {CheckUpdateRow()// The hidden Web Player stuck or crashed: rebuild it without leaving the app.Column(- Modifier.fillMaxWidth().clickable { app.myspoti.host.android.MyspotiRuntime.host.reload() }+ Modifier.fillMaxWidth().clickable {+ app.myspoti.host.android.MyspotiRuntime.host.reload()+ // Reported: nothing said the restart happened.+ android.widget.Toast.makeText(ctx, ctx.getString(R.string.restart_player_done), android.widget.Toast.LENGTH_SHORT).show()+ }.padding(horizontal = 20.dp, vertical = 10.dp),) {Text(stringResource(R.string.restart_player_title), color = Color.White, fontSize = 16.sp)diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xmlindex a81a554d..edf79d0b 100644--- a/base/app/src/main/res/values-de/myspoti_strings.xml+++ b/base/app/src/main/res/values-de/myspoti_strings.xml@@ -326,4 +326,5 @@<string name="support_github_action">Auf GitHub sponsern</string><string name="spotiflac_verify_again">Die SpotiFLAC-Bestätigung ist abgelaufen: Bestätige sie in den Einstellungen erneut, um verlustfrei herunterzuladen</string><string name="download_on_mobile_data">Download über mobile Daten: Er verbraucht dein Datenvolumen</string>+ <string name="restart_player_done">Player neu gestartet</string></resources>diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xmlindex 01d0beef..18c9cb4a 100644--- a/base/app/src/main/res/values-el/myspoti_strings.xml+++ b/base/app/src/main/res/values-el/myspoti_strings.xml@@ -326,4 +326,5 @@<string name="support_github_action">Χορηγία στο GitHub</string><string name="spotiflac_verify_again">Η επαλήθευση του SpotiFLAC έληξε: κάν’ την ξανά στις Ρυθμίσεις για λήψη χωρίς απώλειες</string><string name="download_on_mobile_data">Λήψη με δεδομένα κινητής: χρησιμοποιεί το πακέτο δεδομένων σου</string>+ <string name="restart_player_done">Η αναπαραγωγή ξεκίνησε ξανά</string></resources>diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xmlindex b38135d6..689076f7 100644--- a/base/app/src/main/res/values-es/myspoti_strings.xml+++ b/base/app/src/main/res/values-es/myspoti_strings.xml@@ -326,4 +326,5 @@<string name="support_github_action">Patrocinar en GitHub</string><string name="spotiflac_verify_again">La verificación de SpotiFLAC ha caducado: vuelve a hacerla en Ajustes para descargar sin pérdida</string><string name="download_on_mobile_data">Descarga con datos móviles: usa tu tarifa de datos</string>+ <string name="restart_player_done">Reproductor reiniciado</string></resources>diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xmlindex 191fd6fa..8a67706d 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -413,4 +413,5 @@<string name="player_show_elapsed">Afficher le temps écoulé</string><string name="player_sleep_timer">Minuteur de veille</string><string name="player_speed_a11y">Vitesse de lecture, %1$s×</string>+ <string name="restart_player_done">Lecteur redémarré</string></resources>diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xmlindex a9c01f48..369739ce 100644--- a/base/app/src/main/res/values-pt/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml@@ -326,4 +326,5 @@<string name="support_github_action">Patrocinar no GitHub</string><string name="spotiflac_verify_again">A verificação do SpotiFLAC expirou: volta a fazê-la nas Definições para transferir sem perdas</string><string name="download_on_mobile_data">Transferência com dados móveis: usa o teu tarifário</string>+ <string name="restart_player_done">Player reiniciado</string></resources>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 0ae97d13..1b70e7a6 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -413,4 +413,5 @@<string name="player_show_elapsed">Show the time elapsed</string><string name="player_sleep_timer">Sleep timer</string><string name="player_speed_a11y">Playback speed, %1$s×</string>+ <string name="restart_player_done">Player restarted</string></resources>diff --git a/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.kt b/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.ktindex c266a937..aea91b47 100644--- a/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.kt+++ b/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.kt@@ -23,6 +23,12 @@ class SpotifyImagesTest {assertNull(spotifyImageUrl(" "))}+ // Measured on a public profile: the URL below answers 200 image/jpeg.+ @Test fun mosaicBecomesTheMosaicOfItsFourCovers() = assertEquals(+ "https://mosaic.scdn.co/640/ab67616d00001e025b436ba28d283bc720bb86b8ab67616d00001e02707a76900ebe2c7f5fad3615",+ spotifyImageUrl("spotify:mosaic:ab67616d00001e025b436ba28d283bc720bb86b8:ab67616d00001e02707a76900ebe2c7f5fad3615"),+ )+@Test fun anythingElseIsUntouched() =assertEquals("spotify:track:4cOdK2wGLETKBW3PvgPWqT", spotifyImageUrl("spotify:track:4cOdK2wGLETKBW3PvgPWqT"))}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 1e6e3450..bc23935d 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@@ -180,6 +180,17 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:val net = android.os.SystemClock.uptimeMillis() - askedLogbook.log("relay $method ${shortPath(url)} -> ${it.code} in $net ms")if (it.code >= 400) Logbook.log("relay error body: ${text.take(400)}")+ // B3 (402 on some free accounts): what a tester's report must carry to tell the+ // causes apart — the refusal's own headers, and what the refused command asked+ // (the license the page put in it, a picked song or not). No ids, no cookies.+ if (it.code == 402) {+ val heads = it.headers.names().filterNot { n -> n.equals("set-cookie", true) || n.startsWith("authorization", true) }+ .joinToString(", ") { n -> "$n=${it.header(n)?.take(80)}" }+ Logbook.log("refusal headers: $heads")+ if (body != null) Logbook.log("refused command: ${commandSummary(body)}")+ }+ if (registration) Regex("\"effective_license\"\\s*:\\s*\"([^\"]*)\"").find(text)+ ?.let { m -> Logbook.log("registration: effective_license=${m.groupValues[1]}") }if (debuggable && registration) Logbook.log("registration answered: ${text.take(500)}")if (debuggable && AD_MARK.containsMatchIn(text)) keepAdSample(method, url, body, text)reply(id, it.code, out.toString(), text)@@ -212,6 +223,19 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:Logbook.log("relay: ad in $method ${shortPath(url)} (sample kept)")}+ /** A Connect command's shape, without ids: endpoint, license, picked song, origin. */+ private fun commandSummary(body: String): String = runCatching {+ val c = JSONObject(body).optJSONObject("command") ?: JSONObject(body)+ val opts = c.optJSONObject("options")+ listOf(+ "endpoint=${c.optString("endpoint", "?")}",+ "license=${opts?.optString("license", "<none>") ?: "<no options>"}",+ "skip_to=${opts?.has("skip_to") == true}",+ "origin=${c.optJSONObject("play_origin")?.optString("feature_identifier", "?") ?: "?"}",+ "transfer=${c.has("transfer_options") || JSONObject(body).has("transfer_options")}",+ ).joinToString(" ")+ }.getOrDefault("unreadable")+/*** The path with device ids hidden. A command's `from/<id>/to/<id>` keeps one fact: whether it* targets this player itself (`to/self`) or another device (`to/other`) — a refusal of adiff --git a/tools/playback_test.py b/tools/playback_test.pyindex 4e91fa7e..8529a025 100644--- a/tools/playback_test.py+++ b/tools/playback_test.py@@ -320,6 +320,18 @@ def s_rapid_next(r, ctx):r.healthy(exp, "rapid next x5", settle=15)+def s_rapid_swipe(r, ctx):+ # Reported (beta.9): fast taps on the player's "next" left the screen on the second song+ # for seconds while the page went on. The app's own button path, then what the app shows.+ p = probe()+ exp = p["upcoming"][4] if len(p["upcoming"]) > 4 else None+ for _ in range(5):+ test("swipenext")+ time.sleep(0.12)+ r.healthy(exp, "rapid swipe next x5", settle=15)+ same_on_screen(r, "after the taps")++def s_previous_start(r, ctx):p = probe()if not p.get("previous"):@@ -553,6 +565,21 @@ def s_ad_previous(r, ctx):same_on_screen(r, "after the ad")+def s_ad_pick(r, ctx):+ # Reported (beta.9): a song picked, an ad in its place, then the old queue went on.+ r.healthy(None, "before the pick", allow_track_change=True)+ p = probe()+ tracks = ctx.get("tracks") or []+ exp = next((t for t in reversed(tracks) if t != p["track"]["uri"] and t not in p["upcoming"][:2]), None)+ if not exp:+ raise Fail("no other song to pick")+ test("play", track=exp + "|", context=ctx["playlist"])+ time.sleep(0.15)+ fake_ad()+ r.healthy(exp, "song picked, then an ad", settle=45)+ same_on_screen(r, "after the ad")++def s_reload_taps(r, ctx):p = probe()exp = p["upcoming"][1] if len(p["upcoming"]) > 1 else None@@ -567,6 +594,7 @@ SCENARIOS = [("play_playlist", s_play_playlist, ()),("next", s_next, ()),("rapid_next", s_rapid_next, ()),+ ("rapid_swipe", s_rapid_swipe, ()),("previous_start", s_previous_start, ()),("previous_middle", s_previous_middle, ()),("seek", s_seek, ()),@@ -577,6 +605,8 @@ SCENARIOS = [("reload_taps", s_reload_taps, ("transport failed",)),("ad_taps", s_ad_taps, ()),("ad_previous", s_ad_previous, ()),+ # The fake ad hides the picked song from the app, which asks for it again: provoked.+ ("ad_pick", s_ad_pick, ("play not taken",)),("frozen", s_frozen, ("call timeout", "page not answering", "command failed", "transport failed")),("background", s_background, ()),("cold_start", s_cold_start, ()),