Skip to content

Native Android client for Spotify, built with Jetpack Compose

From two outside audits: queued duplicates kept after a reload, repeat one kept across an empty state, the destroyed activity released

kota-zo5a11af5de4cd
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
index 7504d596..527e3cff 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AdRecoveryRules.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AdRecoveryRules.kt
@@ -96,9 +96,14 @@ object AdRecoveryRules {
* all in their order, but for the one now [playing] (played on from the queue) and those the
* page lists already ([has]). Reported: the queue was gone after an ad got past by a reload (#144).
*/
- fun requeued(queued: List<Uri>, playing: Uri?, has: Set<Uri>): List<Uri> {
+ fun requeued(queued: List<Uri>, playing: Uri?, has: Collection<Uri>): List<Uri> {
// Played on from the queue: that song and the ones before it in the queue are done.
val from = queued.indexOf(playing).let { if (it >= 0) it + 1 else 0 }
- return queued.drop(from).filter { it !in has }
+ // One restored occurrence accounts for one queued occurrence, not every copy of its URI.
+ val counts = has.groupingBy { it }.eachCount().toMutableMap()
+ return queued.drop(from).filter { uri ->
+ val count = counts[uri] ?: 0
+ if (count == 0) true else { counts[uri] = count - 1; false }
+ }
}
}
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 55c3a5d1..15a53aa3 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
@@ -590,7 +590,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
// The queue the page reports after the song it plays on.
delay(REQUEUE_WAIT_MS)
val playing = _state.value?.item?.uri
- val has = _queue.value?.queued.orEmpty().map { it.uri }.toSet()
+ val has = _queue.value?.queued.orEmpty().map { it.uri }
val missing = AdRecoveryRules.requeued(queued.map { it.uri }, playing, has)
if (missing.isEmpty()) return
bridge.logger?.invoke("page back after a reload: ${missing.size} queued songs added to the queue again")
@@ -1589,12 +1589,16 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val asked = lastPlay
if (asked == null || System.currentTimeMillis() - asked.third > LATE_REFUSED_WINDOW_MS ||
(if (asked.second != null) s?.item?.uri == asked.second else s?.contextUri == asked.first)) refusalStep = 0
+ // A transient empty report at the loop must not erase the song that just ended.
+ val repeatBefore = lastTrackState ?: lastSong?.takeIf {
+ System.currentTimeMillis() - lastSongUntil in 0..UNLOAD_NULL_MS
+ }
if (s?.item != null) lastSong = s
else if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()
// Another song: the stall was the last one's (the watcher judges this one on its next tick).
if (s?.item?.uri != lastTrackState?.item?.uri) _stalled.value = false
noteTrackChange(lastTrackState, s, adJustEnded)
- val shown = s?.let { followRepeat(it) }
+ val shown = s?.let { followRepeat(it, repeatBefore) }
lastTrackState = shown
_state.value = shown
// A song plays, the user's pause over: nothing left to play on from after a paused ad.
@@ -2307,7 +2311,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* device), and never set from here while another device plays. [s] is returned as it is shown:
* with the chosen repeat while the page is being told it.
*/
- private fun followRepeat(s: PlayerState): PlayerState {
+ private fun followRepeat(s: PlayerState, before: PlayerState?): PlayerState {
repeatUnread = null
val want = wantedRepeat ?: return s
if (s.item == null || s.repeat == want) return s
@@ -2315,7 +2319,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val afterPlay = now < repeatRestoreUntil
val elsewhere = elsewhere()
val how = RepeatRules.onReport(want, s.repeat, held = now < repeatHeldUntil, afterOwnPlay = afterPlay,
- atLoop = RepeatRules.atLoop(want, lastTrackState, s, now), elsewhere = elsewhere, mirrored = mirroring)
+ atLoop = RepeatRules.atLoop(want, before, s, now), elsewhere = elsewhere, mirrored = mirroring)
when (how) {
RepeatRules.Report.SET_AGAIN -> {
repeatRestoreUntil = 0L
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 e30c9f86..6fcf64bc 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
@@ -105,9 +105,9 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {
logger?.let { log ->
if (type == "state") {
val s = msg["state"] as? JsonObject
- val line = "page state: " + (s?.get("track") as? JsonObject)?.get("name") + " paused=" + s?.get("isPaused") + " buffering=" + s?.get("isBuffering")
+ val line = "page state: " + (s?.get("track") as? JsonObject)?.get("name") + " paused=" + s?.get("isPaused") + " buffering=" + s?.get("isBuffering") + " repeat=" + s?.get("repeat")
// The track's uri, not the whole track: serializing it here cost more than the line.
- val key = ((s?.get("track") as? JsonObject)?.get("uri") as? JsonPrimitive)?.contentOrNull + s?.get("isPaused")
+ val key = ((s?.get("track") as? JsonObject)?.get("uri") as? JsonPrimitive)?.contentOrNull + s?.get("isPaused") + ":" + s?.get("repeat")
if (stateWorthLogging(line, key)) log(line)
} else if (type == "result") {
// Results are logged by call(); never write their values (tokens) here.
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
index e9870bb5..39d91885 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdRecoveryRulesTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AdRecoveryRulesTest.kt
@@ -67,4 +67,11 @@ class AdRecoveryRulesTest {
assertEquals(listOf("t:c"), AdRecoveryRules.requeued(q, playing = "t:a", has = setOf("t:b")))
assertEquals(emptyList<String>(), AdRecoveryRules.requeued(q, playing = "t:c", has = emptySet()))
}
+
+ @Test fun aRestoredOccurrenceDoesNotRemoveEveryDuplicateFromTheQueue() {
+ val q = listOf("t:a", "t:b", "t:b", "t:c")
+ assertEquals(listOf("t:b", "t:c"), AdRecoveryRules.requeued(q, playing = "t:a", has = listOf("t:b")))
+ assertEquals(listOf("t:c"), AdRecoveryRules.requeued(q, playing = "t:a", has = listOf("t:b", "t:b")))
+ assertEquals(listOf("t:b", "t:b", "t:c"), AdRecoveryRules.requeued(q, playing = "t:a", has = emptyList()))
+ }
}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatOneTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatOneTest.kt
index da4e3089..1827b310 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatOneTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatOneTest.kt
@@ -186,4 +186,21 @@ class RepeatOneTest {
waitFor("repeat set again", ms = 10_000) { called("player.setRepeat") > 0 }
assertEquals(1, called("player.setRepeat"))
}
+
+ @Test fun `a transient null at the loop does not discard repeat one`() = runBlocking {
+ readyWithRepeatOne()
+ waitFor("element read", ms = 10_000) { called("media.state") > 0 }
+ // The ordinary loop occurs long after the 20 s restore window and the 5 s set hold.
+ for (name in listOf("repeatRestoreUntil", "repeatHeldUntil")) {
+ SpotifyPlayer::class.java.getDeclaredField(name).apply { isAccessible = true }.setLong(player, 0L)
+ }
+ host.post(state(track("A"), positionMs = 199_000))
+ waitFor("A at its end") { player.state.value?.positionMs == 199_000L }
+ host.post("""{"type":"state","state":null}""")
+ waitFor("transient empty state") { player.state.value == null }
+ val sets = called("player.setRepeat")
+ host.post(state(track("A"), repeat = 0, positionMs = 500))
+ waitFor("repeat restored across the empty state") { called("player.setRepeat") > sets }
+ assertEquals(Repeat.TRACK, player.state.value?.repeat)
+ }
}
diff --git a/base/app/src/androidTest/java/app/myspoti/host/android/WebPlayerHostDetachTest.kt b/base/app/src/androidTest/java/app/myspoti/host/android/WebPlayerHostDetachTest.kt
new file mode 100644
index 00000000..e2eb9b02
--- /dev/null
+++ b/base/app/src/androidTest/java/app/myspoti/host/android/WebPlayerHostDetachTest.kt
@@ -0,0 +1,56 @@
+package app.myspoti.host.android
+
+import android.content.MutableContextWrapper
+import android.widget.FrameLayout
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.*
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/** The process-wide host must release a destroyed Activity's root, including after reattachment. */
+@RunWith(AndroidJUnit4::class)
+class WebPlayerHostDetachTest {
+ @Test fun detachReleasesItsOwnerAndIgnoresAnOlderOwner() {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val app = instrumentation.targetContext.applicationContext
+ lateinit var host: WebPlayerHost
+ lateinit var first: FrameLayout
+ lateinit var second: FrameLayout
+ instrumentation.runOnMainSync {
+ host = WebPlayerHost(app)
+ first = FrameLayout(app)
+ second = FrameLayout(app)
+ host.attach(first, visible = false)
+ }
+ instrumentation.waitForIdleSync()
+ val container = WebPlayerHost::class.java.getDeclaredField("container").apply { isAccessible = true }
+ try {
+ instrumentation.runOnMainSync { host.detach(first) }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync {
+ assertNull("the destroyed root must not remain in the process-wide host", container.get(host))
+ assertNull(host.view.parent)
+ assertSame(app, (host.view.context as MutableContextWrapper).baseContext)
+ host.attach(first, visible = false)
+ }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync { host.attach(second, visible = false) }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync { host.detach(first) }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync {
+ assertSame("an old Activity must not detach the new Activity's view", second, host.view.parent)
+ assertSame(second, container.get(host))
+ host.detach(second)
+ }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync {
+ assertNull(container.get(host))
+ assertNull(host.view.parent)
+ }
+ } finally {
+ instrumentation.runOnMainSync { host.view.destroy() }
+ }
+ }
+}
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index 8c91b3f3..d9f76ca9 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -346,7 +346,7 @@ class MainActivity : AppCompatActivity() {
// The process-wide WebView lives in this activity's root while attached:
// detach it, or view.parent -> root keeps the destroyed activity (and its
// whole view tree) alive for the rest of the playback session.
- MyspotiRuntime.host.detach()
+ MyspotiRuntime.host.detach(root)
super.onDestroy()
}
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index d599a91c..45731fdc 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -450,7 +450,12 @@ object LocalPlayer {
applyRepeat(p)
// Paused before it loads: a player left playing by a song before never starts this one.
if (paused) p.pause()
+ // Timed (on the main thread, as Media3 wants): a long list's timeline is built here, the
+ // hotspot of a 2.3.0 ANR (an audit asked for the measure before any change to it).
+ val built = android.os.SystemClock.elapsedRealtime()
p.setMediaItems(order.map(::item), if (whole) 0 else start, startMs.coerceAtLeast(0L))
+ val took = android.os.SystemClock.elapsedRealtime() - built
+ if (took >= 50) log("setMediaItems: ${order.size} songs in $took ms")
p.prepare()
if (shuffle && !whole) setShuffle(true)
if (!paused) p.play()
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.kt
index 4ff185a7..a3a278c3 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
@@ -452,7 +452,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
// Killed (memory pressure) or crashed: both end here. A late callback from a view
// that was already replaced must not tear down the healthy new one.
if (gone !== [email protected]) return true
- Logbook.log("renderer gone (crashed=${detail.didCrash()}): rebuilding the page")
+ Logbook.log("renderer gone (crashed=${detail.didCrash()}, priority=${detail.rendererPriorityAtExit()}): rebuilding the page")
// The page is gone with it: the calls it had fail now, not each after its timeout.
onPageStarting?.invoke()
rebuild()
@@ -908,7 +908,11 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
else (v.layoutParams as? ViewGroup.MarginLayoutParams)?.let { it.setMargins(0, 0, 0, 0); v.layoutParams = it }
}
- fun detach() = main.post {
+ /** Only the Activity that owns the current attachment may release it. */
+ fun detach(from: ViewGroup) = main.post {
+ if (container !== from) return@post
+ container = null
+ lastVisible = false
(view.parent as? ViewGroup)?.removeView(view)
(view.context as? android.content.MutableContextWrapper)?.baseContext = context.applicationContext
}