Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Stability: a 429 storm on licences holds every repair, a page that never loads or never becomes ready is loaded again, no pause sent to an orphan session
kota-zo5bad5613ce9b
diff --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 298bd7cd..1003923c 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@@ -93,6 +93,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/** Reloads the Web Player page (set by the host); used when a stalled player does not recover. */@Volatile var reloadHost: (suspend () -> Unit)? = null+ /**+ * True while Spotify is limiting this client (a storm of `429` on the audio licences): every+ * repair — a reload, a replay, a seek — asks for licences again and makes the limit last.+ * The watchers stand still until it is over.+ */+ @Volatile var recoveryHeld: () -> Boolean = { false }/** Streaming quality ("auto", "low", "normal", "high", "very_high"), kept for every page load. */@Volatile var audioQuality: String = "auto"@@ -160,6 +166,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop*/private suspend fun reloadAndPlayOn(s: PlayerState?, next: Boolean = true) {val reload = reloadHost ?: return+ if (recoveryHeld()) { bridge.logger?.invoke("reload held: Spotify is limiting playback"); return }ownReload = truetry {runCatching {@@ -180,6 +187,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop*/suspend fun reloadPage(): Boolean {val reload = reloadHost ?: return false+ if (recoveryHeld()) { bridge.logger?.invoke("reload held: Spotify is limiting playback"); return false }ownReload = truetry {reload()@@ -424,6 +432,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopsilentSince = if (playingHere && !moved) (if (silentSince == 0L) now else silentSince) else 0Lval silent = silentSince != 0L && now - silentSince >= SILENT_MSval reason = s?.let { stallOf(it, now, pausedByUser) } ?: (if (silent) SILENT else null)+ if (recoveryHeld()) { key = null; attempts = 0; continue }if (s == null || reason == null) { key = null; attempts = 0; continue }val k = "${s.item?.uri}|$reason"if (k != key) { key = k; since = now; attempts = 0; if (reason != SILENT) continue }@@ -963,7 +972,20 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}}- override suspend fun pause() { pausedByUser = true; endCrossfade(restore = true); command("player.pause") }+ override suspend fun pause() {+ pausedByUser = true+ endCrossfade(restore = true)+ // Nothing playing (no state yet, or already paused): nothing to send. A pause on the+ // orphan session a fresh page finds makes the page claim it with a transfer first —+ // refused with a 402 on some free accounts, and the page then hung ~13 s on it (tester+ // report, beta.9). An ad keeps the old song's state paused-looking: sent then.+ val s = _state.value+ if (!_adPlaying.value && (s == null || s.isPaused)) {+ bridge.logger?.invoke("pause: nothing plays, not sent")+ return+ }+ command("player.pause")+ }override suspend fun resume() { pausedByUser = false; command("player.resume") }override suspend fun seek(positionMs: Long) { endCrossfade(restore = true); command("player.seek", buildJsonObject { put("positionMs", positionMs) }) }override suspend fun next() {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 3a764565..464700ea 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@@ -168,6 +168,15 @@ object SongPlayer {android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.play_refused, android.widget.Toast.LENGTH_LONG).show()}}+ scope.launch {+ MyspotiRuntime.host.licenseLimitedUntil.collect { until ->+ if (until > SystemClock.elapsedRealtime()) main.post {+ playing = false+ boundState?.updatePlayingState(false)+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.spotify_limited, android.widget.Toast.LENGTH_LONG).show()+ }+ }+ }PlaybackService.controls = Controls}diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xmlindex edf79d0b..7dcec7f7 100644--- a/base/app/src/main/res/values-de/myspoti_strings.xml+++ b/base/app/src/main/res/values-de/myspoti_strings.xml@@ -327,4 +327,5 @@<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>+ <string name="spotify_limited">Spotify begrenzt die Wiedergabe gerade. Versuche es in einer Minute erneut.</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 18c9cb4a..e9bc558e 100644--- a/base/app/src/main/res/values-el/myspoti_strings.xml+++ b/base/app/src/main/res/values-el/myspoti_strings.xml@@ -327,4 +327,5 @@<string name="spotiflac_verify_again">Η επαλήθευση του SpotiFLAC έληξε: κάν’ την ξανά στις Ρυθμίσεις για λήψη χωρίς απώλειες</string><string name="download_on_mobile_data">Λήψη με δεδομένα κινητής: χρησιμοποιεί το πακέτο δεδομένων σου</string><string name="restart_player_done">Η αναπαραγωγή ξεκίνησε ξανά</string>+ <string name="spotify_limited">Το Spotify περιορίζει προσωρινά την αναπαραγωγή. Δοκιμάστε ξανά σε ένα λεπτό.</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 689076f7..cec0b6c5 100644--- a/base/app/src/main/res/values-es/myspoti_strings.xml+++ b/base/app/src/main/res/values-es/myspoti_strings.xml@@ -327,4 +327,5 @@<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>+ <string name="spotify_limited">Spotify está limitando la reproducción por ahora. Inténtalo de nuevo en un minuto.</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 8a67706d..908bba76 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -414,4 +414,5 @@<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>+ <string name="spotify_limited">Spotify limite la lecture pour le moment. Réessayez dans une minute.</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 369739ce..3fedfb5d 100644--- a/base/app/src/main/res/values-pt/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml@@ -327,4 +327,5 @@<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>+ <string name="spotify_limited">O Spotify está limitando a reprodução no momento. Tente de novo em um minuto.</string></resources>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 1b70e7a6..f0e00407 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -414,4 +414,5 @@<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>+ <string name="spotify_limited">Spotify is limiting playback for a moment. Try again in a minute.</string></resources>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.ktindex 355d02e1..f4dab261 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,35 @@ object MyspotiRuntime {host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }host.onPageStarting = { spotify.onPageStarting() }spotify.player.reloadHost = { host.reload() }+ spotify.player.recoveryHeld = { host.licenseLimited() }+ // Spotify limiting this client: stop asking (a paused player requests no licence).+ scope.launch {+ host.licenseLimitedUntil.collect { until ->+ if (until > android.os.SystemClock.elapsedRealtime()) runCatching { spotify.player.pause() }+ }+ }// 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 = ""var planLogged = false+ // A page that loaded but whose player never became ready (no bridge, a script that+ // failed): loaded again, after 60 s, then twice as long each time, up to 10 min.+ var notReadySince = 0L+ var notReadyWait = 60_000Lwhile (true) {kotlinx.coroutines.delay(10_000)+ val clock = android.os.SystemClock.elapsedRealtime()+ val waiting = !spotify.ready.value && !host.loginRequired.value && !host.licenseLimited() &&+ host.url.value.startsWith(WebPlayerHost.PLAYER_URL)+ if (!waiting) { notReadySince = 0L; if (spotify.ready.value) notReadyWait = 60_000L }+ else if (notReadySince == 0L) notReadySince = clock+ else if (clock - notReadySince >= notReadyWait) {+ Logbook.log("player not ready for ${(clock - notReadySince) / 1000} s: loading it again")+ notReadySince = 0L+ notReadyWait = (notReadyWait * 2).coerceAtMost(600_000L)+ host.reload()+ }// Once per signed-in session: the account's plan, the first thing a refused play// (402) needs. No name, no id — only what decides what the account may play.if (!planLogged && spotify.ready.value && runCatching { isSignedIn() }.getOrDefault(false)) {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 861877b9..18eb6145 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@@ -47,6 +47,34 @@ class WebPlayerHost(private val context: Context) : BridgeHost {/** The page's current URL. */val url: StateFlow<String> = _url+ /*+ * Spotify limiting this client: measured on the test phone after an evening of test runs,+ * the page asked for an audio licence ~4 times a second, each answered 429, and every repair+ * (reload, replay) asked again. A storm of them ends playback here for a while (growing on+ * repeats) instead of feeding it; [licenseLimitedUntil] tells the app and the player.+ */+ private val license429 = ArrayDeque<Long>()+ private var limitStreak = 0+ private var lastLimitAt = 0L+ private val _licenseLimitedUntil = MutableStateFlow(0L)+ /** Elapsed-realtime end of the current hold, 0 or past when none. */+ val licenseLimitedUntil: StateFlow<Long> = _licenseLimitedUntil+ fun licenseLimited(): Boolean = android.os.SystemClock.elapsedRealtime() < _licenseLimitedUntil.value++ private fun onLicenseLimited() = synchronized(license429) {+ val now = android.os.SystemClock.elapsedRealtime()+ license429.addLast(now)+ while (license429.isNotEmpty() && now - license429.first() > LIMIT_WINDOW_MS) license429.removeFirst()+ if (license429.size < LIMIT_COUNT || licenseLimited()) return@synchronized+ if (now - lastLimitAt > LIMIT_FORGET_MS) limitStreak = 0+ lastLimitAt = now+ val hold = (LIMIT_HOLD_MS shl limitStreak.coerceAtMost(4)).coerceAtMost(LIMIT_HOLD_MAX_MS)+ limitStreak+++ license429.clear()+ Logbook.log("Spotify is limiting audio licences (429 x$LIMIT_COUNT in ${LIMIT_WINDOW_MS / 1000} s): playback held ${hold / 1000} s")+ _licenseLimitedUntil.value = now + hold+ }+private val _loginRequired = MutableStateFlow(false)val loginRequired: StateFlow<Boolean> = _loginRequired@@ -180,6 +208,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {Logbook.log("page start ${url.take(120)}")mainFrameFailed = false+ // A load that never ends (measured: a reload's document request answered nothing+ // for 9 minutes, the page stayed "loading", empty, without the bridge).+ main.removeCallbacks(loadTimeout)+ if (android.net.Uri.parse(url).host == PLAYER_HOST) main.postDelayed(loadTimeout, PAGE_LOAD_TIMEOUT_MS)pageStarts++_url.value = url_loginRequired.value = isLoginPage(url)@@ -189,7 +221,9 @@ class WebPlayerHost(private val context: Context) : BridgeHost {override fun onReceivedError(view: WebView, request: WebResourceRequest, error: android.webkit.WebResourceError) {if (request.url.host?.contains("spotify") == true)Logbook.log("load error ${error.errorCode} ${error.description} ${request.url.toString().take(120)}")- if (request.isForMainFrame && request.url.host == PLAYER_HOST) playerPageFailed("load error ${error.errorCode}")+ // ERR_ABORTED: a load this app stopped itself (a timeout, a newer load) — not a failure.+ if (request.isForMainFrame && request.url.host == PLAYER_HOST && "ERR_ABORTED" !in error.description.toString())+ playerPageFailed("load error ${error.errorCode}")}override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {@@ -197,10 +231,12 @@ class WebPlayerHost(private val context: Context) : BridgeHost {Logbook.log("http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")if (request.isForMainFrame && request.url.host == PLAYER_HOST && (response.statusCode >= 500 || response.statusCode == 429))playerPageFailed("http ${response.statusCode}")+ if (response.statusCode == 429 && request.url.path?.contains("widevine-license") == true) onLicenseLimited()}override fun onPageFinished(view: WebView, url: String) {Logbook.log("page finished ${url.take(120)}")+ main.removeCallbacks(loadTimeout)if (url.startsWith(PLAYER_URL) && !mainFrameFailed) { pageFailures = 0; main.removeCallbacks(retryPlayerPage) }_url.value = url_loginRequired.value = isLoginPage(url)@@ -304,8 +340,14 @@ class WebPlayerHost(private val context: Context) : BridgeHost {private val retryPlayerPage = Runnable {if (!loadAsked || _loginRequired.value) return@RunnableLogbook.log("player page: load again (attempt ${pageFailures + 1})")+ view.stopLoading()view.loadUrl(PLAYER_URL)}+ private val loadTimeout = Runnable {+ if (!loadAsked || _loginRequired.value) return@Runnable+ view.stopLoading()+ playerPageFailed("still loading after ${PAGE_LOAD_TIMEOUT_MS / 1000} s")+ }private fun playerPageFailed(what: String) {mainFrameFailed = true@@ -382,6 +424,12 @@ class WebPlayerHost(private val context: Context) : BridgeHost {const val LOG = "Myspoti"const val PLAYER_URL = "https://open.spotify.com/"private const val PLAYER_HOST = "open.spotify.com"+ private const val PAGE_LOAD_TIMEOUT_MS = 25_000L+ private const val LIMIT_COUNT = 6+ private const val LIMIT_WINDOW_MS = 10_000L+ private const val LIMIT_HOLD_MS = 60_000L+ private const val LIMIT_HOLD_MAX_MS = 600_000L+ private const val LIMIT_FORGET_MS = 1_800_000Lprivate val RETRY_PAGE_MS = longArrayOf(2_000, 5_000, 15_000, 30_000, 60_000)private const val LOAD_WATCH_MS = 4_000Lprivate const val LOAD_RETRIES = 4