Skip to content

Native Android client for Spotify, built with Jetpack Compose

API: artist ban, public and collaborative playlists, sorted playlist rows, save episodes

kota-zobd70a99dc20d
diff --git a/base/api-spotify/README.md b/base/api-spotify/README.md
index a8044970..61f7e2cc 100644
--- a/base/api-spotify/README.md
+++ b/base/api-spotify/README.md
@@ -25,14 +25,19 @@ All of these are exercised by `host-cdp` live tests against a free account:
| Search | all, tracks, artists, albums, playlists, shows, episodes, audiobooks, users, genres, suggestions, recent, clear recent |
| Catalog | track, album, album tracks, artist, top tracks, discography, related artists, appears on, similar albums |
| Library | contains/add/remove, library list with filters, sort and folders, liked songs, pin/unpin, create/rename/delete folders, move to folder |
-| Playlists | playlist, tracks (paged, with row uids), mine, editable, create, rename, description, delete, follow/unfollow, add/remove/move tracks, recommended songs |
+| Playlists | playlist, tracks (paged, with row uids), sorted tracks (client side, ascending or descending), mine, editable, create, rename, description, public, collaborative, delete, follow/unfollow, add/remove/move tracks, recommended songs |
| Home | feed with filters, categories, category pages |
-| Podcasts | show, episodes, episode, audiobook, chapters, saved episodes |
+| Podcasts | show, episodes, episode, audiobook, chapters, saved episodes, save or unsave an episode |
| Users | me, public profile, top artists/tracks, follow/unfollow/is following, history |
-| Track extras | lyrics (line and word sync, colours), canvas, credits, radio for a track or artist, taste-profile exclusion |
+| Track extras | lyrics (line and word sync, colours), canvas, credits, radio for a track or artist, taste-profile exclusion, don't play this artist |
| Devices | list, transfer, pull here |
| Jam | availability, session, start, join, leave, end, invite link, remove member, queue-only, participant volume |
+Added without a live check (same mechanism as a verified neighbour, see the notes in
+[feature-inventory.md](../../docs/api/feature-inventory.md)): don't play this artist (`artistban`),
+save or unsave an episode (`listenlater`), public and collaborative (`PlaylistAPI.updateDetails`,
+read back with `getMetadata`). The full feature list, with what needs a capture, is in that file.
+
Limits seen on the Web Player with a free account:
- Jam: Spotify answers `RESTRICTED`, so `start` fails; join and the rest are wired but unverified.
- Private session: not supported by the Web Player (`isSupported: false`).
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 b0b4567e..56559be7 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
@@ -8,10 +8,12 @@ import app.myspoti.api.LibrarySort
import app.myspoti.api.MediaKind
import app.myspoti.api.Page
import app.myspoti.api.Playlist
+import app.myspoti.api.PlaylistSort
import app.myspoti.api.Playlists
import app.myspoti.api.SavedTrack
import app.myspoti.api.Track
import app.myspoti.api.Uri
+import app.myspoti.api.sortedFor
import app.myspoti.spotify.bridge.Bridge
import app.myspoti.spotify.bridge.service
import app.myspoti.spotify.gql.Gql
@@ -203,16 +205,20 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, private
return r.str("uri") ?: (r as? JsonPrimitive)?.content ?: throw GqlException("createPlaylist", "no uri")
}
- override suspend fun rename(uri: Uri, name: String) = updateDetails(uri, "name", name)
+ override suspend fun rename(uri: Uri, name: String) = updateDetails(uri, "name", JsonPrimitive(name))
- override suspend fun setDescription(uri: Uri, description: String) = updateDetails(uri, "description", description)
+ override suspend fun setDescription(uri: Uri, description: String) = updateDetails(uri, "description", JsonPrimitive(description))
+
+ override suspend fun setPublic(uri: Uri, public: Boolean) = updateDetails(uri, "public", JsonPrimitive(public))
+
+ override suspend fun setCollaborative(uri: Uri, collaborative: Boolean) = updateDetails(uri, "collaborative", JsonPrimitive(collaborative))
/** Two updates sent back to back can lose the second one: check it landed, and resend once. */
- private suspend fun updateDetails(uri: Uri, field: String, value: String) {
+ private suspend fun updateDetails(uri: Uri, field: String, value: JsonElement) {
repeat(2) {
bridge.service("PlaylistAPI", "updateDetails", JsonPrimitive(uri), json(mapOf(field to value)))
repeat(10) {
- if (bridge.service("PlaylistAPI", "getMetadata", JsonPrimitive(uri)).str(field) == value) return
+ if (bridge.service("PlaylistAPI", "getMetadata", JsonPrimitive(uri)).at(field) == value) return
kotlinx.coroutines.delay(300)
}
}
@@ -229,6 +235,19 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, private
bridge.service("RootlistAPI", "remove", json(listOf(mapOf("uri" to uri))))
}
+ /** Pages through the whole playlist (100 rows a request), then sorts it on the client. */
+ override suspend fun sortedTracks(uri: Uri, sort: PlaylistSort, descending: Boolean): List<Track> {
+ val all = mutableListOf<Track>()
+ var offset: Int? = 0
+ while (offset != null) {
+ val page = tracks(uri, offset, 100)
+ if (page.items.isEmpty()) break
+ all += page.items
+ offset = page.nextOffset
+ }
+ return all.sortedFor(sort, descending)
+ }
+
override suspend fun addTracks(uri: Uri, trackUris: List<Uri>) {
gql.query("addToPlaylist", vars(
"playlistItemUris" to trackUris, "playlistUri" to uri,
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt
index e211a4b9..f99262b7 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt
@@ -160,6 +160,11 @@ class SpotifyPodcasts(private val gql: Gql, private val bridge: Bridge) : Podcas
}.filterNotNull()
return Page(items, offset, saved.size, (offset + slice.size).takeIf { it < saved.size })
}
+
+ /** Saves or unsaves an episode in the `listenlater` set that [savedEpisodes] reads. */
+ override suspend fun setEpisodeSaved(uri: Uri, saved: Boolean) {
+ bridge.service("CollectionPlatformAPI", if (saved) "add" else "remove", JsonPrimitive("listenlater"), json(listOf(uri)))
+ }
}
class SpotifyUsers(private val gql: Gql, private val bridge: Bridge, private val http: SpotifyHttp) : Users {
@@ -290,10 +295,20 @@ class SpotifyTrackExtras(private val gql: Gql, private val bridge: Bridge, priva
bridge.service("CollectionPlatformAPI", if (excluded) "add" else "remove", JsonPrimitive("ignoreinrecs"), json(listOf(trackUri)))
}
+ override suspend fun isExcludedFromTaste(trackUris: List<Uri>): List<Boolean> = collectionContains("ignoreinrecs", trackUris)
+
+ /** "Don't play this artist" is the `artistban` collection set, written like the taste exclusion. */
+ override suspend fun setArtistBanned(artistUri: Uri, banned: Boolean) {
+ bridge.service("CollectionPlatformAPI", if (banned) "add" else "remove", JsonPrimitive("artistban"), json(listOf(artistUri)))
+ }
+
+ override suspend fun isArtistBanned(artistUris: List<Uri>): List<Boolean> = collectionContains("artistban", artistUris)
+
/** Asks the server: the page's own contains() answers from a cache that removals do not clear. */
- override suspend fun isExcludedFromTaste(trackUris: List<Uri>): List<Boolean> {
+ private suspend fun collectionContains(set: String, uris: List<Uri>): List<Boolean> {
+ if (uris.isEmpty()) return emptyList()
val username = bridge.service("UserAPI", "getUser").str("username") ?: throw GqlException("collection", "no user")
- val body = json(mapOf("username" to username, "set" to "ignoreinrecs", "items" to trackUris.map { mapOf("uri" to it) })).toString()
+ val body = json(mapOf("username" to username, "set" to set, "items" to uris.map { mapOf("uri" to it) })).toString()
val (code, text) = http.send("POST", "https://spclient.wg.spotify.com/collection/v2/contains?market=from_token", body, contentType = "application/json")
if (code != 200) throw app.myspoti.spotify.gql.HttpException(code, text.take(200))
return Bridge.json.parseToJsonElement(text).list("found").map { (it as? JsonPrimitive)?.content == "true" }
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlaylistSortTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlaylistSortTest.kt
new file mode 100644
index 00000000..75129751
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlaylistSortTest.kt
@@ -0,0 +1,54 @@
+package app.myspoti.spotify
+
+import app.myspoti.api.AlbumRef
+import app.myspoti.api.ArtistRef
+import app.myspoti.api.PlaylistSort
+import app.myspoti.api.Track
+import app.myspoti.api.sortedFor
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+
+/** Client-side playlist sort: the server has no sort parameter, so these rules are the whole behaviour. */
+class PlaylistSortTest {
+ private fun track(name: String, artist: String, album: String, ms: Long, added: String?) = Track(
+ uri = "spotify:track:$name",
+ name = name,
+ durationMs = ms,
+ artists = listOf(ArtistRef("spotify:artist:$artist", artist)),
+ album = AlbumRef("spotify:album:$album", album),
+ addedAt = added,
+ )
+
+ private val rows = listOf(
+ track("b-song", "Zed", "Gold", 200_000, "2026-03-01T10:00:00Z"),
+ track("A-song", "amy", "Blue", 180_000, null),
+ track("c-song", "Bob", "Gold", 200_000, "2026-01-05T08:00:00Z"),
+ )
+
+ private fun List<Track>.names() = map { it.name }
+
+ @Test fun `custom keeps the playlist order, reversed for descending`() {
+ assertEquals(listOf("b-song", "A-song", "c-song"), rows.sortedFor(PlaylistSort.CUSTOM).names())
+ assertEquals(listOf("c-song", "A-song", "b-song"), rows.sortedFor(PlaylistSort.CUSTOM, descending = true).names())
+ }
+
+ @Test fun `title ignores case`() {
+ assertEquals(listOf("A-song", "b-song", "c-song"), rows.sortedFor(PlaylistSort.TITLE).names())
+ assertEquals(listOf("c-song", "b-song", "A-song"), rows.sortedFor(PlaylistSort.TITLE, descending = true).names())
+ }
+
+ @Test fun `artist uses the first artist, ignoring case`() {
+ assertEquals(listOf("A-song", "c-song", "b-song"), rows.sortedFor(PlaylistSort.ARTIST).names())
+ }
+
+ @Test fun `album, and ties keep the playlist order in both directions`() {
+ assertEquals(listOf("A-song", "b-song", "c-song"), rows.sortedFor(PlaylistSort.ALBUM).names())
+ assertEquals(listOf("A-song", "b-song", "c-song"), rows.sortedFor(PlaylistSort.DURATION).names())
+ assertEquals(listOf("b-song", "c-song", "A-song"), rows.sortedFor(PlaylistSort.DURATION, descending = true).names())
+ }
+
+ @Test fun `date added puts rows without a date first`() {
+ assertEquals(listOf("A-song", "c-song", "b-song"), rows.sortedFor(PlaylistSort.ADDED_AT).names())
+ assertEquals(listOf("b-song", "c-song", "A-song"), rows.sortedFor(PlaylistSort.ADDED_AT, descending = true).names())
+ }
+}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt
new file mode 100644
index 00000000..63a0fc25
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt
@@ -0,0 +1,133 @@
+package app.myspoti.spotify
+
+import app.myspoti.api.PlaylistSort
+import app.myspoti.spotify.bridge.Bridge
+import app.myspoti.spotify.bridge.BridgeHost
+import app.myspoti.spotify.gql.Gql
+import app.myspoti.spotify.gql.SpotifyHttp
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import okhttp3.OkHttpClient
+import org.junit.jupiter.api.AfterEach
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+
+/** Answers each `Myspoti.call(id, method, args)` with [reply] and keeps every request it was sent. */
+private class RecordingHost(val reply: (JsonObject) -> JsonElement) : BridgeHost {
+ val calls = mutableListOf<JsonObject>()
+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)
+
+ override suspend fun evaluate(script: String) {
+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""").find(script) ?: return
+ val args = Bridge.json.parseToJsonElement(m.groupValues[3]).jsonObject
+ calls += args
+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":${reply(args)}}""")
+ }
+}
+
+/** Records each GraphQL request's variables and answers with [respond]. */
+private class FakeGql(val respond: (String, JsonObject) -> JsonElement) : Gql {
+ val variables = mutableListOf<JsonObject>()
+ override suspend fun query(name: String, variables: JsonObject): JsonElement {
+ this.variables += variables
+ return respond(name, variables)
+ }
+}
+
+private fun JsonObject.method() = this["method"]!!.jsonPrimitive.content
+private fun JsonObject.args() = this["args"]!!.jsonArray.toString()
+
+/** A `fetchPlaylistContents` answer holding rows `offset until min(total, offset + limit)`. */
+private fun playlistPage(total: Int, offset: Int, limit: Int): JsonElement {
+ val rows = (offset until minOf(total, offset + limit)).joinToString(",") { i ->
+ """{"uid":"u$i","addedAt":{"isoString":"2026-01-01T00:00:00Z"},"itemV2":{"__typename":"TrackResponseWrapper","data":
+ {"__typename":"Track","uri":"spotify:track:t$i","name":"Track ${"%03d".format(i)}","duration":{"totalMilliseconds":1000},
+ "artists":{"items":[{"uri":"spotify:artist:a","profile":{"name":"Artist"}}]},
+ "albumOfTrack":{"uri":"spotify:album:b","name":"Album"}}}}"""
+ }
+ return Bridge.json.parseToJsonElement("""{"data":{"playlistV2":{"__typename":"Playlist","content":{"totalCount":$total,"items":[$rows]}}}}""")
+}
+
+class SpotifyWritesTest {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ @AfterEach fun stop() = scope.cancel()
+
+ private fun runBridge(reply: (JsonObject) -> JsonElement, block: suspend (RecordingHost, Bridge) -> Unit) = runBlocking {
+ val host = RecordingHost(reply)
+ val bridge = Bridge(host, scope)
+ host.messages.subscriptionCount.first { it > 0 }
+ block(host, bridge)
+ }
+
+ @Test fun `don't play this artist writes the artistban set and nothing else`() = runBridge({ JsonNull }) { host, bridge ->
+ val extras = SpotifyTrackExtras(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))
+ extras.setArtistBanned("spotify:artist:a", true)
+ extras.setArtistBanned("spotify:artist:a", false)
+ assertEquals(listOf("add", "remove"), host.calls.map { it.method() })
+ assertEquals("""["artistban",["spotify:artist:a"]]""", host.calls[0].args())
+ assertEquals("CollectionPlatformAPI", host.calls[0]["service"]!!.jsonPrimitive.content)
+ }
+
+ @Test fun `saving an episode uses the listenlater set that savedEpisodes reads`() = runBridge({ JsonNull }) { host, bridge ->
+ val podcasts = SpotifyPodcasts(FakeGql { _, _ -> JsonNull }, bridge)
+ podcasts.setEpisodeSaved("spotify:episode:e", true)
+ podcasts.setEpisodeSaved("spotify:episode:e", false)
+ assertEquals(listOf("add", "remove"), host.calls.map { it.method() })
+ assertEquals("""["listenlater",["spotify:episode:e"]]""", host.calls[0].args())
+ }
+
+ @Test fun `public and collaborative send the flag and check it landed`() = runBridge({ call ->
+ when (call.method()) {
+ "getMetadata" -> Bridge.json.parseToJsonElement("""{"public":true,"collaborative":false,"name":"x"}""")
+ else -> JsonNull
+ }
+ }) { host, bridge ->
+ val playlists = SpotifyPlaylists(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))
+ playlists.setPublic("spotify:playlist:p", true)
+ playlists.setCollaborative("spotify:playlist:p", false)
+ val updates = host.calls.filter { it.method() == "updateDetails" }.map { it.args() }
+ assertEquals(
+ listOf("""["spotify:playlist:p",{"public":true}]""", """["spotify:playlist:p",{"collaborative":false}]"""),
+ updates,
+ )
+ }
+
+ @Test fun `rename still sends the name as a string`() = runBridge({ call ->
+ if (call.method() == "getMetadata") Bridge.json.parseToJsonElement("""{"name":"New"}""") else JsonNull
+ }) { host, bridge ->
+ val playlists = SpotifyPlaylists(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))
+ playlists.rename("spotify:playlist:p", "New")
+ assertEquals("""["spotify:playlist:p",{"name":"New"}]""", host.calls.first { it.method() == "updateDetails" }.args())
+ }
+
+ @Test fun `sorted tracks read every page of 100 and sort on the client`() = runBridge({ JsonNull }) { _, bridge ->
+ val gql = FakeGql { _, v ->
+ playlistPage(250, v["offset"]!!.jsonPrimitive.content.toInt(), v["limit"]!!.jsonPrimitive.content.toInt())
+ }
+ val playlists = SpotifyPlaylists(gql, bridge, SpotifyHttp(OkHttpClient(), bridge))
+ val sorted = playlists.sortedTracks("spotify:playlist:p", PlaylistSort.TITLE, descending = true)
+ assertEquals(listOf("0", "100", "200"), gql.variables.map { it["offset"]!!.jsonPrimitive.content })
+ assertEquals(250, sorted.size)
+ assertEquals("Track 249", sorted.first().name)
+ assertEquals("Track 000", sorted.last().name)
+ }
+
+ @Test fun `custom sort keeps the playlist's own order`() = runBridge({ JsonNull }) { _, bridge ->
+ val gql = FakeGql { _, v -> playlistPage(3, 0, v["limit"]!!.jsonPrimitive.content.toInt()) }
+ val playlists = SpotifyPlaylists(gql, bridge, SpotifyHttp(OkHttpClient(), bridge))
+ assertEquals(listOf("u0", "u1", "u2"), playlists.sortedTracks("spotify:playlist:p").map { it.uid })
+ assertEquals(listOf("u2", "u1", "u0"), playlists.sortedTracks("spotify:playlist:p", PlaylistSort.CUSTOM, true).map { it.uid })
+ }
+}
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 b6989088..c8e3bad4 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
@@ -123,6 +123,8 @@ interface Library {
interface Playlists {
suspend fun playlist(uri: Uri): Playlist
suspend fun tracks(uri: Uri, offset: Int = 0, limit: Int = 100): Page<Track>
+ /** Every row, sorted on the client (the server has no sort). Use [sortedFor] to sort rows already loaded. */
+ suspend fun sortedTracks(uri: Uri, sort: PlaylistSort = PlaylistSort.CUSTOM, descending: Boolean = false): List<Track>
/** The user's own playlists and the ones they follow, in library order, folders flattened. */
suspend fun mine(): List<Playlist>
/** Playlists the user may add tracks to. */
@@ -132,6 +134,10 @@ interface Playlists {
suspend fun create(name: String, folderUri: Uri? = null): Uri
suspend fun rename(uri: Uri, name: String)
suspend fun setDescription(uri: Uri, description: String)
+ /** Public playlists show on the profile and in search; private ones only to the owner. */
+ suspend fun setPublic(uri: Uri, public: Boolean)
+ /** Collaborative playlists let other users add and remove tracks (owner only). */
+ suspend fun setCollaborative(uri: Uri, collaborative: Boolean)
/** Removes the playlist from the library (owners: deletes it; it can be restored for 90 days). */
suspend fun delete(uri: Uri)
suspend fun follow(uri: Uri)
@@ -161,6 +167,7 @@ interface Podcasts {
suspend fun chapters(uri: Uri, offset: Int = 0, limit: Int = 50): Page<Episode>
/** Episodes the user saved ("Your Episodes"). */
suspend fun savedEpisodes(offset: Int = 0, limit: Int = 50): Page<Episode>
+ suspend fun setEpisodeSaved(uri: Uri, saved: Boolean)
}
interface Users {
@@ -185,6 +192,9 @@ interface TrackExtras {
/** Hide this track from recommendations, or show it again. */
suspend fun setExcludedFromTaste(trackUri: Uri, excluded: Boolean)
suspend fun isExcludedFromTaste(trackUris: List<Uri>): List<Boolean>
+ /** "Don't play this artist": the artist is kept out of recommendations and radios. */
+ suspend fun setArtistBanned(artistUri: Uri, banned: Boolean)
+ suspend fun isArtistBanned(artistUris: List<Uri>): List<Boolean>
}
interface Devices {
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Models.kt b/base/api/src/main/kotlin/app/myspoti/api/Models.kt
index 4baf953b..dbdaf14e 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Models.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Models.kt
@@ -60,6 +60,25 @@ data class Playlist(
val followers: Long? = null,
)
+/** Client-side orders for a playlist's rows. [CUSTOM] is the playlist's own order. */
+enum class PlaylistSort { CUSTOM, TITLE, ARTIST, ALBUM, ADDED_AT, DURATION }
+
+/**
+ * Sorts playlist rows the way the Web Player's sort menu does. The server has no sort
+ * parameter, so this runs on rows already loaded. Ties keep the playlist's own order.
+ */
+fun List<Track>.sortedFor(sort: PlaylistSort, descending: Boolean = false): List<Track> {
+ val order: Comparator<Track> = when (sort) {
+ PlaylistSort.CUSTOM -> return if (descending) asReversed() else this
+ PlaylistSort.TITLE -> compareBy<Track> { it.name.lowercase() }
+ PlaylistSort.ARTIST -> compareBy<Track> { it.artists.firstOrNull()?.name?.lowercase() ?: "" }
+ PlaylistSort.ALBUM -> compareBy<Track> { it.album?.name?.lowercase() ?: "" }
+ PlaylistSort.ADDED_AT -> compareBy<Track> { it.addedAt ?: "" }
+ PlaylistSort.DURATION -> compareBy<Track> { it.durationMs }
+ }
+ return sortedWith(if (descending) order.reversed() else order)
+}
+
/** One page of a longer list. [nextOffset] is null on the last page. */
data class Page<T>(val items: List<T>, val offset: Int, val total: Int, val nextOffset: Int?)
diff --git a/docs/api/feature-inventory.md b/docs/api/feature-inventory.md
new file mode 100644
index 00000000..08e79ca0
--- /dev/null
+++ b/docs/api/feature-inventory.md
@@ -0,0 +1,164 @@
+# Web Player feature inventory
+
+What open.spotify.com offers, and what `:api` exposes for it. One row per feature.
+
+Status:
+- **exposed**: in `:api` before this change, through a mechanism that was captured or already used.
+- **added now**: new in `:api` with this change. The write path follows the same mechanism as a verified
+ neighbour, but was not run against a live page; see the note on the row.
+- **needs capture**: the feature exists, but its operation or endpoint is not known well enough to call
+ (no response shape, no variables, or no name in the bundle). Not guessed.
+- **not possible**: the Web Player does not offer it, or it is refused for this account.
+- **needs Premium**: Spotify limits it to Premium. Skipped. No row uses it yet, because no row was verified as Premium-only.
+- **not in :api**: documented under `docs/api`, but not exposed by the `:api` interfaces yet.
+
+Operation names are GraphQL operations (`gql`, sent by name and hash from `gql-ops.json`) unless marked
+as a page service (`service: Name.method`, through the bridge) or an HTTP endpoint.
+
+## Playback
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Play a context, from a track, index or position | exposed | `player.play` (bridge) |
+| Play a sorted playlist in a chosen order | exposed | `Player.play(order)` |
+| Pause, resume, seek, next, previous | exposed | `player.*` (bridge) |
+| Shuffle, repeat | exposed | `player.setShuffle`, `player.setRepeat` (bridge) |
+| Queue: add, remove, clear, play next, reorder, jump to | exposed | `queue.*` (bridge) |
+| Volume | exposed | `volume.get`, `volume.set` (bridge) |
+| Podcast speed | exposed | `Player.setSpeed` (bridge) |
+| Smart shuffle | needs capture | `smartShuffle` (not wired; its Premium status is not verified) |
+
+## Search
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Top results, tracks, artists, albums, playlists | exposed | `searchTopResultsList`, `searchTracks`, `searchArtists`, `searchAlbums`, `searchPlaylists` |
+| Shows, episodes, audiobooks, genres | exposed | `searchPodcasts`, `searchFullEpisodes`, `searchAudiobooks`, `searchGenres` |
+| Profile (user) search | exposed | `searchUsers` (`Search.users`) |
+| Suggestions while typing | exposed | `searchSuggestions` |
+| Recent searches, clear them | exposed | `recentSearches`, `removeRecentSearches` |
+
+## Catalog and artists
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Track, album, album tracks | exposed | `getTrack`, `getAlbum`, `queryAlbumTracks` |
+| Artist page (overview, top tracks, popular releases, biography) | exposed | `queryArtistOverview` |
+| Full discography (all types, newest first) | exposed | `queryArtistDiscographyAll` |
+| Discography split into albums, singles, compilations | needs capture | `queryArtistDiscographyAlbums`, `...Singles`, `...Compilations` (variables known; response shape not documented) |
+| Appears on | exposed | `queryArtistAppearsOn` |
+| Fans also like (related artists) | exposed | `queryArtistRelated` |
+| Similar albums ("more like this") | exposed | `similarAlbumsBasedOnThisTrack` |
+| Artist playlists | needs capture | `queryArtistPlaylists` (no response shape documented) |
+| Featuring | needs capture | `queryArtistFeaturing` (no response shape documented) |
+| Discovered on | needs capture | `queryArtistDiscoveredOn` |
+| Artist "About" modal (more than the biography) | needs capture | `queryArtistAboutModal` |
+| Artist concerts | needs capture | `ArtistConcerts`, `concertFeed`, `concert`, `venue` (variables known for some; no response shape) |
+| Related videos (artist) | needs capture | `queryArtistRelatedVideos` (variables known; no response shape) |
+| Album merch | needs capture | `queryAlbumMerch` (documented as merch only, no response shape) |
+| Monthly listeners, followers, verified badge | exposed | `queryArtistOverview` |
+| ISRC of a track | exposed | spclient `metadata/4/track/{hex}` |
+| Track credits | exposed | `queryTrackCreditsGroupedModal` |
+| Lyrics, line and word sync, colours | exposed | spclient `color-lyrics/v2` |
+| Canvas (looping video) | exposed | `canvas` |
+| Track radio, artist radio | exposed | spclient `inspiredby-mix/v2/seed_to_playlist` |
+| Track page "More like this" albums | exposed | `similarAlbumsBasedOnThisTrack` |
+| Now-playing supplemental sections (related videos, related tracks) | needs capture | `npvV2TrackSupplementalSections`, `queryNpvArtist` (variables known; response shape not documented) |
+
+## Your Library
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Library list with filters (playlists, artists, albums, podcasts, audiobooks) | exposed | `libraryV3` (`filters`) |
+| Library sort: recents, recently added, alphabetical, creator | exposed | `libraryV3` (`order`) |
+| Recently played (the Recents list) | exposed | `RecentlyPlayedAPI.getContexts` (service); `recents` not used |
+| Recently played tracks | needs capture | `recents` (variables known; response not documented) |
+| Liked Songs: list, add, remove, check | exposed | `fetchLibraryTracks` (list); `Library.add/remove` (`library.add`, `library.remove`); `Library.contains` |
+| Follow or save artists, albums, shows, playlists | exposed | `library.add`, `library.remove` (bridge `LibraryAPI`); `Library.contains` |
+| Pin and unpin items | exposed | `pinLibraryItem`, `unpinLibraryItem` |
+| Folders: create (top level or inside a folder), rename, delete | exposed | `RootlistAPI.createFolder`, `renameFolder`, `removeFolder` (service) |
+| Move playlists and folders into a folder | exposed | `RootlistAPI.move`, `moveFolder` (service) |
+| Library changes (this device, and others through dealer pushes) | exposed | `Library.changes` flow |
+| Filter by a text query inside the library | needs capture | `libraryV3` `textFilter` is sent empty; the Web Player's own search box is not captured |
+| Custom order of your own library (drag) | needs capture | rootlist `ops` order (not captured) |
+
+## Playlists
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Playlist page and rows (paged, with row ids) | exposed | `fetchPlaylist`, `fetchPlaylistContents` |
+| Playlist metadata and permissions | not in :api | `fetchPlaylistMetadata`, `playlistPermissions` (shapes in `LIBRARY.md`) |
+| My playlists, playlists I can edit | exposed | rootlist (`RootlistAPI.getContents`); `editablePlaylists` documented |
+| Create a playlist (top level or inside a folder) | exposed | `RootlistAPI.createPlaylist` (service) |
+| Rename | exposed | `PlaylistAPI.updateDetails` (service), checked with `getMetadata` |
+| Description | exposed | `PlaylistAPI.updateDetails` |
+| Public or private | added now | `PlaylistAPI.updateDetails` with `public`, checked with `getMetadata`. Not run live: the read-back may not return the field |
+| Collaborative | added now | `PlaylistAPI.updateDetails` with `collaborative`, same caveat as public |
+| Cover image upload and removal | needs capture | not captured |
+| Add tracks | exposed | `addToPlaylist` |
+| Remove tracks | exposed | `removeFromPlaylist` (by row uid) |
+| Reorder tracks | exposed | `moveItemsInPlaylist` (`BOTTOM_OF_PLAYLIST` and `BEFORE_UID`) |
+| Hide a song in a playlist (Spotify's "Hide song") | needs capture | no operation name in the bundle table and no endpoint captured |
+| Sort the playlist (title, artist, album, date added, duration) with ascending or descending | added now | client side: `Playlists.sortedTracks` reads every page and sorts. The server has no sort parameter |
+| Playlist order as the playback order | exposed | `Player.play(order)` |
+| Delete a playlist | exposed | rootlist `REM` (`Playlists.delete`); for owned playlists the Web Player may do more, not confirmed |
+| Follow and unfollow a playlist | exposed | rootlist changes (`RootlistAPI.add/remove`) |
+| Recommended songs under a playlist | exposed | spclient `playlistextender/extendp` |
+
+## Podcasts and audiobooks
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Show page, episodes, episode, chapters | exposed | `queryShowMetadataV2`, `queryPodcastEpisodes`, `getEpisodeOrChapter`, `queryBookChapters` |
+| Audiobook page | exposed | `queryShowMetadataV2` (union), `getAudiobooksMetadata` not used |
+| Follow or unfollow a show | exposed | `library.add`, `library.remove` |
+| Saved episodes (Your Episodes) | exposed | `CollectionPlatformAPI.get('listenlater')` |
+| Save or unsave an episode | added now | `CollectionPlatformAPI.add/remove('listenlater')`, the set the list reads. Not run live |
+| Played state of episodes | exposed | episode `playedState` in the page data |
+
+## Users and social
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Me (account, country, plan) | exposed | `profileAttributes`, `accountAttributes` |
+| Public profile: name, avatar, follower and following counts, public playlists | exposed | spclient `user-profile-view/v3/profile/{id}` |
+| Follow and unfollow users, check follow state | exposed | `followUsers`, `unfollowUsers`, `isFollowingUsers` |
+| Followers list and following list of a user | needs capture | no operation or endpoint captured |
+| Top artists and tracks (per time range) | exposed | `userTopContent` |
+| Friend activity | not possible | the Web Player has no friend feed; `friendActivity()` returns an empty list |
+| Private session | not possible | the Web Player reports `isSupported: false`; `setPrivateSession` throws |
+| Comments and reactions on entities | needs capture | `getCommentsForEntity`, `addComment`, `addCommentReaction` and others (not wired) |
+
+## Taste and preferences
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Hide a track from recommendations (taste profile exclusion) | exposed | `CollectionPlatformAPI.add/remove('ignoreinrecs')`; check `collection/v2/contains` |
+| Don't play this artist | added now | `CollectionPlatformAPI.add/remove('artistban')`, same mechanism as the taste exclusion; check `collection/v2/contains` with set `artistban`. Not run live |
+| Home filters (music, podcasts, audiobooks) | exposed | `home` (`facet`) |
+
+## Home and browse
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Home feed and shelves | exposed | `home` |
+| Made for you and blends | exposed as shelves of the home feed, not checked one by one | `home` |
+| What's new (from followed artists) | exposed | `queryWhatsNewFeed` |
+| Browse categories and category pages | exposed | `browseAll`, `browsePage` |
+| Country hubs | needs capture | `countryHubsPage`, `countryHubContent` |
+
+## Devices and Jam
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Connect devices: list, transfer, pull here | exposed | `ConnectDevicesAPI.getDevices`, `ConnectTransferAPI` (service) |
+| Jam: start, join, leave, end, invite link, remove member, queue-only | exposed (restricted) | `SocialConnectAPI` (service). Free accounts get `RESTRICTED`, so start is refused |
+| Jam on a free account | not possible | Spotify answers `RESTRICTED` |
+
+## Other
+
+| Feature | Status | Operation / endpoint |
+|---|---|---|
+| Ads | out of scope | the host blocks ad audio (`AdBlock`); no API surface |
+| Concert location settings | needs capture | `saveLocation`, `deleteLocation`, `concertLocationsByLatLon` (not wired) |
+| Promo codes | needs capture | `requestPromoCode` (not wired) |