Skip to content

Native Android client for Spotify, built with Jetpack Compose

V2 hardening: foreign ads blocked and muted, durable pause, safe download index, GraphQL writes never replayed, rollbacks, search and page error states, logout and data saver fixes, lyrics button, Jam link join, CI runs API tests

kota-zo7acd8a4b6bd7
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
index 19e220b8..bac26360 100644
--- a/.github/workflows/android.yml
+++ b/.github/workflows/android.yml
@@ -32,8 +32,10 @@ jobs:
- uses: gradle/actions/setup-gradle@v6
+ # App unit tests, plus the JVM modules (API contracts, ad block, offline index, GraphQL
+ # errors). The live tests in host-cdp skip themselves without a browser to drive.
- name: Unit tests
- run: ./gradlew testDebugUnitTest
+ run: ./gradlew testDebugUnitTest :api:test :api-spotify:test :host-cdp:test
- name: Debug APK
if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ab3441e..525c211c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,17 @@
Each release on GitHub shows its section below. The app shows it too when it offers the update. Every detail: [docs/CHANGELOG-full.md](docs/CHANGELOG-full.md).
+## 2.0.0-beta.6
+
+- **Fewer ads abroad**: ads from other countries' ad servers are blocked too; an ad that still gets through is muted and skipped.
+- **A pause stays a pause**, even right at the end of a song.
+- **Downloads are safe**: a damaged download list no longer deletes your downloaded songs.
+- **Changes Spotify refuses are undone on screen** (likes, playlist visibility), with a message.
+- **Search** keeps your query when you come back, and says when it is loading, empty or failed (with Try again). Artist and profile pages can be reloaded too.
+- **Lyrics button** in the player; **Jam**: join with a copied link; sharing an episode works.
+- **Logout** stops everything (local songs, video, notification); the data saver applies from launch.
+- Player buttons are named for TalkBack.
+
## 2.0.0-beta.5
- **Encrypted downloads**: downloaded songs only play in Myspoti, on your phone.
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 be4dd407..ba85d923 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
@@ -29,8 +29,10 @@ import kotlinx.serialization.json.putJsonArray
*
* 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).
+ * one is played. An ad that gets through (other markets serve ads from other places) is
+ * muted at once and skipped the same way after [AD_PLAYING_SKIP_MS]; if the page still
+ * holds on to it after one reload, it stays muted until it ends. [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;
@@ -48,7 +50,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
val adPlaying: StateFlow<Boolean> = _adPlaying
@Volatile private var adSince = 0L
@Volatile private var adState: PlayerState? = null
- @Volatile private var pausedByUserAt = 0L
+ /** The page's volume before an ad muted it, put back when the ad is over. */
+ @Volatile private var volumeBeforeAd: Double? = null
+ /** A pause asked through [pause]; it holds until playback is asked for again, never expires. */
+ @Volatile private var pausedByUser = false
/** 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
@@ -69,8 +74,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
}
scope.launch { watchStalls() }
+ // One collector, so a mute and the unmute after it never run out of order.
+ scope.launch { _adPlaying.collect { if (it) muteForAd() else unmuteAfterAd() } }
// A reloaded page starts on "auto": the chosen quality is set again.
- scope.launch { bridge.ready.collect { if (it && audioQuality != "auto") applyAudioQuality() } }
+ scope.launch {
+ bridge.ready.collect {
+ if (!it) return@collect
+ if (audioQuality != "auto") applyAudioQuality()
+ // The page keeps its volume: an app closed during a muted ad must not stay silent.
+ runCatching { if (volume() == 0.0) setVolume(volumeBeforeAd ?: 1.0) }
+ }
+ }
}
private suspend fun watchStalls() {
@@ -78,6 +92,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
var since = 0L
var attempts = 0
var adAttempts = 0
+ var adReloaded = false
while (true) {
delay(WATCH_TICK_MS)
val s = _state.value
@@ -85,8 +100,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
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) {
+ val refused = ad != null && (ad.isBuffering || ad.speed == 0.0) && now - adSince > AD_STUCK_MS
+ val playing = ad != null && !refused && now - adSince > AD_PLAYING_SKIP_MS && !adReloaded
+ if (refused || playing || now - adSince > AD_BREAK_MAX_MS) {
adAttempts++
val last = lastTrackState
// Playing on can land on the same refused ad again: after a few tries the
@@ -96,6 +112,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
last?.let { runCatching { playOn(it) } }
} else {
adAttempts = 0
+ adReloaded = true
bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: reloading the player")
val reload = reloadHost
if (reload != null) runCatching {
@@ -111,8 +128,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
continue
}
// A song really playing again: the ad break is over.
- if (s != null && !s.isPaused && !s.isBuffering) adAttempts = 0
- val reason = s?.let { stallOf(it, now, pausedByUserAt) }
+ if (s != null && !s.isPaused && !s.isBuffering) { adAttempts = 0; adReloaded = false }
+ val reason = s?.let { stallOf(it, now, pausedByUser) }
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 }
@@ -149,7 +166,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
private fun onState(s: PlayerState?) {
if (s?.item?.kind == ItemKind.AD) {
// Keep showing the last real track, buffering, while the ad plays.
- if (!_adPlaying.value) adSince = System.currentTimeMillis()
+ if (!_adPlaying.value) {
+ adSince = System.currentTimeMillis()
+ }
adState = s
_adPlaying.value = true
_state.value = lastTrackState?.copy(isBuffering = true) ?: s.copy(item = null)
@@ -161,8 +180,20 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
+ private suspend fun muteForAd() = runCatching {
+ if (volumeBeforeAd == null) volumeBeforeAd = volume().takeIf { it > 0.0 } ?: 1.0
+ bridge.call("volume.set", buildJsonObject { put("level", 0.0) })
+ }
+
+ private suspend fun unmuteAfterAd() = runCatching {
+ val v = volumeBeforeAd ?: return@runCatching
+ bridge.call("volume.set", buildJsonObject { put("level", v) })
+ volumeBeforeAd = null
+ }
+
override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?, order: List<Uri>?) {
lastOrder = order?.let { contextUri to it }
+ pausedByUser = false
bridge.call("player.play", buildJsonObject {
put("contextUri", contextUri)
order?.let { uris -> putJsonArray("order") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } } }
@@ -172,11 +203,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
})
}
- override suspend fun pause() { pausedByUserAt = System.currentTimeMillis(); bridge.call("player.pause") }
- override suspend fun resume() { bridge.call("player.resume") }
+ override suspend fun pause() { pausedByUser = true; bridge.call("player.pause") }
+ override suspend fun resume() { pausedByUser = false; 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") }
- override suspend fun previous() { bridge.call("player.previous") }
+ override suspend fun next() { pausedByUser = false; bridge.call("player.next") }
+ override suspend fun previous() { pausedByUser = false; bridge.call("player.previous") }
override suspend fun setShuffle(on: Boolean) { bridge.call("player.setShuffle", buildJsonObject { put("on", on) }) }
override suspend fun setRepeat(mode: Repeat) {
@@ -199,7 +230,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
private fun ref(item: NowPlaying) = buildJsonObject { put("uri", item.uri); item.uid?.let { put("uid", it) } }
- override suspend fun skipTo(item: NowPlaying) { bridge.call("queue.skipTo", ref(item)) }
+ override suspend fun skipTo(item: NowPlaying) { pausedByUser = false; bridge.call("queue.skipTo", ref(item)) }
override suspend fun playNext(uris: List<Uri>) {
val first = _queue.value?.queued?.firstOrNull()
@@ -255,6 +286,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
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
+ /** An ad that really plays (muted) is skipped after that long. */
+ const val AD_PLAYING_SKIP_MS = 1_500L
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
@@ -272,12 +305,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* 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? {
+ fun stallOf(s: PlayerState, now: Long, userPaused: Boolean): 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
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 dcf9cfb2..a9c24b48 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
@@ -39,14 +39,33 @@ object BridgeScript {
* [app.myspoti.spotify.SpotifyPlayer] starts the next song.
*/
object AdBlock {
- val blockedHosts = listOf("adstudio-assets.scdn.co")
+ /**
+ * Ad audio and ad servers. Outside Switzerland ads also come from Google's ad servers
+ * (audio and video ads) and the ad event tracker, so these are refused too.
+ */
+ val blockedHosts = listOf(
+ "adstudio-assets.scdn.co",
+ "adeventtracker.spotify.com",
+ "pubads.g.doubleclick.net",
+ "securepubads.g.doubleclick.net",
+ "googleads.g.doubleclick.net",
+ "pagead2.googlesyndication.com",
+ "imasdk.googleapis.com",
+ )
+
+ /** Ad endpoints on Spotify's api hosts (spclient): ad slots, ad logic and ad delivery. */
+ val blockedPaths = listOf("/ads/", "/ad-logic/")
/** 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") }
+ val rest = url.substringAfter("://")
+ val host = rest.substringBefore('/').substringBefore('?').substringBefore(':').lowercase()
+ if (blockedHosts.any { host == it || host.endsWith(".$it") }) return true
+ if (!host.endsWith(".spotify.com") || "spclient" !in host) return false
+ val path = "/" + rest.substringAfter('/', "").substringBefore('?')
+ return blockedPaths.any { path.startsWith(it) }
}
/** The player's registration (POST track-playback/v1/devices), to rewrite with [withoutAdFormats]. */
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
index 3a8b9847..48340be6 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
@@ -17,6 +17,7 @@ import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
+import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.UUID
@@ -51,9 +52,11 @@ class BridgeGql(private val bridge: Bridge, private val source: OpsSource) : Gql
override suspend fun query(name: String, variables: JsonObject): JsonElement =
bridge.call("gql.query", buildJsonObject {
put("name", name)
+ // The page's own definitions say "mutation" for writes (never cached or deduplicated).
+ put("operation", if (isMutation(name)) "mutation" else "query")
put("hash", ops.hash(name))
put("variables", variables)
- })
+ }).also { checkErrors(name, it) }
}
class HttpException(val code: Int, message: String) : Exception("HTTP $code: $message")
@@ -80,6 +83,9 @@ class SpotifyHttp(
/** Sends a request with browser headers. Returns the status and body text. */
suspend fun send(method: String, url: String, body: String? = null, contentType: String = JSON_TYPE, accept: String = "application/json"): Pair<Int, String> {
+ // The account's token only ever goes to Spotify itself.
+ val host = url.toHttpUrl().host
+ require(host == "spotify.com" || host.endsWith(".spotify.com")) { "not a Spotify host: $host" }
val (w, c) = tokens()
val builder = Request.Builder().url(url)
.header("authorization", "Bearer ${w.access}")
@@ -159,6 +165,25 @@ class SpotifyHttp(
}
}
+/** Operations that change something: not replayed when their outcome is unknown, and any error fails them. */
+fun isMutation(name: String): Boolean =
+ Regex("^(add|remove|move|update|delete|set|create|follow|unfollow|pin|unpin|edit|save|ban|unban|clear)[A-Z]").containsMatchIn(name)
+
+/**
+ * Throws when [response] reports a failure: errors without data for a read, any error or
+ * no data at all for a mutation, where partial data would otherwise pass for a success.
+ */
+fun checkErrors(name: String, response: JsonElement) {
+ val obj = response as? JsonObject ?: return
+ val errors = obj["errors"]?.let { it as? kotlinx.serialization.json.JsonArray }?.takeIf { it.isNotEmpty() }
+ val data = obj["data"]?.takeIf { it !is kotlinx.serialization.json.JsonNull } as? JsonObject
+ val failed = if (isMutation(name)) errors != null || data == null
+ else errors != null && data == null
+ if (!failed) return
+ val message = runCatching { errors!!.first().jsonObject["message"]!!.jsonPrimitive.content }.getOrDefault("no result")
+ throw GqlException(name, message)
+}
+
/** GraphQL straight to api-partner: fastest, parallel, independent of the page. Falls back to [fallback]. */
class HttpGql(private val http: SpotifyHttp, private val source: OpsSource, private val fallback: Gql) : Gql {
private val ops get() = source.ops
@@ -177,16 +202,26 @@ class HttpGql(private val http: SpotifyHttp, private val source: OpsSource, priv
}
}
}
- val (code, text) = runCatching { http.send("POST", "https://api-partner.spotify.com/pathfinder/v2/query", body.toString()) }
- .getOrElse { fellBack.incrementAndGet(); return fallback.query(name, variables) }
- if (code != 200) { fellBack.incrementAndGet(); return fallback.query(name, variables) }
+ val mutation = isMutation(name)
+ val (code, text) = try {
+ http.send("POST", "https://api-partner.spotify.com/pathfinder/v2/query", body.toString())
+ } catch (e: kotlinx.coroutines.CancellationException) {
+ throw e
+ } catch (e: java.io.IOException) {
+ // The write may have reached Spotify before the connection broke: never sent twice.
+ if (mutation) throw GqlException(name, "no answer: ${e.message}")
+ fellBack.incrementAndGet(); return fallback.query(name, variables)
+ } catch (e: Exception) {
+ fellBack.incrementAndGet(); return fallback.query(name, variables)
+ }
+ if (code != 200) {
+ // A server error may come after the write was done; a refusal (4xx) was not applied.
+ if (mutation && code >= 500) throw GqlException(name, "HTTP $code")
+ fellBack.incrementAndGet(); return fallback.query(name, variables)
+ }
direct.incrementAndGet()
val response = Bridge.json.parseToJsonElement(text)
- val errors = (response as? JsonObject)?.get("errors")
- if (errors != null && (response as JsonObject)["data"].let { it == null || it is kotlinx.serialization.json.JsonNull }) {
- val message = runCatching { errors.jsonArray.first().jsonObject["message"]!!.jsonPrimitive.content }.getOrDefault("error")
- throw GqlException(name, message)
- }
+ checkErrors(name, response)
return response
}
}
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
index 649c0fc0..355f44b6 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
@@ -16,14 +16,15 @@ class StallTest {
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))
+ @Test fun `a playing song is fine`() = assertNull(SpotifyPlayer.stallOf(state(100_000, 0), 50_000, false))
+ @Test fun `clock past the end`() = assertEquals("past the end", SpotifyPlayer.stallOf(state(190_000, 0), 20_000, false))
+ @Test fun `paused by itself at the end`() = assertEquals("paused at the end", SpotifyPlayer.stallOf(state(199_500, 0, paused = true), 60_000, false))
+ @Test fun `paused by the user at the end`() = assertNull(SpotifyPlayer.stallOf(state(199_500, 0, paused = true), 60_000, true))
+ @Test fun `last song of the list`() = assertNull(SpotifyPlayer.stallOf(state(199_500, 0, paused = true, next = null), 60_000, false))
+ @Test fun `a user pause at the end never expires`() = assertNull(SpotifyPlayer.stallOf(state(199_500, 0, paused = true), 600_000, true))
+ @Test fun `paused mid-song`() = assertNull(SpotifyPlayer.stallOf(state(50_000, 0, paused = true), 60_000, false))
+ @Test fun `buffering for long`() = assertEquals("buffering", SpotifyPlayer.stallOf(state(0, 0, buffering = true), 20_000, false))
+ @Test fun `buffering a moment`() = assertNull(SpotifyPlayer.stallOf(state(0, 0, buffering = true), 5_000, false))
@Test fun `a stuck ad is skipped twice, then the page reloads`() {
assertEquals("next", SpotifyPlayer.adRecovery(1))
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt
index 771409d6..eceaf32c 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockTest.kt
@@ -13,6 +13,18 @@ class AdBlockTest {
assertFalse(AdBlock.isBlocked("https://evil.com/adstudio-assets.scdn.co/x.mp3"))
}
+ @Test
+ fun `blocks foreign ad servers and spclient ad paths`() {
+ assertTrue(AdBlock.isBlocked("https://pubads.g.doubleclick.net/gampad/ads?x=1"))
+ assertTrue(AdBlock.isBlocked("https://imasdk.googleapis.com/js/sdkloader/ima3.js"))
+ assertTrue(AdBlock.isBlocked("https://spclient.wg.spotify.com/ads/v2/config"))
+ assertTrue(AdBlock.isBlocked("https://gew4-spclient.spotify.com/ad-logic/state/config?a=b"))
+ assertFalse(AdBlock.isBlocked("https://gew4-spclient.spotify.com/track-playback/v1/devices"))
+ assertFalse(AdBlock.isBlocked("https://gew4-spclient.spotify.com/metadata/4/track/abc?ads=1"))
+ assertFalse(AdBlock.isBlocked("https://api-partner.spotify.com/pathfinder/v2/query"))
+ assertFalse(AdBlock.isBlocked("https://open.spotify.com/ads/"))
+ }
+
@Test
fun `base62 ids convert to metadata gids`() {
// Pair checked against a captured metadata/4 request.
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/gql/GqlErrorsTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/gql/GqlErrorsTest.kt
new file mode 100644
index 00000000..00535630
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/gql/GqlErrorsTest.kt
@@ -0,0 +1,37 @@
+package app.myspoti.spotify.gql
+
+import app.myspoti.spotify.bridge.Bridge
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.assertDoesNotThrow
+import org.junit.jupiter.api.assertThrows
+
+class GqlErrorsTest {
+ private fun json(s: String) = Bridge.json.parseToJsonElement(s)
+
+ @Test fun `writes are told from reads`() {
+ assertTrue(isMutation("addToPlaylist"))
+ assertTrue(isMutation("unfollowUsers"))
+ assertTrue(isMutation("removeRecentSearches"))
+ assertFalse(isMutation("fetchPlaylist"))
+ assertFalse(isMutation("searchTracks"))
+ assertFalse(isMutation("address"))
+ }
+
+ @Test fun `a refused write with partial data fails`() {
+ assertThrows<GqlException> {
+ checkErrors("addToPlaylist", json("""{"data":{"addToPlaylist":null},"errors":[{"message":"Forbidden"}]}"""))
+ }
+ assertThrows<GqlException> { checkErrors("addToPlaylist", json("""{"data":null}""")) }
+ }
+
+ @Test fun `a done write passes`() = assertDoesNotThrow {
+ checkErrors("addToPlaylist", json("""{"data":{"addToPlaylist":{"__typename":"AddToPlaylistResponse"}}}"""))
+ }
+
+ @Test fun `a read keeps partial data`() {
+ assertDoesNotThrow { checkErrors("home", json("""{"data":{"home":{}},"errors":[{"message":"one shelf failed"}]}""")) }
+ assertThrows<GqlException> { checkErrors("home", json("""{"data":null,"errors":[{"message":"boom"}]}""")) }
+ }
+}
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index 7daea128..2331fa83 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -95,6 +95,17 @@ class MainActivity : AppCompatActivity() {
handle(intent)
}
+ // The clip player follows the app on screen: paused with its side jobs in the background.
+ override fun onStart() {
+ super.onStart()
+ com.music.spotui.video.MusicVideoController.onForeground()
+ }
+
+ override fun onStop() {
+ super.onStop()
+ if (!isChangingConfigurations) com.music.spotui.video.MusicVideoController.onBackground()
+ }
+
override fun onDestroy() {
// The process-wide WebView lives in this activity's root while attached:
// detach it, or view.parent -> root keeps the destroyed activity (and its
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
index 547c2c53..ee60d777 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
@@ -74,28 +74,47 @@ object OfflineStore {
fun init(context: Context) {
if (::root.isInitialized) return
- root = File(context.filesDir, "offline")
- audioDir.mkdirs(); coverDir.mkdirs()
- // The index lists only finished files; anything else in the folders is a leftover.
- val list = readIndex()
- val kept = list.filter { File(audioDir, it.file).isFile }
- kept.forEach { tracks[it.trackId] = it }
- if (kept.size != list.size) writeIndex()
- val names = kept.map { it.file }.toSet()
- audioDir.listFiles()?.forEach { if (it.name !in names) it.delete() }
- val covers = kept.map { it.cover }.toSet()
- coverDir.listFiles()?.forEach { if (it.name !in covers) it.delete() }
+ val plain = load(File(context.filesDir, "offline"))
// Songs downloaded before encryption existed: encrypted once, in the background.
- val plain = kept.map { File(audioDir, it.file) }
if (plain.isNotEmpty()) Thread {
plain.forEach { f -> runCatching { OfflineCrypto.encryptInPlace(context.applicationContext, f) }
.onFailure { android.util.Log.w("Offline", "could not encrypt ${f.name}: ${it.message}") } }
}.apply { name = "offline-encrypt"; priority = Thread.MIN_PRIORITY }.start()
}
+ /** Reads the downloads in [dir] into [tracks]; returns the audio files of the songs found. */
+ internal fun load(dir: File): List<File> {
+ root = dir
+ tracks.clear()
+ audioDir.mkdirs(); coverDir.mkdirs()
+ // The index lists only finished files; anything else in the folders is a leftover.
+ // An index that cannot be read fully is never trusted to delete anything: the last
+ // good copy is used instead, and if that fails too the files are all kept.
+ val read = readIndex(indexFile) ?: run {
+ if (indexFile.exists()) {
+ indexFile.copyTo(File(root, "index.corrupt-${System.currentTimeMillis()}.json"), overwrite = true)
+ runCatching { android.util.Log.w("Offline", "download index unreadable; using the backup, no file deleted") }
+ }
+ readIndex(backupFile)
+ }
+ val list = read?.tracks.orEmpty()
+ val kept = list.filter { File(audioDir, it.file).isFile }
+ kept.forEach { tracks[it.trackId] = it }
+ if (read != null && read.complete) {
+ if (kept.size != list.size || read.file == backupFile) writeIndex()
+ val names = kept.map { it.file }.toSet()
+ audioDir.listFiles()?.forEach { if (it.name !in names) it.delete() }
+ val covers = kept.map { it.cover }.toSet()
+ coverDir.listFiles()?.forEach { if (it.name !in covers) it.delete() }
+ }
+ return kept.map { File(audioDir, it.file) }
+ }
+
val audioDir: File get() = File(root, "audio")
val coverDir: File get() = File(root, "covers")
private val indexFile: File get() = File(root, "index.json")
+ /** The index before the last write, the fallback when [indexFile] is damaged. */
+ private val backupFile: File get() = File(root, "index.json.bak")
internal val pendingFile: File get() = File(root, "pending.json")
val tmpDir: File get() = File(root, "tmp").apply { mkdirs() }
@@ -178,16 +197,25 @@ object OfflineStore {
fun byLocalId(id: Long): OfflineTrack? =
tracks.values.firstOrNull { localIdOf(it.trackId) == id }
- private fun readIndex(): List<OfflineTrack> = runCatching {
- val a = JSONArray(indexFile.readText())
- (0 until a.length()).mapNotNull { runCatching { OfflineTrack.fromJson(a.getJSONObject(it)) }.getOrNull() }
- }.getOrDefault(emptyList())
+ /** An index read from [file]; [complete] is false when some entries could not be read. */
+ internal class IndexRead(val file: File, val tracks: List<OfflineTrack>, val complete: Boolean)
+
+ /** [file] read, an empty index when it does not exist, null when it cannot be parsed. */
+ internal fun readIndex(file: File): IndexRead? {
+ if (!file.exists()) return if (file == indexFile && !backupFile.exists()) IndexRead(file, emptyList(), true) else null
+ return runCatching {
+ val a = JSONArray(file.readText())
+ val all = (0 until a.length()).map { runCatching { OfflineTrack.fromJson(a.getJSONObject(it)) }.getOrNull() }
+ IndexRead(file, all.filterNotNull(), all.none { it == null })
+ }.getOrNull()
+ }
private fun writeIndex() {
val a = JSONArray()
tracks.values.forEach { a.put(it.toJson()) }
val tmp = File(root, "index.json.tmp")
tmp.writeText(a.toString())
+ if (indexFile.exists() && readIndex(indexFile)?.complete == true) indexFile.copyTo(backupFile, overwrite = true)
tmp.renameTo(indexFile)
}
}
diff --git a/base/app/src/main/java/com/music/spotui/di/Graph.kt b/base/app/src/main/java/com/music/spotui/di/Graph.kt
index 0e196cd3..c08bb538 100644
--- a/base/app/src/main/java/com/music/spotui/di/Graph.kt
+++ b/base/app/src/main/java/com/music/spotui/di/Graph.kt
@@ -12,8 +12,10 @@ object Graph {
fun init(application: Application) {
app = application
+ // The data saver first: on a metered network with it on, nothing may go out, not even the page.
+ com.music.spotui.data.DataSaver.init(application)
// The Spotify session: hidden Web Player + API (operation hashes refresh themselves).
- MyspotiRuntime.start(application)
+ MyspotiRuntime.start(application, loadPage = !com.music.spotui.data.DataSaver.active)
// The streaming quality the user chose, set on the player at every page load.
com.music.spotui.data.preferences.applyStreamingQuality(com.music.spotui.data.preferences.getStreamingQuality(application))
com.music.spotui.data.local.ListenHistory.init(application)
@@ -25,7 +27,6 @@ object Graph {
com.music.spotui.data.offline.OfflineCollections.refreshAll(application)
com.music.spotui.data.local.LocalPlaylists.init(application)
com.music.spotui.data.local.LibraryOrder.init(application)
- com.music.spotui.data.DataSaver.init(application)
runCatching { com.music.spotui.data.DataSaverGlide.install(application) }
com.music.spotui.data.offline.OfflineDownloader.resumePending()
}
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.kt
index dcc5b175..dcd9a342 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
@@ -1,7 +1,9 @@
package com.music.spotui.di
import app.myspoti.host.android.MyspotiRuntime
+import app.myspoti.host.android.PlaybackService
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.StateFlow
/** Session-wide actions the screens trigger. */
@@ -20,6 +22,12 @@ object SessionActions {
val app = context.applicationContext
app.getSharedPreferences("myspoti_prefs", android.content.Context.MODE_PRIVATE)
.edit().putBoolean("LoggedIn", false).remove("CurrentAccountName").apply()
+ // Nothing of the account keeps playing or showing: local songs, the clip, the notification.
+ LocalPlayer.stop()
+ com.music.spotui.video.MusicVideoController.clearSession()
+ PlaybackService.end()
+ runCatching { MyspotiRuntime.scope.launch { runCatching { MyspotiRuntime.api.player.pause() } } }
+ com.music.spotui.ui.screens.ContextViewModel.clearCache()
com.music.spotui.data.api.Api.HomeCache.clear()
com.music.spotui.data.api.Api.LikedCache.tracks = null
com.music.spotui.data.api.ProfileCache.clearSession()
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 5e4c028f..b7aba67a 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
@@ -16,6 +16,7 @@ import app.myspoti.host.android.NowPlayingInfo
import app.myspoti.host.android.PlaybackService
import com.music.spotui.data.entity.SongsModel
import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.withLock
import java.util.concurrent.ConcurrentHashMap
/**
@@ -652,15 +653,31 @@ object SongPlayer {
intentUntil = SystemClock.elapsedRealtime() + 3000
onLibraryItem(uri, on)
val track = uri.startsWith(SPOTIFY_TRACK_PREFIX)
- command {
- if (uri.startsWith("spotify:playlist:")) {
- if (on) api.playlists.follow(uri) else api.playlists.unfollow(uri)
- } else {
- if (on) api.library.add(listOf(uri)) else api.library.remove(listOf(uri))
+ val write = libraryWrites.incrementAndGet()
+ scope.launch {
+ // One write at a time; a refused one is undone on screen if no newer tap replaced it.
+ libraryLock.withLock {
+ runCatching {
+ if (uri.startsWith("spotify:playlist:")) {
+ if (on) api.playlists.follow(uri) else api.playlists.unfollow(uri)
+ } else {
+ if (on) api.library.add(listOf(uri)) else api.library.remove(listOf(uri))
+ }
+ }.onSuccess {
+ if (track) likedChanges.value++
+ }.onFailure {
+ Log.w(TAG, "library change failed: ${it.message}")
+ if (write == libraryWrites.get()) {
+ intentUntil = 0
+ onLibraryItem(uri, !on)
+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.library_change_failed, android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
}
- if (track) likedChanges.value++
}
}
+ private val libraryLock = kotlinx.coroutines.sync.Mutex()
+ private val libraryWrites = java.util.concurrent.atomic.AtomicInteger()
// ── Music video: Spotify's own clips are not played by this engine; the YouTube
// clips (MusicVideoController) are. These keep the player screen's contract. ──
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ErrorRetry.kt b/base/app/src/main/java/com/music/spotui/ui/components/ErrorRetry.kt
new file mode 100644
index 00000000..013d3927
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/ErrorRetry.kt
@@ -0,0 +1,33 @@
+package com.music.spotui.ui.components
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+
+/** A page or list that could not load: what happened, and a Try again button. */
+@Composable
+fun ErrorRetry(message: String, modifier: Modifier = Modifier, onRetry: () -> Unit) {
+ Column(modifier.fillMaxWidth().padding(24.dp, 40.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(message, color = Color.White, fontSize = 15.sp, textAlign = TextAlign.Center)
+ Spacer(Modifier.height(14.dp))
+ Text(stringResource(R.string.retry_button), color = Color.Black, fontSize = 14.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.clip(RoundedCornerShape(50)).background(Color.White)
+ .pressable(0.96f) { onRetry() }.padding(horizontal = 22.dp, vertical = 10.dp))
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt b/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt
index 9250938f..74c66637 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt
@@ -28,7 +28,7 @@ fun Modifier.pressable(
): Modifier = composed {
val source = remember { MutableInteractionSource() }
val hinted = if (onPressHint == null) Modifier else Modifier.pressHint(onPressHint)
- hinted.then(pressScale(source, pressedScale)).clickable(source, indication = null, enabled = enabled, onClick = onClick)
+ hinted.then(pressScale(source, pressedScale)).clickable(source, indication = null, enabled = enabled, role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
}
/**
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index 4b358962..f4bbc02f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -311,6 +311,18 @@ private fun JamSection(onDismiss: () -> Unit) {
if (token == null || runCatching { jam.join(token) }.isFailure) failed() else onDismiss()
}
}
+ // No scanner on this phone (Play services missing or too old): say so.
+ .addOnFailureListener { failed() }
+ }.padding(vertical = 10.dp))
+ // Join: an invite link copied from a message.
+ Text(stringResource(R.string.jam_paste_link), color = Green, fontSize = 15.sp,
+ modifier = Modifier.fillMaxWidth().clickable {
+ val clip = context.getSystemService(android.content.ClipboardManager::class.java)?.primaryClip
+ val raw = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(context)?.toString().orEmpty()
+ scope.launch {
+ val token = JamLinks.token(raw)
+ if (token == null || runCatching { jam.join(token) }.isFailure) failed() else onDismiss()
+ }
}.padding(vertical = 10.dp))
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt
index ab43b261..039db9c9 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt
@@ -66,6 +66,7 @@ import com.music.spotui.data.entity.ContextPageModel
import com.music.spotui.ui.theme.AppAccent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
/**
@@ -93,6 +94,23 @@ fun PlaylistOptionsSheet(
if (mine) access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()
}
+ // Taps are sent one at a time, in order; a refused one puts back what Spotify really has.
+ val accessWrites = remember { kotlinx.coroutines.sync.Mutex() }
+ fun setAccess(target: PlaylistAccess) {
+ if (access == target) return
+ access = target
+ scope.launch {
+ accessWrites.withLock {
+ runCatching { MyspotiRuntime.api.playlists.setAccess(page.uri, target) }
+ .onSuccess { onChanged() }
+ .onFailure {
+ access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()
+ android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+ }
+
fun run(block: suspend () -> Unit, after: () -> Unit = onChanged) = scope.launch {
runCatching { block() }
.onSuccess { after() }
@@ -108,13 +126,13 @@ fun PlaylistOptionsSheet(
Text(stringResource(R.string.playlist_access_title), color = Color(0xFFB3B3B3), fontSize = 13.sp,
modifier = Modifier.padding(20.dp, 12.dp, 20.dp, 4.dp))
AccessRow(Icons.Outlined.Public, R.string.playlist_access_public, R.string.playlist_access_public_detail, access == PlaylistAccess.PUBLIC) {
- access = PlaylistAccess.PUBLIC; run({ MyspotiRuntime.api.playlists.setAccess(page.uri, PlaylistAccess.PUBLIC) }, {})
+ setAccess(PlaylistAccess.PUBLIC)
}
AccessRow(Icons.Outlined.Lock, R.string.playlist_access_private, R.string.playlist_access_private_detail, access == PlaylistAccess.PRIVATE) {
- access = PlaylistAccess.PRIVATE; run({ MyspotiRuntime.api.playlists.setAccess(page.uri, PlaylistAccess.PRIVATE) }, {})
+ setAccess(PlaylistAccess.PRIVATE)
}
AccessRow(Icons.Outlined.Group, R.string.playlist_access_collaborative, R.string.playlist_access_collaborative_detail, access == PlaylistAccess.COLLABORATIVE) {
- access = PlaylistAccess.COLLABORATIVE; run({ MyspotiRuntime.api.playlists.setAccess(page.uri, PlaylistAccess.COLLABORATIVE) }, {})
+ setAccess(PlaylistAccess.COLLABORATIVE)
}
Spacer(Modifier.height(8.dp))
OptionRow(Icons.Outlined.Delete, stringResource(R.string.local_delete_playlist)) { deleting = true }
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt
index c08f4caf..f4e3a4de 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt
@@ -99,10 +99,16 @@ fun ArtistScreen(navController: NavController, artistName: String, artistId: Str
) {
when (val state = overview) {
is Response.Loading -> Loader(SkeletonKind.Header)
- is Response.Error -> ArtistOverviewContent(
- navController, artistViewModel,
- ArtistOverviewModel(name = artistName), artistName,
- )
+ is Response.Error -> androidx.compose.foundation.layout.Column(Modifier.fillMaxSize().statusBarsPadding()) {
+ androidx.compose.material3.Icon(
+ androidx.compose.material.icons.Icons.AutoMirrored.Filled.ArrowBack,
+ stringResource(R.string.accessibility_navigate_back), tint = Color.White,
+ modifier = Modifier.pressable(0.96f) { navController.navigateUp() }.padding(16.dp).size(26.dp),
+ )
+ com.music.spotui.ui.components.ErrorRetry(stringResource(R.string.page_load_failed)) {
+ artistViewModel.loadArtistOverview(artistName, artistId)
+ }
+ }
is Response.Success -> ArtistOverviewContent(
navController, artistViewModel, state.data, artistName,
)
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 e69686b5..7a874d16 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
@@ -100,6 +100,9 @@ class ContextViewModel(
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Response<ContextPageModel>>?) = size > 12
}.let { java.util.Collections.synchronizedMap(it) }
+ /** Signed out: the pages shown belong to the old account. */
+ fun clearCache() { recent.clear(); inflight.values.forEach { it.cancel() }; inflight.clear() }
+
// Look-ups started by a touch (see pressHint), joined by the page when it opens.
private val inflight = java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.Deferred<Unit>>()
private val prefetchScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)
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 b1973c14..c795f843 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
@@ -74,6 +74,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.music.spotui.ui.components.pressable
+import androidx.compose.material.icons.outlined.Lyrics
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.runtime.setValue
@@ -446,6 +447,7 @@ fun PlayerScreen(navController: NavController) {
context = context,
onDevices = { showDevices = true },
onQueue = { showQueue = true },
+ onLyrics = { showLyrics = true },
)
Spacer(modifier = Modifier.height(20.dp))
}
@@ -569,7 +571,7 @@ fun PlayerTopBar(
},
painter = painterResource(id = R.drawable.ic_down),
tint = Color.White,
- contentDescription = "")
+ contentDescription = stringResource(R.string.a11y_close_player))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
@@ -826,28 +828,6 @@ fun CustomSlider(
}
}
-@Composable
-fun PlayerEndInfo() {
- Row(verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.SpaceBetween,
- modifier = Modifier
- .fillMaxWidth()
- .padding(20.dp)){
- Icon(
- modifier = Modifier
- .size(22.dp),
- painter = painterResource(id = R.drawable.ic_devices),
- tint = Color.White,
- contentDescription = "")
- Icon(
- modifier = Modifier
- .size(16.dp),
- painter = painterResource(id = R.drawable.ic_share),
- tint = Color.White,
- contentDescription = "")
- }
-}
-
@Composable
fun PlayerFull(
songPlayingState: Boolean,
@@ -892,7 +872,7 @@ fun PlayerFull(
Color.White
},
painter = painterResource(id = R.drawable.ic_player_shuffle),
- contentDescription = "")
+ contentDescription = stringResource(if (shuffle) R.string.notif_shuffle_disable else R.string.notif_shuffle_enable))
Icon(
modifier = Modifier
@@ -905,7 +885,7 @@ fun PlayerFull(
,
tint = Color.White,
painter = painterResource(id = R.drawable.ic_player_back),
- contentDescription = "")
+ contentDescription = stringResource(R.string.np_content_desc_prev))
androidx.compose.foundation.layout.Box(
modifier = Modifier
// requiredSize forces an exact 64×64 square even if the parent Column
@@ -952,7 +932,7 @@ fun PlayerFull(
else
painterResource(id = R.drawable.play_svgrepo_com)
,
- contentDescription = "")
+ contentDescription = stringResource(if (songPlayingState) R.string.notif_action_pause else R.string.notif_action_play))
}
Icon(
@@ -965,7 +945,7 @@ fun PlayerFull(
,
tint = Color.White,
painter = painterResource(id = R.drawable.ic_player_skip),
- contentDescription = "")
+ contentDescription = stringResource(R.string.np_content_desc_next))
Icon(
modifier = Modifier
.size(20.dp)
@@ -991,6 +971,7 @@ fun PlayerConnectRow(
context: Context,
onDevices: () -> Unit,
onQueue: () -> Unit,
+ onLyrics: () -> Unit = {},
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -1025,6 +1006,14 @@ fun PlayerConnectRow(
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
+ // Lyrics also show below the player; this button makes them easy to find.
+ Icon(
+ imageVector = androidx.compose.material.icons.Icons.Outlined.Lyrics,
+ tint = Color.White,
+ modifier = Modifier.size(22.dp).pressable { onLyrics() },
+ contentDescription = stringResource(R.string.lyrics_fullscreen),
+ )
+ Spacer(modifier = Modifier.width(24.dp))
Icon(
painter = painterResource(id = R.drawable.ic_share),
tint = Color.White,
@@ -1034,11 +1023,14 @@ fun PlayerConnectRow(
interactionSource = remember { MutableInteractionSource() },
indication = null,
) {
- val id = SongPlayer.currentTrackId
- if (id.isBlank()) return@clickable
+ // Songs and episodes alike: the link follows what plays (spotify:<kind>:<id>).
+ val parts = SongPlayer.nowPlaying.value.uri.split(':')
+ val link = if (parts.size == 3 && parts[0] == "spotify") "https://open.spotify.com/${parts[1]}/${parts[2]}"
+ else SongPlayer.currentTrackId.takeIf { it.isNotBlank() }?.let { "https://open.spotify.com/track/$it" }
+ if (link == null) return@clickable
val send = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
- putExtra(Intent.EXTRA_TEXT, "https://open.spotify.com/track/$id")
+ putExtra(Intent.EXTRA_TEXT, link)
}
context.startActivity(Intent.createChooser(send, context.getString(R.string.action_share_label)))
},
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt
index 41770829..065934c7 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt
@@ -68,7 +68,9 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String
var following by remember(userId) { mutableStateOf<Boolean?>(null) }
val me = com.music.spotui.data.api.ProfileCache.id == userId
val scope = rememberCoroutineScope()
- LaunchedEffect(userId) {
+ var attempt by remember(userId) { mutableStateOf(0) }
+ LaunchedEffect(userId, attempt) {
+ failed = false
runCatching { MyspotiRuntime.api.users.profile(uri) }
.onSuccess { profile = it }.onFailure { failed = true }
if (!me) following = runCatching { MyspotiRuntime.api.users.isFollowing(listOf(uri)).single() }.getOrNull()
@@ -134,7 +136,7 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String
}
}
p == null -> item {
- Text(stringResource(R.string.home_error), color = Color.White, modifier = Modifier.padding(16.dp))
+ com.music.spotui.ui.components.ErrorRetry(stringResource(R.string.page_load_failed)) { attempt++ }
}
p.publicPlaylists.isNotEmpty() -> {
item {
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
index 2b7da9ea..f24763b5 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
@@ -97,7 +97,8 @@ fun SearchScreen(navController: NavController) {
.fillMaxSize()
.background(Color(AppBackground.toArgb()))
) {
- SumUpSearchScreen(navController = navController, searchResults, searchViewModel)
+ SumUpSearchScreen(navController = navController, searchResults, searchViewModel,
+ loading = results is Response.Loading, failed = results is Response.Error)
}
}
@@ -108,12 +109,12 @@ fun SumUpSearchScreen(
navController: NavController,
results: SearchResults,
searchViewModel: SearchViewModel,
+ loading: Boolean = false,
+ failed: Boolean = false,
) {
val context = LocalContext.current
- var text by remember {
- mutableStateOf("")
- }
+ val text = searchViewModel.query
// Recents are the *items opened from results* (songs/artists/albums), not the
// typed queries, and only appear once the user taps into the search bar.
var searchFocused by remember { mutableStateOf(false) }
@@ -122,7 +123,7 @@ fun SumUpSearchScreen(
}
var menuSong by remember { mutableStateOf<SongsModel?>(null) }
// Spotify's filter chips: Top (mixed), or one kind of result.
- var filter by remember { mutableStateOf(SearchFilter.Top) }
+ val filter = searchViewModel.filter
menuSong?.let { sel ->
SongOptionsSheet(
song = sel,
@@ -172,7 +173,6 @@ fun SumUpSearchScreen(
text,
onFocusChange = { searchFocused = it },
) {
- text = it
searchViewModel.search(it)
}
}
@@ -275,7 +275,7 @@ fun SumUpSearchScreen(
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(RoundedCornerShape(50)).background(Color(0xFF2A2A2A))
- .pressable(0.96f) { text = q; searchViewModel.search(q) }
+ .pressable(0.96f) { searchViewModel.search(q) }
.padding(horizontal = 12.dp, vertical = 7.dp),
) {
Icon(androidx.compose.material.icons.Icons.Default.Search, null, tint = Color(0xFFB3B3B3), modifier = Modifier.size(14.dp))
@@ -285,7 +285,11 @@ fun SumUpSearchScreen(
}
}
}
- item { SearchFilterChips(filter) { filter = it } }
+ item { SearchFilterChips(filter) { searchViewModel.filter = it } }
+ // Loading, nothing found and a failure each say what they are (never an empty page).
+ if (filter != SearchFilter.Profiles && mixed.isEmpty() && results.shows.isEmpty() && results.episodes.isEmpty()) item {
+ SearchStatus(text, loading, failed) { searchViewModel.retry() }
+ }
if (filter == SearchFilter.Profiles) {
items(profiles.size) { i ->
val u = profiles[i]
@@ -374,6 +378,19 @@ sealed class SearchRow {
}
/** The search filter chips (official labels). Podcasts shows shows + episodes. */
+@Composable
+private fun SearchStatus(query: String, loading: Boolean, failed: Boolean, onRetry: () -> Unit) {
+ Column(Modifier.fillMaxWidth().padding(24.dp, 40.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ when {
+ loading -> androidx.compose.material3.CircularProgressIndicator(color = com.music.spotui.ui.theme.AppAccent)
+ failed -> com.music.spotui.ui.components.ErrorRetry(stringResource(R.string.search_failed), Modifier.padding(0.dp), onRetry)
+ else -> Text(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, query.trim()),
+ color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold,
+ textAlign = androidx.compose.ui.text.style.TextAlign.Center)
+ }
+ }
+}
+
enum class SearchFilter(@androidx.annotation.StringRes val label: Int) {
Top(R.string.assisted_curation_search_filter_top),
Songs(R.string.assisted_curation_search_filter_songs),
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/ArtistViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/ArtistViewModel.kt
index 72879b45..3c623d94 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/ArtistViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/ArtistViewModel.kt
@@ -77,6 +77,8 @@ class ArtistViewModel constructor(private val repository: AppRepository = Graph.
viewModelScope.launch(Dispatchers.IO) {
repository.provideArtistOverview(artistName, artistId).collect { overview ->
_overview.value = overview
+ // A failed page may be loaded again (Try again, or opening it anew).
+ if (overview is Response.Error) loadedOverview = null
// Keep the legacy songs flow in sync (popular tracks) so any
// other consumer and the play/queue helpers still work.
if (overview is Response.Success) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt
index dd2feace..88103738 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/SearchViewModel.kt
@@ -2,6 +2,8 @@ package com.music.spotui.ui.viewmodel
import com.music.spotui.di.Graph
import androidx.compose.runtime.State
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.music.spotui.data.api.Response
@@ -35,6 +37,13 @@ class SearchViewModel constructor(private val repository: AppRepository = Graph.
private var searchJob: Job? = null
+ /** What is typed and the chip picked: kept here so they are still there back from a result. */
+ var query by androidx.compose.runtime.mutableStateOf("")
+ var filter by androidx.compose.runtime.mutableStateOf(com.music.spotui.ui.screens.SearchFilter.Top)
+
+ /** Runs the last search again (after an error). */
+ fun retry() = search(query)
+
init {
// Start empty — results come from live searches, not the rate-limited
// personalized top-tracks feed (which returned 429 and blanked the screen).
@@ -70,11 +79,14 @@ class SearchViewModel constructor(private val repository: AppRepository = Graph.
}
fun search(query: String) {
+ this.query = query
searchJob?.cancel()
searchJob = viewModelScope.launch(Dispatchers.IO) {
delay(150) // short debounce for snappy real-time results
repository.searchEverything(query).collect { result ->
- _results.value = result
+ // While the next results load, the last ones stay on screen.
+ val keep = result is Response.Loading && (_results.value as? Response.Success)?.data?.let { it != SearchResults() } == true
+ if (!keep) _results.value = result
// Keep the legacy songs flow in sync for any remaining consumers.
_songs.value = when (result) {
is Response.Success -> Response.Success(result.data.songs)
diff --git a/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt b/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt
index 69c8e9bf..20d2f4fe 100644
--- a/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt
+++ b/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt
@@ -529,7 +529,8 @@ object MusicVideoController {
}
}
}
- @Volatile private var appVisible = true
+ // Set by the activity's onStart / onStop; nothing is on screen before the first start.
+ @Volatile private var appVisible = false
/** The app is on screen (look-ups at track start then, not in the background). */
val inForeground: Boolean get() = appVisible
@@ -770,6 +771,19 @@ object MusicVideoController {
}
}
+ /** Signed out: no clip, no lookups, nothing kept from the account's songs. */
+ fun clearSession() {
+ wantVideo = false
+ on.value = false
+ prepareJob?.cancel()
+ prefetchJobs.values.forEach { it.cancel() }
+ stop()
+ player?.stop()
+ currentTrackId = ""
+ warmedFor = null
+ state.value = State.Idle
+ }
+
/** App in the background: the video pauses (nothing to show), video mode stays. */
fun onBackground() {
appVisible = false
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 85121c04..7da0ca7f 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -298,4 +298,12 @@
<string name="more_like_this">Dans le même style</string>
<string name="library_sort_recents">Récents</string>
<string name="library_sort_recently_added">Ajoutés récemment</string>
+ <string name="library_change_failed">Impossible de mettre à jour ta bibliothèque, réessaie</string>
+ <string name="a11y_close_player">Fermer le lecteur</string>
+ <string name="a11y_devices">Appareils</string>
+ <string name="a11y_share">Partager</string>
+ <string name="search_failed">La recherche a échoué. Vérifie ta connexion.</string>
+ <string name="retry_button">Réessayer</string>
+ <string name="page_load_failed">Impossible de charger cette page.\nVérifie ta connexion et réessaie.</string>
+ <string name="jam_paste_link">Rejoindre avec un lien copié</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index db3c739a..9916abfe 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -298,4 +298,12 @@
<string name="more_like_this">Simili</string>
<string name="library_sort_recents">Recenti</string>
<string name="library_sort_recently_added">Aggiunti di recente</string>
+ <string name="library_change_failed">Impossibile aggiornare la libreria, riprova</string>
+ <string name="a11y_close_player">Chiudi il lettore</string>
+ <string name="a11y_devices">Dispositivi</string>
+ <string name="a11y_share">Condividi</string>
+ <string name="search_failed">Ricerca non riuscita. Controlla la connessione.</string>
+ <string name="retry_button">Riprova</string>
+ <string name="page_load_failed">Impossibile caricare questa pagina.\nControlla la connessione e riprova.</string>
+ <string name="jam_paste_link">Partecipa con un link copiato</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 f1a67ffc..98a572d8 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -298,4 +298,12 @@
<string name="more_like_this">More like this</string>
<string name="library_sort_recents">Recents</string>
<string name="library_sort_recently_added">Recently added</string>
+ <string name="library_change_failed">Could not update your library, try again</string>
+ <string name="a11y_close_player">Close the player</string>
+ <string name="a11y_devices">Devices</string>
+ <string name="a11y_share">Share</string>
+ <string name="search_failed">Search failed. Check your connection.</string>
+ <string name="retry_button">Try again</string>
+ <string name="page_load_failed">Couldn\'t load this page.\nCheck your connection and try again.</string>
+ <string name="jam_paste_link">Join with a copied link</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/data/offline/OfflineIndexTest.kt b/base/app/src/test/java/com/music/spotui/data/offline/OfflineIndexTest.kt
new file mode 100644
index 00000000..e5bb7d71
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/offline/OfflineIndexTest.kt
@@ -0,0 +1,53 @@
+package com.music.spotui.data.offline
+
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+import java.nio.file.Files
+
+class OfflineIndexTest {
+ private fun entry(id: String) = JSONObject().put("id", id).put("file", "$id.m4a").put("cover", "$id.jpg")
+
+ private fun folder(index: String?, vararg ids: String): File {
+ val root = Files.createTempDirectory("offline").toFile()
+ File(root, "audio").mkdirs(); File(root, "covers").mkdirs()
+ ids.forEach { File(root, "audio/$it.m4a").writeText("x"); File(root, "covers/$it.jpg").writeText("x") }
+ index?.let { File(root, "index.json").writeText(it) }
+ return root
+ }
+
+ @Test fun truncatedIndexKeepsEveryFile() {
+ val root = folder("[{\"id\":\"a\",\"file\":\"a.m4a\"", "a", "b")
+ OfflineStore.load(root)
+ assertEquals(2, File(root, "audio").list()!!.size)
+ assertEquals(2, File(root, "covers").list()!!.size)
+ assertTrue(root.list()!!.any { it.startsWith("index.corrupt-") })
+ }
+
+ @Test fun unreadableEntryKeepsEveryFile() {
+ val root = folder(JSONArray().put(entry("a")).put(JSONObject().put("title", "no id")).toString(), "a", "b")
+ OfflineStore.load(root)
+ assertEquals(setOf("a"), OfflineStore.tracks.keys.toSet())
+ assertEquals(2, File(root, "audio").list()!!.size)
+ }
+
+ @Test fun backupIsUsedWhenTheIndexIsDamaged() {
+ val root = folder("{oops", "a", "b")
+ File(root, "index.json.bak").writeText(JSONArray().put(entry("a")).put(entry("b")).toString())
+ OfflineStore.load(root)
+ assertEquals(setOf("a", "b"), OfflineStore.tracks.keys.toSet())
+ assertEquals(2, File(root, "audio").list()!!.size)
+ }
+
+ @Test fun validIndexStillRemovesLeftovers() {
+ val root = folder(JSONArray().put(entry("a")).toString(), "a", "b")
+ OfflineStore.load(root)
+ assertEquals(setOf("a"), OfflineStore.tracks.keys.toSet())
+ assertFalse(File(root, "audio/b.m4a").exists())
+ assertTrue(File(root, "audio/a.m4a").exists())
+ }
+}
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 5d7313cd..b85b1f9b 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
@@ -25,7 +25,8 @@ object MyspotiRuntime {
val isStarted: Boolean get() = ::host.isInitialized
val loginRequired: StateFlow<Boolean> get() = host.loginRequired
- fun start(context: Context) {
+ /** [loadPage] false (data saver on a metered network): nothing goes out until [resume]. */
+ fun start(context: Context, loadPage: Boolean = true) {
if (isStarted) return
val updater = app.myspoti.spotify.gql.GqlOpsUpdater(okhttp3.OkHttpClient(), java.io.File(context.filesDir, "spotify/gql-ops.json"))
host = WebPlayerHost(context)
@@ -42,6 +43,7 @@ object MyspotiRuntime {
"track=${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering} url=${host.url.value.take(60)}")
}
}
+ if (!loadPage) return
host.load()
// New Spotify build: pick up its operation hashes (public bundles, no account).
scope.launch {
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt
index 01b8091a..f3e99759 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt
@@ -375,6 +375,18 @@ class PlaybackService : MediaBrowserServiceCompat() {
svc.show(info)
}
+ /** Signed out: the notification and the media session go, nothing of the account stays. */
+ fun end() {
+ current = null
+ instance?.let { svc ->
+ svc.handler.removeCallbacksAndMessages(null)
+ ServiceCompat.stopForeground(svc, ServiceCompat.STOP_FOREGROUND_REMOVE)
+ svc.foreground = false
+ svc.session.isActive = false
+ svc.stopSelf()
+ }
+ }
+
/** [remote] when a Connect device plays; [volume] 0..100. */
fun setPlaybackDevice(remote: Boolean, volume: Int) { instance?.setRemote(remote, volume) }
}
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 ed7b343c..6b627481 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
@@ -141,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/*") }) }
+ AdBlock.blockedPaths.forEach { p -> add(buildJsonObject { put("urlPattern", "*spclient*$p*") }) }
add(buildJsonObject { put("urlPattern", "*/track-playback/v1/devices") })
})
})
diff --git a/docs/CHANGELOG-full.md b/docs/CHANGELOG-full.md
index eca86d9e..ef081916 100644
--- a/docs/CHANGELOG-full.md
+++ b/docs/CHANGELOG-full.md
@@ -2,6 +2,21 @@
Every change, release by release. The short version is in [CHANGELOG.md](../CHANGELOG.md), which the app and the GitHub releases show.
+## 2.0.0-beta.6
+
+- **Ads in other countries**: Google's ad servers (audio and video ads), the ad event tracker and Spotify's ad endpoints (`/ads/`, `/ad-logic/` on spclient) are refused. An ad that plays anyway is muted at once and skipped after 1.5 s; if the page holds on to it after one reload, it stays muted until it ends. The volume comes back after the ad, and after a restart if the app was closed during one.
+- **Pause**: a pause you ask for no longer expires; the stall watchdog never restarts playback after it, even when paused in the last seconds of a song.
+- **Download index**: an index that cannot be read fully is never used to delete files. The last good copy (`index.json.bak`) is used, the damaged one is kept aside (`index.corrupt-*.json`), and no file is deleted.
+- **Spotify writes**: a write (add to playlist, follow…) is never sent twice when its answer is lost; a GraphQL error on a write is a failure, not a success. Likes, library saves and playlist visibility go one at a time and come back to the real state when Spotify refuses, with a message.
+- **Search**: query and chip kept when coming back from a result; loading, no results and failure are shown apart, with Try again. Artist and profile pages show an error with Try again instead of an empty page.
+- **Player**: a lyrics button next to share (lyrics were only reachable by scrolling); share sends the episode link for episodes; play, pause, next, previous, shuffle, close and devices have names for TalkBack.
+- **Jam**: "Join with a copied link"; a phone without the QR scanner gets a message instead of nothing.
+- **Logout** stops local playback, the music video and the notification, pauses Spotify and drops the cached pages.
+- **Data saver**: on mobile data with the saver on, the Spotify page is not loaded at launch.
+- **Music video** pauses with its lookups when the app leaves the screen.
+- The account token is only ever sent to Spotify hosts.
+- CI also runs the API tests.
+
## 2.0.0-beta.5
- **Downloads are encrypted**: a downloaded song only plays in Myspoti, on the phone that downloaded it. Songs downloaded before are encrypted in the background.