Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Library podcasts (#136): the podcasts filter is the id the account's library offers, and shows filed in folders are read too
kota-zo9d8ba2e36ebe
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.ktindex 9f491db8..b0f6024c 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@@ -33,6 +33,16 @@ import kotlinx.serialization.json.jsonPrimitiveprivate fun uris(list: List<Uri>) = json(mapOf("uris" to list))+/**+ * The id of the shows filter among the [offered] ids of the library (`availableFilters`: the ids are+ * fixed words, the names are localised). "Podcasts" when none offered looks like one: that is the+ * id the app sent before, and an id the server does not know fails the whole list (#136).+ */+internal fun podcastFilterId(offered: List<String>): String =+ offered.firstOrNull { it.equals("Podcasts", ignoreCase = true) }+ ?: offered.firstOrNull { id -> listOf("podcast", "show").any { id.contains(it, ignoreCase = true) } }+ ?: "Podcasts"+class SpotifyLibrary(private val bridge: Bridge, private val gql: Gql) : Library {private val _changes = MutableSharedFlow<Unit>(extraBufferCapacity = 8)override val changes: SharedFlow<Unit> = _changes@@ -75,9 +85,12 @@ class SpotifyLibrary(private val bridge: Bridge, private val gql: Gql) : Librarybridge.call("library.remove", uris(uris) as kotlinx.serialization.json.JsonObject); changed()}- override suspend fun items(filter: LibraryFilter, sort: LibrarySort, folderUri: Uri?, offset: Int, limit: Int): Page<LibraryItem> {+ /** The filter ids the account's library offers, from its last list answer (`availableFilters`). */+ @Volatile private var offeredFilters: List<String>? = null++ private suspend fun libraryV3(filters: List<String>, sort: LibrarySort, folderUri: Uri?, offset: Int, limit: Int): JsonElement {val lib = gql.query("libraryV3", vars(- "filters" to listOfNotNull(filter.id),+ "filters" to filters,"order" to sort.id,"textFilter" to "","features" to listOf("LIKED_SONGS", "YOUR_EPISODES_V2", "PRERELEASES", "PRERELEASES_V2", "CLIPS", "EVENTS"),@@ -85,6 +98,21 @@ class SpotifyLibrary(private val bridge: Bridge, private val gql: Gql) : Library"flatten" to false, "expandedFolders" to emptyList<String>(),"folderUri" to folderUri, "includeFoldersWhenFlattening" to true,)).entity("data.me.libraryV3", "libraryV3")+ offeredFilters = lib.list("availableFilters").mapNotNull { it.str("id") }+ return lib+ }++ /** The offered filter ids; one short unfiltered read when no list answer was seen yet. */+ private suspend fun offeredFilterIds(): List<String> {+ offeredFilters?.let { return it }+ libraryV3(emptyList(), LibrarySort.RECENTS, null, 0, 1)+ return offeredFilters.orEmpty()+ }++ override suspend fun items(filter: LibraryFilter, sort: LibrarySort, folderUri: Uri?, offset: Int, limit: Int): Page<LibraryItem> {+ // The shows filter's id is not fixed: the account is offered the one Spotify knows (#136).+ val filterId = if (filter == LibraryFilter.PODCASTS) podcastFilterId(offeredFilterIds()) else filter.id+ val lib = libraryV3(listOfNotNull(filterId), sort, folderUri, offset, limit)val rows = lib.list("items")val items = rows.mapNotNull { row ->val c = card(row.at("item")) ?: return@mapNotNull nulldiff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyLibraryTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyLibraryTest.ktnew file mode 100644index 00000000..d6803c31--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyLibraryTest.kt@@ -0,0 +1,86 @@+package app.myspoti.spotify++import app.myspoti.api.LibraryFilter+import app.myspoti.api.LibrarySort+import app.myspoti.api.MediaKind+import app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.bridge.BridgeHost+import app.myspoti.spotify.gql.Gql+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.Flow+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonPrimitive+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Test++/** A host that never answers: the library reads do not go through the bridge. */+private class SilentHost : BridgeHost {+ override val messages: Flow<String> = MutableSharedFlow(extraBufferCapacity = 1)+ override suspend fun evaluate(script: String) {}+}++/** Records each GraphQL request's variables and answers with [respond]. */+private class LibraryGql(val respond: (JsonObject) -> JsonElement) : Gql {+ val filters = mutableListOf<List<String>>()+ override suspend fun query(name: String, variables: JsonObject): JsonElement {+ filters += variables["filters"]!!.jsonArray.map { it.jsonPrimitive.content }+ return respond(variables)+ }+}++/**+ * A libraryV3 answer: [offered] are the account's filter ids; [shows] the show rows, unless the+ * request asked for a filter other than [acceptedFilter] (then the server answers no rows at all).+ */+private fun libraryAnswer(variables: JsonObject, offered: List<String>, acceptedFilter: String?, shows: List<String>): JsonElement {+ val filters = variables["filters"]!!.jsonArray.map { it.jsonPrimitive.content }+ val asked = filters.firstOrNull()+ val answersRows = asked == null || asked == acceptedFilter+ val offeredJson = offered.joinToString(",") { """{"id":"$it","name":"$it"}""" }+ val rows = if (!answersRows) "" else shows.joinToString(",") { uri ->+ """{"addedAt":{"isoString":"2026-01-01T00:00:00Z"},"depth":0,"pinned":false,"item":{"__typename":"PodcastResponseWrapper",+ "_uri":"$uri","data":{"__typename":"Podcast","uri":"$uri","name":"Show ${uri.substringAfterLast(':')}",+ "publisher":{"name":"Publisher"},"coverArt":{"sources":[]}}}}"""+ }+ return Bridge.json.parseToJsonElement("""{"data":{"me":{"libraryV3":{"__typename":"LibraryPage",+ "availableFilters":[$offeredJson],"items":[$rows],"totalCount":${if (answersRows) shows.size else 0}}}}}""")+}++class SpotifyLibraryTest {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ @AfterEach fun stop() = scope.cancel()++ @Test fun `the shows filter is the id the account is offered`() {+ assertEquals("Podcasts", podcastFilterId(listOf("Playlists", "Artists", "Albums")))+ assertEquals("Podcasts & Shows", podcastFilterId(listOf("Playlists", "Podcasts & Shows", "Artists")))+ assertEquals("Shows", podcastFilterId(listOf("Playlists", "Shows")))+ assertEquals("Podcasts", podcastFilterId(emptyList()))+ }++ @Test fun `the podcasts chip reads the shows under the offered id`() {+ val gql = LibraryGql { v -> libraryAnswer(v, listOf("Playlists", "Podcasts & Shows"), "Podcasts & Shows", listOf("spotify:show:s1", "spotify:show:s2")) }+ val library = SpotifyLibrary(Bridge(SilentHost(), scope), gql)+ val page = kotlinx.coroutines.runBlocking {+ library.items(LibraryFilter.PODCASTS, LibrarySort.RECENTS, null, 0, 50)+ }+ // One short read to learn the offered ids, then the filtered list.+ assertEquals(listOf(emptyList(), listOf("Podcasts & Shows")), gql.filters)+ assertEquals(listOf("spotify:show:s1", "spotify:show:s2"), page.items.map { it.uri })+ assertEquals(setOf(MediaKind.SHOW), page.items.map { it.kind }.toSet())+ }++ @Test fun `an account without a shows filter keeps the default id`() {+ val gql = LibraryGql { v -> libraryAnswer(v, listOf("Playlists", "Artists"), "Podcasts", emptyList()) }+ val library = SpotifyLibrary(Bridge(SilentHost(), scope), gql)+ kotlinx.coroutines.runBlocking { library.items(LibraryFilter.PODCASTS, LibrarySort.RECENTS, null, 0, 50) }+ assertEquals(listOf(emptyList(), listOf("Podcasts")), gql.filters)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.ktindex c2b74be7..ef43a9ae 100644--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt@@ -350,20 +350,27 @@ class Api constructor(return Result.success(listOf(news) + out)}- /** The shows of the library list read with [filter], page after page; failing on a first page that fails. */- private suspend fun readShows(filter: LibraryFilter): Result<List<app.myspoti.api.LibraryItem>> {+ /**+ * The shows of the library list read with [filter], page after page, and of the folders in it+ * (a show filed in a folder is only listed inside it), three levels down at most; failing on+ * a first page that fails.+ */+ private suspend fun readShows(filter: LibraryFilter, folderUri: String? = null, depth: Int = 0): Result<List<app.myspoti.api.LibraryItem>> {val out = ArrayList<app.myspoti.api.LibraryItem>()+ val folders = ArrayList<String>()var offset = 0while (true) {- val page = runCatching { api.library.items(filter = filter, offset = offset, limit = 50) }.getOrElse {+ val page = runCatching { api.library.items(filter = filter, folderUri = folderUri, offset = offset, limit = 50) }.getOrElse {if (it is CancellationException) throw it- Log.e("Api", "getFollowedShows ($filter) failed at $offset", it)+ Log.e("Api", "getFollowedShows ($filter${folderUri?.let { f -> " in $f" }.orEmpty()}) failed at $offset", it)if (offset == 0) return Result.failure(it)null} ?: breakout += page.items.filter { it.kind == MediaKind.SHOW }+ folders += page.items.filter { it.kind == MediaKind.FOLDER }.map { it.uri }offset = page.nextOffset ?: break}+ if (depth < 3) folders.distinct().forEach { f -> readShows(filter, f, depth + 1).getOrNull()?.let { out += it } }return Result.success(out.distinctBy { it.uri })}