Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Network: lists paged four at a time, a hardened API client, ops looked at every 6 h, covers wait 10 s
kota-zoa66956acd741
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.ktindex c053d8d7..9931d857 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/GqlOpsUpdater.kt@@ -30,8 +30,26 @@ class GqlOpsUpdater(private val http: OkHttpClient, private val cache: File) {/** The cached table if any, else the bundled one. */fun load(): GqlOps = runCatching { parse(cache.readText()) }.getOrNull() ?: GqlOps.bundled()- /** Fetches the current build; returns a new table when it changed, else null. */- suspend fun refresh(current: GqlOps): GqlOps? = withContext(Dispatchers.IO) {+ /** When the build was last looked at (a file beside the table). */+ private val checked = File(cache.path + ".checked")++ /**+ * Whether a look at the current build is due: not within [minGapMs] of the last one. Every cold+ * start fetched open.spotify.com before (and every Spotify build its ~6 MB of bundles), next to+ * the page loading the same; Spotify ships a build about a day.+ */+ fun due(now: Long = System.currentTimeMillis(), minGapMs: Long = CHECK_GAP_MS): Boolean {+ val last = runCatching { checked.readText().trim().toLong() }.getOrNull() ?: return true+ return now - last !in 0 until minGapMs+ }++ /**+ * Fetches the current build; returns a new table when it changed, else null. Without+ * [bundlesAllowed] (a metered network) a changed build is only noted: its bundles are read on+ * the next look on Wi-Fi, the table in use meanwhile (an unknown operation falls back to the+ * page, see BridgeGql).+ */+ suspend fun refresh(current: GqlOps, bundlesAllowed: Boolean = true, now: Long = System.currentTimeMillis()): GqlOps? = withContext(Dispatchers.IO) {val html = get("https://open.spotify.com/")val build = script(html, "appServerConfig")?.let { (it["buildVersion"] as? JsonPrimitive)?.content }val urls = LinkedHashSet<String>()@@ -47,8 +65,12 @@ class GqlOpsUpdater(private val http: OkHttpClient, private val cache: File) {.joinToString("") { "%02x".format(it) }val cached = runCatching { Bridge.json.parseToJsonElement(cache.readText()).jsonObject }.getOrNull()val cachedBuild = cached?.get("buildVersion")?.jsonPrimitive?.content- if (build != null && build == cachedBuild) return@withContext null- if (build == null && bundleKey == cached?.get("bundleKey")?.jsonPrimitive?.content) return@withContext null+ if ((build != null && build == cachedBuild) || (build == null && bundleKey == cached?.get("bundleKey")?.jsonPrimitive?.content)) {+ markChecked(now)+ return@withContext null+ }+ // A new build on mobile data: not marked checked, so the next look (on Wi-Fi) reads it.+ if (!bundlesAllowed) return@withContext nullval found = HashMap<String, String>()val gate = Semaphore(6)coroutineScope {@@ -64,9 +86,12 @@ class GqlOpsUpdater(private val http: OkHttpClient, private val cache: File) {}cache.parentFile?.mkdirs()cache.writeText(json.toString())+ markChecked(now)GqlOps(merged)}+ private fun markChecked(now: Long) { runCatching { cache.parentFile?.mkdirs(); checked.writeText(now.toString()) } }+private fun parse(text: String): GqlOps {val ops = Bridge.json.parseToJsonElement(text).jsonObject["operations"] as? JsonObject ?: throw GqlException("ops", "no operations in the table")return GqlOps(ops.mapValues { (name, op) ->@@ -89,6 +114,9 @@ class GqlOpsUpdater(private val http: OkHttpClient, private val cache: File) {}companion object {+ /** The least time between two looks at Spotify's current build. */+ const val CHECK_GAP_MS = 6 * 3_600_000L+private val BUNDLE = Regex("https://open\\.spotifycdn\\.com/cdn/build/web-player/[^\"']+?\\.js")private val OP = Regex("new [\\w$]+(?:\\.[\\w$]+)?\\(\"(\\w+)\",\"(query|mutation|subscription)\",\"([0-9a-f]{64})\"")}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/gql/GqlOpsUpdaterTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/gql/GqlOpsUpdaterTest.ktnew file mode 100644index 00000000..1ff5e15e--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/gql/GqlOpsUpdaterTest.kt@@ -0,0 +1,54 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package app.myspoti.spotify.gql++import kotlinx.coroutines.runBlocking+import okhttp3.Interceptor+import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBody+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertFalse+import org.junit.jupiter.api.Assertions.assertNotNull+import org.junit.jupiter.api.Assertions.assertNull+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.Test+import org.junit.jupiter.api.io.TempDir+import java.io.File++/** The build is looked at every 6 h at most, and a new build's bundles wait for a network that is not metered. */+class GqlOpsUpdaterTest {+ @TempDir lateinit var dir: File++ private val hash = "a".repeat(64)+ private var build = "b1"+ private val asked = mutableListOf<String>()+ private val http = OkHttpClient.Builder().addInterceptor(Interceptor { chain ->+ val r = chain.request(); asked += r.url.toString()+ val body = if (r.url.host == "open.spotify.com")+ """<script id="appServerConfig" type="text/plain">{"buildVersion":"$build"}</script>+ <script src="https://open.spotifycdn.com/cdn/build/web-player/web-player.x1.js"></script>"""+ else """x=new A("fetchLibraryTracks","query","$hash")"""+ Response.Builder().request(r).protocol(Protocol.HTTP_1_1).code(200).message("OK").body(body.toResponseBody()).build()+ }).build()++ @Test fun lookedAtEverySixHoursAndBundlesOffMeteredNetworks() = runBlocking {+ val u = GqlOpsUpdater(http, File(dir, "gql-ops.json"))+ val ops = GqlOps(mapOf("fetchLibraryTracks" to "0".repeat(64)))+ assertTrue(u.due(now = 0))+ // Metered: the new build is seen, its bundles are not read and the look stays due.+ assertNull(u.refresh(ops, bundlesAllowed = false, now = 1_000))+ assertEquals(1, asked.count { "spotifycdn" !in it }); assertEquals(0, asked.count { "spotifycdn" in it })+ assertTrue(u.due(now = 2_000))+ // On Wi-Fi: read, then not due for 6 h.+ val fresh = u.refresh(ops, bundlesAllowed = true, now = 3_000)+ assertNotNull(fresh); assertEquals(hash, fresh!!.hash("fetchLibraryTracks"))+ assertFalse(u.due(now = 3_000 + GqlOpsUpdater.CHECK_GAP_MS - 1))+ assertTrue(u.due(now = 3_000 + GqlOpsUpdater.CHECK_GAP_MS))+ // Same build later: nothing downloaded beyond the page, and marked checked.+ asked.clear()+ assertNull(u.refresh(fresh, bundlesAllowed = false, now = 30_000_000))+ assertEquals(0, asked.count { "spotifycdn" in it })+ assertFalse(u.due(now = 30_000_001))+ }+}diff --git a/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt b/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.ktindex 921bcf66..bf55ff2e 100644--- a/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt+++ b/base/app/src/main/java/com/music/spotui/data/DataSaverGlide.kt@@ -22,6 +22,7 @@ import java.io.InputStreamobject DataSaverGlide {/** Glide's default is 250 MB; covers are small, so the cache stays at 150 MB. */private const val DISK_CACHE_BYTES = 150L * 1024 * 1024+ private const val TIMEOUT_MS = 10_000fun install(context: Context) {// Before the first Glide.get: no annotation processor here, so the default builder is replaced by hand.@@ -37,7 +38,10 @@ object DataSaverGlide {private class Loader(private val inner: ModelLoader<GlideUrl, InputStream>) : ModelLoader<GlideUrl, InputStream> {override fun buildLoadData(model: GlideUrl, width: Int, height: Int, options: Options): ModelLoader.LoadData<InputStream>? {- val data = inner.buildLoadData(model, width, height, options) ?: return null+ // Glide waits 2.5 s to connect and 2.5 s per read, then gives up for good: on a slow+ // mobile network the covers stayed grey. 10 s, as the app's other clients.+ val timed = Options().apply { putAll(options); set(HttpGlideUrlLoader.TIMEOUT, TIMEOUT_MS) }+ val data = inner.buildLoadData(model, width, height, timed) ?: return nullreturn ModelLoader.LoadData(data.sourceKey, data.alternateKeys, Fetcher(data.fetcher))}override fun handles(model: GlideUrl) = inner.handles(model)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 652e494c..50c00c55 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@@ -871,20 +871,16 @@ class Api constructor(merged}.getOrNull()+ private val LIKED_PAGE = 50+/** The newest Liked Songs: one page of 50. */private suspend fun likedHead(): List<SongsModel> =api.library.likedTracks(0, 50).items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }private suspend fun allLiked(onPage: suspend (List<SongsModel>) -> Unit): List<SongsModel> {- val out = ArrayList<SongsModel>()- var offset = 0- while (true) {- val page = api.library.likedTracks(offset, 50)- out += page.items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }- onPage(out.toList())- offset = page.nextOffset ?: break- }- return out+ fun songs(p: app.myspoti.api.Page<app.myspoti.api.SavedTrack>) = p.items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }+ val first = api.library.likedTracks(0, LIKED_PAGE)+ return PagedFetch.inOrder(songs(first), first.total, LIKED_PAGE, fetch = { o -> songs(api.library.likedTracks(o, LIKED_PAGE)) }, onBatch = onPage)}/**@@ -1063,14 +1059,10 @@ class Api constructor(}private suspend fun libraryLevel(folderUri: String?, filter: LibraryFilter = LibraryFilter.ALL): List<app.myspoti.api.LibraryItem> {- val out = ArrayList<app.myspoti.api.LibraryItem>()- var offset = 0- repeat(40) {- val page = api.library.items(filter = filter, folderUri = folderUri, offset = offset, limit = 50)- out += page.items- offset = page.nextOffset ?: return out- }- return out+ val first = api.library.items(filter = filter, folderUri = folderUri, offset = 0, limit = 50)+ // 40 pages at most, as before (2,000 items); the rest four at a time instead of one by one.+ return PagedFetch.inOrder(first.items, minOf(first.total, 40 * 50), 50,+ fetch = { o -> api.library.items(filter = filter, folderUri = folderUri, offset = o, limit = 50).items })}/** Flat library (Android Auto, pickers): Liked Songs, playlists, then albums. */diff --git a/base/app/src/main/java/com/music/spotui/data/api/PagedFetch.kt b/base/app/src/main/java/com/music/spotui/data/api/PagedFetch.ktnew file mode 100644index 00000000..f5991c15--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/data/api/PagedFetch.kt@@ -0,0 +1,37 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package com.music.spotui.data.api++import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope++/**+ * The pages of a list whose size the first page told: the rest asked [parallel] at a time and+ * kept in order. A 3,000-song Liked Songs was 60 requests one after the other (15 to 20 s); four+ * at a time it is 15 rounds. [onBatch] gets the whole list so far after the first page and after+ * each round (not after each page: a screen redrawn 60 times for one list).+ */+internal object PagedFetch {+ suspend fun <T> inOrder(+ first: List<T>,+ total: Int,+ pageSize: Int,+ parallel: Int = 4,+ fetch: suspend (offset: Int) -> List<T>,+ onBatch: suspend (List<T>) -> Unit = {},+ ): List<T> = coroutineScope {+ val out = ArrayList<T>(maxOf(total, first.size)).apply { addAll(first) }+ onBatch(out.toList())+ // A first page shorter than asked is the whole list, whatever the total said.+ if (first.size < pageSize) return@coroutineScope out+ val offsets = (first.size until total step pageSize).toList()+ for (round in offsets.chunked(parallel.coerceAtLeast(1))) {+ val pages = round.map { o -> async { fetch(o) } }.awaitAll()+ pages.forEach { out += it }+ onBatch(out.toList())+ // A page shorter than asked: the list ended sooner than its total (songs removed meanwhile).+ if (pages.any { it.size < pageSize }) break+ }+ out+ }+}diff --git a/base/app/src/test/java/com/music/spotui/data/api/PagedFetchTest.kt b/base/app/src/test/java/com/music/spotui/data/api/PagedFetchTest.ktnew file mode 100644index 00000000..406627e7--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/data/api/PagedFetchTest.kt@@ -0,0 +1,40 @@+/* SPDX-License-Identifier: GPL-3.0-only */+package com.music.spotui.data.api++import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import java.util.concurrent.atomic.AtomicInteger++class PagedFetchTest {+ private fun page(offset: Int, size: Int, total: Int) = (offset until minOf(total, offset + size)).toList()++ @Test fun pagesComeInOrderFourAtATime() = runBlocking {+ val total = 523+ val running = AtomicInteger(); var most = 0+ val batches = mutableListOf<Int>()+ val all = PagedFetch.inOrder(page(0, 50, total), total, 50, fetch = { o ->+ most = maxOf(most, running.incrementAndGet())+ delay((50 - o % 50 + (o / 50) * 7 % 13).toLong()) // answers out of order+ running.decrementAndGet()+ page(o, 50, total)+ }, onBatch = { batches += it.size })+ assertEquals((0 until total).toList(), all)+ assertTrue("at most 4 at a time, saw $most", most in 2..4)+ // The first page, then one update per round of four: 1 + ceil(10 / 4).+ assertEquals(listOf(50, 250, 450, 523), batches)+ }++ @Test fun aShortFirstPageIsTheWholeList() = runBlocking {+ var asked = 0+ val all = PagedFetch.inOrder(page(0, 50, 30), total = 400, pageSize = 50, fetch = { asked++; emptyList<Int>() })+ assertEquals(30, all.size); assertEquals(0, asked)+ }++ @Test fun aListShorterThanItsTotalStops() = runBlocking {+ val all = PagedFetch.inOrder(page(0, 50, 120), total = 1000, pageSize = 50, fetch = { o -> page(o, 50, 120) })+ assertEquals((0 until 120).toList(), all)+ }+}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.ktindex 6cd751de..d4e6f2c3 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@@ -9,6 +9,7 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.launch+import kotlinx.coroutines.flow.firstimport java.util.Locale/**@@ -30,14 +31,34 @@ object MyspotiRuntime {val isStarted: Boolean get() = ::host.isInitializedval loginRequired: StateFlow<Boolean> get() = host.loginRequired+ /**+ * The client of every read the app makes itself (GraphQL, the client token, the operations+ * update), one pool for them all. It was a bare OkHttpClient: 10 s default timeouts on a+ * connection the mobile network had dropped while idle, and the old network's connections kept+ * after a switch. As the relay's: 10 s to connect, 15 s without a byte (an answer of a few+ * hundred KB comes well within), a ping on idle HTTP/2 connections, and the pool emptied when+ * the phone changes network ([resetApiConnections]).+ */+ val apiHttp: okhttp3.OkHttpClient by lazy {+ okhttp3.OkHttpClient.Builder()+ .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)+ .readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)+ .pingInterval(20, java.util.concurrent.TimeUnit.SECONDS)+ .retryOnConnectionFailure(true)+ .build()+ }++ /** The phone moved to another network: the API's idle connections belong to the old one. Not on the main thread. */+ fun resetApiConnections() { if (::host.isInitialized) apiHttp.connectionPool.evictAll() }+/** [loadPage] false (data saver on a metered network): nothing goes out until [resume]. */fun start(context: Context, loadPage: Boolean = true) {if (isStarted) returnappContext = context.applicationContext- val updater = app.myspoti.spotify.gql.GqlOpsUpdater(okhttp3.OkHttpClient(), java.io.File(context.filesDir, "spotify/gql-ops.json"))+ val updater = app.myspoti.spotify.gql.GqlOpsUpdater(apiHttp, java.io.File(context.filesDir, "spotify/gql-ops.json"))host = WebPlayerHost(context)AudioModeWatch.install(context.applicationContext)- spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load(), deviceId = clientDeviceId(context, host.accounts.list.value.active), userAgent = host.userAgent,+ spotify = SpotifyApi(host, scope, http = apiHttp, language = Locale.getDefault().language, ops = updater.load(), deviceId = clientDeviceId(context, host.accounts.list.value.active), userAgent = host.userAgent,tokenStore = clientTokens(context))spotify.bridge.logger = { line -> Logbook.log(line) }host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }@@ -127,9 +148,15 @@ object MyspotiRuntime {}if (!loadPage) returnhost.load()- // New Spotify build: pick up its operation hashes (public bundles, no account).- scope.launch {- runCatching { updater.refresh(spotify.opsInUse) }.getOrNull()?.let(spotify::updateOps)+ // New Spotify build: pick up its operation hashes (public bundles, no account). Once the+ // page is up rather than beside its load, at most every 6 h, and a new build's bundles+ // (~6 MB) only off mobile data.+ if (updater.due()) scope.launch {+ kotlinx.coroutines.withTimeoutOrNull(30_000) { spotify.ready.first { it } }+ val metered = runCatching {+ (context.getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager).isActiveNetworkMetered+ }.getOrDefault(true)+ runCatching { updater.refresh(spotify.opsInUse, bundlesAllowed = !metered) }.getOrNull()?.let(spotify::updateOps)}}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.ktindex 87d017a4..4ff185a7 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt@@ -136,8 +136,9 @@ class WebPlayerHost(private val context: Context) : BridgeHost {setOnline(true)// The first call names the network the app started on: nothing to drop.if (was == null || was == network) return- Logbook.log("network changed: the relay's idle connections dropped")+ Logbook.log("network changed: the relay's and the API's idle connections dropped")ControlRelay.resetConnections()+ MyspotiRuntime.resetApiConnections()}override fun onCapabilitiesChanged(network: android.net.Network, caps: android.net.NetworkCapabilities) {