Skip to content

Native Android client for Spotify, built with Jetpack Compose

Ads while an extension song plays: the Spotify page only mirrors it, so after an ad or a reload nothing is resumed or unmuted there and the mirror alone plays the current song once the page's device has joined; a hushed page stays silent when unmuted; GraphQL reads are cancelled with their caller

kota-zo3bc66634f870
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AdRecoveryRules.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AdRecoveryRules.kt
new file mode 100644
index 00000000..f6a6a279
--- /dev/null
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AdRecoveryRules.kt
@@ -0,0 +1,75 @@
+package app.myspoti.spotify
+
+/**
+ * How [SpotifyPlayer] gets past an ad and what plays on a new page, without the page.
+ *
+ * While the page only mirrors a song the app plays itself ([SpotifyPlayer.setMirroring]: the
+ * local player is heard, the page plays the same song unheard so Spotify counts it), the app's
+ * mirror alone says what the page plays. Reported (2.1.0, log seen): an ad on the mirror, the
+ * user's next, a reload; then the song the mirror had sent before the ad ("picked before the
+ * ad") and an even older one ("page back after a reload: … goes on") were both played on the new
+ * page, next to the mirror's own song, and the ad's unmute made the page heard over the local player.
+ */
+object AdRecoveryRules {
+ /** What is done about an ad stuck on the page. */
+ enum class Stuck {
+ /** Play the song after it (the page's own queue). */
+ NEXT,
+ /** Reload the page, then play on from the song before the ad. */
+ RELOAD,
+ /**
+ * Reload the page and play nothing there: the mirror plays its song again once the new
+ * page's device has joined. Waiting is no option: a refused ad stays current for good
+ * (20 min measured) and refuses every play, so the mirror's song would never be counted,
+ * and Spotify would start from a page still stuck when the local player hands over.
+ * Playing on is none either: it plays the page's own queue, never the mirror's song.
+ */
+ RELOAD_ONLY,
+ }
+
+ /** The [attempt]-th try on a stuck ad; [playing]: a muted ad that plays (not refused). */
+ fun stuck(attempt: Int, playing: Boolean, mirrored: Boolean): Stuck = when {
+ mirrored -> Stuck.RELOAD_ONLY
+ SpotifyPlayer.adRecovery(attempt, playing) == "next" -> Stuck.NEXT
+ else -> Stuck.RELOAD
+ }
+
+ /**
+ * Whether a song played just before an ad (the ad came in its place) is kept to be played
+ * again after the break. Not the mirror's: it sends the local player's song itself, which may
+ * be another one by then.
+ */
+ fun keepsPickBeforeAd(mirrored: Boolean): Boolean = !mirrored
+
+ /** What a page that is ready again plays. */
+ enum class PageBack {
+ /** Nothing (our own reload says itself what plays, or nothing played). */
+ NOTHING,
+ /** The song picked before an ad, held over the reload. */
+ PICK,
+ /** What played when the page went away, where it was. */
+ RESUME,
+ /** The song the user asked for during the reload. */
+ INTENT,
+ /** Nothing from here: the mirror plays the local player's song again. */
+ MIRROR,
+ }
+
+ /**
+ * [ownReload]: the page came back from a reload of ours, read when "ready" came (not after a
+ * call that waits for the page, by which time our reload may be over). [pickHeld]: a song
+ * picked before an ad waits for the new page; [lost]: something played when the page went;
+ * [intent]: the user asked for a song meanwhile.
+ */
+ fun pageBack(ownReload: Boolean, mirrored: Boolean, pickHeld: Boolean, lost: Boolean, intent: Boolean): PageBack = when {
+ mirrored -> PageBack.MIRROR
+ ownReload -> PageBack.NOTHING
+ pickHeld -> PageBack.PICK
+ lost -> PageBack.RESUME
+ intent -> PageBack.INTENT
+ else -> PageBack.NOTHING
+ }
+
+ /** After our own reload: whether the player plays a song there itself (else the mirror does). */
+ fun playsAfterOwnReload(mirrored: Boolean): Boolean = !mirrored
+}
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 adcbb25b..daf76f29 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
@@ -209,12 +209,23 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
val lost = playingAtLoss
playingAtLoss = null
+ // Read now: the hush below waits for the page (0.5 s seen), by when our own reload
+ // can be over, and this page was then taken for one that was not ours (log seen: the
+ // song before an ad resumed next to the mirror's).
+ val own = ownReload
+ val mirrored = mirroring
// A new page forgot it was unheard (clip sound, a mirror): told again before it plays on.
if (clipHushed || localMuted) { hushedUri = null; applyHush() }
// A pick held over a reload that was not ours, or whose own play did not run: played now.
- if (!ownReload && pickAfterReload != null) scope.launch { delay(RESTORE_GAP_MS); playPickAfterReload() }
- else if (!ownReload && (lost != null || liveIntent() != null)) scope.launch {
- runCatching { if (lost != null) resumeAfterReload(lost) else { delay(RESTORE_GAP_MS); playIntent() } }
+ when (AdRecoveryRules.pageBack(own, mirrored, pickAfterReload != null, lost != null, liveIntent() != null)) {
+ AdRecoveryRules.PageBack.MIRROR -> {
+ pickAfterReload = null
+ if (lost != null) bridge.logger?.invoke("page back: it mirrors a song played here, ${lost.item?.name} not resumed (the mirror plays its song again)")
+ }
+ AdRecoveryRules.PageBack.PICK -> scope.launch { delay(RESTORE_GAP_MS); playPickAfterReload() }
+ AdRecoveryRules.PageBack.RESUME -> scope.launch { runCatching { resumeAfterReload(lost ?: return@runCatching) } }
+ AdRecoveryRules.PageBack.INTENT -> scope.launch { runCatching { delay(RESTORE_GAP_MS); playIntent() } }
+ AdRecoveryRules.PageBack.NOTHING -> {}
}
repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS
if (streamingLevel != "auto") applyAudioQuality()
@@ -248,6 +259,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
try {
runCatching {
if (!reloadAndWait(reload)) return@runCatching
+ // The page only mirrors: the mirror plays its song again there, nothing from here.
+ if (!AdRecoveryRules.playsAfterOwnReload(mirroring)) {
+ pickAfterReload = null
+ bridge.logger?.invoke("page back after a reload: it mirrors a song played here, the mirror plays it again")
+ return@runCatching
+ }
if (playPickAfterReload()) return@runCatching
if (s == null) return@runCatching
if (next) { delay(1_500); playOn(s) } else resumeAfterReload(s)
@@ -292,6 +309,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
private suspend fun reloadAndWait(reload: suspend () -> Unit): Boolean {
val gone = bridge.pagesGone
+ // The old page still says "ready" for a moment: its device is not one to command from now.
+ app.myspoti.spotify.bridge.PageDevice.pageGone()
reload()
return withTimeoutOrNull(45_000) { delay(1_500); bridge.ready.first { it && bridge.pagesGone != gone } } != null
}
@@ -559,9 +578,19 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (stuck) {
adAttempts++
val last = lastTrackState
- if (adRecovery(adAttempts, playing = playing && !refused) == "next") {
+ val how = AdRecoveryRules.stuck(adAttempts, playing = playing && !refused, mirrored = mirroring)
+ if (how == AdRecoveryRules.Stuck.NEXT) {
bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song (attempt $adAttempts)")
last?.let { runCatching { playOn(it) } }
+ } else if (how == AdRecoveryRules.Stuck.RELOAD_ONLY) {
+ // The page only mirrors (unheard): a stuck ad keeps the song from being
+ // counted and refuses every play, so the page is reloaded; nothing is
+ // resumed there, the mirror plays its song again once the device has joined.
+ adReloaded = true
+ muteUntilSong = true
+ pickBeforeAd = null
+ bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: the page only mirrors, reloading it with nothing resumed (attempt $adAttempts)")
+ reloadAndPlayOn(null)
} else {
adReloaded = true
// Until a real song plays on the new page, it stays muted (see [muteUntilSong]).
@@ -1019,8 +1048,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val came = p?.takeIf {
adSince - it.third < PICK_AD_MS && it.second != null && lastTrackState?.item?.uri != it.second
}?.let { Pick(it.first, it.second, it.third, lastOrder?.takeIf { o -> o.first == it.first }?.second, index = lastIndex) }
- // A pick held from an earlier break stays until it was played or went stale.
- pickBeforeAd = came ?: pickBeforeAd
+ // A pick held from an earlier break stays until it was played or went stale. Not
+ // while the page only mirrors: that play was the mirror's, which sends its song again.
+ pickBeforeAd = if (AdRecoveryRules.keepsPickBeforeAd(mirroring)) came ?: pickBeforeAd else null
}
adState = s
adStateAt = System.currentTimeMillis()
@@ -1037,11 +1067,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
// A page reloaded to get past an ad: heard again only once a real song plays on it.
if (muteUntilSong && s?.item != null && !s.isPaused && !s.isBuffering) {
muteUntilSong = false
- bridge.logger?.invoke("a song plays after the reload: ${s.item?.name} heard again")
+ // The ad's mute only: a page that mirrors stays unheard ('media.mute' keeps the hush).
+ bridge.logger?.invoke("a song plays after the reload: ${s.item?.name} ${if (localMuted || clipHushed) "out of the ad's mute, still unheard (hushed)" else "heard again"}")
scope.launch { unmuteAfterAd() }
}
val pick = pickBeforeAd
- if (adJustEnded && pick != null) {
+ if (adJustEnded && pick != null && !AdRecoveryRules.keepsPickBeforeAd(mirroring)) {
+ pickBeforeAd = null
+ bridge.logger?.invoke("song picked before the ad: left to the mirror (the page only mirrors)")
+ } else 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.
@@ -1075,7 +1109,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
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) {
+ lastPlay?.third == playedAt && !remoteActive && !mirroring) {
bridge.logger?.invoke("paused after the ad break, nobody paused: ${now.item?.name} resumed")
runCatching { resume() }
}
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 2829656f..8ecca93f 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
@@ -142,6 +142,7 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {
fun pageGone() {
pagesGone++
gone = true
+ PageDevice.pageGone()
_ready.value = false
pending.values.forEach { it.completeExceptionally(BridgeException("page reloaded")) }
}
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/PageDevice.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/PageDevice.kt
new file mode 100644
index 00000000..3c1531ca
--- /dev/null
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/PageDevice.kt
@@ -0,0 +1,27 @@
+package app.myspoti.spotify.bridge
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * Whether the page's playback device has joined Spotify Connect since the page last loaded. A new
+ * page says "ready" before that: a command sent then is refused (log seen: a play 0.3 s after
+ * "ready", answered DEVICE_NOT_FOUND, the device's join coming 0.3 s later). The host reports the
+ * join (the page's connect-state PUT answered); the player and the bridge report a page going away.
+ */
+object PageDevice {
+ private val _joined = MutableStateFlow(false)
+ /** The current page's device has joined. */
+ val joined: StateFlow<Boolean> = _joined.asStateFlow()
+
+ /** A join was reported once in this process: the host reports them, so [joined] can be waited for. */
+ @Volatile var reported = false
+ private set
+
+ /** The page's device joined Spotify Connect (its connect-state PUT was answered 2xx). */
+ fun joined() { reported = true; _joined.value = true }
+
+ /** The page is going away (a reload asked for or started): its device is not one to command. */
+ fun pageGone() { _joined.value = false }
+}
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 42dcd52d..9691500a 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
@@ -2,7 +2,11 @@ package app.myspoti.spotify.gql
import app.myspoti.spotify.bridge.Bridge
import app.myspoti.spotify.bridge.BridgeException
+import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
@@ -148,11 +152,29 @@ class SpotifyHttp(
// Bytes keep the content type exactly as given (OkHttp appends a charset to String bodies,
// which some Spotify endpoints reject with 400).
builder.method(method, body?.toByteArray()?.toRequestBody(contentType.toMediaType()) ?: if (method == "GET" || method == "DELETE") null else ByteArray(0).toRequestBody(null))
- val result = withContext(Dispatchers.IO) { http.newCall(builder.build()).execute().use { it.code to it.body.string() } }
+ val call = http.newCall(builder.build())
+ // A read is given up with its caller (a timeout, a song skipped): a blocking execute ignores
+ // the coroutine's cancellation, and a caller's 3 s timeout then lasted the client's 10 s
+ // (log seen: an extension asked for a skipped-to song 10 s late, behind its ISRC lookup).
+ // Writes still run to their end: a caller gone must not leave one half sent.
+ val result = if (method == "GET") call.executeCancellable() else withContext(Dispatchers.IO) { call.execute().use { it.code to it.body.string() } }
if (result.first == 401) lock.withLock { web = null }
return result
}
+ /** Runs the call on the IO pool; the coroutine cancelled, the call is cancelled too (it then fails at once). */
+ private suspend fun okhttp3.Call.executeCancellable(): Pair<Int, String> = coroutineScope {
+ val call = this@executeCancellable
+ val done = java.util.concurrent.atomic.AtomicBoolean(false)
+ val watch = launch(start = CoroutineStart.UNDISPATCHED) { try { awaitCancellation() } finally { if (!done.get()) call.cancel() } }
+ try {
+ withContext(Dispatchers.IO) { call.execute().use { it.code to it.body.string() } }
+ } finally {
+ done.set(true)
+ watch.cancel()
+ }
+ }
+
/** What [sendRaw] got back: the status, lower-case header names (values joined by ", "), the body text. */
data class RawResponse(val status: Int, val headers: Map<String, String>, val body: String)
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 6c45e847..cfbdf202 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -460,9 +460,11 @@
window.__mspMuted = !!a.on;
const player = await localPlayer().catch(() => null);
const els = new Set([...(window.__mspMedia || []), ...document.querySelectorAll('audio, video'), ...await playerMedia()]);
+ // The end of an ad's mute leaves a hushed page unheard ('media.hush'): seen, the page heard
+ // over the local player it mirrors after an ad, on an element the hush had not reached yet.
for (const el of els) {
el.muted = false;
- el.volume = a.on ? SILENT : (player && el === player._player ? ownLevel(player) : 1);
+ el.volume = a.on || window.__mspHushed ? SILENT : (player && el === player._player ? ownLevel(player) : 1);
}
return els.size;
},
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdRecoveryRulesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdRecoveryRulesTest.kt
new file mode 100644
index 00000000..f5c4f17a
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdRecoveryRulesTest.kt
@@ -0,0 +1,43 @@
+package app.myspoti.spotify
+
+import app.myspoti.spotify.AdRecoveryRules.PageBack
+import app.myspoti.spotify.AdRecoveryRules.Stuck
+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.Test
+
+class AdRecoveryRulesTest {
+ @Test fun spotifyAloneKeepsItsLevers() {
+ assertEquals(Stuck.RELOAD, AdRecoveryRules.stuck(1, playing = false, mirrored = false))
+ assertEquals(Stuck.NEXT, AdRecoveryRules.stuck(2, playing = false, mirrored = false))
+ assertEquals(Stuck.NEXT, AdRecoveryRules.stuck(1, playing = true, mirrored = false))
+ assertEquals(Stuck.RELOAD, AdRecoveryRules.stuck(2 + SpotifyPlayer.AD_SKIPS_AFTER_RELOAD, playing = false, mirrored = false))
+ }
+
+ @Test fun aMirroringPageIsOnlyReloaded() {
+ for (attempt in 1..5) for (playing in listOf(false, true))
+ assertEquals(Stuck.RELOAD_ONLY, AdRecoveryRules.stuck(attempt, playing, mirrored = true))
+ assertFalse(AdRecoveryRules.playsAfterOwnReload(mirrored = true))
+ assertTrue(AdRecoveryRules.playsAfterOwnReload(mirrored = false))
+ }
+
+ @Test fun theMirrorsPlayIsNoPickBeforeAnAd() {
+ assertFalse(AdRecoveryRules.keepsPickBeforeAd(mirrored = true))
+ assertTrue(AdRecoveryRules.keepsPickBeforeAd(mirrored = false))
+ }
+
+ @Test fun aPageBackWhileMirroringResumesNothing() {
+ // Log seen: a pick held, the song before the ad lost, the reload ours but over by then.
+ assertEquals(PageBack.MIRROR, AdRecoveryRules.pageBack(ownReload = false, mirrored = true, pickHeld = true, lost = true, intent = true))
+ assertEquals(PageBack.MIRROR, AdRecoveryRules.pageBack(ownReload = true, mirrored = true, pickHeld = false, lost = true, intent = false))
+ }
+
+ @Test fun aPageBackOnSpotifyAloneIsUnchanged() {
+ assertEquals(PageBack.NOTHING, AdRecoveryRules.pageBack(ownReload = true, mirrored = false, pickHeld = true, lost = true, intent = true))
+ assertEquals(PageBack.PICK, AdRecoveryRules.pageBack(ownReload = false, mirrored = false, pickHeld = true, lost = true, intent = true))
+ assertEquals(PageBack.RESUME, AdRecoveryRules.pageBack(ownReload = false, mirrored = false, pickHeld = false, lost = true, intent = true))
+ assertEquals(PageBack.INTENT, AdRecoveryRules.pageBack(ownReload = false, mirrored = false, pickHeld = false, lost = false, intent = true))
+ assertEquals(PageBack.NOTHING, AdRecoveryRules.pageBack(ownReload = false, mirrored = false, pickHeld = false, lost = false, intent = false))
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
index a6742e78..5bae4432 100644
--- a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
+++ b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
@@ -5,6 +5,7 @@ import android.os.Looper
import android.os.SystemClock
import app.myspoti.api.PlayerState
import app.myspoti.host.android.MyspotiRuntime
+import app.myspoti.spotify.bridge.PageDevice
import com.music.spotui.data.local.LocalTrack
import com.music.spotui.data.preferences.ConnectMirrorPref
import com.music.spotui.di.MirrorRules.Follow
@@ -117,13 +118,31 @@ object ConnectMirror {
MyspotiRuntime.scope.launch { page.playsElsewhere.collect { away -> if (away) wentAway() else cameBack() } }
// Commands are held during an ad and while the page reloads (it refuses them: "local player
// is disabled"); the page usable again gets the song the local player is on, where it is.
+ // A page ready again takes commands only once its device has joined Spotify Connect: the
+ // song is sent then (or after JOIN_WAIT_MS without a join).
MyspotiRuntime.scope.launch {
- combine(api.ready, page.adPlaying) { ready, ad -> ready && !ad }.distinctUntilChanged().collect { usable -> if (usable) pageBack() }
+ combine(api.ready, page.adPlaying, PageDevice.joined) { ready, ad, joined ->
+ if (!ready) { joinWaitedOut = false; main.removeCallbacks(joinWait) }
+ else if (!ad && !joined && PageDevice.reported && !joinWaitedOut) { main.removeCallbacks(joinWait); main.postDelayed(joinWait, MirrorRules.JOIN_WAIT_MS) }
+ pageUsable()
+ }.distinctUntilChanged().collect { usable -> if (usable) pageBack() }
}
}
- /** The page can take commands: loaded, and no ad on. */
- private fun pageUsable(): Boolean = api.ready.value && !page.adPlaying.value
+ /** The page's device has not joined [MirrorRules.JOIN_WAIT_MS] after it was ready: commanded anyway. */
+ private var joinWaitedOut = false
+ private val joinWait = Runnable {
+ if (!api.ready.value || page.adPlaying.value || PageDevice.joined.value) return@Runnable
+ joinWaitedOut = true
+ if (want != null && running) log("the page's device has not joined Spotify Connect ${MirrorRules.JOIN_WAIT_MS / 1000} s after the page was back: its song is sent anyway")
+ pageBack()
+ }
+
+ /** The page can take commands: loaded, no ad on, its device joined (see [MirrorRules.pageUsable]). */
+ private fun pageUsable(): Boolean = MirrorRules.pageUsable(
+ ready = api.ready.value, ad = page.adPlaying.value,
+ joined = PageDevice.joined.value, joinReported = PageDevice.reported, waitedOut = joinWaitedOut,
+ )
/** The local player's song or state changed (SongPlayer.onLocalState, main thread). */
fun onLocal(t: LocalTrack, playing: Boolean, positionMs: Long, durationMs: Long) {
diff --git a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
index 88e911be..656afddf 100644
--- a/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
+++ b/base/app/src/main/java/com/music/spotui/di/MirrorRules.kt
@@ -178,6 +178,18 @@ object MirrorRules {
fun backHere(playingHere: Boolean, handedAway: Boolean, moved: Boolean, intended: Boolean, on: Boolean): Boolean =
on && playingHere && !intended && (handedAway || moved)
+ /** How long a page ready again is given for its device to join Spotify Connect before it is commanded anyway. */
+ const val JOIN_WAIT_MS = 8_000L
+
+ /**
+ * Whether the page takes the mirror's commands: loaded ([ready]), no [ad] on, and its device
+ * [joined] to Spotify Connect (a play sent between "ready" and the join was refused:
+ * DEVICE_NOT_FOUND). The join is only waited for when the host reports joins ([joinReported]),
+ * and no longer than [JOIN_WAIT_MS] ([waitedOut]).
+ */
+ fun pageUsable(ready: Boolean, ad: Boolean, joined: Boolean, joinReported: Boolean, waitedOut: Boolean): Boolean =
+ ready && !ad && (joined || !joinReported || waitedOut)
+
/**
* The loop guard: a command the mirror sends is answered by Web Player states that must not be
* taken for a remote device's commands. Until [sent]'s window is over, its states are its echo.
diff --git a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
index 2d5e4f2e..ea35db39 100644
--- a/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
+++ b/base/app/src/test/java/com/music/spotui/di/MirrorRulesTest.kt
@@ -265,4 +265,17 @@ class MirrorRulesTest {
assertEquals(Follow.Retry, onWeb(Web(d, paused = false, positionMs = 0), landed = false))
assertEquals(Follow.Nothing, onWeb(Web(a, paused = false, positionMs = 60_000), landed = false))
}
+
+ @Test fun pageBackAfterAReloadWaitsForItsDeviceToJoin() {
+ // Ready, no ad, but the device not joined yet: a play now was refused (DEVICE_NOT_FOUND).
+ assertFalse(MirrorRules.pageUsable(ready = true, ad = false, joined = false, joinReported = true, waitedOut = false))
+ assertTrue(MirrorRules.pageUsable(ready = true, ad = false, joined = true, joinReported = true, waitedOut = false))
+ // No join came within the wait: commanded anyway.
+ assertTrue(MirrorRules.pageUsable(ready = true, ad = false, joined = false, joinReported = true, waitedOut = true))
+ // A host that never reports joins is not waited on.
+ assertTrue(MirrorRules.pageUsable(ready = true, ad = false, joined = false, joinReported = false, waitedOut = false))
+ // An ad or a page not loaded: never.
+ assertFalse(MirrorRules.pageUsable(ready = true, ad = true, joined = true, joinReported = true, waitedOut = true))
+ assertFalse(MirrorRules.pageUsable(ready = false, ad = false, joined = true, joinReported = true, waitedOut = true))
+ }
}
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 a743bead..e9b54044 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
@@ -329,6 +329,9 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:
// The page's connect-state PUT (joining the cluster): its status and its answer's header names.
if (method == "PUT" && url.contains("/connect-state/v1/devices/"))
app.myspoti.spotify.report.Refusal402.connectStatePut(it.code, it.headers.map { h -> h.first.lowercase() }.distinct().sorted().joinToString(","))
+ // Joined: the page's device now takes commands (the app's mirror waits for this after a reload).
+ if (method == "PUT" && url.contains("/connect-state/v1/devices/") && it.code in 200..299)
+ app.myspoti.spotify.bridge.PageDevice.joined()
if (registration && it.code in 200..299) runCatching { JSONObject(text).optLong("initial_seq_num", 0) }.getOrNull()?.let(devices::answered)
if (method == "DELETE" && it.code in 200..299 && url.contains("/track-playback/v1/devices/")) devices.deregistered(url)
if (registration) Logbook.fact("registration", "${it.code}" + (Regex("\"effective_license\"\\s*:\\s*\"([^\"]*)\"").find(text)?.let { m -> " effective_license=${m.groupValues[1]}" } ?: ""))