Skip to content

Native Android client for Spotify, built with Jetpack Compose

Myspoti shuffle, an option of the playback settings (off by default, both looks): with shuffle on, a playlist, an album or Liked Songs played on Spotify plays every one of its songs once, in an order Myspoti draws from all its pages with the song picked first, before it starts over; the order goes to the page as a sorted list's does with Spotify's shuffle off and stays while the list plays (a skip goes on in it, a song picked in the list plays next, songs added join what is to come), shuffle turned on or off in the player keeps the song where it is (at the next play when paused), a list played from elsewhere keeps Spotify's shuffle, and a list Spotify keeps on its own shuffle for the account is left to it with a message [skip ci]

kota-zod1f82391620d
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
index 849b7114..c5c7229b 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
@@ -47,6 +47,23 @@ object AutoplayPref {
}
}
+/**
+ * "Myspoti shuffle" (off by default): with shuffle on, a list plays every one of its songs once, in
+ * an order Myspoti draws, before it starts over, instead of Spotify's shuffle (see
+ * [com.music.spotui.di.AppShuffle]). Off: Spotify shuffles, as before.
+ */
+object AppShufflePref {
+ private const val KEY = "myspoti_shuffle"
+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, false))
+ private set
+
+ fun set(c: Context, value: Boolean) {
+ on = value
+ prefs(c).edit().putBoolean(KEY, value).apply()
+ if (!value) com.music.spotui.di.AppShuffle.forget()
+ }
+}
+
/**
* "Count extension plays on Spotify" (on by default): a song an extension streams is played by the
* Web Player too, unheard, so Spotify counts it and Spotify Connect sees and controls it (see
diff --git a/base/app/src/main/java/com/music/spotui/di/AppShuffle.kt b/base/app/src/main/java/com/music/spotui/di/AppShuffle.kt
new file mode 100644
index 00000000..d19dd551
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/AppShuffle.kt
@@ -0,0 +1,269 @@
+package com.music.spotui.di
+
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import app.myspoti.host.android.MyspotiRuntime
+import app.myspoti.engine.R
+import com.music.spotui.data.api.Response
+import com.music.spotui.data.entity.ContextPageModel
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.data.preferences.AppShufflePref
+import com.music.spotui.ui.screens.SmartShuffle
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.filterIsInstance
+import kotlinx.coroutines.flow.lastOrNull
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * Myspoti shuffle (an option, [AppShufflePref]). Reported (5 people): Spotify's shuffle plays the
+ * same ~15 songs of a 40-song list again and again, and songs heard already before the rest. With
+ * the option and shuffle on, a list played on Spotify plays in an order Myspoti draws once
+ * ([ShuffleOrder]): every song of the list once, the one picked first, before the list starts
+ * over. The order goes to the page as a sorted list's does (the list played as that order, see
+ * player-bridge.js), with Spotify's shuffle off, and stays while the list plays: a skip goes on in
+ * it, a song picked in the list plays next in it, songs added to the list join what is to come.
+ * The player shows shuffle on.
+ *
+ * The local player (extensions, downloads, files of the device) deals its own order the same way
+ * already (LocalPlayer.setShuffle): nothing changes there. A list Spotify keeps on its own shuffle
+ * (an account that may only shuffle, see SpotifyPlayer.onRefused) is left to it, and the user told.
+ */
+object AppShuffle {
+ private const val TRACK = "spotify:track:"
+ /** The page reporting another list for that long after a play: the play did not land. */
+ private const val LAND_MS = 15_000L
+ /** The page turning its shuffle back on within that after a play is Spotify keeping it. */
+ private const val IMPOSED_MS = 30_000L
+
+ private val main = Handler(Looper.getMainLooper())
+ /** Bumped by every play and by the end of the shuffle: a list loaded for an older one plays nothing. */
+ private val gen = AtomicInteger()
+
+ /** The list played in Myspoti's order (null: none). */
+ @Volatile private var list: String? = null
+ /** Its track uris in that order, [at]: the song playing. */
+ private var order: List<String> = emptyList()
+ private var at = -1
+ /** The order the list plays in without shuffle (a sorted list's; null: the list's own). */
+ private var plain: List<String>? = null
+ /** The page reported the list since the play. */
+ private var landed = false
+ private var startedAt = 0L
+ /** Spotify's shuffle came back on once and was turned off again. */
+ private var retried = false
+ /** Shuffle turned on or off while paused: the song goes on in its new order at the next play. */
+ private var due: (() -> Boolean)? = null
+ /** Lists Spotify keeps on its own shuffle for this account, this session. */
+ private val imposed = java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap<String, Boolean>())
+
+ /** The last list played from its page, for shuffle turned on in the player. */
+ private class Noted(val uri: String, val tracks: List<SongsModel>, val plain: List<String>?, val complete: Boolean)
+ @Volatile private var noted: Noted? = null
+
+ /** Myspoti's order may play [contextUri] now. */
+ private fun usable(contextUri: String): Boolean =
+ AppShufflePref.on && contextUri.isNotBlank() && contextUri !in imposed && SmartShuffle.on.value != contextUri &&
+ // Another device plays: the page only commands it, and the order is the page's own.
+ SongPlayer.activeDevice.value == null
+
+ /** A list Myspoti reads in full: a playlist, an album, Liked Songs. */
+ private fun dealable(contextUri: String): Boolean =
+ contextUri.startsWith("spotify:playlist:") || contextUri.startsWith("spotify:album:") || contextUri.contains(":collection")
+
+ /**
+ * [song] picked in [p] (ContextViewModel, on Spotify), [plain] the order the list plays in
+ * without shuffle. True: it plays in Myspoti's order (shuffle on, the option on); false: the
+ * caller plays it as before.
+ */
+ fun play(p: ContextPageModel, song: SongsModel, plain: List<String>?): Boolean {
+ if (!AppShufflePref.on) return false
+ noted = Noted(p.uri, p.tracks, plain, p.complete)
+ if (!Graph.currentSongState.shuffle.value || !usable(p.uri) || !dealable(p.uri) || song.spotifyTrackId.isBlank()) return false
+ val first = TRACK + song.spotifyTrackId
+ if (p.complete) return start(p.uri, p.tracks, first, plain)
+ // The list is still loading: every page of it first, so all its songs are dealt.
+ val g = gen.incrementAndGet()
+ MyspotiRuntime.scope.launch {
+ val all = load(p.uri)?.takeIf { l -> l.any { it.spotifyTrackId == song.spotifyTrackId } } ?: p.tracks
+ main.post { if (g == gen.get()) start(p.uri, all, first, plain) }
+ }
+ return true
+ }
+
+ /**
+ * Shuffle turned on or off while a list plays on Spotify (SongPlayer.setShuffle). True: done
+ * here (the song playing goes on where it is, in the list's new order); false: Spotify's shuffle.
+ */
+ fun toggle(on: Boolean): Boolean {
+ if (!AppShufflePref.on) return false
+ val np = SongPlayer.nowPlaying.value
+ val ctx = np.contextUri
+ if (!on) {
+ val was = list ?: return false
+ val back = plain
+ val dealt = order.isNotEmpty()
+ clear()
+ if (ctx != was || SmartShuffle.on.value == was || !np.uri.startsWith(TRACK)) return false
+ Graph.currentSongState.shuffle.value = false
+ // Turned off before the list was dealt: it still plays in its own order.
+ if (!dealt) return true
+ whenPlaying {
+ val now = SongPlayer.nowPlaying.value
+ if (now.contextUri != was || !now.uri.startsWith(TRACK)) return@whenPlaying false
+ app.myspoti.host.android.Logbook.log("shuffle: Myspoti's off, $was back in its order")
+ SongPlayer.playSong(now.uri, contextUri = was, order = back, positionMs = SongPlayer.getCurrentPosition(), askExtensions = false)
+ true
+ }
+ return true
+ }
+ if (!usable(ctx) || !dealable(ctx) || !np.uri.startsWith(TRACK)) return false
+ val g = gen.incrementAndGet()
+ synchronized(this) { list = ctx; order = emptyList(); at = -1; plain = noted?.takeIf { it.uri == ctx }?.plain; landed = true; startedAt = SystemClock.elapsedRealtime(); retried = false; due = null }
+ Graph.currentSongState.shuffle.value = true
+ MyspotiRuntime.scope.launch {
+ val tracks = load(ctx)
+ main.post {
+ if (g != gen.get()) return@post
+ val now = SongPlayer.nowPlaying.value
+ if (tracks == null || now.contextUri != ctx || LocalPlayer.active.value) {
+ clear()
+ // The list could not be read: Spotify's shuffle, as without the option.
+ if (tracks == null && now.contextUri == ctx) SongPlayer.setPageShuffle(true)
+ return@post
+ }
+ val back = plain
+ whenPlaying {
+ val cur = SongPlayer.nowPlaying.value
+ if (g != gen.get() || cur.contextUri != ctx) return@whenPlaying false
+ // A song not in the list (one the user queued): Spotify's shuffle, as without the option.
+ start(ctx, tracks, cur.uri, back, SongPlayer.getCurrentPosition()).also { if (!it) { clear(); SongPlayer.setPageShuffle(true) } }
+ }
+ }
+ }
+ return true
+ }
+
+ /** Shuffle changed while paused: what [due] holds plays at the next play (SongPlayer.play). True: done here. */
+ fun resume(): Boolean {
+ val d = synchronized(this) { due.also { due = null } } ?: return false
+ return d()
+ }
+
+ private fun whenPlaying(block: () -> Boolean) {
+ if (SongPlayer.isPlaying()) block() else synchronized(this) { due = block }
+ }
+
+ /**
+ * Deals [tracks] ([first] first, or next in the order dealt already) and plays it from [first].
+ * False: [first] is not in the list, nothing plays.
+ */
+ private fun start(uri: String, tracks: List<SongsModel>, first: String, back: List<String>?, positionMs: Long? = null): Boolean {
+ val songs = tracks.filter { it.spotifyTrackId.isNotBlank() }.associateBy { TRACK + it.spotifyTrackId }
+ // Each song once, even one the list holds twice.
+ val uris = songs.keys.toList()
+ if (first !in songs) return false
+ val (dealt, from) = synchronized(this) {
+ // A list still loading for an older play or toggle plays nothing now.
+ gen.incrementAndGet()
+ // Still in this list: the order dealt goes on, with the list as it is now.
+ val same = list == uri && landed && order.isNotEmpty() && SongPlayer.nowPlaying.value.contextUri == uri
+ val kept = if (same) ShuffleOrder.refresh(order, at, uris) else null
+ val picked = kept?.let { (o, a) -> ShuffleOrder.pick(o, a, first) }
+ val dealt = picked ?: (ShuffleOrder.draw(uris, first) to 0)
+ list = uri; order = dealt.first; at = dealt.second; plain = back
+ landed = same; startedAt = SystemClock.elapsedRealtime(); retried = false; due = null
+ dealt
+ }
+ val song = songs.getValue(dealt[from])
+ app.myspoti.host.android.Logbook.log("shuffle: Myspoti's order for $uri, ${dealt.size} songs, playing at ${from + 1}")
+ val state = Graph.currentSongState
+ // Spotify's shuffle would mix the order again.
+ SongPlayer.setPageShuffle(false)
+ state.shuffle.value = true
+ state.updateQueue(dealt.mapNotNull(songs::get))
+ SongPlayer.playSong(song.url, contextUri = uri, order = dealt, positionMs = positionMs, askExtensions = false)
+ return true
+ }
+
+ /**
+ * A state of the page (SongPlayer.applyState) on [contextUri] and the song [uri]; [trusted]: its
+ * [shuffle] is not an older state than the last shuffle asked for. True: Myspoti's order plays
+ * the list (the player shows shuffle on).
+ */
+ fun onPage(contextUri: String, uri: String, shuffle: Boolean, trusted: Boolean): Boolean {
+ var told: String? = null
+ var restore = false
+ val mine = synchronized(this) {
+ val l = list ?: return false
+ when {
+ !AppShufflePref.on || SmartShuffle.on.value == l -> { clearLocked(); false }
+ // The play asked for is on its way, or another list plays now (played from elsewhere
+ // than its page): shuffle stays on there, Spotify's, as without the option.
+ contextUri != l -> if (landed || SystemClock.elapsedRealtime() - startedAt > LAND_MS) {
+ // Shown on meanwhile: the page's shuffle is on its way.
+ clearLocked(); restore = !shuffle; restore
+ } else true
+ else -> {
+ landed = true
+ order.indexOf(uri).takeIf { it >= 0 }?.let { at = it }
+ if (!shuffle || !trusted) true
+ else if (SystemClock.elapsedRealtime() - startedAt > IMPOSED_MS) {
+ // Spotify's shuffle turned on later (another device): it plays the list now.
+ clearLocked(); false
+ } else if (!retried) {
+ // The page loaded with its own shuffle on (the first command came too early): once more.
+ retried = true
+ SongPlayer.setPageShuffle(false)
+ true
+ } else {
+ imposed += l; told = l; clearLocked(); false
+ }
+ }
+ }
+ }
+ if (restore) SongPlayer.setPageShuffle(true)
+ told?.let { l ->
+ app.myspoti.host.android.Logbook.log("shuffle: Spotify keeps its own shuffle on $l, Myspoti's order left")
+ main.post { android.widget.Toast.makeText(Graph.app, Graph.app.getString(R.string.myspoti_shuffle_imposed), android.widget.Toast.LENGTH_LONG).show() }
+ }
+ return mine
+ }
+
+ /** The order a play of [contextUri] in [sent] leaves when shuffle is off (SongPlayer's plain order). */
+ fun unshuffled(contextUri: String, sent: List<String>?): List<String>? =
+ synchronized(this) { if (list == contextUri && sent != null && sent == order) plain else sent }
+
+ /** The option turned off: a list playing in Myspoti's order goes on in Spotify's shuffle. */
+ fun forget() {
+ val was = list
+ clear()
+ noted = null
+ if (was != null && SongPlayer.nowPlaying.value.contextUri == was) SongPlayer.setPageShuffle(true)
+ }
+
+ private fun clear() = synchronized(this) { clearLocked() }
+
+ private fun clearLocked() {
+ gen.incrementAndGet()
+ list = null; order = emptyList(); at = -1; plain = null; landed = false; due = null
+ }
+
+ /** Every song of the list [contextUri] (all its pages), null when it cannot be read in full. */
+ private suspend fun load(contextUri: String): List<SongsModel>? {
+ noted?.takeIf { it.uri == contextUri && it.complete && it.tracks.isNotEmpty() }?.let { return it.tracks }
+ val api = Graph.api
+ val id = contextUri.substringAfterLast(':')
+ val flow: Flow<Response<ContextPageModel>> = when {
+ contextUri.contains(":collection") -> api.getLikedPage()
+ contextUri.startsWith("spotify:playlist:") -> api.getPlaylistPage(id)
+ contextUri.startsWith("spotify:album:") -> api.getAlbumPage(id)
+ else -> return null
+ }
+ val page = withContext(Dispatchers.IO) { runCatching { flow.filterIsInstance<Response.Success<ContextPageModel>>().lastOrNull()?.data }.getOrNull() }
+ return page?.takeIf { it.complete }?.tracks?.takeIf { it.isNotEmpty() }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/ShuffleOrder.kt b/base/app/src/main/java/com/music/spotui/di/ShuffleOrder.kt
new file mode 100644
index 00000000..8078ed41
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/ShuffleOrder.kt
@@ -0,0 +1,58 @@
+package com.music.spotui.di
+
+import kotlin.random.Random
+
+/**
+ * Myspoti's shuffle of a list (see [AppShuffle]): every song of the list once, in an order drawn
+ * once, before the list starts over. A song twice in the list is there twice. [at] is the index of
+ * the song playing in the order.
+ */
+internal object ShuffleOrder {
+ /** Fisher-Yates over [songs]; [first] (one of them) opens the order. */
+ fun <T> draw(songs: List<T>, first: T?, random: Random = Random.Default): List<T> {
+ val order = songs.toMutableList()
+ for (i in order.lastIndex downTo 1) {
+ val j = random.nextInt(i + 1)
+ val t = order[i]; order[i] = order[j]; order[j] = t
+ }
+ val from = if (first == null) -1 else order.indexOf(first)
+ if (from > 0) order.add(0, order.removeAt(from))
+ return order
+ }
+
+ /**
+ * The order dealt before, for the list as it is now ([songs]): the songs still in it keep their
+ * place, the ones gone are dropped, and the ones added since go at random places after the song
+ * playing, so they still come in this round. The new order and the playing song's index in it.
+ */
+ fun <T> refresh(order: List<T>, at: Int, songs: List<T>, random: Random = Random.Default): Pair<List<T>, Int> {
+ val left = songs.groupingBy { it }.eachCount().toMutableMap()
+ val kept = ArrayList<T>(songs.size)
+ var now = -1
+ order.forEachIndexed { i, t ->
+ val n = left[t] ?: 0
+ if (n > 0) {
+ left[t] = n - 1
+ if (i == at) now = kept.size
+ kept += t
+ } else if (i <= at) now = kept.lastIndex
+ }
+ val added = songs.filter { t -> (left[t] ?: 0).let { n -> if (n > 0) { left[t] = n - 1; true } else false } }
+ added.forEach { kept.add(now + 1 + random.nextInt(kept.size - now), it) }
+ return kept to now
+ }
+
+ /**
+ * [song] picked in the list while its order plays: it plays now, right after the song at [at]
+ * (the songs before stay as heard, the rest keeps its order). Its first place still to come is
+ * taken, else its last one. The new order and the picked song's index; null: not in the order.
+ */
+ fun <T> pick(order: List<T>, at: Int, song: T): Pair<List<T>, Int>? {
+ val from = (at + 1 until order.size).firstOrNull { order[it] == song } ?: order.lastIndexOf(song).takeIf { it >= 0 } ?: return null
+ val to = if (from > at) at + 1 else at.coerceAtLeast(0)
+ if (from == to) return order to to
+ val moved = order.toMutableList()
+ moved.add(to, moved.removeAt(from))
+ return moved to to
+ }
+}
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 7707eb45..1766a4b7 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
@@ -632,7 +632,10 @@ object SongPlayer {
val state = boundState ?: return
val holding = SystemClock.elapsedRealtime() < shuffleWantedUntil
if (holding && s.shuffle == shuffleWanted) shuffleWantedUntil = 0L
- if (!holding || s.shuffle == shuffleWanted) state.shuffle.value = s.shuffle
+ // Myspoti's shuffle plays the list in its own order with Spotify's off: shown on.
+ val trusted = !holding || s.shuffle == shuffleWanted
+ val dealt = AppShuffle.onPage(s.contextUri.orEmpty(), uri, s.shuffle, trusted)
+ if (trusted) state.shuffle.value = s.shuffle || dealt
// The page reports a speed other than 1 only for episodes: music stays at 1.
_speed.value = s.speed.takeIf { it > 0.0 } ?: 1.0
// A song from an extension keeps its own repeat: the muted Spotify copy that counts it
@@ -1045,7 +1048,7 @@ object SongPlayer {
if (ctx != null) {
val sent = order?.takeIf { ctx == contextUri }
playedOrder = ctx to sent
- if (com.music.spotui.ui.screens.SmartShuffle.on.value != ctx) { plainOrder = ctx to sent; smartPlayed = null }
+ if (com.music.spotui.ui.screens.SmartShuffle.on.value != ctx) { plainOrder = ctx to AppShuffle.unshuffled(ctx, sent); smartPlayed = null }
else if (sent != null) smartPlayed = ctx
}
markPending(if (episodeId != null) "" else trackId, itemUri)
@@ -1298,6 +1301,8 @@ object SongPlayer {
if (resumeThroughExtensions()) { Haptics.click(); return }
// Smart shuffle was turned off while paused: the list's order comes back as it plays on.
plainOrderDue?.let { if (restorePlainOrder(it)) return }
+ // Myspoti's shuffle turned on or off while paused: the song goes on in the list's new order.
+ if (AppShuffle.resume()) { Haptics.click(); return }
Haptics.click(); intendPlaying(); playing = true; positionAt = SystemClock.elapsedRealtime()
// Loading until the page plays: the clock ran from the tap before, over silence when the
// resume came late or never (reported on a slow network).
@@ -1672,6 +1677,12 @@ object SongPlayer {
fun setShuffle(on: Boolean) {
Haptics.toggle(on)
if (LocalPlayer.active.value) { LocalPlayer.setShuffle(on); return }
+ if (AppShuffle.toggle(on)) return
+ setPageShuffle(on)
+ }
+
+ /** Spotify's own shuffle, set on the page (Myspoti's, [AppShuffle], keeps it off). */
+ internal fun setPageShuffle(on: Boolean) {
shuffleWanted = on
shuffleWantedUntil = SystemClock.elapsedRealtime() + SHUFFLE_HOLD_MS
command { api.player.setShuffle(on) }
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index 56acc1ef..115a944d 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -225,6 +225,14 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> U
detail = stringResource(R.string.settings_autoplay_detail),
)
}
+ row {
+ ImmersiveSwitchRow(
+ stringResource(R.string.myspoti_shuffle_title),
+ checked = com.music.spotui.data.preferences.AppShufflePref.on,
+ onChecked = { com.music.spotui.data.preferences.AppShufflePref.set(ctx, it) },
+ detail = stringResource(R.string.myspoti_shuffle_detail),
+ )
+ }
row {
ImmersiveGroupRow(
stringResource(R.string.settings_crossfade_title), detail = stringResource(R.string.settings_crossfade_detail),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index dda79537..e2b2a9fa 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -505,6 +505,11 @@ class ContextViewModel(
// Sorted by the user: Spotify plays the list in that order, not the playlist's. An
// artist's liked songs are a part of Liked Songs: always given, so only they play.
val order = if (sort.isCustom && p.type != "liked-artist") null else sort.apply(p.tracks).filter { it.spotifyTrackId.isNotBlank() }.map { "spotify:track:${it.spotifyTrackId}" }
+ // Myspoti's shuffle (an option): with shuffle on, every song of the list once, in an order of its own.
+ if (com.music.spotui.di.AppShuffle.play(p, song, order)) {
+ state.updateSongState(song.coverUri, song.title, song.singer, true, song.id, 0, song.album)
+ return
+ }
if (order != null) state.updateQueue(sort.apply(p.tracks))
// The audio-source extensions were asked already (or the phone is offline): Spotify plays.
SongPlayer.playSong(song.url, contextUri = p.uri, order = order, askExtensions = false)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
index 75bfccba..1698cbfe 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -110,6 +110,12 @@ fun SettingsScreen(navController: NavController) {
checked = com.music.spotui.data.preferences.AutoplayPref.on,
onChecked = { com.music.spotui.data.preferences.AutoplayPref.set(ctx, it) },
)
+ OptionRow(
+ label = stringResource(R.string.myspoti_shuffle_title),
+ detail = stringResource(R.string.myspoti_shuffle_detail),
+ checked = com.music.spotui.data.preferences.AppShufflePref.on,
+ onChecked = { com.music.spotui.data.preferences.AppShufflePref.set(ctx, it) },
+ )
CrossfadeRow()
var keepPlaying by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.keepsPlayingOnClose(ctx)) }
OptionRow(
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index f0483361..89fde0bc 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -388,6 +388,9 @@
<string name="share_as_image">Share as image</string>
<string name="settings_autoplay_title">Autoplay</string>
<string name="settings_autoplay_detail">When your music ends, keep playing similar songs</string>
+ <string name="myspoti_shuffle_title">Myspoti shuffle</string>
+ <string name="myspoti_shuffle_detail">With shuffle on, a playlist, album or Liked Songs plays every song once, in a random order, before starting over. Off: Spotify\'s shuffle. A free account may keep Spotify\'s shuffle on some lists.</string>
+ <string name="myspoti_shuffle_imposed">Spotify keeps its own shuffle on this list for your account: Myspoti shuffle is off for it.</string>
<string name="settings_crossfade_title">Crossfade</string>
<string name="settings_crossfade_detail">Songs from extensions, downloads and local files overlap: the end of one fades out while the next fades in. Spotify streams cannot overlap (one audio stream): they only fade out and in.</string>
<string name="settings_crossfade_off">Off</string>
diff --git a/base/app/src/test/java/com/music/spotui/di/ShuffleOrderTest.kt b/base/app/src/test/java/com/music/spotui/di/ShuffleOrderTest.kt
new file mode 100644
index 00000000..af7048e4
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/di/ShuffleOrderTest.kt
@@ -0,0 +1,61 @@
+package com.music.spotui.di
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.random.Random
+
+class ShuffleOrderTest {
+ private val list = (1..40).map { "s$it" }
+
+ @Test fun everySongOnceAndThePickedOneFirst() {
+ repeat(50) { seed ->
+ val order = ShuffleOrder.draw(list, "s17", Random(seed))
+ assertEquals("s17", order.first())
+ assertEquals(list.sorted(), order.sorted())
+ }
+ // Nothing picked (or a song not in the list): the list shuffled as it is.
+ assertEquals(list.sorted(), ShuffleOrder.draw(list, null, Random(1)).sorted())
+ assertEquals(list.sorted(), ShuffleOrder.draw(list, "x", Random(1)).sorted())
+ }
+
+ @Test fun theDrawIsUniform() {
+ // Reported: Spotify's shuffle came back to the same ~15 songs of 40. Each song is about as
+ // often in each place: the first ten of 4000 draws hold every song about 1000 times.
+ val random = Random(7)
+ val seen = HashMap<String, Int>()
+ repeat(4000) { ShuffleOrder.draw(list, null, random).take(10).forEach { seen[it] = (seen[it] ?: 0) + 1 } }
+ assertEquals(40, seen.size)
+ assertTrue(seen.toString(), seen.values.all { it in 850..1150 })
+ }
+
+ @Test fun aPickPlaysNextAndTheRestKeepsItsOrder() {
+ val order = listOf("A", "B", "C", "D", "E", "F")
+ // C plays; E is picked: it comes right after C, nothing else moves.
+ assertEquals(listOf("A", "B", "C", "E", "D", "F") to 3, ShuffleOrder.pick(order, 2, "E"))
+ // A song heard already is heard again now, right after the one playing.
+ assertEquals(listOf("B", "C", "A", "D", "E", "F") to 2, ShuffleOrder.pick(order, 2, "A"))
+ // The next song, or the one playing: nothing moves.
+ assertEquals(order to 3, ShuffleOrder.pick(order, 2, "D"))
+ assertEquals(order to 2, ShuffleOrder.pick(order, 2, "C"))
+ assertNull(ShuffleOrder.pick(order, 2, "X"))
+ }
+
+ @Test fun theListChangingKeepsTheOrderAndNewSongsComeThisRound() {
+ val order = listOf("A", "B", "C", "D", "E")
+ // B and E left the list, X and Y joined it, C plays.
+ repeat(20) { seed ->
+ val (now, at) = ShuffleOrder.refresh(order, 2, listOf("Y", "A", "C", "D", "X"), Random(seed))
+ assertEquals("C", now[at])
+ assertEquals(listOf("A", "C"), now.take(at + 1))
+ assertEquals(listOf("D"), now.drop(at + 1).filter { it in order })
+ assertEquals(listOf("A", "C", "D", "X", "Y"), now.sorted())
+ }
+ // The song playing left the list: the order goes on after the last song heard.
+ val (now, at) = ShuffleOrder.refresh(order, 2, listOf("A", "B", "D", "E"), Random(1))
+ assertEquals(listOf("A", "B", "D", "E") to 1, now to at)
+ // Nothing changed: the same order.
+ assertEquals(order to 2, ShuffleOrder.refresh(order, 2, order.reversed(), Random(1)))
+ }
+}