Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Repeat one keeps looping through ads, stalls and reloads (the song's end left on the ad, the song played again before an ad, after it and when playing on, the chosen repeat set again at the loop but taken from another device and never sent to it), a song autoplay or a station brought is not replayed from the start of its list, and a station reloaded past an ad goes on in the order it had
kota-zoda75ff7c73fe
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/RepeatRules.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/RepeatRules.ktnew file mode 100644index 00000000..a879ca13--- /dev/null+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/RepeatRules.kt@@ -0,0 +1,91 @@+package app.myspoti.spotify++import app.myspoti.api.ItemKind+import app.myspoti.api.NowPlaying+import app.myspoti.api.PlayerState+import app.myspoti.api.Repeat+import app.myspoti.api.Uri++/**+ * How [SpotifyPlayer] keeps the repeat the user chose, and what it plays again, without the page.+ *+ * Reported (2.1.0 to 2.3.0): repeat one loops a song two or three times, then the next song+ * plays. An ad took the song's end (see AdBlock.withoutAds), a play or a reload started the page+ * on its own options (repeat off), and the page dropped repeat one at the loop. The choice is one+ * value, [SpotifyPlayer.setRepeat]'s: set again where the page forgot it, given up where the+ * page's repeat was changed from another device.+ */+object RepeatRules {+ /** What a state the page reports does to the repeat the user chose. */+ enum class Report {+ /** The page plays the repeat chosen, or is being told it (a set of ours not answered yet). */+ KEPT,+ /** Set again on the page: it starts a play of ours, or comes round the loop, with less. */+ SET_AGAIN,+ /** The page's repeat is the choice from now on: changed on another device, or from there. */+ THEIRS,+ /** Left as it is: the page only mirrors, its repeat is not the user's. */+ IGNORED,+ }++ /**+ * [held]: our own set is not answered yet. [afterOwnPlay]: the state is the first of a play or+ * a page of ours (it starts on its own options). [atLoop]: the song (or the list) is coming+ * round again, see [atLoop]. [elsewhere]: another device plays, and nothing is ever set on it+ * from here. [mirrored]: the page only mirrors.+ */+ fun onReport(wanted: Repeat, reported: Repeat, held: Boolean, afterOwnPlay: Boolean, atLoop: Boolean, elsewhere: Boolean, mirrored: Boolean): Report = when {+ reported == wanted || held -> Report.KEPT+ elsewhere -> Report.THEIRS+ afterOwnPlay -> Report.SET_AGAIN+ mirrored -> Report.IGNORED+ // Less repeat away from the loop is a change from another device (or the page's own word+ // after a skip): theirs. At the loop it is the page forgetting it.+ atLoop && reported < wanted -> Report.SET_AGAIN+ else -> Report.THEIRS+ }++ /**+ * The song [s] reports is coming round again under [wanted]: its clock within [LOOP_WINDOW_MS]+ * of its end, or the page just went from a song at its end ([before]) to the start of the+ * same song (repeat one) or of any song (repeat all: the list's last song, then its first).+ */+ fun atLoop(wanted: Repeat, before: PlayerState?, s: PlayerState, now: Long): Boolean {+ val item = s.item ?: return false+ val at = s.positionAt(now)+ if (item.durationMs > 0 && at >= item.durationMs - LOOP_WINDOW_MS) return true+ val was = before?.item ?: return false+ val wasAtEnd = was.durationMs > 0 && before.positionAt(now) >= was.durationMs - LOOP_WINDOW_MS+ return wasAtEnd && at <= LOOP_RESTART_MS && (wanted != Repeat.TRACK || was.uri == item.uri)+ }++ /**+ * The list [s]'s song is played again in, or null to play it alone. Reported (#135): a song+ * autoplay brought, played again in the list the page names, started that list from its+ * first song: the song is not in it. A station is made again on every play, the song with it.+ */+ fun replayList(s: PlayerState): Uri? =+ s.contextUri?.takeIf { s.item?.provider != "autoplay" && !isStation(it) }++ fun isStation(contextUri: Uri?): Boolean = contextUri?.startsWith("spotify:station:") == true++ /**+ * The order a station is played on in after our reload, from what came next on the page that+ * went ([nextUp]): [target] first, then the songs and episodes after it. Reported (#122): the+ * station played again without one was made again, and what came next was new. Null when+ * nothing comes after [target]. Given to that one play only: kept, it would turn the station+ * into a list that ends.+ */+ fun stationOrder(target: Uri, nextUp: List<NowPlaying>): List<Uri>? {+ val songs = nextUp.filter { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE }.map { it.uri }+ val after = songs.indexOf(target).let { at -> if (at >= 0) songs.drop(at + 1) else songs }.filter { it != target }+ return if (after.isEmpty()) null else listOf(target) + after+ }++ /** The page's clock this close to the end: the song was ending (the page reports every few seconds). */+ const val LOOP_WINDOW_MS = 5_000L+ /** A song the page shows this close to 0:00 started again. */+ const val LOOP_RESTART_MS = 10_000L+ /** Our own set of the repeat: the page's older reports are not taken for its answer this long. */+ const val REPEAT_HOLD_MS = 5_000L+}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 5a5f4e55..295c4a86 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@@ -332,6 +332,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval reload = reloadHost ?: returnif (repairsHeld()) { bridge.logger?.invoke("reload held: a sign-in page is open or Spotify is limiting or refusing playback"); return }val startedAt = System.currentTimeMillis()+ // A station without an order of ours: what came next on this page, taken before it goes+ // (the new page's is a new station, see RepeatRules.stationOrder).+ val nextUp = s?.takeIf { RepeatRules.isStation(it.contextUri) && !it.shuffle && lastOrder?.first != it.contextUri }+ ?.let { _queue.value?.nextUp }ownReload = truetry {runCatching {@@ -352,7 +356,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopbridge.logger?.invoke("page back after a reload: played or picked meanwhile, ${s.item?.name} not played on")return@runCatching}- if (next) playOnNewPage { playOn(s) } else { awaitDeviceJoined(); resumeAfterReload(s) }+ if (next) playOnNewPage { playOn(s, nextUp) } else { awaitDeviceJoined(); resumeAfterReload(s, nextUp) }}} finally {ownReload = false@@ -455,7 +459,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop* all, and takes commands only once its device is registered again. The song goes on from* where it was, checked and tried again, unless the user paused or played something since.*/- private suspend fun resumeAfterReload(lost: PlayerState) {+ private suspend fun resumeAfterReload(lost: PlayerState, nextUp: List<NowPlaying>? = null) {if (licenceRefusedHold) { bridge.logger?.invoke("page back after a reload: nothing resumed, Spotify refuses this account's licences"); return }// Skipped during the reload: that song, not the one that played before it.if (liveIntent() != null) {@@ -485,7 +489,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// A state without a list would play the song alone, and Spotify then goes on// with its own autoplay: the list of the song before it is the next best.val ctx = lost.contextUri ?: lastSong?.contextUri ?: uri- playNow(ctx, trackUri = uri.takeIf { ctx != it }, positionMs = at, order = lastOrder?.takeIf { it.first == ctx }?.second, origin = "restore")+ val station = nextUp?.takeIf { ctx == lost.contextUri }?.let { RepeatRules.stationOrder(uri, it) }+ playNow(ctx, trackUri = uri.takeIf { ctx != it }, positionMs = at, order = station ?: lastOrder?.takeIf { it.first == ctx }?.second,+ keepsOrder = station == null, origin = "restore")}}.onFailure { bridge.logger?.invoke("restore attempt $attempt failed: ${it.message}") }// The play just sent is ours, not the user's.@@ -1068,7 +1074,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop/*** Plays [a]'s next song [AD_AHEAD_LEAD_MS] before the song [a] names ends, unless another song- * plays by then (a skip, a pick). Waits while it is paused or buffering.+ * plays by then (a skip, a pick). Waits while it is paused or buffering. Under repeat one the+ * song itself is played again instead: its end is the song again, not the next one.*/private suspend fun playBeforeAd(a: app.myspoti.spotify.bridge.AdBlock.AdAhead) {fun isThat(item: NowPlaying?) = item != null && ((a.songUid != null && item.uid == a.songUid) || item.uri == a.songUri)@@ -1091,7 +1098,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// Re-read now and then: a seek or a late state moves the end.delay((left - AD_AHEAD_LEAD_MS).coerceAtMost(AD_AHEAD_CHECK_MS))}- val ctx = _state.value?.contextUri ?: return+ val song = _state.value ?: return+ val ctx = song.contextUri ?: returnif (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@@ -1099,6 +1107,14 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// finish, or the skip is sent and its put-back never is.withContext(NonCancellable) {app.myspoti.spotify.bridge.AdBlock.ahead.compareAndSet(a, null)+ // Repeat one, read now (the user may have changed it while the song played): the ad+ // is avoided by a new play of the same song, as it would be by the next one.+ if (wantedRepeat == Repeat.TRACK) {+ bridge.logger?.invoke("ad after this song, repeat one: ${song.item?.name} played again before its end")+ runCatching { playAgain(song, origin = "repeat one, before an ad") }+ .onFailure { bridge.logger?.invoke("play again before the ad refused: ${it.message}") }+ return@withContext+ }bridge.logger?.invoke("ad after this song: ${a.nextUri} played before its end")if (skipPastAd(a)) return@withContextrunCatching { playNow(ctx, trackUri = a.nextUri, order = lastOrder?.takeIf { it.first == ctx }?.second, origin = "before an ad") }@@ -1142,7 +1158,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop.onFailure { bridge.logger?.invoke("skip past the ad: ${target.name} not put back: ${it.message}") }}- private suspend fun playOn(s: PlayerState) {+ /**+ * Plays on from [s], a song stuck at its end or before an ad: what the user asked for+ * meanwhile, the song again under repeat one, or the song after it. [nextUp]: what came next+ * on a page our reload took away (a station's, see [reloadAndPlayOn]).+ */+ private suspend fun playOn(s: PlayerState, nextUp: List<NowPlaying>? = null) {// The user skipped meanwhile: their song, not the one after the last state seen.if (playIntent()) return// Or picked one during the ad that is being got past: that one, in the order it was picked.@@ -1152,22 +1173,47 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopplayNow(pick.context, trackUri = pick.track, index = pick.index, positionMs = pick.positionMs, order = pick.order, refusable = true, origin = "pick during the ad")return}+ // Repeat one: the way on from the song is the song again (that is its end). An ad takes that+ // end in Spotify's state machine (see AdBlock.machineWithoutAds), and the page is left on the+ // next song after it, or a reload to get past one plays on: the song is played again instead.+ if (wantedRepeat == Repeat.TRACK && s.item?.let { it.kind != ItemKind.AD } == true) {+ bridge.logger?.invoke("repeat one: ${s.item?.name} played again, not the next song")+ playAgain(s, origin = "repeat one")+ return+ }val ctx = s.contextUri- val target = onwardTarget(s, _queue.value?.nextUp.orEmpty())+ val target = onwardTarget(s, nextUp ?: _queue.value?.nextUp.orEmpty())// A new play reshuffles a shuffled list (measured 21/10) and does not find a song the user// queued in the list: both go on within the queue the page has, as a skip would.val inQueue = target?.let { t -> upcoming().firstOrNull { it.uri == t } }if (inQueue != null && (s.shuffle || inQueue.provider == "queue") &&runCatching { command("queue.skipTo", ref(inQueue), timeoutMs = PLAY_TIMEOUT_MS) }.isSuccess) return+ val station = nextUp?.let { target?.let { t -> RepeatRules.stationOrder(t, it) } }when {- ctx != null && target != null -> playNow(ctx, trackUri = target, order = lastOrder?.takeIf { it.first == ctx }?.second, origin = "play on")+ ctx != null && target != null -> playNow(ctx, trackUri = target, order = station ?: lastOrder?.takeIf { it.first == ctx }?.second,+ keepsOrder = station == null, origin = "play on")target != null -> next()// Nothing after it: a song is started again (the page's own end-of-context behaviour);- // an episode is left finished rather than replayed from the start.+ // an episode is left finished rather than replayed from the start. Not a song autoplay+ // brought or a station's: its list would start over (#135), the page goes on itself.+ ctx != null && s.item?.kind == ItemKind.TRACK && RepeatRules.replayList(s) == null -> {+ bridge.logger?.invoke("play on: nothing after ${s.item?.name} (autoplay or a station), the page's next asked for")+ command("player.next")+ }ctx != null && s.item?.kind == ItemKind.TRACK -> playNow(ctx, trackUri = s.item?.uri, origin = "play on")}}+ /**+ * [s]'s song from its start, in its list (with the order it was played in) or alone where+ * the list would not find it ([RepeatRules.replayList]).+ */+ private suspend fun playAgain(s: PlayerState, origin: String) {+ val song = s.item ?: return+ val list = RepeatRules.replayList(s)+ playNow(list ?: song.uri, trackUri = song.uri.takeIf { list != null }, order = lastOrder?.takeIf { list != null && it.first == list }?.second, origin = origin)+ }+private val skipChain = TrackChanges.Chain()private val commandsExplained = TrackChanges.Commands()private val _skipChained = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(extraBufferCapacity = 1)@@ -1250,6 +1296,23 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval adJustEnded = _adPlaying.value_adPlaying.value = falseif (adJustEnded) bridge.logger?.invoke("ad break over after ${(System.currentTimeMillis() - adSince) / 1000} s: ${s?.item?.name ?: "nothing"}${if (s?.isPaused == true) " (paused)" else ""}")+ // The page plays on from an ad by itself, on its own options: its repeat then is no change of the user's.+ if (adJustEnded) repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS+ // Repeat one: the song's end is the song again, but an ad took that end (see+ // AdBlock.machineWithoutAds) and the page went on from the ad to another song. The song+ // before the ad plays again, unless the user picked or skipped something meanwhile.+ val beforeAd = lastTrackState+ val songBeforeAd = beforeAd?.item+ if (adJustEnded && wantedRepeat == Repeat.TRACK && pickBeforeAd == null && liveIntent() == null && userMoveAt < adSince &&+ !pausedByUser && !remoteActive && !mirroring && !ownReload && bridge.ready.value &&+ beforeAd != null && songBeforeAd != null && songBeforeAd.kind == ItemKind.TRACK &&+ s != null && s.item?.kind == ItemKind.TRACK && s.item?.uri != songBeforeAd.uri) {+ bridge.logger?.invoke("ad break over: repeat one, ${songBeforeAd.name} played again instead of ${s.item?.name}")+ scope.launch {+ runCatching { playAgain(beforeAd, origin = "repeat one after an ad") }+ .onFailure { bridge.logger?.invoke("repeat one after the ad refused: ${it.message}") }+ }+ }// 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@@ -1319,8 +1382,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// 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 = falsenoteTrackChange(lastTrackState, s, adJustEnded)- lastTrackState = s- _state.value = s+ val shown = s?.let { followRepeat(it) }+ lastTrackState = shown+ _state.value = shown// A song plays, the user's pause over: nothing left to play on from after a paused ad.if (s?.item != null && !s.isPaused && !pausedByUser) { onwardAfterPausedAd = null; pickAfterPause = null }// Reported (2.0.2-beta.3, log seen): Spotify refusing the audio licences (429), the page@@ -1336,17 +1400,6 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopbridge.logger?.invoke("playback held (Spotify limiting): ${s.item?.name} paused")scope.launch { runCatching { pause() } }}- // 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?.uriwhen {@@ -1700,17 +1753,22 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopplayNow(contextUri, trackUri, index, positionMs, order, refusable = true, origin = origin)}- /** A play sent to the page; [refusable]: the user's own, whose refusal walks [onRefused]'s steps. */- private suspend fun playNow(contextUri: Uri, trackUri: Uri? = null, index: Int? = null, positionMs: Long? = null, order: List<Uri>? = null, refusable: Boolean = false, origin: String) {+ /**+ * A play sent to the page; [refusable]: the user's own, whose refusal walks [onRefused]'s steps.+ * [keepsOrder] false: [order] is for this play only, later plays of the list go without it.+ */+ private suspend fun playNow(contextUri: Uri, trackUri: Uri? = null, index: Int? = null, positionMs: Long? = null, order: List<Uri>? = null, refusable: Boolean = false, keepsOrder: Boolean = true, origin: String) {// A new song picked (or the intent itself played): any earlier skip is over.if (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = null- lastOrder = order?.let { contextUri to it }+ lastOrder = order?.takeIf { keepsOrder }?.let { contextUri to it }lastPlay = Triple(contextUri, trackUri, System.currentTimeMillis())lastIndex = indexlastPlayRefusable = refusablerefusalStep = 0pausedByUser = false+ // The play starts the page on its own options: what it reports next is no answer to a set of ours.repeatRestoreUntil = System.currentTimeMillis() + REPEAT_RESTORE_MS+ repeatHeldUntil = 0LwithFade {try {command("player.play", timeoutMs = PLAY_TIMEOUT_MS, label = origin, args = buildJsonObject {@@ -1992,10 +2050,48 @@ 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]). */+ /**+ * The repeat mode the user chose last, the one value of it ([followRepeat]): put back where a+ * play, a reload or the loop leaves the page on less, taken from the page where another device+ * changed it.+ */@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+ /** Until when the page has not answered our last set of [wantedRepeat] yet. */+ @Volatile private var repeatHeldUntil = 0L++ /**+ * Reported: the repeat button forgets what it was, and repeat one loops a song two or three+ * times, then the next song plays. A play command (and a reloaded page, an ad over) starts the+ * page on its own options, repeat off, and the page drops repeat one at the loop: the mode the+ * user chose is set again there. Anywhere else a repeat other than the choice is theirs (another+ * 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 {+ val want = wantedRepeat ?: return s+ if (s.item == null || s.repeat == want) return s+ val now = System.currentTimeMillis()+ val afterPlay = now < repeatRestoreUntil+ val how = RepeatRules.onReport(want, s.repeat, held = now < repeatHeldUntil, afterOwnPlay = afterPlay,+ atLoop = RepeatRules.atLoop(want, lastTrackState, s, now), elsewhere = remoteActive, mirrored = mirroring)+ when (how) {+ RepeatRules.Report.SET_AGAIN -> {+ repeatRestoreUntil = 0L+ // Held from now: the next report may come before the set below is sent.+ repeatHeldUntil = now + RepeatRules.REPEAT_HOLD_MS+ bridge.logger?.invoke("repeat is ${s.repeat} ${if (afterPlay) "after a play" else "at the loop"}, $want was chosen: set again")+ scope.launch { runCatching { setRepeat(want) } }+ }+ RepeatRules.Report.THEIRS -> {+ wantedRepeat = s.repeat+ bridge.logger?.invoke("repeat is ${s.repeat} from the page${if (remoteActive) " (another device plays)" else ""}: $want no longer kept")+ }+ RepeatRules.Report.KEPT, RepeatRules.Report.IGNORED -> {}+ }+ return if (how == RepeatRules.Report.KEPT || how == RepeatRules.Report.SET_AGAIN) s.copy(repeat = want) else s+ }/*** The repeat mode chosen in an earlier run of the app: nothing is sent now. The page starts@@ -2009,6 +2105,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun setRepeat(mode: Repeat) {wantedRepeat = mode+ repeatHeldUntil = System.currentTimeMillis() + RepeatRules.REPEAT_HOLD_MSbridge.call("player.setRepeat", buildJsonObject { put("mode", mode.ordinal) })}diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.ktindex d4afb0eb..82bcf662 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt@@ -218,6 +218,12 @@ object AdBlock {notes += "$key after ${nameOf(i)}: repeated instead of an ad"continue}+ // Repeat one: the ad is the song's only way round when Spotify sends no repeat state+ // of it. Sent to the skip's target instead, the repeat ended there (reported: "loops+ // 2-3 times then plays the next song"); left as it is, the ad plays and Spotify's own+ // way on from it is the same song again (the player plays it again otherwise, see+ // SpotifyPlayer.playOn).+ if (key == "advance" && repeatsTrack(i)) continueif (target == null) { notes += "$key after ${nameOf(i)}: an ad, and no song to send it to"; continue }next[key] = JsonObject(target.toMutableMap().apply { t["paused"]?.let { put("paused", it) } })notes += "$key after ${nameOf(i)}: ${indexOf(target)?.let(::nameOf)} instead of an ad"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.ktnew file mode 100644index 00000000..a01d9260--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatOneTest.kt@@ -0,0 +1,153 @@+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.assertTrue+import org.junit.jupiter.api.BeforeEach+import org.junit.jupiter.api.Test+import java.util.concurrent.CopyOnWriteArrayList++/**+ * Repeat one through what takes a song's end away from it: an ad, a song stuck at its end, the+ * ad-avoiding play. Reported (2.1.0 to 2.3.0): the song looped two or three times, then the next+ * one played.+ */+class RepeatOneTest {+ private class FakeHost : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ /** Every call the player made: method to its arguments (json text). */+ 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: this phone the active device, or another one.+ 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 bridge: Bridge+ private lateinit var player: SpotifyPlayer++ @BeforeEach fun up() {+ AdBlock.ahead.value = null+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ host = FakeHost()+ bridge = Bridge(host, scope)+ player = SpotifyPlayer(bridge, scope)+ // A message posted before the bridge listens is lost (a slow CI machine): wait for it.+ waitFor("bridge listening") { host.messages.subscriptionCount.value > 0 }+ }++ @AfterEach fun down() {+ AdBlock.ahead.value = null+ scope.cancel()+ }++ private fun track(name: String, ms: Long = 200_000, provider: String? = null) =+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":$ms${provider?.let { ""","provider":"$it"""" }.orEmpty()}}"""++ private fun state(item: String, next: String? = null, repeat: Int = 2, positionMs: Long = 0, buffering: Boolean = false) =+ """{"type":"state","state":{"track":$item,"contextUri":"spotify:playlist:C","next":${next ?: "null"},"isPaused":false,"isBuffering":$buffering,+ |"repeat":$repeat,"positionMs":$positionMs,"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 plays() = host.calls.filter { it.first == "player.play" }.map { it.second }+ private fun called(method: String) = host.calls.count { it.first == method }++ private suspend fun readyWithRepeatOne() {+ host.post("""{"type":"ready"}""")+ waitFor("ready") { bridge.ready.value }+ player.setRepeat(Repeat.TRACK)+ }++ @Test fun `an ad over under repeat one plays the song before it again, not the one the page went to`() = runBlocking {+ readyWithRepeatOne()+ host.post(state(track("A"), track("B")))+ waitFor("A") { player.state.value?.item?.uri == "spotify:track:A" }+ host.post(state(ad))+ waitFor("ad flag") { player.adPlaying.value }+ host.post(state(track("B"), track("C")))+ waitFor("A played again") { plays().isNotEmpty() }+ assertTrue("\"trackUri\":\"spotify:track:A\"" in plays().single(), "the song before the ad: ${plays()}")+ }++ @Test fun `a skip during the ad under repeat one is the user's, the song before it is not played again`() = runBlocking {+ readyWithRepeatOne()+ host.post(state(track("A"), track("B")))+ waitFor("A") { player.state.value?.item?.uri == "spotify:track:A" }+ host.post(state(ad))+ waitFor("ad flag") { player.adPlaying.value }+ player.next()+ host.post(state(track("B"), track("C")))+ delay(600)+ assertTrue(plays().none { "spotify:track:A" in it }, "the skip stands: ${plays()}")+ }++ @Test fun `the ad-avoiding play under repeat one plays the song again, not the next one`() = runBlocking {+ readyWithRepeatOne()+ host.post(state(track("A", ms = 1_500), track("B")))+ waitFor("A") { player.state.value != null }+ AdBlock.ahead.value = AdBlock.AdAhead("uA", "spotify:track:A", "spotify:track:B")+ waitFor("played before the end") { plays().isNotEmpty() }+ val sent = plays().single()+ assertTrue("\"trackUri\":\"spotify:track:A\"" in sent && "spotify:track:B" !in sent, "the song itself: $sent")+ assertTrue(host.calls.none { it.first == "queue.skipTo" }, "no skip to the next song")+ }++ @Test fun `a song stuck past its end under repeat one is played again`() = runBlocking {+ readyWithRepeatOne()+ host.post(state(track("A"), track("B"), positionMs = 202_000))+ waitFor("stall repaired", ms = 10_000) { plays().isNotEmpty() }+ assertTrue("\"trackUri\":\"spotify:track:A\"" in plays().first(), "the song again, not B: ${plays()}")+ }++ @Test fun `a song autoplay brought, stuck past its end with nothing after it, is not played again in the list`() = runBlocking {+ host.post("""{"type":"ready"}""")+ host.post(state(track("A", provider = "autoplay"), repeat = 0, positionMs = 202_000))+ waitFor("stall repaired", ms = 10_000) { called("player.next") > 0 }+ assertTrue(plays().isEmpty(), "the list would start over (#135): ${plays()}")+ }++ @Test fun `another device playing is never given the repeat from here, and its repeat is the choice`() = runBlocking {+ host.mediaActive = false+ host.mediaPaused = true+ host.post("""{"type":"ready"}""")+ host.post(state(track("A"), repeat = 0))+ // The watcher reads the element at its first tick (up to 4 s after it started).+ waitFor("another device seen", ms = 10_000) { player.remoteActive }+ // The repeat of an earlier run, restored as after a play; the other device reports off at the loop.+ player.restoreRepeat(Repeat.TRACK)+ host.post(state(track("A"), repeat = 0, positionMs = 198_000))+ delay(400)+ host.post(state(track("A"), repeat = 0, positionMs = 199_500))+ delay(400)+ assertEquals(0, called("player.setRepeat"), "nothing sent to the other device: ${host.calls.map { it.first }}")+ assertEquals(Repeat.OFF, player.state.value?.repeat)+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatRulesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatRulesTest.ktnew file mode 100644index 00000000..a159007b--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/RepeatRulesTest.kt@@ -0,0 +1,88 @@+package app.myspoti.spotify++import app.myspoti.api.ItemKind+import app.myspoti.api.NowPlaying+import app.myspoti.api.PlayerRestrictions+import app.myspoti.api.PlayerState+import app.myspoti.api.Repeat+import app.myspoti.spotify.RepeatRules.Report+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertFalse+import org.junit.jupiter.api.Assertions.assertNull+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.Test++class RepeatRulesTest {+ private fun item(name: String, kind: ItemKind = ItemKind.TRACK, provider: String? = null, ms: Long = 200_000) =+ NowPlaying(kind, "spotify:${kind.name.lowercase()}:$name", "u$name", name, emptyList(), null, null, ms, provider = provider)++ private fun at(item: NowPlaying, pos: Long, ctx: String? = "spotify:playlist:C", now: Long = 1_000_000L) =+ PlayerState(item = item, contextUri = ctx, isPaused = false, isBuffering = false, positionMs = pos, timestampMs = now,+ speed = 1.0, shuffle = false, repeat = Repeat.OFF, restrictions = PlayerRestrictions())++ private fun report(wanted: Repeat, reported: Repeat, held: Boolean = false, afterOwnPlay: Boolean = false, atLoop: Boolean = false,+ elsewhere: Boolean = false, mirrored: Boolean = false) =+ RepeatRules.onReport(wanted, reported, held, afterOwnPlay, atLoop, elsewhere, mirrored)++ @Test fun `less repeat at the loop is the page forgetting it, set again`() {+ assertEquals(Report.SET_AGAIN, report(Repeat.TRACK, Repeat.CONTEXT, atLoop = true))+ assertEquals(Report.SET_AGAIN, report(Repeat.TRACK, Repeat.OFF, atLoop = true))+ assertEquals(Report.SET_AGAIN, report(Repeat.CONTEXT, Repeat.OFF, atLoop = true))+ // A play of ours starts the page on its own options, wherever the song is.+ assertEquals(Report.SET_AGAIN, report(Repeat.TRACK, Repeat.OFF, afterOwnPlay = true))+ }++ @Test fun `less repeat away from the loop, or more anywhere, is the other device's and becomes the choice`() {+ // Seen in review of #139: repeat one turned off on another device came back at the next song's end.+ assertEquals(Report.THEIRS, report(Repeat.TRACK, Repeat.OFF))+ assertEquals(Report.THEIRS, report(Repeat.CONTEXT, Repeat.OFF))+ assertEquals(Report.THEIRS, report(Repeat.CONTEXT, Repeat.TRACK, atLoop = true))+ }++ @Test fun `another device playing is never given the repeat from here`() {+ assertEquals(Report.THEIRS, report(Repeat.TRACK, Repeat.OFF, atLoop = true, elsewhere = true))+ assertEquals(Report.THEIRS, report(Repeat.TRACK, Repeat.OFF, afterOwnPlay = true, elsewhere = true))+ }++ @Test fun `a set of ours not answered yet, the same repeat or a mirror leave the choice alone`() {+ assertEquals(Report.KEPT, report(Repeat.TRACK, Repeat.OFF, held = true))+ assertEquals(Report.KEPT, report(Repeat.TRACK, Repeat.OFF, held = true, elsewhere = true))+ assertEquals(Report.KEPT, report(Repeat.TRACK, Repeat.TRACK, atLoop = true))+ assertEquals(Report.IGNORED, report(Repeat.TRACK, Repeat.OFF, atLoop = true, mirrored = true))+ assertEquals(Report.IGNORED, report(Repeat.TRACK, Repeat.OFF, mirrored = true))+ }++ @Test fun `the loop is the song's end, or its start again just after it`() {+ val a = item("A")+ val now = 1_000_000L+ assertTrue(RepeatRules.atLoop(Repeat.TRACK, null, at(a, 197_000), now))+ assertFalse(RepeatRules.atLoop(Repeat.TRACK, null, at(a, 60_000), now))+ // The same song at its end, then near 0:00: repeat one came round.+ assertTrue(RepeatRules.atLoop(Repeat.TRACK, at(a, 199_000), at(a, 500), now))+ // Another song after the end is no loop of repeat one (the next song), but is one of repeat all.+ assertFalse(RepeatRules.atLoop(Repeat.TRACK, at(a, 199_000), at(item("B"), 500), now))+ assertTrue(RepeatRules.atLoop(Repeat.CONTEXT, at(a, 199_000), at(item("B"), 500), now))+ // A skip mid-song, or a report long into the song, is no loop.+ assertFalse(RepeatRules.atLoop(Repeat.TRACK, at(a, 60_000), at(a, 0), now))+ assertFalse(RepeatRules.atLoop(Repeat.TRACK, at(a, 199_000), at(a, 30_000), now))+ }++ @Test fun `a song autoplay brought, or a station's, is played again alone`() {+ assertEquals("spotify:playlist:C", RepeatRules.replayList(at(item("A"), 0)))+ assertNull(RepeatRules.replayList(at(item("A", provider = "autoplay"), 0)))+ assertNull(RepeatRules.replayList(at(item("A"), 0, ctx = "spotify:station:track:X")))+ assertNull(RepeatRules.replayList(at(item("A"), 0, ctx = null)))+ }++ @Test fun `a station goes on after a reload in the order it had, from the target`() {+ val up = listOf(item("B"), item("ad", ItemKind.AD), item("C"), item("E", ItemKind.EPISODE), item("D"))+ // The target first, once, then what came after it; no ad.+ assertEquals(listOf("spotify:track:B", "spotify:track:C", "spotify:episode:E", "spotify:track:D"), RepeatRules.stationOrder("spotify:track:B", up))+ assertEquals(listOf("spotify:track:C", "spotify:episode:E", "spotify:track:D"), RepeatRules.stationOrder("spotify:track:C", up))+ // A target not in the list (the state's own next): put before all of it.+ assertEquals(listOf("spotify:track:Z", "spotify:track:B", "spotify:track:C", "spotify:episode:E", "spotify:track:D"), RepeatRules.stationOrder("spotify:track:Z", up))+ // Nothing after the target: no order, the station is played as it is.+ assertNull(RepeatRules.stationOrder("spotify:track:D", up))+ assertNull(RepeatRules.stationOrder("spotify:track:B", emptyList()))+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.ktindex 533d29da..93357376 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt@@ -94,13 +94,38 @@ class AdQueueTest {assertEquals(listOf("advance after Playing: repeated instead of an ad"), notes)}- @Test fun `a repeated song with no state of its repeat falls back to the skip's target`() {- val noRepeat = reply(- listOf(track("AD", "An ad"), track("TRACK", "Playing"), track("TRACK", "After")),- listOf(repeatState(0, true), repeatState(1, true, advance = 0, next = 2, show = 3), repeatState(2, false, show = 3), repeatState(2, false)),- current = 1,- )- assertEquals(2, index(transitions(AdBlock.withoutAds(noRepeat)!!.first, 1), "advance"))+ // Captured on the phone (1/11, free account, repeat one on): the song's end goes to the ad, its+ // skip to the next song, and no state of the song repeats it. Repeat one was lost there.+ private val noRepeatState = reply(+ listOf(track("AD", "An ad"), track("TRACK", "Playing"), track("TRACK", "After")),+ listOf(repeatState(0, true), repeatState(1, true, advance = 0, next = 2, show = 3), repeatState(2, false, show = 3), repeatState(2, false)),+ current = 1,+ )++ @Test fun `a repeated song with no state of its repeat keeps the ad, which leads back to it`() {+ // Sent to the skip's target (the next song) the repeat ended there; left as it is, the ad+ // plays and Spotify's own way on from it is the same song again.+ assertNull(AdBlock.withoutAds(noRepeatState))+ assertNull(AdBlock.adAhead(noRepeatState))+ }++ // Repeat one with an ad left out once already: the song's end and its skip both go to the ad,+ // and a state of the song repeats it.+ private val bothToTheAd = reply(+ listOf(track("AD", "An ad"), track("TRACK", "Playing"), track("TRACK", "After")),+ listOf(repeatState(0, true), repeatState(1, true, advance = 0, next = 0, show = 4), repeatState(1, true, show = 4),+ repeatState(2, false, show = 4), repeatState(2, false)),+ current = 1,+ )++ @Test fun `a repeated song whose skip goes to the ad too has its end sent to its repeat, and nothing played before it`() {+ val (body, notes) = AdBlock.withoutAds(bothToTheAd)!!+ assertEquals(2, index(transitions(body, 1), "advance"))+ assertEquals(listOf("advance after Playing: repeated instead of an ad", "skip_next after Playing: an ad, and no song to send it to"), notes)+ // What the host reads (ControlRelay): the reply as sent, its end now the repeat. Read on+ // Spotify's own reply, the next song would be played before the end, and repeat one lost.+ assertNull(AdBlock.adAhead(body))+ assertEquals("spotify:track:After", AdBlock.adAhead(bothToTheAd)!!.nextUri)}@Test fun `a reply without an ad is left alone`() {