Skip to content

Native Android client for Spotify, built with Jetpack Compose

Ads left out, stalls recovered, smart shuffle, sorted playback

kota-zocd2762fe92ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07cafc65..ebdea22e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,8 +21,15 @@ A new engine, written from scratch, and a cleaner app on top of it.
- **Setup screen** after signing in: notifications, local music, Bluetooth and unrestricted battery, each with its own button.
- **Folders in Local Files**: choose the folders shown; WhatsApp, Telegram, recordings and ringtones start hidden.
- **Lock screen and Now Bar**: play / pause in the middle (like, previous, play, next, shuffle) and a centred app icon.
+- **Music no longer stops after a few songs**: when the player gets stuck between two songs, the next one starts by itself, and the player reloads if that is not enough.
+- **Smart shuffle** in playlists (tap shuffle twice): the playlist shuffled, with a Spotify recommendation every three songs.
+- **Sort by plays in that order**: a sorted playlist plays and queues in the order shown.
+- **Saved in** shows your folders and the playlists' covers; a folder's menu creates a playlist inside it.
+- **Home loads again by itself** after an error, with a Try again button.
+- **Spotify account pages** open in the app's language when Spotify has them in it.
+- **Foldables and wide screens**: the player keeps its controls on screen.
- **Spotify keeps working after its updates**: the app picks up the Web Player's new operations by itself when Spotify ships a new version.
-- **No ads**: the ad audio is refused, so the player skips the ad within a second, and nothing false is reported to Spotify.
+- **No ads**: the player tells Spotify it cannot play the ad audio formats, so an ad comes with nothing to play and the next song starts within a couple of seconds. Nothing false is reported to Spotify (no ad is ever marked as heard).
- **Podcasts and audiobooks are back**: shows, episodes, chapters, **Your Episodes** in Your Library, and **playback speed** (from the song menu) for episodes.
- **New releases** in Search: what the artists you follow just released, then the latest releases.
- **Browse all** shows Spotify's real categories (pages of playlists and albums), not keyword searches.
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
index 20d4d421..5380d25e 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
@@ -196,8 +196,10 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, private
return mine().filter { it.editable || (me != null && it.owner == me) }
}
- override suspend fun create(name: String): Uri {
- val r = bridge.service("RootlistAPI", "createPlaylist", JsonPrimitive(name), json(mapOf("before" to "start")))
+ override suspend fun create(name: String, folderUri: Uri?): Uri {
+ // "After the folder" is the first place inside it.
+ val where = if (folderUri != null) json(mapOf("after" to mapOf("uri" to folderUri))) else json(mapOf("before" to "start"))
+ val r = bridge.service("RootlistAPI", "createPlaylist", JsonPrimitive(name), where)
return r.str("uri") ?: (r as? JsonPrimitive)?.content ?: throw GqlException("createPlaylist", "no uri")
}
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 10009477..f5dba5e9 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
@@ -11,6 +11,8 @@ import app.myspoti.spotify.bridge.Bridge
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
@@ -25,9 +27,14 @@ import kotlinx.serialization.json.putJsonArray
/**
* The Web Player's own player, driven through the bridge.
*
- * Ads: hosts refuse the ad audio, so the page skips an ad within a second. If an ad item
- * still stays current longer than [AD_GRACE_MS] (new ad host, video ad), the next real
- * track is played. Ads are never exposed in [state].
+ * Ads: hosts refuse the ad audio they know. Such an ad then stays current, buffering at
+ * 0:00, and the page never moves on by itself: after [AD_STUCK_MS] the song after the last
+ * one is played. An ad that really plays is left to its end. [adPlaying] says an ad is on;
+ * ads are never exposed in [state] (the last song stays there, buffering).
+ *
+ * Stalls: on some phones the page stops between two songs (stuck past the end, paused at
+ * the end with a next song, buffering for ever). After [STUCK_MS] the next song is played;
+ * if that does not help either, [reloadHost] reloads the page and playback resumes there.
*/
class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScope) : Player {
private val _state = MutableStateFlow<PlayerState?>(null)
@@ -36,7 +43,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
override val queue: StateFlow<Queue?> = _queue
private var lastTrackState: PlayerState? = null
- private var adWatch: Job? = null
+ private val _adPlaying = MutableStateFlow(false)
+ /** An ad is playing (the page plays it to its end). */
+ val adPlaying: StateFlow<Boolean> = _adPlaying
+ @Volatile private var adSince = 0L
+ @Volatile private var adState: PlayerState? = null
+ @Volatile private var pausedByUserAt = 0L
+ /** The order given to the last [play] (context uri to songs), kept for a stall restart. */
+ @Volatile private var lastOrder: Pair<Uri, List<Uri>>? = null
+
+ /** Reloads the Web Player page (set by the host); used when a stalled player does not recover. */
+ @Volatile var reloadHost: (suspend () -> Unit)? = null
init {
scope.launch {
@@ -47,36 +64,90 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
}
}
+ scope.launch { watchStalls() }
+ }
+
+ private suspend fun watchStalls() {
+ var key: String? = null
+ var since = 0L
+ var attempts = 0
+ while (true) {
+ delay(WATCH_TICK_MS)
+ val s = _state.value
+ val now = System.currentTimeMillis()
+ if (_adPlaying.value) {
+ val ad = adState
+ // A refused ad sits at 0:00, buffering; a real one plays to its end.
+ val stuck = ad != null && (ad.isBuffering || ad.speed == 0.0) && now - adSince > AD_STUCK_MS
+ if (stuck || now - adSince > AD_BREAK_MAX_MS) {
+ bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song")
+ lastTrackState?.let { runCatching { playOn(it) } }
+ adSince = now
+ }
+ key = null
+ continue
+ }
+ val reason = s?.let { stallOf(it, now, pausedByUserAt) }
+ if (s == null || reason == null) { key = null; attempts = 0; continue }
+ val k = "${s.item?.uri}|$reason"
+ if (k != key) { key = k; since = now; attempts = 0; continue }
+ if (now - since < (if (reason == "past the end") END_STUCK_MS else STUCK_MS)) continue
+ since = now
+ attempts++
+ bridge.logger?.invoke("player stalled ($reason) on ${s.item?.name}, attempt $attempts")
+ if (attempts == 1) runCatching { playOn(s) }
+ else {
+ attempts = 0
+ val reload = reloadHost ?: continue
+ runCatching {
+ reload()
+ withTimeoutOrNull(45_000) { delay(1_500); bridge.ready.first { it } } ?: return@runCatching
+ delay(1_500)
+ playOn(s)
+ }
+ }
+ }
+ }
+
+ /** Plays the song after [s] (or [s] again when it is the last one) in its context. */
+ private suspend fun playOn(s: PlayerState) {
+ val ctx = s.contextUri
+ val target = s.next?.takeIf { it.kind == ItemKind.TRACK }?.uri
+ ?: _queue.value?.nextUp?.firstOrNull { it.kind == ItemKind.TRACK }?.uri
+ when {
+ ctx != null && target != null -> play(ctx, trackUri = target, order = lastOrder?.takeIf { it.first == ctx }?.second)
+ target != null -> next()
+ ctx != null -> play(ctx, trackUri = s.item?.uri)
+ }
}
private fun onState(s: PlayerState?) {
if (s?.item?.kind == ItemKind.AD) {
- // Keep showing the last real track, buffering, while the ad is being dropped.
+ // Keep showing the last real track, buffering, while the ad plays.
+ if (!_adPlaying.value) adSince = System.currentTimeMillis()
+ adState = s
+ _adPlaying.value = true
_state.value = lastTrackState?.copy(isBuffering = true) ?: s.copy(item = null)
- if (adWatch?.isActive != true) adWatch = scope.launch { skipAdIfStuck(s.contextUri) }
return
}
- adWatch?.cancel()
+ _adPlaying.value = false
lastTrackState = s
_state.value = s
}
- private suspend fun skipAdIfStuck(contextUri: Uri?) {
- delay(AD_GRACE_MS)
- val next = _queue.value?.nextUp?.firstOrNull { it.kind == ItemKind.TRACK } ?: return
- if (contextUri != null) runCatching { play(contextUri, trackUri = next.uri) }
- }
- override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?) {
+ override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?, order: List<Uri>?) {
+ lastOrder = order?.let { contextUri to it }
bridge.call("player.play", buildJsonObject {
put("contextUri", contextUri)
+ order?.let { uris -> putJsonArray("order") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } } }
trackUri?.let { put("trackUri", it) }
index?.let { put("index", it) }
positionMs?.let { put("positionMs", it) }
})
}
- override suspend fun pause() { bridge.call("player.pause") }
+ override suspend fun pause() { pausedByUserAt = System.currentTimeMillis(); bridge.call("player.pause") }
override suspend fun resume() { bridge.call("player.resume") }
override suspend fun seek(positionMs: Long) { bridge.call("player.seek", buildJsonObject { put("positionMs", positionMs) }) }
override suspend fun next() { bridge.call("player.next") }
@@ -138,6 +209,33 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
companion object {
- const val AD_GRACE_MS = 1_000L
+ /** A refused ad left current that long: the page will not move on by itself. */
+ const val AD_STUCK_MS = 4_000L
+ /** Longer than any ad break: the page is stuck in it. */
+ const val AD_BREAK_MAX_MS = 4 * 60_000L
+ const val STUCK_MS = 8_000L
+ /** A song over with nothing after it: where an ad was left out. Next song quickly. */
+ const val END_STUCK_MS = 1_000L
+ private const val WATCH_TICK_MS = 2_000L
+ /** Buffering longer than this on one song is a stall, not a slow network. */
+ const val BUFFERING_STALL_MS = 25_000L
+
+ /**
+ * Why [s] looks stalled at [now], or null. A song is stalled when its clock ran past
+ * its end without a new song, when it paused itself at its end with a song after it,
+ * or while it buffers too long.
+ */
+ fun stallOf(s: PlayerState, now: Long, pausedByUserAt: Long): String? {
+ val item = s.item ?: return null
+ if (item.kind != ItemKind.TRACK || item.durationMs <= 0) return null
+ if (s.isPaused) {
+ val atEnd = s.positionMs >= item.durationMs - 2_000
+ val userPaused = now - pausedByUserAt < 20_000
+ return if (atEnd && s.next != null && !userPaused) "paused at the end" else null
+ }
+ if (s.isBuffering) return if (now - s.timestampMs > BUFFERING_STALL_MS - STUCK_MS) "buffering" else null
+ val clock = s.positionMs + ((now - s.timestampMs) * s.speed).toLong()
+ return if (clock > item.durationMs + 1_500) "past the end" else null
+ }
}
}
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.kt
index fdc5ac1d..dae8f296 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
@@ -1,6 +1,13 @@
package app.myspoti.spotify.bridge
import kotlinx.coroutines.flow.Flow
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
/**
* Where the Web Player page runs: an Android WebView or desktop Chrome over CDP.
@@ -24,12 +31,35 @@ object BridgeScript {
}
}
-/** Requests every host refuses. Blocking the ad audio makes the player skip the ad itself. */
+/**
+ * Audio ads. Spotify's server puts them in the player's queue (track-playback state machine),
+ * each with an audio file in a format of its own. The player registers itself without those
+ * formats ([withoutAdFormats]), so an ad comes with nothing to play; the ad audio host is
+ * refused as well. The player then halts at the end of the song before the ad, and
+ * [app.myspoti.spotify.SpotifyPlayer] starts the next song.
+ */
object AdBlock {
val blockedHosts = listOf("adstudio-assets.scdn.co")
+ /** Formats only ads use: the ad mp3 links and the ad manifests. Songs and episodes use others. */
+ val adFormats = setOf("manifest_urls_audio_ad", "file_urls_mp3")
+
fun isBlocked(url: String): Boolean {
val host = url.substringAfter("://").substringBefore('/').substringBefore(':')
return blockedHosts.any { host == it || host.endsWith(".$it") }
}
+
+ /** The player's registration (POST track-playback/v1/devices), to rewrite with [withoutAdFormats]. */
+ fun isDeviceRegistration(method: String, url: String): Boolean =
+ method.equals("POST", ignoreCase = true) && url.substringBefore('?').endsWith("/track-playback/v1/devices")
+
+ /** [body] (the registration JSON) without [adFormats] in its manifest formats; unchanged when unreadable. */
+ fun withoutAdFormats(body: String): String = runCatching {
+ val root = Json.parseToJsonElement(body).jsonObject
+ val device = root["device"]?.jsonObject ?: return body
+ val caps = device["capabilities"]?.jsonObject ?: return body
+ val formats = caps["manifest_formats"]?.jsonArray ?: return body
+ val kept = JsonArray(formats.filter { (it as? JsonPrimitive)?.contentOrNull !in adFormats })
+ JsonObject(root + ("device" to JsonObject(device + ("capabilities" to JsonObject(caps + ("manifest_formats" to kept)))))).toString()
+ }.getOrDefault(body)
}
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 43f0dae5..14281428 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -188,7 +188,11 @@
const extra = {};
if (Object.keys(skipTo).length) extra.skipTo = skipTo;
if (a.positionMs) extra.seekTo = a.positionMs;
- return need().player.play({ uri: a.contextUri }, {}, extra);
+ // A given order (sorted playlist): the context plays as one page of those songs.
+ const context = Array.isArray(a.order) && a.order.length
+ ? { uri: a.contextUri, url: 'context://' + a.contextUri + '?order=' + Date.now(), pages: [{ items: a.order.map(uri => ({ uri })) }] }
+ : { uri: a.contextUri };
+ return need().player.play(context, {}, extra);
},
'player.pause': () => need().player.pause(),
'player.resume': () => need().player.resume(),
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
new file mode 100644
index 00000000..50634020
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
@@ -0,0 +1,27 @@
+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 org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertNull
+import org.junit.jupiter.api.Test
+
+class StallTest {
+ private val song = NowPlaying(kind = ItemKind.TRACK, uri = "spotify:track:a", uid = null, name = "A", artists = emptyList(), album = null, imageUrl = null, durationMs = 200_000)
+ private val after = song.copy(uri = "spotify:track:b", name = "B")
+ private fun state(pos: Long, at: Long, paused: Boolean = false, buffering: Boolean = false, next: NowPlaying? = after) =
+ PlayerState(item = song, contextUri = "spotify:playlist:x", next = next, isPaused = paused, isBuffering = buffering,
+ positionMs = pos, timestampMs = at, speed = 1.0, shuffle = false, repeat = Repeat.OFF, restrictions = PlayerRestrictions())
+
+ @Test fun `a playing song is fine`() = assertNull(SpotifyPlayer.stallOf(state(100_000, 0), 50_000, 0))
+ @Test fun `clock past the end`() = assertEquals("past the end", SpotifyPlayer.stallOf(state(190_000, 0), 20_000, 0))
+ @Test fun `paused by itself at the end`() = assertEquals("paused at the end", SpotifyPlayer.stallOf(state(199_500, 0, paused = true), 60_000, 0))
+ @Test fun `paused by the user at the end`() = assertNull(SpotifyPlayer.stallOf(state(199_500, 0, paused = true), 60_000, 50_000))
+ @Test fun `last song of the list`() = assertNull(SpotifyPlayer.stallOf(state(199_500, 0, paused = true, next = null), 60_000, 0))
+ @Test fun `paused mid-song`() = assertNull(SpotifyPlayer.stallOf(state(50_000, 0, paused = true), 60_000, 0))
+ @Test fun `buffering for long`() = assertEquals("buffering", SpotifyPlayer.stallOf(state(0, 0, buffering = true), 20_000, 0))
+ @Test fun `buffering a moment`() = assertNull(SpotifyPlayer.stallOf(state(0, 0, buffering = true), 5_000, 0))
+}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdFormatsTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdFormatsTest.kt
new file mode 100644
index 00000000..3e511413
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdFormatsTest.kt
@@ -0,0 +1,27 @@
+package app.myspoti.spotify.bridge
+
+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 AdFormatsTest {
+ private val registration = """{"device":{"brand":"spotify","capabilities":{"change_volume":true,"manifest_formats":["file_ids_mp3","file_urls_mp3","manifest_urls_audio_ad","manifest_ids_video","file_urls_external","file_ids_mp4","file_ids_mp4_dual","manifest_urls_audio_ad"]},"device_id":"x"},"volume":65535}"""
+
+ @Test fun `registration loses the ad formats only`() {
+ val out = AdBlock.withoutAdFormats(registration)
+ assertTrue(""""manifest_formats":["file_ids_mp3","manifest_ids_video","file_urls_external","file_ids_mp4","file_ids_mp4_dual"]""" in out, out)
+ assertTrue(""""device_id":"x"""" in out && """"volume":65535""" in out)
+ }
+
+ @Test fun `other bodies stay as they are`() {
+ assertEquals("not json", AdBlock.withoutAdFormats("not json"))
+ assertEquals("""{"seq_num":2}""", AdBlock.withoutAdFormats("""{"seq_num":2}"""))
+ }
+
+ @Test fun `only the registration is rewritten`() {
+ assertTrue(AdBlock.isDeviceRegistration("POST", "https://gew4-spclient.spotify.com/track-playback/v1/devices"))
+ assertFalse(AdBlock.isDeviceRegistration("PUT", "https://gew4-spclient.spotify.com/track-playback/v1/devices/abc/state"))
+ assertFalse(AdBlock.isDeviceRegistration("POST", "https://gew4-spclient.spotify.com/track-playback/v1/devices/abc/state"))
+ }
+}
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Api.kt b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
index d61edc5d..b6989088 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
@@ -27,7 +27,11 @@ interface Player {
val queue: StateFlow<Queue?>
/** Plays [contextUri] (playlist, album, artist, show, collection...), starting at [trackUri] or [index] if given. */
- suspend fun play(contextUri: Uri, trackUri: Uri? = null, index: Int? = null, positionMs: Long? = null)
+ /**
+ * Plays [contextUri] from [trackUri] (or [index]). With [order], the context's songs play
+ * in that order instead of the context's own (a sorted playlist).
+ */
+ suspend fun play(contextUri: Uri, trackUri: Uri? = null, index: Int? = null, positionMs: Long? = null, order: List<Uri>? = null)
suspend fun pause()
suspend fun resume()
suspend fun seek(positionMs: Long)
@@ -124,7 +128,8 @@ interface Playlists {
/** Playlists the user may add tracks to. */
suspend fun editable(): List<Playlist>
- suspend fun create(name: String): Uri
+ /** A new playlist at the top of the library, or at the top of [folderUri]. */
+ suspend fun create(name: String, folderUri: Uri? = null): Uri
suspend fun rename(uri: Uri, name: String)
suspend fun setDescription(uri: Uri, description: String)
/** Removes the playlist from the library (owners: deletes it; it can be restored for 90 days). */
diff --git a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt
index 75340fbb..d6ad1b58 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt
@@ -1,15 +1,57 @@
package com.music.spotui.data.api
+import app.myspoti.api.LibraryFilter
+import app.myspoti.api.MediaKind
import app.myspoti.api.best
import app.myspoti.host.android.MyspotiRuntime
-/** A playlist the user can add tracks to, for the "Add to playlist" pickers. */
-data class EditablePlaylist(val id: String, val name: String, val trackCount: Int, val imageUrl: String?)
+/**
+ * A playlist the user can add tracks to, for the "Add to playlist" pickers. With a
+ * [folderUri] the row is a library folder instead, opened in place.
+ */
+data class EditablePlaylist(
+ val id: String,
+ val name: String,
+ val trackCount: Int,
+ val imageUrl: String?,
+ val folderUri: String? = null,
+) {
+ val isFolder: Boolean get() = folderUri != null
+}
object EditablePlaylists {
- /** The user's own and collaborative playlists, in library order. */
+ /** The user's own and collaborative playlists, in library order, folders flattened. */
suspend fun load(): List<EditablePlaylist> =
runCatching { MyspotiRuntime.api.playlists.editable() }.getOrDefault(emptyList()).map {
EditablePlaylist(it.uri.substringAfterLast(':'), it.name, it.trackCount, it.images.best(160)?.url)
}
+
+ /**
+ * One level of the library as Spotify shows it: its folders, then the playlists the user
+ * can change, with their covers (Spotify's playlist list has none for mosaic covers;
+ * the library has them). Falls back to [load] when the library cannot be read.
+ */
+ suspend fun level(folderUri: String?): List<EditablePlaylist> {
+ val api = MyspotiRuntime.api
+ val editable = runCatching { api.playlists.editable() }.getOrNull()?.associateBy { it.uri } ?: return load()
+ val items = ArrayList<app.myspoti.api.LibraryItem>()
+ runCatching {
+ var offset = 0
+ repeat(40) {
+ val page = api.library.items(filter = LibraryFilter.ALL, folderUri = folderUri, offset = offset, limit = 50)
+ items += page.items
+ offset = page.nextOffset ?: return@runCatching
+ }
+ }.onFailure { if (items.isEmpty()) return if (folderUri == null) load() else emptyList() }
+ return items.mapNotNull { item ->
+ when (item.kind) {
+ MediaKind.FOLDER -> EditablePlaylist(item.uri, item.name, item.count ?: 0, null, folderUri = item.uri)
+ MediaKind.PLAYLIST -> editable[item.uri]?.let {
+ EditablePlaylist(item.uri.substringAfterLast(':'), item.name, it.trackCount,
+ item.images.best(160)?.url ?: it.images.best(160)?.url)
+ }
+ else -> null
+ }
+ }
+ }
}
diff --git a/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt b/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt
index 74739558..a6ad4f5f 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt
@@ -57,17 +57,18 @@ object SpotifySync {
}
/** Creates a playlist (and adds the track when given). */
- fun createPlaylistWithTrack(context: Context, name: String, trackId: String, onDone: (Boolean) -> Unit = {}) {
+ fun createPlaylistWithTrack(context: Context, name: String, trackId: String, folderUri: String? = null, onDone: (Boolean) -> Unit = {}) {
if (name.isBlank()) { onDone(false); return }
scope.launch {
val ok = runCatching {
- val uri = api.playlists.create(name.trim())
+ val uri = api.playlists.create(name.trim(), folderUri)
if (trackId.isNotBlank()) {
api.playlists.addTracks(uri, listOf("spotify:track:$trackId"))
membershipCache[uri.substringAfterLast(':')] = ConcurrentHashMap.newKeySet<String>().apply { add(trackId) }
}
}.onFailure { Log.w(TAG, "create playlist '$name' failed: ${it.message}") }.isSuccess
Api.HomeCache.libraryRoot = null
+ folderUri?.let { Api.HomeCache.folders.remove(it) }
onDone(ok)
}
}
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 ffb24206..667bec91 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
@@ -413,7 +413,8 @@ object SongPlayer {
* Play [song] (a play key "spotify:track:<id>|<text>" or "episode:<id>"). [contextUri] is
* the list it was picked from; when null, the last list that registered this track is used.
*/
- fun playSong(song: String, context: Context? = null, contextUri: String? = null) {
+ /** [order]: the context's track uris in the order to play them (a sorted playlist). */
+ fun playSong(song: String, context: Context? = null, contextUri: String? = null, order: List<String>? = null) {
// Data saver on mobile data: Spotify can't stream, only downloads and Local Files play.
if (com.music.spotui.data.DataSaver.active) {
main.post {
@@ -428,7 +429,7 @@ object SongPlayer {
val ctx = contextUri ?: contextRegistry[song]
markPending(if (episodeId != null) "" else trackId, itemUri)
command {
- if (ctx != null) api.player.play(ctx, trackUri = itemUri)
+ if (ctx != null) api.player.play(ctx, trackUri = itemUri, order = order?.takeIf { ctx == contextUri })
else api.player.play(itemUri)
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt
index 2d86a5cf..911564ce 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt
@@ -24,6 +24,9 @@ import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
+import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -86,17 +89,22 @@ fun SavedInSheet(
val membership = remember { mutableStateMapOf<String, Boolean>() }
var creating by remember { mutableStateOf(false) }
var newName by remember { mutableStateOf("") }
+ // Folders opened so far (uri to name); the last one is shown.
+ val folders = remember { androidx.compose.runtime.mutableStateListOf<Pair<String, String>>() }
+ val folder = folders.lastOrNull()
- LaunchedEffect(Unit) {
- // Only playlists the user can change: theirs and collaborative ones.
- playlists = com.music.spotui.data.api.EditablePlaylists.load()
+ LaunchedEffect(folder?.first) {
+ // Only playlists the user can change (theirs and collaborative ones), level by level.
+ playlists = null
+ playlists = com.music.spotui.data.api.EditablePlaylists.level(folder?.first)
}
+ androidx.activity.compose.BackHandler(enabled = folders.isNotEmpty()) { folders.removeAt(folders.lastIndex) }
fun createNow() {
val name = newName.trim().ifBlank { context.getString(R.string.my_playlist) }
creating = false
newName = ""
- SpotifySync.createPlaylistWithTrack(context, name, song.spotifyTrackId)
+ SpotifySync.createPlaylistWithTrack(context, name, song.spotifyTrackId, folderUri = folder?.first)
onDismiss()
}
@@ -113,7 +121,14 @@ fun SavedInSheet(
.fillMaxWidth()
.padding(20.dp, 4.dp, 20.dp, 12.dp),
) {
- Text(stringResource(R.string.add_to_playlist_saved_in_section_header), color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold)
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f, fill = false)) {
+ if (folder != null) Icon(
+ Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null, tint = Color.White,
+ modifier = Modifier.padding(end = 12.dp).size(24.dp).clickable { folders.removeAt(folders.lastIndex) },
+ )
+ Text(folder?.second ?: stringResource(R.string.add_to_playlist_saved_in_section_header), color = Color.White,
+ fontSize = 20.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
Text(
stringResource(R.string.add_to_playlist_new_playlist_button_text),
color = SpotifyGreen,
@@ -173,7 +188,7 @@ fun SavedInSheet(
}
// ── Liked Songs ──
- SavedInRow(
+ if (folder == null) SavedInRow(
name = stringResource(R.string.collection_liked_songs_title),
subtitle = "",
saved = liked,
@@ -200,6 +215,12 @@ fun SavedInSheet(
else -> LazyColumn(modifier = Modifier.heightIn(max = 420.dp)) {
items(list.size) { i ->
val pl = list[i]
+ if (pl.isFolder) {
+ FolderRow(pl.name, pluralStringResource(R.plurals.add_to_playlist_folder_subtitle_playlists_count, pl.trackCount, pl.trackCount.toString())) {
+ folders.add(pl.folderUri!! to pl.name)
+ }
+ return@items
+ }
// Resolve membership lazily (cached per session in SpotifySync).
LaunchedEffect(pl.id, song.spotifyTrackId) {
if (membership[pl.id] == null && song.spotifyTrackId.isNotBlank()) {
@@ -246,6 +267,26 @@ fun SavedInSheet(
}
}
+@Composable
+private fun FolderRow(name: String, subtitle: String, onOpen: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(horizontal = 20.dp, vertical = 8.dp),
+ ) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)).background(Color(0xFF333333)),
+ ) {
+ Icon(Icons.Outlined.Folder, contentDescription = null, tint = Color(0xFFB3B3B3), modifier = Modifier.size(24.dp))
+ }
+ Column(Modifier.padding(start = 12.dp).weight(1f)) {
+ Text(name, color = Color.White, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(subtitle, color = Color(0xFFB3B3B3), fontSize = 13.sp, maxLines = 1)
+ }
+ Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null, tint = Color(0xFFB3B3B3))
+ }
+}
+
@Composable
private fun SavedInRow(
name: String,
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt b/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt
index 375a69ef..6cde2f24 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt
@@ -10,6 +10,14 @@ import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.OnBackPressedCallback
import androidx.activity.ComponentActivity
+import androidx.lifecycle.lifecycleScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.util.concurrent.TimeUnit
/**
* Spotify's account pages (plan, privacy, apps, devices) in a browser that shares the
@@ -26,7 +34,12 @@ class AccountBrowser : ComponentActivity() {
settings.domStorageEnabled = true
CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
webViewClient = WebViewClient()
- loadUrl(intent.getStringExtra(EXTRA_URL) ?: ACCOUNT_URL)
+ }
+ val url = intent.getStringExtra(EXTRA_URL) ?: ACCOUNT_URL
+ val language = com.music.spotui.data.AppLanguage.current(this).ifEmpty { null }
+ ?.let { java.util.Locale.forLanguageTag(it).language } ?: resources.configuration.locales[0].language
+ lifecycleScope.launch {
+ web.loadUrl(withContext(Dispatchers.IO) { runCatching { localized(url, language) }.getOrNull() } ?: url)
}
setContentView(web)
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
@@ -40,6 +53,32 @@ class AccountBrowser : ComponentActivity() {
}
companion object {
+ private val http by lazy {
+ OkHttpClient.Builder().followRedirects(false).callTimeout(6, TimeUnit.SECONDS).build()
+ }
+ private val MARKET = Regex("^/([a-z]{2})(?:-[a-z]{2})?/")
+
+ /**
+ * www.spotify.com picks the page language from the country it sees ("/ch-de/"), not
+ * from the app: the same page in the app's language ("/ch-en/") when Spotify has it.
+ */
+ private fun localized(url: String, language: String): String? {
+ val target = url.toHttpUrlOrNull() ?: return null
+ if (target.host != "www.spotify.com") return null
+ val path = target.encodedPath
+ val market = MARKET.find(path)?.groupValues?.get(1) ?: run {
+ val probe = Request.Builder().url("https://www.spotify.com/premium/").head().build()
+ val where = http.newCall(probe).execute().use { it.header("Location") } ?: return null
+ MARKET.find(where.toHttpUrlOrNull()?.encodedPath ?: return null)?.groupValues?.get(1) ?: return null
+ }
+ val prefix = "/$market-$language/"
+ // Spotify answers 200 for the combinations it has, and redirects the others.
+ val check = Request.Builder().url("https://www.spotify.com${prefix}premium/").head().build()
+ if (http.newCall(check).execute().use { it.code } != 200) return null
+ val rest = MARKET.find(path)?.let { path.substring(it.range.last + 1) } ?: path.removePrefix("/")
+ return target.newBuilder().encodedPath(prefix + rest).build().toString()
+ }
+
const val ACCOUNT_URL = "https://www.spotify.com/account/overview/"
private const val EXTRA_URL = "url"
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 fea8bfc2..d4135129 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
@@ -77,6 +77,10 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import androidx.compose.foundation.layout.offset
+import androidx.compose.material.icons.filled.AutoAwesome
+import app.myspoti.host.android.MyspotiRuntime
private val SpotifyGreen: Color get() = com.music.spotui.ui.theme.AppAccent
private val PageBackground: Color get() = com.music.spotui.ui.theme.AppBackground
@@ -198,7 +202,33 @@ class ContextViewModel(
SongPlayer.setSaved(p.uri, on)
}
- fun play(p: ContextPageModel, song: SongsModel) {
+ /**
+ * Smart shuffle (Spotify keeps its own for Premium): the playlist shuffled, with one of
+ * Spotify's recommendations for it after every [SmartShuffle.EVERY] songs.
+ */
+ fun playSmart(p: ContextPageModel, first: SongsModel?) {
+ viewModelScope.launch {
+ val recs = withContext(Dispatchers.IO) {
+ runCatching { MyspotiRuntime.api.playlists.recommended(p.uri, limit = 20) }.getOrDefault(emptyList())
+ }.filter { r -> p.tracks.none { "spotify:track:${it.spotifyTrackId}" == r.uri } }.map(api::songOf)
+ val shuffled = p.tracks.shuffled().let { list -> first?.let { f -> listOf(f) + (list - f) } ?: list }
+ val mixed = ArrayList<SongsModel>()
+ val more = recs.iterator()
+ shuffled.forEachIndexed { i, s ->
+ mixed += s
+ if ((i + 1) % SmartShuffle.EVERY == 0 && more.hasNext()) mixed += more.next()
+ }
+ SmartShuffle.recommended.value = recs.map { it.spotifyTrackId }.toSet()
+ // Spotify's shuffle would mix the given order again.
+ SongPlayer.setShuffle(false); state.shuffle.value = false
+ state.updateQueue(mixed)
+ val start = mixed.first()
+ SongPlayer.playSong(start.url, contextUri = p.uri, order = mixed.map { "spotify:track:${it.spotifyTrackId}" })
+ state.updateSongState(start.coverUri, start.title, start.singer, true, start.id, 0, start.album)
+ }
+ }
+
+ fun play(p: ContextPageModel, song: SongsModel, sort: TrackSort = TrackSort.CUSTOM) {
// No connection (the Web Player cannot stream), or the data saver on mobile data:
// the page's downloaded songs play from the phone.
val app = Graph.app
@@ -213,7 +243,10 @@ class ContextViewModel(
}
state.updateQueue(p.tracks)
if (p.type == "liked") SongPlayer.registerLikedSongs(p.tracks.map { it.url })
- SongPlayer.playSong(song.url, contextUri = p.uri)
+ // Sorted by the user: Spotify plays the list in that order, not the playlist's.
+ val order = if (sort == TrackSort.CUSTOM) null else sort.apply(p.tracks).map { "spotify:track:${it.spotifyTrackId}" }
+ if (order != null) state.updateQueue(sort.apply(p.tracks))
+ SongPlayer.playSong(song.url, contextUri = p.uri, order = order)
state.updateSongState(song.coverUri, song.title, song.singer, true, song.id, 0, song.album)
}
}
@@ -401,22 +434,39 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
}
}
Spacer(Modifier.weight(1f))
+ val smart = SmartShuffle.on.value == p.uri
+ Box {
Icon(
painter = painterResource(id = R.drawable.ic_player_shuffle),
- contentDescription = stringResource(R.string.play_mode_item_shuffle_title),
- tint = if (shuffle) SpotifyGreen else Color.White.copy(alpha = 0.8f),
+ contentDescription = stringResource(if (smart) R.string.smart_shuffle_title else R.string.play_mode_item_shuffle_title),
+ tint = if (shuffle || smart) SpotifyGreen else Color.White.copy(alpha = 0.8f),
modifier = Modifier
.size(26.dp)
.drawWithContent {
drawContent()
- if (shuffle) drawCircle(SpotifyGreen, radius = 2.dp.toPx(),
+ if (shuffle || smart) drawCircle(SpotifyGreen, radius = 2.dp.toPx(),
center = androidx.compose.ui.geometry.Offset(size.width / 2, size.height + 7.dp.toPx()))
}
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
- ) { playerVm.updateShuffleState(!shuffle) },
+ ) {
+ when {
+ smart -> { SmartShuffle.on.value = null; playerVm.updateShuffleState(false) }
+ shuffle && p.type == "playlist" -> {
+ SmartShuffle.on.value = p.uri
+ android.widget.Toast.makeText(context, context.getString(R.string.smart_shuffle_on), android.widget.Toast.LENGTH_SHORT).show()
+ if (isThisContext) vm.playSmart(p, p.tracks.firstOrNull { it.id == currentSongId })
+ }
+ else -> playerVm.updateShuffleState(!shuffle)
+ }
+ },
+ )
+ if (smart) Icon(
+ androidx.compose.material.icons.Icons.Default.AutoAwesome, contentDescription = null, tint = SpotifyGreen,
+ modifier = Modifier.align(Alignment.TopEnd).offset(x = 6.dp, y = (-6).dp).size(11.dp),
)
+ }
Spacer(Modifier.width(20.dp))
Box(
contentAlignment = Alignment.Center,
@@ -426,7 +476,8 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
when {
isThisContext && playing -> SongPlayer.pause()
isThisContext -> SongPlayer.play()
- p.tracks.isNotEmpty() -> vm.play(p, if (shuffle) p.tracks.random() else p.tracks.first())
+ p.tracks.isNotEmpty() && SmartShuffle.on.value == p.uri -> vm.playSmart(p, null)
+ p.tracks.isNotEmpty() -> vm.play(p, if (shuffle) p.tracks.random() else sort.apply(p.tracks).first(), sort)
}
}
.clip(CircleShape)
@@ -467,7 +518,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
isCurrent = song.id == currentSongId,
saved = SongPlayer.library["spotify:track:${song.spotifyTrackId}"] ?: ("spotify:track:${song.spotifyTrackId}" in saved),
offline = com.music.spotui.data.offline.OfflineStore.statusOf(song.spotifyTrackId),
- onClick = { vm.play(p, song) },
+ onClick = { if (SmartShuffle.on.value == p.uri) vm.playSmart(p, song) else vm.play(p, song, sort) },
onMore = { menuSong = song },
) }
}
@@ -570,6 +621,14 @@ private fun LikedCover(modifier: Modifier) {
/** "Sort by" for the songs of a playlist or Liked Songs; [CUSTOM] is Spotify's own order. */
+/** Smart shuffle, per playlist (uri), for this session. */
+object SmartShuffle {
+ const val EVERY = 3
+ val on = androidx.compose.runtime.mutableStateOf<String?>(null)
+ /** The recommendations mixed into the playing list. */
+ val recommended = androidx.compose.runtime.mutableStateOf<Set<String>>(emptySet())
+}
+
enum class TrackSort(val label: Int) {
CUSTOM(R.string.your_library_sort_order_custom),
TITLE(R.string.track_sort_title),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
index 27d41b3b..e8756027 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
@@ -115,11 +115,16 @@ fun HomeScreen(navController: NavController){
Box(modifier = Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
when {
home is Response.Loading -> Loader(SkeletonKind.Home)
- else -> Text(
- text = if (home is Response.Error) stringResource(R.string.home_error) else stringResource(R.string.home_empty),
- color = Color.White,
- textAlign = TextAlign.Center,
- )
+ else -> androidx.compose.foundation.layout.Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = if (home is Response.Error) stringResource(R.string.home_error) else stringResource(R.string.home_empty),
+ color = Color.White,
+ textAlign = TextAlign.Center,
+ )
+ if (home is Response.Error) androidx.compose.material3.TextButton(onClick = { homeViewModel.retry() }) {
+ Text(stringResource(R.string.home_retry), color = Color(0xFF1DB954))
+ }
+ }
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt
index 2177fbe0..5762efd6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt
@@ -200,6 +200,7 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)
var entries by remember { mutableStateOf<List<LibraryEntry>?>(null) }
var menu by remember { mutableStateOf(false) }
var renaming by remember { mutableStateOf(false) }
+ var newPlaylist by remember { mutableStateOf(false) }
var generation by remember { mutableStateOf(0) }
LaunchedEffect(uri, generation) {
withContext(Dispatchers.IO) {
@@ -208,9 +209,21 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)
}
if (menu) ModalBottomSheet(onDismissRequest = { menu = false }, containerColor = SheetColor) {
Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {
+ SheetRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.add_to_playlist_new_playlist_button_text)) { menu = false; newPlaylist = true }
SheetRow(Icons.Outlined.Edit, stringResource(R.string.context_menu_rename_folder)) { menu = false; renaming = true }
}
}
+ // A Spotify playlist created straight inside this folder.
+ if (newPlaylist) NameDialog(stringResource(R.string.create_playlist_content_description), context.getString(R.string.my_playlist),
+ stringResource(R.string.create_playlist_create_button), onDismiss = { newPlaylist = false }) { playlistName ->
+ newPlaylist = false
+ SpotifySync.createPlaylistWithTrack(context, playlistName, "", folderUri = uri) { ok ->
+ scope.launch {
+ if (ok) generation++
+ else Toast.makeText(context, context.getString(R.string.playlist_change_refused), Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
if (renaming) NameDialog(stringResource(R.string.context_menu_rename_folder), name, stringResource(R.string.local_rename),
onDismiss = { renaming = false }) { newName ->
renaming = false
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index 09cec607..214afd9b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
@@ -25,6 +25,7 @@ import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -40,7 +41,6 @@ import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
@@ -328,7 +328,11 @@ fun PlayerScreen(navController: NavController) {
Spacer(modifier = Modifier.height(28.dp))
// Media area: artwork (swipe to change track) or the music video, with
// Spotify's "Passer à la vidéo" pill over it (black, like the official app).
- Box(modifier = Modifier.fillMaxWidth().aspectRatio(1f)) {
+ // Square, but never taller than what the controls leave (foldables, landscape-ish
+ // screens): otherwise play / pause ends up under the lyrics card.
+ val screen = androidx.compose.ui.platform.LocalConfiguration.current
+ val artMax = (screen.screenHeightDp - PLAYER_CONTROLS_DP).coerceAtLeast(160).dp
+ Box(modifier = Modifier.widthIn(max = artMax).fillMaxWidth().aspectRatio(1f)) {
if (showVideo) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(),
@@ -1219,3 +1223,6 @@ private fun CanvasVideo(url: String, playing: Boolean, modifier: Modifier = Modi
},
)
}
+
+/** Height the player needs under the artwork: top bar, title, seek bar, controls, Connect row. */
+private const val PLAYER_CONTROLS_DP = 450
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/HomeViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/HomeViewModel.kt
index d7dabfb9..7d1739b0 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/HomeViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/HomeViewModel.kt
@@ -22,6 +22,29 @@ class HomeViewModel constructor(private val repository: AppRepository = Graph.re
init {
fetchHome()
+ // A Home that failed (player still signing in, network back) loads again by itself:
+ // when the player is ready again, then a few times with growing pauses.
+ viewModelScope.launch {
+ app.myspoti.host.android.MyspotiRuntime.api.ready.collect { ready ->
+ if (ready && _home.value is Response.Error) fetchHome()
+ }
+ }
+ viewModelScope.launch {
+ var tries = 0
+ _home.collect { state ->
+ if (state is Response.Success) tries = 0
+ if (state is Response.Error && tries < RETRY_DELAYS_MS.size) {
+ kotlinx.coroutines.delay(RETRY_DELAYS_MS[tries++])
+ if (_home.value is Response.Error) fetchHome()
+ }
+ }
+ }
+ }
+
+ /** Tries again now (the Home error's button). */
+ fun retry() {
+ _home.value = Response.Loading()
+ fetchHome()
}
fun selectFacet(f: String) {
@@ -29,6 +52,10 @@ class HomeViewModel constructor(private val repository: AppRepository = Graph.re
fetchHome()
}
+ private companion object {
+ val RETRY_DELAYS_MS = longArrayOf(2_000, 5_000, 15_000, 30_000)
+ }
+
private fun fetchHome() {
homeJob?.cancel()
val f = facet.value
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 9b36eabc..f7d8d5e9 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -37,6 +37,7 @@
<string name="lyrics_fullscreen">Ouvrir les paroles en plein écran</string>
<string name="browse_all">Parcourir tout</string>
<string name="home_error">Impossible de charger l\'accueil.\nVérifie ta connexion et réessaie.</string>
+ <string name="home_retry">Réessayer</string>
<string name="home_empty">Rien à afficher pour le moment.</string>
<string name="spotify_account">Compte Spotify</string>
<string name="spotify_user">Utilisateur Spotify</string>
@@ -185,4 +186,6 @@
<string name="local_folders_button">Dossiers</string>
<string name="local_folders_title">Dossiers</string>
<string name="local_folders_detail">Choisis les dossiers affichés dans Fichiers locaux. Les applis de messagerie et les enregistrements sont masqués au départ.</string>
+ <string name="smart_shuffle_title">Lecture aléatoire intelligente</string>
+ <string name="smart_shuffle_on">Aléatoire intelligent : des recommandations Spotify se glissent dans la playlist mélangée.</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index a28621ae..4f9a6674 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -37,6 +37,7 @@
<string name="lyrics_fullscreen">Open lyrics full screen</string>
<string name="browse_all">Browse all</string>
<string name="home_error">Couldn\'t load Home.\nCheck your connection and try again.</string>
+ <string name="home_retry">Try again</string>
<string name="home_empty">Nothing to show yet.</string>
<string name="spotify_account">Spotify account</string>
<string name="spotify_user">Spotify user</string>
@@ -185,4 +186,6 @@
<string name="local_folders_button">Folders</string>
<string name="local_folders_title">Folders</string>
<string name="local_folders_detail">Choose the folders shown in Local Files. Messaging apps and recordings start hidden.</string>
+ <string name="smart_shuffle_title">Smart shuffle</string>
+ <string name="smart_shuffle_on">Smart shuffle: Spotify recommendations join the shuffled playlist.</string>
</resources>
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 0e1863e1..e5e65d55 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
@@ -62,8 +62,10 @@ internal class ControlRelay(private val view: WebView) {
headers["User-Agent"] = WebPlayerHost.DESKTOP_UA
headers["Origin"] = "https://open.spotify.com"
headers["Referer"] = "https://open.spotify.com/"
+ // The player's registration leaves out the ad formats (see AdBlock).
+ val sent = if (body != null && app.myspoti.spotify.bridge.AdBlock.isDeviceRegistration(method, url)) app.myspoti.spotify.bridge.AdBlock.withoutAdFormats(body) else body
// Bytes, not a String body: OkHttp would append "; charset=utf-8" to the content type.
- val payload = if (method == "GET" || method == "HEAD") null else (body ?: "").toByteArray().toRequestBody(null)
+ val payload = if (method == "GET" || method == "HEAD") null else (sent ?: "").toByteArray().toRequestBody(null)
val request = Request.Builder().url(url).headers(headers.build()).method(method, payload).build()
http.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
index 9f14f14d..5d7313cd 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
@@ -32,6 +32,7 @@ object MyspotiRuntime {
spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load())
spotify.bridge.logger = { line -> android.util.Log.d(WebPlayerHost.LOG, line) }
host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }
+ spotify.player.reloadHost = { host.reload() }
// Every 10 s: is the bridge ready, what does the player say (diagnostics in Logcat).
scope.launch {
while (true) {
diff --git a/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt b/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt
index a2b36e2e..ed7b343c 100644
--- a/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt
+++ b/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt
@@ -90,8 +90,14 @@ class CdpHost private constructor(private val socket: WebSocket, private val lis
if (params["name"]?.jsonPrimitive?.content == BINDING) messages.tryEmit(params["payload"]!!.jsonPrimitive.content)
"Fetch.requestPaused" -> {
val requestId = params["requestId"]!!.jsonPrimitive.content
- val url = params["request"]!!.jsonObject["url"]!!.jsonPrimitive.content
- val reply = if (AdBlock.isBlocked(url)) {
+ val request = params["request"]!!.jsonObject
+ val url = request["url"]!!.jsonPrimitive.content
+ val method = request["method"]?.jsonPrimitive?.content ?: "GET"
+ val post = request["postData"]?.jsonPrimitive?.content
+ val reply = if (post != null && AdBlock.isDeviceRegistration(method, url)) {
+ val body = java.util.Base64.getEncoder().encodeToString(AdBlock.withoutAdFormats(post).toByteArray())
+ buildJsonObject { put("id", ids.incrementAndGet()); put("method", "Fetch.continueRequest"); putJsonObject("params") { put("requestId", requestId); put("postData", body) } }
+ } else if (AdBlock.isBlocked(url)) {
buildJsonObject { put("id", ids.incrementAndGet()); put("method", "Fetch.failRequest"); putJsonObject("params") { put("requestId", requestId); put("errorReason", "BlockedByClient") } }
} else {
buildJsonObject { put("id", ids.incrementAndGet()); put("method", "Fetch.continueRequest"); putJsonObject("params") { put("requestId", requestId) } }
@@ -135,6 +141,7 @@ class CdpHost private constructor(private val socket: WebSocket, private val lis
host.send("Fetch.enable", buildJsonObject {
put("patterns", buildJsonArray {
AdBlock.blockedHosts.forEach { h -> add(buildJsonObject { put("urlPattern", "*://$h/*") }) }
+ add(buildJsonObject { put("urlPattern", "*/track-playback/v1/devices") })
})
})
return host
diff --git a/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveEpisodeTest.kt b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveEpisodeTest.kt
new file mode 100644
index 00000000..ccad91d9
--- /dev/null
+++ b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveEpisodeTest.kt
@@ -0,0 +1,36 @@
+package app.myspoti.host.cdp
+
+import app.myspoti.spotify.SpotifyApi
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty
+
+/** Episodes still play with the ad formats left out of the player's registration. */
+@EnabledIfSystemProperty(named = "myspoti.cdp", matches = ".+")
+class LiveEpisodeTest {
+ @Test
+ fun `an episode plays`() = runBlocking {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ val host = CdpHost.connect(System.getProperty("myspoti.cdp"))
+ val api = SpotifyApi(host, scope, language = "fr")
+ host.reload(); host.awaitLoad(); api.onPageLoaded(); api.awaitReady()
+ for (query in listOf("france inter", "the daily", "joe rogan")) {
+ val ep = api.search.episodes(query, limit = 1).items.firstOrNull() ?: continue
+ try {
+ api.player.play(ep.uri)
+ val s = withTimeout(30_000) { api.player.state.first { it?.item?.uri == ep.uri && !it.isPaused && !it.isBuffering } }!!
+ delay(4_000)
+ val pos = api.player.state.value!!.positionAt(System.currentTimeMillis())
+ println("episode ${ep.name}: position $pos")
+ assertTrue(pos > 2_000)
+ } finally { runCatching { api.player.pause() } }
+ }
+ }
+}
diff --git a/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt
new file mode 100644
index 00000000..5c04b02b
--- /dev/null
+++ b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt
@@ -0,0 +1,62 @@
+package app.myspoti.host.cdp
+
+import app.myspoti.spotify.SpotifyApi
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty
+
+/** A sorted playlist plays in the sorted order, next song included. */
+@EnabledIfSystemProperty(named = "myspoti.cdp", matches = ".+")
+class LiveOrderTest {
+ @Test
+ fun `plays a playlist in a given order`() = runBlocking {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ val host = CdpHost.connect(System.getProperty("myspoti.cdp"))
+ val api = SpotifyApi(host, scope, language = "fr")
+ host.reload(); host.awaitLoad(); api.onPageLoaded(); api.awaitReady()
+ val list = "spotify:playlist:37i9dQZF1DXcBWIGoYBM5M"
+ val songs = api.playlists.tracks(list, 0, 10).items.map { it.uri }
+ val order = songs.reversed()
+ try {
+ api.player.play(list, trackUri = order[0], order = order)
+ val s = withTimeout(30_000) { api.player.state.first { it?.item?.uri == order[0] && !it.isPaused } }!!
+ println("now ${s.item?.name}, next ${s.next?.name}, context ${s.contextUri}")
+ assertEquals(order[1], s.next?.uri)
+ api.player.next()
+ val t = withTimeout(30_000) { api.player.state.first { it?.item?.uri != order[0] && it?.item != null } }!!
+ println("after next: ${t.item?.name}")
+ assertEquals(order[1], t.item?.uri)
+ } finally {
+ runCatching { api.player.pause() }
+ }
+ }
+
+ /** Smart shuffle: a recommended song (not in the playlist) plays inside its order. */
+ @Test
+ fun `plays recommendations inside a playlist order`() = runBlocking {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ val host = CdpHost.connect(System.getProperty("myspoti.cdp"))
+ val api = SpotifyApi(host, scope, language = "fr")
+ host.reload(); host.awaitLoad(); api.onPageLoaded(); api.awaitReady()
+ val list = "spotify:playlist:37i9dQZF1DXcBWIGoYBM5M"
+ val songs = api.playlists.tracks(list, 0, 5).items.map { it.uri }
+ val rec = api.playlists.recommended(list, 5).first { it.uri !in songs }.uri
+ val order = listOf(songs[0], rec, songs[1])
+ try {
+ api.player.play(list, trackUri = songs[0], order = order)
+ withTimeout(30_000) { api.player.state.first { it?.item?.uri == songs[0] && !it.isPaused } }
+ api.player.next()
+ val t = withTimeout(30_000) { api.player.state.first { it?.item != null && it.item!!.uri != songs[0] } }!!
+ println("recommended: ${t.item?.name} context ${t.contextUri}")
+ assertEquals(rec, t.item?.uri)
+ } finally {
+ runCatching { api.player.pause() }
+ }
+ }
+}
diff --git a/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LivePlaythroughTest.kt b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LivePlaythroughTest.kt
new file mode 100644
index 00000000..df82150a
--- /dev/null
+++ b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LivePlaythroughTest.kt
@@ -0,0 +1,66 @@
+package app.myspoti.host.cdp
+
+import app.myspoti.spotify.SpotifyApi
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty
+
+/**
+ * A free account plays through several songs in a row, ads included: each song is
+ * jumped to its last seconds, and the next one must start by itself.
+ *
+ * ./gradlew :host-cdp:test -Pcdp=http://localhost:9222 --tests '*LivePlaythroughTest*'
+ */
+@EnabledIfSystemProperty(named = "myspoti.cdp", matches = ".+")
+class LivePlaythroughTest {
+ @Test
+ fun `plays song after song`() = runBlocking {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ val host = CdpHost.connect(System.getProperty("myspoti.cdp"))
+ val api = SpotifyApi(host, scope, language = "fr")
+ host.reload(); host.awaitLoad(); api.onPageLoaded(); api.awaitReady()
+ api.bridge.logger = { line -> if ("stalled" in line || "ad stuck" in line || "call #" in line && "player.play" in line) println(line) }
+ api.player.reloadHost = { println("reloading the page"); host.reload(); host.awaitLoad(); api.onPageLoaded() }
+ scope.launch { api.player.adPlaying.collect { println("ad playing: $it") } }
+ scope.launch {
+ var last = ""
+ api.player.state.collect { s ->
+ val line = "${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering}"
+ if (line != last) { println("state: $line"); last = line }
+ }
+ }
+ val songs = (System.getProperty("myspoti.songs") ?: System.getenv("MSP_SONGS") ?: "8").toInt()
+ api.player.play("spotify:playlist:37i9dQZF1DXcBWIGoYBM5M", index = 0)
+ var played = 0
+ try {
+ repeat(songs) { n ->
+ val s = withTimeout(300_000) { api.player.state.first { it?.item != null && !it.isPaused && !it.isBuffering } }!!
+ println("song ${n + 1}: ${s.item!!.name}")
+ played++
+ // An ad being dropped refuses the seek for a moment.
+ for (attempt in 1..10) {
+ if (runCatching { api.player.seek((s.item!!.durationMs - 4_000).coerceAtLeast(0)) }.isSuccess) break
+ delay(1_000)
+ }
+ val moved = kotlinx.coroutines.withTimeoutOrNull(300_000) { api.player.state.first { it?.item != null && it.item!!.uri != s.item!!.uri } }
+ if (moved == null) {
+ println("stuck; page says: " + api.bridge.call("player.state").toString().take(1500))
+ error("no next song after ${s.item!!.name}")
+ }
+ }
+ } finally {
+ runCatching { api.player.pause() }
+ println("played $played of $songs")
+ delay(500)
+ }
+ assertTrue(played == songs)
+ }
+}