Skip to content

Native Android client for Spotify, built with Jetpack Compose

Playback: a refused play that is acknowledged and never played goes on to the fallbacks, a pause after an ad break is undone, repeat is set again after a play, nothing is repaired from here while another device plays, a WebView without Widevine is said so

kota-zoe7bca057c62b
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.kt
index ef74fde0..a1cd9024 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
@@ -105,6 +105,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
val refused: kotlinx.coroutines.flow.SharedFlow<Unit> = _refused
+ private val _drmMissing = kotlinx.coroutines.flow.MutableStateFlow(false)
+ /**
+ * The WebView has no working Widevine: nothing Spotify streams can play on this device, whatever
+ * is tried, and the user has to update or change the WebView (see player-bridge.js).
+ */
+ val drmMissing: kotlinx.coroutines.flow.StateFlow<Boolean> = _drmMissing
+
/** Reloads the Web Player page (set by the host); used when a stalled player does not recover. */
@Volatile var reloadHost: (suspend () -> Unit)? = null
/**
@@ -130,7 +137,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
when (type) {
"state" -> onState(playerState(payload))
"queue" -> queue(payload)?.let { q -> _queue.value = q.copy(nextUp = q.nextUp.filter { it.kind != ItemKind.AD }) }
- "refused" -> onRefused()
+ "refused" -> onRefused(late = ((payload as? JsonObject)?.get("late") as? kotlinx.serialization.json.JsonPrimitive)?.booleanOrNull == true)
+ "drm" -> (payload as? JsonObject)?.let { _drmMissing.value = (it["ok"] as? kotlinx.serialization.json.JsonPrimitive)?.booleanOrNull == false }
}
}
}
@@ -162,6 +170,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (!ownReload && (lost != null || liveIntent() != null)) scope.launch {
runCatching { if (lost != null) resumeAfterReload(lost) else { delay(RESTORE_GAP_MS); playIntent() } }
}
+ repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS
if (audioQuality != "auto") applyAudioQuality()
// The page keeps its volume: an app closed during a muted ad must not stay silent.
runCatching { if (volume() == 0.0) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }
@@ -268,6 +277,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
/** The media element as the watcher last read it. */
@Volatile private var lastMedia: Media? = null
+ /**
+ * Another device of the account is Spotify Connect's active one: this page's element stands
+ * still while the state is that device's. Judged on the element too, as the active flag is read
+ * every few seconds and lags a transfer to this phone (whose element then moves).
+ */
+ private val remoteActive: Boolean get() = lastMedia?.let { it.active == false && it.paused } == true
+
/** Loads the song after the current one in advance (see "player.preloadNext"); on by default. */
@Volatile var preloadNext = true
/** "current|next" already preloaded. */
@@ -451,6 +467,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
// A song really playing again: the ad break is over.
if (s != null && !s.isPaused && !s.isBuffering) { adAttempts = 0; adReloaded = false }
+ // Another device of the account plays (Spotify Connect, the desktop app): the state is
+ // its, followed and never repaired. A stall judged on its clock — "past the end" on a
+ // state that came a moment late, "buffering" on its report — was answered with a seek or
+ // a play of the next song, i.e. a command that skipped a track on that other device.
+ if (remoteActive) {
+ if (key != null || attempts != 0) bridge.logger?.invoke("another device plays: nothing repaired from here")
+ key = null; attempts = 0; silentSince = 0L
+ continue
+ }
// Silent: the state says this phone plays, yet its media element stands still.
val fading = fadeBackTo != null || fadeBack?.isActive == true
val playingHere = s != null && !s.isPaused && !s.isBuffering && media != null && media.active != false && !fading
@@ -487,6 +512,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
private suspend fun guardVolume(s: PlayerState?, media: Media?) {
if (s == null || s.isPaused || s.isBuffering || _adPlaying.value || fadeBackTo != null || fadeBack?.isActive == true) return
+ // Its volume is set through Connect: with another device playing it would be that device's.
+ if (remoteActive) return
// A crossfade owns the element level until it ends: the guard must not undo the ramp.
// Past its deadline, though, it is exactly the lost unmute it exists to catch.
if (crossfadeArmed) {
@@ -527,10 +554,14 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* 3. the list on shuffle (an account that may only shuffle);
* then the user is told.
*/
- private fun onRefused() {
+ private fun onRefused(late: Boolean = false) {
val last = lastPlay ?: return
val now = System.currentTimeMillis()
- if (now - last.third > REFUSED_WINDOW_MS) return
+ if (now - last.third > if (late) LATE_REFUSED_WINDOW_MS else REFUSED_WINDOW_MS) return
+ // A command acknowledged and never delivered: the page's media element stood still for 10 s
+ // while its state may well say "playing". Not a refusal if the user paused, an ad is on or
+ // another device plays.
+ if (late && (pausedByUser || _adPlaying.value || remoteActive)) return
// A play of ours (an ad recovery, a reload restore): refused during an ad, and the steps
// below would replay the list from its start and turn shuffle on, which nobody asked for.
if (!lastPlayRefusable) { bridge.logger?.invoke("play refused by Spotify: not the user's, left alone"); return }
@@ -699,6 +730,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
val ctx = _state.value?.contextUri ?: return
if (userMoveAt != movedAt) return
+ // Another device plays this list (the ad is this phone's page's, not its): not skipped from here.
+ if (remoteActive) return
// Clearing the flow below cancels this very block (collectLatest): what follows must
// finish, or the skip is sent and its put-back never is.
withContext(NonCancellable) {
@@ -827,6 +860,23 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
shufflePending?.takeIf { System.currentTimeMillis() - it.second < PICK_REPLAY_MS }?.let { (on, _) ->
if (adJustEnded && s?.shuffle != on) scope.launch { runCatching { setShuffle(on) } }
}
+ // Reported (2.0, stable): the ad is got past, then the music stays paused until Play is
+ // pressed. The page can leave the song it moves on to paused when the ad's audio was
+ // refused. Nobody paused (a pause is [pausedByUser]), so the song is resumed once the
+ // state has settled, unless something else was played or picked meanwhile.
+ if (adJustEnded && s?.item != null && s.isPaused && !pausedByUser && s.item?.kind != ItemKind.AD) {
+ val playedAt = lastPlay?.third
+ val uri = s.item?.uri
+ scope.launch {
+ delay(AD_END_SETTLE_MS)
+ val now = _state.value
+ if (now != null && now.item?.uri == uri && now.isPaused && !pausedByUser && !_adPlaying.value && liveIntent() == null &&
+ lastPlay?.third == playedAt && !remoteActive) {
+ bridge.logger?.invoke("paused after the ad break, nobody paused: ${now.item?.name} resumed")
+ runCatching { resume() }
+ }
+ }
+ }
adsOffSent = false
adMuteTries = 0
// A real song is playing: the fallback after a refusal (play the list without picking the
@@ -836,6 +886,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
else if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()
lastTrackState = s
_state.value = s
+ // Reported: the repeat button forgets what it was. A play command (and a reloaded page) starts
+ // the page on its own options, repeat off; the mode the user chose is set again, once, when the
+ // first song of that play reports another. Only within a few seconds of our own play: a repeat
+ // changed from another device later is theirs.
+ wantedRepeat?.let { want ->
+ if (s?.item != null && s.repeat != want && System.currentTimeMillis() < repeatRestoreUntil) {
+ repeatRestoreUntil = 0L
+ bridge.logger?.invoke("repeat is ${s.repeat} after a play, $want was chosen: set again")
+ scope.launch { runCatching { setRepeat(want) } }
+ }
+ }
val i = liveIntent() ?: run { intent = null; return }
val uri = s?.item?.uri
when {
@@ -1119,6 +1180,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
lastPlayRefusable = refusable
refusalStep = 0
pausedByUser = false
+ repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS
withFade {
command("player.play", timeoutMs = PLAY_TIMEOUT_MS, args = buildJsonObject {
put("contextUri", contextUri)
@@ -1328,7 +1390,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
}
+ /** The repeat mode the user chose last: a play or a reload that leaves the page on another one is put back (see [onState]). */
+ @Volatile private var wantedRepeat: Repeat? = null
+ /** Until when a page reporting another repeat mode than [wantedRepeat] counts as having forgotten it. */
+ @Volatile private var repeatRestoreUntil = 0L
+
override suspend fun setRepeat(mode: Repeat) {
+ wantedRepeat = mode
bridge.call("player.setRepeat", buildJsonObject { put("mode", mode.ordinal) })
}
@@ -1509,9 +1577,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
const val PLAY_TIMEOUT_MS = 10_000L
/** A refusal that long after a play belongs to it. */
const val REFUSED_WINDOW_MS = 5_000L
+ /** A play that leaves the page's repeat mode other than the user's: set again if it shows within this long. */
+ const val REPEAT_RESTORE_MS = 20_000L
+ /** An acknowledged command that never played is told 10 s after it was sent. */
+ const val LATE_REFUSED_WINDOW_MS = 25_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. */
+ /** After an ad break, a pause nobody asked for is undone once the page's state has settled this long. */
+ const val AD_END_SETTLE_MS = 1_200L
const val PICK_REPLAY_MS = 120_000L
/** How long a resume waits for a page that went silent while paused before loading it again. */
const val RESUME_PING_MS = 1_500L
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 7ab33bb3..686427e6 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
@@ -73,6 +73,8 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {
"queue" -> _events.tryEmit("queue" to (msg["queue"] ?: JsonNull))
// Spotify refused a playback command (HTTP 402/403 on Connect), see ControlRelay.
"refused" -> _events.tryEmit("refused" to msg)
+ // The page's EME probe (see player-bridge.js): whether Widevine works in this WebView.
+ "drm" -> _events.tryEmit("drm" to msg)
"error" -> _ready.value = false
}
}
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 81bb22cc..d9996881 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -680,9 +680,26 @@
window.addEventListener('error', e => post({ type: 'jserror', error: String(e.message || e.error || '').slice(0, 300) }));
window.addEventListener('unhandledrejection', e => post({ type: 'jserror', error: String((e.reason && (e.reason.stack || e.reason.message)) || e.reason || '').slice(0, 300) }));
+ // Widevine, which every Spotify stream is encrypted with: a WebView without a working one (an
+ // outdated or stripped Android System WebView, a device without a licence) plays nothing, which
+ // looks like "no sound", "refused" or "stuck at 0:00". Asked once per page, from the page's own
+ // EME; an empty robustness is the weakest level every Widevine device has (L3).
+ let drm = null;
+ const probeDrm = () => {
+ const report = (ok, error) => { drm = { type: 'drm', ok, error: error || '' }; post(drm); };
+ try {
+ if (!navigator.requestMediaKeySystemAccess) return report(false, 'no EME in this WebView');
+ navigator.requestMediaKeySystemAccess('com.widevine.alpha', [{
+ initDataTypes: ['cenc'],
+ audioCapabilities: [{ contentType: 'audio/mp4; codecs="mp4a.40.2"' }],
+ }]).then(() => report(true), e => report(false, String((e && e.message) || e).slice(0, 200)));
+ } catch (e) { report(false, String((e && e.message) || e).slice(0, 200)); }
+ };
+
const announce = () => {
if (!services) return;
post({ type: 'ready', version: VERSION });
+ if (drm) post(drm);
lastState = '';
pushState();
};
@@ -714,6 +731,7 @@
park();
post({ type: 'ready', version: VERSION });
pushState();
+ probeDrm();
return;
}
if (Date.now() - started > READY_TIMEOUT_MS) {
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlaybackFollowUpTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlaybackFollowUpTest.kt
new file mode 100644
index 00000000..2ffed7a2
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlaybackFollowUpTest.kt
@@ -0,0 +1,134 @@
+package app.myspoti.spotify
+
+import app.myspoti.api.Repeat
+import app.myspoti.spotify.bridge.AdBlock
+import app.myspoti.spotify.bridge.Bridge
+import app.myspoti.spotify.bridge.BridgeHost
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.runBlocking
+import org.junit.jupiter.api.AfterEach
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * What the player does after the page did something the user did not ask for: a pause at the end
+ * of an ad break, a repeat mode forgotten by a play, a WebView without Widevine.
+ */
+class PlaybackFollowUpTest {
+ private class FakeHost : BridgeHost {
+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)
+ val calls = CopyOnWriteArrayList<Pair<String, String>>()
+ override suspend fun evaluate(script: String) {
+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return
+ calls += m.groupValues[2] to m.groupValues[3]
+ // The page's media element: standing still, this phone the active device (or not).
+ val value = if (m.groupValues[2] == "media.state") """{"paused":${mediaPaused},"muted":false,"level":1,"own":1,"time":0,"active":${mediaActive}}""" else "null"
+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":$value}""")
+ }
+ suspend fun post(json: String) = messages.emit(json)
+ @Volatile var mediaActive = true
+ @Volatile var mediaPaused = false
+ }
+
+ private lateinit var scope: CoroutineScope
+ private lateinit var host: FakeHost
+ private lateinit var player: SpotifyPlayer
+
+ @BeforeEach fun up() {
+ AdBlock.ahead.value = null
+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ host = FakeHost()
+ player = SpotifyPlayer(Bridge(host, scope), scope)
+ }
+
+ @AfterEach fun down() {
+ AdBlock.ahead.value = null
+ scope.cancel()
+ }
+
+ private fun track(name: String) =
+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":200000}"""
+
+ private fun state(item: String, paused: Boolean = false, repeat: Int = 0) =
+ """{"type":"state","state":{"track":$item,"contextUri":"spotify:playlist:C","next":${track("N")},"isPaused":$paused,"isBuffering":false,
+ |"repeat":$repeat,"positionMs":0,"timestamp":${System.currentTimeMillis()},"restrictions":{}}}""".trimMargin()
+
+ private val ad = """{"kind":"ad","uri":"spotify:ad:1","name":"ad","durationMs":30000}"""
+
+ private fun waitFor(what: String, ms: Long = 4_000, cond: () -> Boolean) = runBlocking {
+ val end = System.currentTimeMillis() + ms
+ while (!cond()) {
+ check(System.currentTimeMillis() < end) { "timed out: $what" }
+ delay(20)
+ }
+ }
+
+ private fun called(method: String) = host.calls.count { it.first == method }
+
+ @Test fun `a song left paused by the page after an ad break is resumed`() = runBlocking {
+ host.post("""{"type":"ready"}""")
+ host.post(state(track("A")))
+ host.post(state(ad))
+ waitFor("ad flag") { player.adPlaying.value }
+ host.post(state(track("B"), paused = true))
+ waitFor("resumed") { called("player.resume") > 0 }
+ }
+
+ @Test fun `a pause by the user during the ad break is left alone`() = runBlocking {
+ host.post("""{"type":"ready"}""")
+ host.post(state(track("A")))
+ host.post(state(ad))
+ waitFor("ad flag") { player.adPlaying.value }
+ runCatching { player.pause() }
+ val before = called("player.resume")
+ host.post(state(track("B"), paused = true))
+ delay(SpotifyPlayer.AD_END_SETTLE_MS + 500)
+ assertEquals(before, called("player.resume"), "the user's pause holds")
+ }
+
+ @Test fun `the repeat mode the user chose is set again when a play leaves the page on another`() = runBlocking {
+ host.post("""{"type":"ready"}""")
+ host.post(state(track("A"), repeat = 1))
+ player.setRepeat(Repeat.CONTEXT)
+ val sent = called("player.setRepeat")
+ player.play("spotify:playlist:C", trackUri = "spotify:track:P")
+ host.post(state(track("P"), repeat = 0))
+ waitFor("repeat set again") { called("player.setRepeat") == sent + 1 }
+ // Set again once, not on every state until the page agrees.
+ host.post(state(track("P"), repeat = 0))
+ delay(300)
+ assertEquals(sent + 1, called("player.setRepeat"))
+ }
+
+ @Test fun `a webview without widevine is reported`() = runBlocking {
+ assertFalse(player.drmMissing.value)
+ host.post("""{"type":"drm","ok":true}""")
+ delay(100)
+ assertFalse(player.drmMissing.value)
+ host.post("""{"type":"drm","ok":false,"error":"no EME in this WebView"}""")
+ waitFor("drm flag") { player.drmMissing.value }
+ assertTrue(player.drmMissing.value)
+ }
+
+ @Test fun `a refusal told late is dropped while another device plays`() = runBlocking {
+ host.mediaActive = false
+ host.mediaPaused = true
+ host.post("""{"type":"ready"}""")
+ host.post(state(track("A")))
+ player.play("spotify:playlist:C", trackUri = "spotify:track:P")
+ // The watcher reads the element within its tick.
+ waitFor("element read") { called("media.state") > 0 }
+ host.post("""{"type":"refused","status":402,"late":true}""")
+ delay(300)
+ assertEquals(1, host.calls.count { it.first == "player.play" }, "no fallback play on another device: ${host.calls.map { it.first }}")
+ }
+}
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.kt
index f2d37a63..5581bc98 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
@@ -208,9 +208,17 @@ object SongPlayer {
}
scope.launch {
MyspotiRuntime.spotify.player.refused.collect {
- android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.play_refused, android.widget.Toast.LENGTH_LONG).show()
+ // No Widevine in this WebView: the refusal is the WebView's, not the account's.
+ val message = if (MyspotiRuntime.spotify.player.drmMissing.value) app.myspoti.engine.R.string.drm_missing else app.myspoti.engine.R.string.play_refused
+ android.widget.Toast.makeText(Graph.app, message, android.widget.Toast.LENGTH_LONG).show()
}
}
+ // Said once the page has asked its WebView: a device that cannot decrypt Spotify's streams
+ // plays nothing (no sound, 0:00), and nothing else in the app says why.
+ scope.launch {
+ MyspotiRuntime.spotify.player.drmMissing.first { it }
+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.drm_missing, android.widget.Toast.LENGTH_LONG).show()
+ }
scope.launch {
MyspotiRuntime.host.licenseLimitedUntil.collect { until ->
if (until > SystemClock.elapsedRealtime()) main.post {
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index b1dd693b..0091b16c 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -363,6 +363,7 @@
<string name="page_load_failed">Impossible de charger cette page.\nVérifiez votre connexion et réessayez.</string>
<string name="jam_paste_link">Rejoindre avec un lien copié</string>
<string name="play_refused">Spotify a refusé cette lecture sur votre compte. Dans certains pays, un compte gratuit ne joue qu’en aléatoire : essayez le bouton aléatoire.</string>
+ <string name="drm_missing">Lecture impossible ici : l’Android System WebView de ce téléphone n’a pas de DRM Widevine fonctionnel, dont Spotify a besoin. Mettez à jour Android System WebView et Chrome dans le Play Store, puis choisissez-le dans Paramètres > Options pour les développeurs > Implémentation WebView.</string>
<string name="artist_liked_songs">Titres likés</string>
<plurals name="artist_liked_songs_count">
<item quantity="one">%1$d titre de %2$s</item>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 4967b10a..da789139 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -363,6 +363,7 @@
<string name="page_load_failed">Couldn\'t load this page.\nCheck your connection and try again.</string>
<string name="jam_paste_link">Join with a copied link</string>
<string name="play_refused">Spotify refused to play this on your account. Free accounts in some countries can only play shuffled: try the shuffle button.</string>
+ <string name="drm_missing">Playback is impossible here: this phone\'s Android System WebView has no working Widevine DRM, which Spotify needs. Update Android System WebView and Chrome in the Play Store, and pick it under Settings > Developer options > WebView implementation.</string>
<string name="artist_liked_songs">Liked songs</string>
<plurals name="artist_liked_songs_count">
<item quantity="one">%1$d song by %2$s</item>
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.kt
index 1a5a94cc..be9c3346 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
@@ -336,9 +336,11 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
const original = window.fetch;
const command = /player\/command|connect\/transfer/;
// A refused play or transfer (free accounts in some countries): the app tries another way.
- const tell = (status, url) => {
+ // late: the command was acknowledged but nothing played (see trust): the host judges it
+ // more than its usual few seconds after the play.
+ const tell = (status, url, late) => {
if ((status === 402 || status === 403) && command.test(url) && window.MyspotiHost) {
- try { window.MyspotiHost.postMessage(JSON.stringify({ type: 'refused', status, path: url.split('?')[0].replace(/^.*\/v1\//, '').replace(/\/from\/.*$/, '') })); } catch (e) { /* host gone */ }
+ try { window.MyspotiHost.postMessage(JSON.stringify({ type: 'refused', status, late: !!late, path: url.split('?')[0].replace(/^.*\/v1\//, '').replace(/\/from\/.*$/, '') })); } catch (e) { /* host gone */ }
}
};
const note = (value) => { try { window.MyspotiNet.postMessage(JSON.stringify(Object.assign({ type: 'direct' }, value))); } catch (e) { /* host gone */ } };
@@ -348,13 +350,18 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
// it took. Kept only if something plays within 10 s: a command sent from the page can
// be acknowledged and never delivered (X-Requested-With, see above).
const plays = () => [...media].some(m => !m.paused && !m.ended && m.readyState > 2);
- const trust = () => {
+ const trust = (url) => {
if (window.__mspDirect) return;
window.__mspDirect = true;
setTimeout(() => {
const kept = plays();
if (!kept) window.__mspDirect = false;
note({ kept });
+ // Acknowledged and never delivered: the page showed a song at 0:00 that never
+ // started (reported after 2.0.1: "I can press play, the clock moves, nothing
+ // plays"). Told as a refusal, so the app's fallbacks run and, failing all of
+ // them, the user is told instead of left on a silent player.
+ if (!kept) tell(402, url, true);
}, 10000);
};
const direct = (url, init) => original.call(window, url, init).then(r => { tell(r.status, url); return r; });
@@ -370,7 +377,7 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
if (status === 402 && command.test(p.url) && !window.__mspDirect) {
original.call(window, p.url, p.init).then(r => {
note({ status: r.status });
- if (r.ok) trust(); else tell(r.status, p.url);
+ if (r.ok) trust(p.url); else tell(r.status, p.url);
p.resolve(r);
}, () => { tell(status, p.url); p.resolve(relayedAnswer()); });
return;