Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Likes and follows kept for later are kept under the account that made them: another account signed in on the phone never receives them, they wait for their own account to sign in again (those of an older version go to the account still signed in at the update, or are put aside unsent when nobody was); one change Spotify refuses for good (400/404) is dropped with a diagnostic line instead of holding back all the others, a server error keeps it and still sends the next ones, no connection, too many requests or a refused session keep them and try again on their own after 5 s, doubled up to 10 min, or at once when a like is made, the network comes back or the Web Player is ready again; and one worker sends them, so rounds started together no longer send the same like twice [skip ci]
kota-zo356949eb6ca4
diff --git a/base/app/src/main/java/com/music/spotui/data/LibraryOutbox.kt b/base/app/src/main/java/com/music/spotui/data/LibraryOutbox.ktindex 9a6f2d4b..63d790fa 100644--- a/base/app/src/main/java/com/music/spotui/data/LibraryOutbox.kt+++ b/base/app/src/main/java/com/music/spotui/data/LibraryOutbox.kt@@ -3,15 +3,24 @@ package com.music.spotui.dataimport android.content.Contextimport android.net.ConnectivityManagerimport android.net.Network+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.launchimport org.json.JSONObject/*** Likes, unlikes, saves and follows made without a connection: shown at once, kept here (the last- * tap on an item wins) and sent to Spotify when the network is back, in the order they were made.+ * tap on an item wins) and sent to Spotify when it answers again, in the order they were made.+ * Each change is kept under the account that made it: another account signed in on the phone+ * never receives it, and it waits for its own account to come back.*/object LibraryOutbox {private const val PREFS = "library_outbox"- private const val KEY = "pending"+ /** Before accounts were told apart: uri -> saved, of whoever was signed in. Moved to [BOOK]. */+ private const val LEGACY = "pending"+ private const val BOOK = "book"/** What waits, in order: item uri -> saved. Pure, for tests: see [Pending]. */class Pending(text: String?) {@@ -26,21 +35,236 @@ object LibraryOutbox {fun text(): String = JSONObject(items as Map<*, *>).toString()}- private var context: Context? = null- private var send: (suspend (uri: String, saved: Boolean) -> Unit)? = null+ /**+ * The changes of every account, each list in tap order. [account] is the Spotify user id of+ * the session (kept across restarts, forgotten at sign-out); changes made before it is known+ * go to the session's own list, which becomes the account's as soon as it is known, or is+ * put aside at sign-out (never sent: nobody knows whose they are). Pure, for tests.+ */+ class Book(text: String?) {+ private val lists = LinkedHashMap<String, Pending>()+ var account: String? = null+ private set- private fun prefs() = context?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)- @Synchronized private fun read() = Pending(prefs()?.getString(KEY, null))- @Synchronized private fun write(p: Pending) { prefs()?.edit()?.putString(KEY, p.text())?.apply() }+ init {+ runCatching { JSONObject(text ?: "{}") }.getOrNull()?.let { o ->+ account = o.optString("account").ifBlank { null }+ o.optJSONObject("lists")?.let { l -> l.keys().forEach { k -> lists[k] = Pending(l.optJSONObject(k)?.toString()) } }+ }+ }++ /** The list sent now: the account's, or the session's while its account is not known. */+ val key: String get() = account ?: SESSION+ fun due(key: String): Map<String, Boolean> = lists[key]?.all.orEmpty()+ /** Changes kept for another account (or put aside), not sent in this session. */+ val keptForOthers: Int get() = lists.filterKeys { it != key }.values.sumOf { it.all.size }++ fun put(uri: String, saved: Boolean) = list(key).put(uri, saved)+ fun sent(key: String, uri: String, saved: Boolean) {+ lists[key]?.let { it.sent(uri, saved); if (it.all.isEmpty()) lists.remove(key) }+ }++ /** The session's account is [id]: what the session did before is that account's (and newer). */+ fun signedIn(id: String) {+ if (id == account || id.isBlank() || id == SESSION || id == ASIDE) return+ account = id+ move(SESSION, id)+ }++ /** Signed out: what the session did without knowing its account is put aside, never sent. */+ fun signedOut() {+ move(SESSION, ASIDE)+ account = null+ }++ /**+ * The changes of an older version, which kept one list for whoever was signed in:+ * the session still signed in at the update made them (older than anything here);+ * signed out at the update, nobody knows whose they are and they are put aside.+ */+ fun adopt(legacy: String?, signedIn: Boolean) {+ val old = Pending(legacy).all+ if (old.isEmpty()) return+ val to = if (signedIn) key else ASIDE+ val merged = Pending(null)+ old.forEach { (u, s) -> merged.put(u, s) }+ lists[to]?.all?.forEach { (u, s) -> merged.put(u, s) }+ lists[to] = merged+ }++ fun text(): String = JSONObject().apply {+ account?.let { put("account", it) }+ put("lists", JSONObject().apply { lists.forEach { (k, p) -> if (p.all.isNotEmpty()) put(k, JSONObject(p.text())) } })+ }.toString()++ private fun list(key: String) = lists.getOrPut(key) { Pending(null) }+ private fun move(from: String, to: String) {+ val moved = lists.remove(from)?.all ?: return+ val into = list(to)+ moved.forEach { (u, s) -> into.put(u, s) }+ }++ companion object {+ const val SESSION = "~session"+ const val ASIDE = "~aside"+ }+ }++ /** Why a change was not taken, and what is done with it. */+ enum class Failure {+ /** No connection, a timeout, the page reloading, too many requests: kept, the rest waits too. */+ NETWORK,+ /** Spotify failed (5xx) or said something unknown: kept, the next ones are still sent. */+ SERVER,+ /** The session was refused (401/403): kept, the rest waits for the session. */+ SESSION,+ /** Spotify refused this change for good (400/404/410): dropped. */+ REFUSED,+ }++ private val statusCode = Regex("""(?i)\b(?:http|status(?:\s*code)?|code)\D{0,3}([1-5]\d\d)\b""")++ fun failureOf(e: Throwable): Failure {+ if (e is java.io.IOException) return Failure.NETWORK+ if (e is IllegalArgumentException) return Failure.REFUSED+ val message = e.message.orEmpty()+ val code = statusCode.find(message)?.groupValues?.get(1)?.toIntOrNull()+ return when {+ code == 408 || code == 429 -> Failure.NETWORK+ code == 401 || code == 403 -> Failure.SESSION+ code == 400 || code == 404 || code == 410 -> Failure.REFUSED+ code != null -> Failure.SERVER+ message.startsWith("timeout") || message == "not ready" || message == "page reloaded" -> Failure.NETWORK+ else -> Failure.SERVER+ }+ }++ /** The wait before the next try after [failures] failed rounds: 5 s, doubled, at most 10 min. */+ fun backoff(failures: Int): Long = (5_000L shl failures.coerceIn(0, 7)).coerceAtMost(600_000L)- @Synchronized fun put(uri: String, saved: Boolean) = write(read().apply { put(uri, saved) })- val waiting: Int get() = read().all.size+ /**+ * One worker sends what waits: rounds never overlap, and a round asked while one runs is+ * run once after it (a change is never sent twice by rounds started together). A round+ * that leaves changes it could not send asks for another after [backoff]; any other+ * request (a new change, the network back, the session ready) starts one at once.+ */+ class Sync(+ private val book: Book,+ private val save: (String) -> Unit,+ private val send: suspend (uri: String, saved: Boolean) -> Unit,+ /** Waits for Spotify to answer (the engine started, the Web Player ready). */+ private val ready: suspend () -> Unit,+ /** The signed-in account's Spotify user id, when known. */+ private val account: () -> String?,+ private val pause: suspend (Long) -> Unit,+ private val log: (String) -> Unit,+ private val scope: CoroutineScope,+ ) {+ private val requests = Channel<Unit>(Channel.CONFLATED)+ private var failures = 0+ private var retry: Job? = null++ init {+ scope.launch { for (r in requests) { retry?.cancel(); round() } }+ }++ fun request() { requests.trySend(Unit) }++ fun put(uri: String, saved: Boolean) {+ synchronized(book) { claim(); book.put(uri, saved); save(book.text()) }+ request()+ }++ fun signedOut() = synchronized(book) { book.signedOut(); save(book.text()) }++ val waiting: Int get() = synchronized(book) { claim(); book.due(book.key).size }++ private fun claim() {+ val id = account() ?: return+ if (id == book.account) return+ book.signedIn(id)+ save(book.text())+ book.keptForOthers.takeIf { it > 0 }?.let { log("library: $it change(s) of another account kept for it, not sent to this one") }+ }++ private suspend fun round() {+ if (waiting == 0) { failures = 0; return }+ ready()+ when (pass()) {+ Outcome.DONE -> failures = 0+ Outcome.AGAIN -> request()+ Outcome.LATER -> {+ val wait = backoff(failures++)+ retry = scope.launch { pause(wait); request() }+ }+ }+ }++ private enum class Outcome { DONE, AGAIN, LATER }++ /** Sends the session account's changes, oldest first. */+ private suspend fun pass(): Outcome {+ val (key, due) = synchronized(book) { claim(); book.key to book.due(book.key).toList() }+ var later = false+ for ((uri, saved) in due) {+ // Another account signed in meanwhile: its own list, in a new round.+ if (synchronized(book) { claim(); book.key } != key) return Outcome.AGAIN+ val error = try { send(uri, saved); null } catch (e: CancellationException) { throw e } catch (e: Exception) { e }+ if (error == null) {+ synchronized(book) { book.sent(key, uri, saved); save(book.text()) }+ log("library: $uri ${if (saved) "saved" else "removed"} on Spotify (kept from earlier)")+ continue+ }+ val why = "${error.javaClass.simpleName} ${error.message}"+ when (failureOf(error)) {+ Failure.REFUSED -> {+ synchronized(book) { book.sent(key, uri, saved); save(book.text()) }+ log("library: $uri dropped, Spotify refused it ($why)")+ }+ Failure.SERVER -> { later = true; log("library: $uri still kept for later ($why)") }+ Failure.NETWORK -> { log("library: $uri still kept for later ($why)"); return Outcome.LATER }+ Failure.SESSION -> { log("library: $uri still kept for later, waiting for the session ($why)"); return Outcome.LATER }+ }+ }+ return if (later) Outcome.LATER else Outcome.DONE+ }+ }++ @Volatile private var sync: Sync? = null++ fun put(uri: String, saved: Boolean) { sync?.put(uri, saved) }+ /** Sends what waits (one worker: see [Sync]). */+ fun request() { sync?.request() }+ /** At sign-out: the account's changes stay its own, the next account starts with none. */+ fun signedOut() { sync?.signedOut() }/** [sender] writes one change to Spotify (throws when it cannot); called when the network is back. */- fun init(c: Context, sender: suspend (uri: String, saved: Boolean) -> Unit, onAvailable: () -> Unit) {- if (context != null) return- context = c.applicationContext- send = sender+ @Synchronized fun init(+ c: Context,+ scope: CoroutineScope,+ sender: suspend (uri: String, saved: Boolean) -> Unit,+ ready: suspend () -> Unit,+ account: () -> String?,+ onAvailable: () -> Unit,+ ) {+ if (sync != null) return+ val prefs = c.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+ val book = Book(prefs.getString(BOOK, null))+ prefs.getString(LEGACY, null)?.let { legacy ->+ val signedIn = c.applicationContext.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).getBoolean("LoggedIn", false)+ book.adopt(legacy, signedIn)+ prefs.edit().putString(BOOK, book.text()).remove(LEGACY).apply()+ }+ sync = Sync(+ book,+ save = { prefs.edit().putString(BOOK, it).apply() },+ send = sender,+ ready = ready,+ account = account,+ pause = { kotlinx.coroutines.delay(it) },+ log = { android.util.Log.i("LibraryOutbox", it); app.myspoti.host.android.Logbook.log(it) },+ scope = scope,+ ).also { it.request() }val cm = c.getSystemService(ConnectivityManager::class.java) ?: returnrunCatching {cm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {@@ -48,18 +272,4 @@ object LibraryOutbox {})}}-- /** Sends what waits, oldest first; stops at the first failure (the rest waits for the next network). */- suspend fun flush() {- val sender = send ?: return- for ((uri, saved) in read().all.entries.toList()) {- runCatching { sender(uri, saved) }.onFailure {- android.util.Log.w("LibraryOutbox", "kept for later: $uri (${it.message})")- app.myspoti.host.android.Logbook.log("library: $uri still kept for later (${it.javaClass.simpleName} ${it.message})")- return- }- synchronized(this) { write(read().apply { sent(uri, saved) }) }- app.myspoti.host.android.Logbook.log("library: $uri ${if (saved) "saved" else "removed"} on Spotify (kept from earlier)")- }- }}diff --git a/base/app/src/main/java/com/music/spotui/di/SessionActions.kt b/base/app/src/main/java/com/music/spotui/di/SessionActions.ktindex 55d3a285..5fcc56aa 100644--- a/base/app/src/main/java/com/music/spotui/di/SessionActions.kt+++ b/base/app/src/main/java/com/music/spotui/di/SessionActions.kt@@ -39,6 +39,8 @@ object SessionActions {com.music.spotui.data.api.Api.LikedCache.tracks = nullcom.music.spotui.data.api.TopStats.clear()com.music.spotui.data.api.ProfileCache.clearSession()+ // Likes kept for later stay this account's, sent when it signs in again; the next account gets none.+ com.music.spotui.data.LibraryOutbox.signedOut()SongPlayer.clearSession()listOf("PlaybackState", "LibraryCache", "RecentItems", "LikedSongs","LikedSongsFromSpotify", "LikedAlbums", "FollowedArtists").forEach { name ->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.ktindex 9fd6844a..7c6e1780 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@@ -2054,9 +2054,8 @@ object SongPlayer {if (!com.music.spotui.data.offline.OfflineStore.isOnline(Graph.app)) {com.music.spotui.data.LibraryOutbox.put(uri, on)app.myspoti.host.android.Logbook.log("library: $uri ${if (on) "saved" else "removed"} kept for later (offline${if (com.music.spotui.data.DataSaver.active) ", data saver" else ""})")- // Sent as soon as Spotify answers, not only when Android reports a network coming up:- // a network already there (or the data saver turned off) never reports one.- scope.launch { flushLibraryOutbox() }+ // Sent as soon as Spotify answers (put asks for it), not only when Android reports a+ // network coming up: a network already there (or the data saver turned off) never reports one.return}scope.launch {@@ -2095,19 +2094,20 @@ object SongPlayer {}/** The library changes made offline ([com.music.spotui.data.LibraryOutbox]), sent once Spotify is reachable. */- fun startLibraryOutbox(context: Context) = com.music.spotui.data.LibraryOutbox.init(context,- sender = { uri, on -> libraryLock.withLock { writeLibrary(uri, on) }; if (uri.startsWith(SPOTIFY_TRACK_PREFIX)) likedChanges.value++ },- onAvailable = { scope.launch { kotlinx.coroutines.delay(3_000); flushLibraryOutbox() } },- ).also { scope.launch { flushLibraryOutbox() } }-- private suspend fun flushLibraryOutbox() {- if (com.music.spotui.data.LibraryOutbox.waiting == 0) return- // The engine is started after the app's graph: wait for it, then for Spotify to answer.- while (!MyspotiRuntime.isStarted) kotlinx.coroutines.delay(1_000)- api.ready.first { it }- com.music.spotui.data.LibraryOutbox.flush()+ fun startLibraryOutbox(context: Context) {+ com.music.spotui.data.LibraryOutbox.init(context, scope,+ sender = { uri, on -> libraryLock.withLock { writeLibrary(uri, on) }; if (uri.startsWith(SPOTIFY_TRACK_PREFIX)) likedChanges.value++ },+ // The engine is started after the app's graph: wait for it, then for Spotify to answer.+ ready = { awaitEngine(); api.ready.first { it } },+ account = { com.music.spotui.data.api.ProfileCache.id },+ onAvailable = { scope.launch { kotlinx.coroutines.delay(3_000); com.music.spotui.data.LibraryOutbox.request() } },+ )+ // The Web Player ready again (a reload, a new sign-in): what waits is sent (nothing is asked when nothing waits).+ scope.launch { awaitEngine(); api.ready.collect { if (it) com.music.spotui.data.LibraryOutbox.request() } }}+ private suspend fun awaitEngine() { while (!MyspotiRuntime.isStarted) kotlinx.coroutines.delay(1_000) }+// ── Music video: Spotify's own clips are not played by this engine; the YouTube// clips (MusicVideoController) are. These keep the player screen's contract. ──data class VideoState(val available: Boolean = false, val on: Boolean = false, val ready: Boolean = false, val aspect: Float = 0f, val placed: Boolean = false)diff --git a/base/app/src/test/java/com/music/spotui/data/LibraryOutboxTest.kt b/base/app/src/test/java/com/music/spotui/data/LibraryOutboxTest.ktindex 7b948d4b..d189d376 100644--- a/base/app/src/test/java/com/music/spotui/data/LibraryOutboxTest.kt+++ b/base/app/src/test/java/com/music/spotui/data/LibraryOutboxTest.kt@@ -1,6 +1,13 @@package com.music.spotui.data+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.yieldimport org.junit.Assert.assertEquals+import org.junit.Assert.assertTrueimport org.junit.Testclass LibraryOutboxTest {@@ -21,4 +28,191 @@ class LibraryOutboxTest {assertEquals(listOf("spotify:track:a" to false), again.all.toList())assertEquals(emptyMap<String, Boolean>(), LibraryOutbox.Pending("not json").all)}++ @Test fun eachAccountKeepsItsOwnChangesAcrossRestartsAndSignOuts() {+ val book = LibraryOutbox.Book(null)+ book.put("spotify:track:before", true) // account not known yet: the session's+ book.signedIn("a")+ book.put("spotify:track:x", true)+ assertEquals(listOf("spotify:track:before" to true, "spotify:track:x" to true), book.due(book.key).toList())+ book.signedOut()+ book.put("spotify:track:unknown", true) // signed out before anyone was known again: put aside+ book.signedOut()+ book.signedIn("b")+ assertEquals(emptyMap<String, Boolean>(), book.due(book.key))++ val again = LibraryOutbox.Book(book.text())+ assertEquals("b", again.account)+ again.signedIn("a")+ assertEquals(listOf("spotify:track:before" to true, "spotify:track:x" to true), again.due(again.key).toList())+ assertEquals(1, again.keptForOthers) // the one put aside, never sent+ }++ @Test fun changesOfAnOlderVersionGoToTheSessionSignedInAtTheUpdateOnly() {+ val legacy = LibraryOutbox.Pending(null).apply { put("spotify:track:old", true) }.text()+ val signedIn = LibraryOutbox.Book(null).apply { adopt(legacy, signedIn = true); put("spotify:track:new", false) }+ signedIn.signedIn("a")+ assertEquals(listOf("spotify:track:old" to true, "spotify:track:new" to false), signedIn.due("a").toList())++ val signedOut = LibraryOutbox.Book(null).apply { adopt(legacy, signedIn = false) }+ signedOut.signedIn("b")+ assertEquals(emptyMap<String, Boolean>(), signedOut.due(signedOut.key))+ assertEquals(1, signedOut.keptForOthers)+ }++ @Test fun failuresAreToldApart() {+ assertEquals(LibraryOutbox.Failure.NETWORK, LibraryOutbox.failureOf(java.net.UnknownHostException("x")))+ assertEquals(LibraryOutbox.Failure.NETWORK, LibraryOutbox.failureOf(Exception("timeout after 20000 ms: library.add")))+ assertEquals(LibraryOutbox.Failure.NETWORK, LibraryOutbox.failureOf(Exception("Request failed with status code 429")))+ assertEquals(LibraryOutbox.Failure.SESSION, LibraryOutbox.failureOf(Exception("HTTP 401: token expired")))+ assertEquals(LibraryOutbox.Failure.REFUSED, LibraryOutbox.failureOf(Exception("HTTP 404: no such playlist")))+ assertEquals(LibraryOutbox.Failure.REFUSED, LibraryOutbox.failureOf(IllegalArgumentException("not a Spotify address")))+ assertEquals(LibraryOutbox.Failure.SERVER, LibraryOutbox.failureOf(Exception("HTTP 503: busy")))+ assertEquals(LibraryOutbox.Failure.SERVER, LibraryOutbox.failureOf(Exception("something odd")))+ assertEquals(listOf(5_000L, 10_000L, 20_000L, 600_000L), listOf(0, 1, 2, 30).map(LibraryOutbox::backoff))+ }++ /** A worker on a fake Spotify: [fail] decides each send's error (null: taken). */+ private class Rig(scope: CoroutineScope) {+ var account: String? = "a"+ val sent = mutableListOf<Triple<String?, String, Boolean>>()+ var fail: (String) -> Exception? = { null }+ var hold: CompletableDeferred<Unit>? = null+ val pauses = mutableListOf<Long>()+ val resume = Channel<Unit>(Channel.UNLIMITED)+ val saved = mutableListOf<String>()+ val sync = LibraryOutbox.Sync(+ LibraryOutbox.Book(null),+ save = { saved += it },+ send = { uri, on ->+ val to = account // the account the request goes to, when it is made+ hold?.await()+ fail(uri)?.let { throw it }+ sent += Triple(to, uri, on)+ },+ ready = {},+ account = { account },+ pause = { pauses += it; resume.receive() },+ log = {},+ scope = scope,+ )+ }++ private fun test(block: suspend CoroutineScope.(Rig) -> Unit) = runBlocking {+ val job = Job()+ val scope = CoroutineScope(coroutineContext + job)+ block(Rig(scope))+ job.cancel()+ }++ private suspend fun settle() = repeat(200) { yield() }++ @Test fun anotherAccountNeverReceivesTheChangesOfTheFirst() = test { rig ->+ rig.hold = CompletableDeferred()+ rig.sync.put("spotify:track:x", true)+ settle()+ // A signs out while its like waits; B signs in and likes something.+ rig.sync.signedOut()+ rig.account = "b"+ rig.sync.put("spotify:track:y", true)+ rig.hold!!.complete(Unit)+ settle()+ // The request already made for x when A left was A's; B's like goes to B, and nothing else.+ assertEquals(listOf(Triple("a", "spotify:track:x", true), Triple("b", "spotify:track:y", true)), rig.sent)+ assertEquals(0, rig.sync.waiting)+ }++ @Test fun aChangeWaitingForItsAccountIsSentOnlyWhenItSignsInAgain() = test { rig ->+ rig.sync.put("spotify:track:x", true)+ settle()+ rig.sent.clear()+ // Offline: A likes, nothing goes; A signs out, B signs in.+ rig.fail = { java.io.IOException("offline") }+ rig.sync.put("spotify:track:a-like", true)+ settle()+ rig.sync.signedOut()+ rig.account = "b"+ rig.fail = { null }+ rig.sync.request() // the network is back+ settle()+ assertEquals(emptyList<Any>(), rig.sent)+ rig.sync.put("spotify:track:b-like", true)+ settle()+ assertEquals(listOf(Triple("b", "spotify:track:b-like", true)), rig.sent)+ // A comes back: its like goes to A, the one time.+ rig.sync.signedOut()+ rig.account = "a"+ rig.sync.request()+ settle()+ assertEquals(Triple("a", "spotify:track:a-like", true), rig.sent.last())+ assertEquals(2, rig.sent.size)+ }++ @Test fun roundsAskedTogetherSendEachChangeOnce() = test { rig ->+ rig.hold = CompletableDeferred()+ rig.sync.put("spotify:track:a", true)+ rig.sync.put("spotify:track:b", false)+ repeat(5) { rig.sync.request() } // a like, the network back, the session ready...+ settle()+ rig.hold!!.complete(Unit)+ settle()+ assertEquals(listOf("spotify:track:a" to true, "spotify:track:b" to false), rig.sent.map { it.second to it.third })+ assertEquals(0, rig.sync.waiting)+ }++ @Test fun aRefusedChangeIsDroppedAndTheNextOnesAreStillSent() = test { rig ->+ rig.fail = { if (it == "spotify:playlist:gone") Exception("HTTP 404: not found") else null }+ rig.sync.put("spotify:playlist:gone", true)+ rig.sync.put("spotify:track:b", true)+ settle()+ assertEquals(listOf("spotify:track:b"), rig.sent.map { it.second })+ assertEquals(0, rig.sync.waiting)+ assertEquals(emptyList<Long>(), rig.pauses) // nothing left: no retry+ }++ @Test fun tooManyRequestsWaitsLongerEachTimeThenSendsEverything() = test { rig ->+ var refusals = 2+ rig.fail = { if (refusals > 0) { refusals--; Exception("status code 429") } else null }+ rig.sync.put("spotify:track:a", true)+ rig.sync.put("spotify:track:b", true)+ settle()+ assertEquals(emptyList<Any>(), rig.sent) // b is not tried while Spotify says "too many"+ assertEquals(listOf(5_000L), rig.pauses)+ rig.resume.send(Unit)+ settle()+ assertEquals(listOf(5_000L, 10_000L), rig.pauses)+ rig.resume.send(Unit)+ settle()+ assertEquals(listOf("spotify:track:a", "spotify:track:b"), rig.sent.map { it.second })+ assertEquals(0, rig.sync.waiting)+ }++ @Test fun aServerErrorKeepsTheChangeButNotTheOthersWaiting() = test { rig ->+ var down = true+ rig.fail = { if (down && it == "spotify:track:a") Exception("HTTP 502: bad gateway") else null }+ rig.sync.put("spotify:track:a", true)+ rig.sync.put("spotify:track:b", true)+ settle()+ assertEquals(listOf("spotify:track:b"), rig.sent.map { it.second })+ assertEquals(1, rig.sync.waiting)+ down = false+ rig.resume.send(Unit)+ settle()+ assertEquals(listOf("spotify:track:b", "spotify:track:a"), rig.sent.map { it.second })+ }++ @Test fun theNetworkBackSendsAtOnceWithoutWaitingForTheRetry() = test { rig ->+ rig.fail = { java.io.IOException("offline") }+ rig.sync.put("spotify:track:a", true)+ settle()+ assertEquals(listOf(5_000L), rig.pauses)+ rig.fail = { null }+ rig.sync.request() // the network is back, before the retry is due+ settle()+ assertEquals(listOf("spotify:track:a"), rig.sent.map { it.second })+ // The cancelled retry sends nothing more.+ settle()+ assertEquals(1, rig.sent.size)+ assertTrue(rig.saved.isNotEmpty())+ }}