Skip to content

Native Android client for Spotify, built with Jetpack Compose

Discreet ad blocking; transport commands queued with play check; fades against the pop; smart shuffle in the player; Apple word-synced lyrics; remote state refresh; end-of-track timer for every source; full discography

kota-zo8d58ad141676
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c2885e7..25451e73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,13 @@ Each release on GitHub shows its section below. The app shows it too when it off
## 2.0.0-beta.6
-- **Fewer ads abroad**: ads from other countries' ad servers, sponsored playlists and promotion shelves are blocked; ads are recognised even when they look like songs; an ad that still gets through is muted and skipped.
+- **Fewer ads abroad**: ads from other countries' ad servers are blocked, sponsored playlists and promotion shelves are hidden; ads are recognised even when they look like songs; an ad that still gets through is muted and skipped.
+- **Steadier player**: play, pause and skips go one at a time (fast taps no longer jam it), and a song that did not start is asked again.
+- **No more "pop" between songs**: a very short fade on every skip.
+- **Smart shuffle from the player**: tap shuffle twice on a playlist or Liked Songs.
+- **Word-by-word lyrics from Apple Music** when they exist, replacing line-by-line ones as soon as they arrive.
+- **Remote control**: with another device playing, the notification and the slider keep up.
+- **Sleep timer "end of track"** works with episodes, local files and repeat one; artist pages load the whole discography.
- **Artist discography** (Releases) shows albums and singles again.
- **Long names fit**: long playlist names and artist mixes no longer push the layout; big titles shrink to fit, cards in a row keep the same height.
- **A pause stays a pause**, even right at the end of a song.
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 ba85d923..c464b35f 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
@@ -180,8 +180,43 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
+ // ── Fades: a song cut off at full volume pops in the phone's speaker. Each skip or play
+ // lowers the sound over ~0.1 s first and brings it back once the next song plays. ──
+
+ /** The volume a fade comes back to, while one is under way. */
+ @Volatile private var fadeBackTo: Double? = null
+ private var fadeBack: kotlinx.coroutines.Job? = null
+
+ private suspend fun setLevel(level: Double) {
+ bridge.call("volume.set", buildJsonObject { put("level", level.coerceIn(0.0, 1.0)) })
+ }
+
+ private suspend fun withFade(block: suspend () -> Unit) {
+ val s = _state.value
+ // Nothing heard (paused, an ad muted): nothing to fade.
+ if (s == null || s.isPaused || _adPlaying.value || volumeBeforeAd != null) { block(); return }
+ val target = fadeBackTo ?: runCatching { volume() }.getOrNull()?.takeIf { it > 0.0 } ?: run { block(); return }
+ fadeBackTo = target
+ fadeBack?.cancel()
+ runCatching { for (f in FADE_STEPS) { setLevel(target * f); delay(FADE_STEP_MS) } }
+ try {
+ block()
+ } finally {
+ fadeBack = scope.launch {
+ delay(FADE_STEP_MS * 3)
+ // The next song really plays (or give up waiting): the sound comes back.
+ withTimeoutOrNull(FADE_BACK_MAX_MS) { _state.first { it != null && !it.isBuffering && !it.isPaused } }
+ if (_adPlaying.value) { if (volumeBeforeAd == null) volumeBeforeAd = target; fadeBackTo = null; return@launch }
+ val back = fadeBackTo ?: target
+ runCatching { for (f in FADE_STEPS.reversed().drop(1)) { setLevel(back * f); delay(FADE_STEP_MS) }; setLevel(back) }
+ .onFailure { runCatching { setLevel(back) } }
+ fadeBackTo = null
+ }
+ }
+ }
+
private suspend fun muteForAd() = runCatching {
- if (volumeBeforeAd == null) volumeBeforeAd = volume().takeIf { it > 0.0 } ?: 1.0
+ if (volumeBeforeAd == null) volumeBeforeAd = fadeBackTo ?: volume().takeIf { it > 0.0 } ?: 1.0
bridge.call("volume.set", buildJsonObject { put("level", 0.0) })
}
@@ -194,20 +229,22 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
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)) } } }
- trackUri?.let { put("trackUri", it) }
- index?.let { put("index", it) }
- positionMs?.let { put("positionMs", it) }
- })
+ withFade {
+ bridge.call("player.play", buildJsonObject {
+ put("contextUri", contextUri)
+ order?.let { uris -> putJsonArray("order") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } } }
+ trackUri?.let { put("trackUri", it) }
+ index?.let { put("index", it) }
+ positionMs?.let { put("positionMs", it) }
+ })
+ }
}
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() { pausedByUser = false; bridge.call("player.next") }
- override suspend fun previous() { pausedByUser = false; bridge.call("player.previous") }
+ override suspend fun next() { pausedByUser = false; withFade { bridge.call("player.next") } }
+ override suspend fun previous() { pausedByUser = false; withFade { bridge.call("player.previous") } }
override suspend fun setShuffle(on: Boolean) { bridge.call("player.setShuffle", buildJsonObject { put("on", on) }) }
override suspend fun setRepeat(mode: Repeat) {
@@ -230,7 +267,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) { pausedByUser = false; bridge.call("queue.skipTo", ref(item)) }
+ override suspend fun skipTo(item: NowPlaying) { pausedByUser = false; withFade { bridge.call("queue.skipTo", ref(item)) } }
override suspend fun playNext(uris: List<Uri>) {
val first = _queue.value?.queued?.firstOrNull()
@@ -255,6 +292,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
override suspend fun volume(): Double = bridge.call("volume.get").jsonPrimitive.double
override suspend fun setVolume(level: Double) {
+ if (fadeBackTo != null) fadeBackTo = level.coerceIn(0.0, 1.0)
bridge.call("volume.set", buildJsonObject { put("level", level.coerceIn(0.0, 1.0)) })
}
@@ -286,6 +324,11 @@ 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
+ /** Volume steps of a fade (down; reversed to come back). */
+ val FADE_STEPS = listOf(0.55, 0.25, 0.08, 0.0)
+ const val FADE_STEP_MS = 25L
+ /** The sound always comes back after that long, whatever the page does. */
+ const val FADE_BACK_MAX_MS = 4_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
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 3f13fb4c..2b7b129c 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
@@ -40,28 +40,29 @@ object BridgeScript {
*/
object AdBlock {
/**
- * 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.
+ * Only ad media and third-party ad servers are refused. Spotify's own ad endpoints (ad
+ * config, ad events, sponsored recommendations) are left alone on purpose: a client that
+ * never calls them stands out. Ads that come anyway are muted and skipped by the player,
+ * and sponsored content is dropped from the screens.
*/
val blockedHosts = listOf(
+ // The ad audio files.
"adstudio-assets.scdn.co",
- "adeventtracker.spotify.com",
+ // Google's ad servers (audio and video ads served in other markets).
"pubads.g.doubleclick.net",
"securepubads.g.doubleclick.net",
"googleads.g.doubleclick.net",
"pagead2.googlesyndication.com",
"imasdk.googleapis.com",
- // Sponsored playlists and recommendations.
- "sponsored-recommendations.spotify.com",
- // Ad and audience trackers the page loads (nothing it needs to play).
+ // Third-party audience trackers the page loads (nothing it needs to play).
"googletagmanager.com",
"google-analytics.com",
"scorecardresearch.com",
"fastly-insights.com",
)
- /** Ad endpoints on Spotify's api hosts (spclient): ad slots, ad logic and ad delivery. */
- val blockedPaths = listOf("/ads/", "/ad-logic/")
+ /** Paths refused on Spotify's api hosts; none, see [blockedHosts]. */
+ val blockedPaths = emptyList<String>()
/** 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")
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 46a73925..5d3b0df0 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
@@ -14,11 +14,14 @@ class AdBlockTest {
}
@Test
- fun `blocks foreign ad servers and spclient ad paths`() {
+ fun `blocks foreign ad servers only`() {
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"))
+ // Spotify's own ad endpoints stay reachable: a client that never calls them stands out.
+ assertFalse(AdBlock.isBlocked("https://spclient.wg.spotify.com/ads/v2/config"))
+ assertFalse(AdBlock.isBlocked("https://gew4-spclient.spotify.com/ad-logic/state/config?a=b"))
+ assertFalse(AdBlock.isBlocked("https://adeventtracker.spotify.com/x"))
+ assertFalse(AdBlock.isBlocked("https://sponsored-recommendations.spotify.com/x"))
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"))
diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
index 59356dd2..cb82f4cc 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
@@ -50,6 +50,8 @@ class Api constructor(
/** Process-level caches: screens show the last result at once, then refresh. */
companion object HomeCache {
+ /** Releases loaded for an artist page, at most. */
+ const val DISCOGRAPHY_MAX = 300
/** Sentinel id for the pinned "Liked Songs" library entry. */
const val LIKED_SONGS_ID = "liked-songs"
/** The "Local Files" folder pinned under Liked Songs in the library (not a Spotify item). */
@@ -430,7 +432,18 @@ class Api constructor(
)
emit(Response.Success(model))
// The overview carries only part of the discography: the whole list follows.
- val all = runCatching { api.catalog.discography(uri, 0, 50).items }.getOrNull().orEmpty()
+ // Every page of it (big artists have hundreds of singles), up to a sane cap.
+ val all = runCatching {
+ val out = ArrayList<app.myspoti.api.Album>()
+ var offset: Int? = 0
+ while (offset != null && out.size < DISCOGRAPHY_MAX) {
+ val page = api.catalog.discography(uri, offset, 50)
+ if (page.items.isEmpty()) break
+ out += page.items
+ offset = page.nextOffset
+ }
+ out
+ }.getOrNull().orEmpty()
val known = page.popularReleases.map { it.uri }.toSet()
if (all.any { it.uri !in known }) {
val merged = (page.popularReleases + all).distinctBy { it.uri }.sortedByDescending { it.releaseDate.orEmpty() }
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
index 18d09616..e366d46e 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt
@@ -21,8 +21,11 @@ import java.net.URLEncoder
* 1. Spotify's own color-lyrics, by track id: exactly what the official app shows,
* with its colours and credits.
* 2. LRCLIB (lrclib.net, open API for third-party apps), line-synced or plain.
- * 3. Opt-in ("sources supplémentaires"): LyricsPlus (Apple Music word-synced lyrics),
- * NetEase Cloud Music (line-synced LRC) and Genius (plain text). Off by default.
+ * Apple Music's word-synced lyrics (LyricsPlus mirrors) are always asked too: Spotify's
+ * lyrics show at once, and are swapped for Apple's word-by-word ones when those arrive
+ * ([upgrades]), since they follow every word.
+ * 3. Opt-in ("sources supplémentaires"): NetEase Cloud Music (line-synced LRC) and
+ * Genius (plain text). Off by default.
*
* Fallback results are only kept when title, artist and length match the track.
* LRCLIB asks clients to send a descriptive User-Agent; we oblige.
@@ -32,7 +35,6 @@ object LyricsApi {
private const val UA = "Myspoti (https://github.com/)"
private val LYRICSPLUS = listOf(
"https://lyricsplus.binimum.org",
- "https://lyricsplus.atomix.one",
"https://lyricsplus.prjktla.my.id",
)
@@ -58,9 +60,23 @@ object LyricsApi {
private val scope =
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO)
- /** Set by the settings: also ask the word-synced Apple Music mirrors. */
+ /** Set by the settings: also ask NetEase and Genius when nothing better is found. */
@Volatile var extraSources: Boolean = false
+ /** Word-synced lyrics that replaced a track's first ones after the fact (track key, lyrics). */
+ val upgrades = kotlinx.coroutines.flow.MutableSharedFlow<Pair<String, Lyrics>>(extraBufferCapacity = 8)
+
+ /** Looks for Apple's word-synced lyrics behind line-synced ones; a better result replaces them. */
+ private fun upgradeLater(track: Track, first: Lyrics) {
+ if (first.wordSynced) return
+ scope.launch {
+ val apple = runCatching { fromLyricsPlus(cleanTitle(track.title), track.artist.substringBefore(",").trim(), (track.durationMs / 1000).toInt()) }.getOrNull()
+ if (apple == null || !apple.wordSynced || apple.isEmpty) return@launch
+ cache[track.key] = apple
+ upgrades.tryEmit(track.key to apple)
+ }
+ }
+
fun cached(track: Track): Lyrics? = cache[track.key] as? Lyrics
/** Warm the cache in the background (current track and the next one). */
@@ -95,18 +111,20 @@ object LyricsApi {
}
private suspend fun resolve(track: Track): Lyrics? {
- val result = fromSpotify(track) ?: coroutineScope {
+ val spotify = fromSpotify(track)
+ if (spotify != null) upgradeLater(track, spotify)
+ val result = spotify ?: coroutineScope {
val title = cleanTitle(track.title)
val artist = track.artist.substringBefore(",").trim()
val durationSec = (track.durationMs / 1000).toInt()
- val extra = if (extraSources) async { fromLyricsPlus(title, artist, durationSec) } else null
+ val extra = async { fromLyricsPlus(title, artist, durationSec) }
val netease = if (extraSources) async { fromNetEase(title, artist, durationSec) } else null
val genius = if (extraSources) async { fromGenius(title, artist) } else null
val exact = async { lrclibGet(title, artist, track.album, durationSec) }
val fuzzy = async { lrclibSearch("$LRCLIB/search?track_name=${enc(title)}&artist_name=${enc(artist)}", title, artist, durationSec) }
val lrclib = exact.await() ?: fuzzy.await()
?: lrclibSearch("$LRCLIB/search?track_name=${enc(title)}", title, artist, durationSec)
- val word = extra?.await()
+ val word = extra.await()
val ne = netease?.await()
// Word-synced beats line-synced beats plain.
when {
@@ -247,7 +265,8 @@ object LyricsApi {
for (server in LYRICSPLUS) {
val url = "$server/v2/lyrics/get?title=${enc(title)}&artist=${enc(artist)}" +
(if (durationSec > 0) "&duration=$durationSec" else "")
- val o = httpGet(url, timeoutMs = 6000)?.let { runCatching { JSONObject(it) }.getOrNull() } ?: continue
+ // The mirror asks Apple then its other sources: a slow answer is still worth it.
+ val o = httpGet(url, timeoutMs = 12_000)?.let { runCatching { JSONObject(it) }.getOrNull() } ?: continue
val meta = o.optJSONObject("metadata")
val gotTitle = meta?.optString("title").orEmpty().ifBlank { o.optString("trackName") }
if (gotTitle.isNotBlank() && !overlaps(matchKey(cleanTitle(gotTitle)), matchKey(title))) continue
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 b7aba67a..60132338 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,8 @@ 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.flow.collectLatest
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.ConcurrentHashMap
@@ -30,6 +32,14 @@ import java.util.concurrent.ConcurrentHashMap
object SongPlayer {
private const val SPOTIFY_TRACK_PREFIX = "spotify:track:"
private const val PENDING_MS = 6000L
+ /** The end-of-track timer pauses this close to the end (before the next item starts). */
+ private const val END_OF_TRACK_MARGIN_MS = 600L
+ /** How often the state is read again while another device plays. */
+ private const val REMOTE_REFRESH_MS = 3_000L
+ /** A transport command that has not answered by then is given up (the next one runs). */
+ private const val TRANSPORT_TIMEOUT_MS = 15_000L
+ /** How long a play has to show up in the page's state before it is sent again. */
+ private const val PLAY_CHECK_MS = 4_000L
/** "Next" taps closer than this are sent as one jump. */
private const val SKIP_BURST_MS = 350L
/** After a local file starts, engine states this recent still predate the pause. */
@@ -125,6 +135,18 @@ object SongPlayer {
com.music.spotui.data.preferences.isLyricsExtraSources(Graph.app)
restoreLastTrack(state)
scope.launch { api.player.state.collect { s -> if (acceptsSessionUpdates()) applyState(s) } }
+ // Another device plays (the phone as a remote): the page does not always report its
+ // changes, so the state is read again every few seconds and the notification, the
+ // mini player and the slider follow that device.
+ scope.launch {
+ androidx.compose.runtime.snapshotFlow { _activeDevice.value }.collectLatest { remote ->
+ if (remote == null) return@collectLatest
+ while (true) {
+ kotlinx.coroutines.delay(REMOTE_REFRESH_MS)
+ runCatching { MyspotiRuntime.spotify.player.refresh() }
+ }
+ }
+ }
scope.launch { api.player.queue.collect { q -> if (acceptsSessionUpdates()) applyQueue(q) } }
scope.launch { api.library.changes.collect { refreshCurrentLiked() } }
PlaybackService.controls = Controls
@@ -267,7 +289,7 @@ object SongPlayer {
if (resumeWhenReady) {
resumeWhenReady = false
// The Web Player restored the last session paused: play what was tapped.
- if (s.isPaused) command { api.player.resume() }
+ if (s.isPaused) transport { api.player.resume() }
}
val item = s.item
val uri = item?.uri.orEmpty()
@@ -405,6 +427,40 @@ object SongPlayer {
}
}
+ private val transportLock = kotlinx.coroutines.sync.Mutex()
+ private val transportGen = java.util.concurrent.atomic.AtomicInteger()
+
+ /**
+ * Play, pause, skip: sent one at a time and only the newest one counts. Taps sent all
+ * at once raced in the Web Player (a skip and a play crossing, a player stuck on one
+ * song until restarted); one still waiting when a newer one comes is dropped.
+ */
+ private fun transport(block: suspend (isLatest: () -> Boolean) -> Unit) {
+ val gen = transportGen.incrementAndGet()
+ scope.launch {
+ transportLock.withLock {
+ if (gen != transportGen.get()) return@withLock
+ runCatching { kotlinx.coroutines.withTimeout(TRANSPORT_TIMEOUT_MS) { block { gen == transportGen.get() } } }
+ .onFailure { Log.w(TAG, "transport failed: ${it.message}") }
+ }
+ }
+ }
+
+ /**
+ * Plays [itemUri], then checks that the page really moved to it; a play the page lost
+ * (busy, reloading) is sent once more instead of leaving the old song playing.
+ */
+ private suspend fun playChecked(itemUri: String, isLatest: () -> Boolean, play: suspend () -> Unit) {
+ play()
+ repeat(2) { attempt ->
+ val moved = kotlinx.coroutines.withTimeoutOrNull(PLAY_CHECK_MS) {
+ api.player.state.first { it?.item?.uri == itemUri || !isLatest() }
+ }
+ if (moved != null || !isLatest()) return
+ if (attempt == 0) { Log.w(TAG, "play of $itemUri not taken: sent again"); play() }
+ }
+ }
+
/** Remember the Spotify context the given play keys belong to. */
fun registerContext(urls: List<String>, contextUri: String) {
urls.forEach { contextRegistry[it] = contextUri }
@@ -444,9 +500,11 @@ object SongPlayer {
val itemUri = if (episodeId != null) "spotify:episode:$episodeId" else SPOTIFY_TRACK_PREFIX + trackId
val ctx = contextUri ?: contextRegistry[song]
markPending(if (episodeId != null) "" else trackId, itemUri)
- command {
- if (ctx != null) api.player.play(ctx, trackUri = itemUri, order = order?.takeIf { ctx == contextUri })
- else api.player.play(itemUri)
+ transport { isLatest ->
+ playChecked(itemUri, isLatest) {
+ if (ctx != null) api.player.play(ctx, trackUri = itemUri, order = order?.takeIf { ctx == contextUri })
+ else api.player.play(itemUri)
+ }
}
}
@@ -455,7 +513,7 @@ object SongPlayer {
Haptics.click(); intendPlaying(); playing = true; positionAt = SystemClock.elapsedRealtime()
// Tapped on the restored mini player while the Web Player is still loading.
if (!stateSeen) resumeWhenReady = true
- command { api.player.resume() }
+ transport { api.player.resume() }
}
fun pause() { Haptics.click(); pauseSilently() }
@@ -464,7 +522,7 @@ object SongPlayer {
if (LocalPlayer.active.value) { LocalPlayer.pause(); return }
intendPaused()
positionMs = getCurrentPosition(); positionAt = SystemClock.elapsedRealtime(); playing = false
- command { api.player.pause() }
+ transport { api.player.pause() }
}
fun stop() = pause()
@@ -486,9 +544,9 @@ object SongPlayer {
if (n <= 0) return@Runnable
val upcoming = apiQueue?.let { it.queued + it.nextUp }.orEmpty()
val target = upcoming.getOrNull(n - 1)
- command { if (n == 1 || target == null) api.player.next() else api.player.skipTo(target) }
+ transport { if (n == 1 || target == null) api.player.next() else api.player.skipTo(target) }
}
- fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); command { api.player.previous() } }
+ fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); transport { api.player.previous() } }
/** Tracks shufflePlay plays without a context: the first one, plus up to 49 queued. */
private const val SHUFFLE_QUEUE_MAX = 50
@@ -499,7 +557,7 @@ object SongPlayer {
LocalPlayer.stop()
val ctx = contextRegistry[songs.first().url]
intendPlaying()
- command {
+ transport {
api.player.setShuffle(true)
if (ctx == null) {
// No registered context: play the list in a shuffled order (first
@@ -754,10 +812,16 @@ object SongPlayer {
/** [minutes] null = off, 0 = at the end of the current track. */
fun setSleepTimer(minutes: Int?) {
main.removeCallbacks(sleepRunnable)
+ main.removeCallbacks(endOfTrackWatch)
sleepTrackId = null
when {
minutes == null -> _sleepEndsAt.value = null
- minutes == 0 -> { sleepTrackId = currentTrackId; _sleepEndsAt.value = -1L }
+ minutes == 0 -> {
+ // Any source (song, episode, local file, repeat one): the uri and the clock.
+ sleepTrackId = _nowPlaying.value.uri.ifBlank { currentTrackId }
+ _sleepEndsAt.value = -1L
+ main.removeCallbacks(endOfTrackWatch); main.post(endOfTrackWatch)
+ }
else -> {
_sleepEndsAt.value = SystemClock.elapsedRealtime() + minutes * 60_000L
main.postDelayed(sleepRunnable, minutes * 60_000L)
@@ -765,12 +829,25 @@ object SongPlayer {
}
}
- private fun checkEndOfTrackTimer(newTrackId: String) {
- val t = sleepTrackId ?: return
- if (newTrackId.isNotBlank() && newTrackId != t) {
- sleepTrackId = null
- _sleepEndsAt.value = null
- pauseSilently()
+ private fun checkEndOfTrackTimer(@Suppress("UNUSED_PARAMETER") newTrackId: String) {
+ // Done by [endOfTrackWatch], which pauses before the next item starts.
+ }
+
+ /** "End of track": pauses just before the item ends, or as soon as another one plays. */
+ private val endOfTrackWatch = object : Runnable {
+ override fun run() {
+ val t = sleepTrackId ?: return
+ val uri = _nowPlaying.value.uri.ifBlank { currentTrackId }
+ val duration = getDuration()
+ val moved = uri.isNotBlank() && uri != t
+ val atEnd = duration > 0 && isPlaying() && getCurrentPosition() >= duration - END_OF_TRACK_MARGIN_MS
+ if (moved || atEnd) {
+ sleepTrackId = null
+ _sleepEndsAt.value = null
+ pauseSilently()
+ return
+ }
+ main.postDelayed(this, 250)
}
}
@@ -802,7 +879,7 @@ object SongPlayer {
durationMs = item.song.durationMs.toLong()
pushNotification(item.song, false)
val target = apiItem(item) ?: return
- command { api.player.skipTo(target) }
+ transport { api.player.skipTo(target) }
}
/** "Clear queue": drops the tracks the user queued (not the context's next ones). */
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 63644f69..e3f8f1bd 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
@@ -240,29 +240,7 @@ class ContextViewModel(
* Spotify's recommendations for it after every [SmartShuffle.EVERY] songs.
*/
fun playSmart(p: ContextPageModel, first: SongsModel?) {
- viewModelScope.launch {
- val inList = p.tracks.map { it.spotifyTrackId }.toSet()
- val recs = withContext(Dispatchers.IO) {
- if (p.type == "liked") {
- // Spotify's playlist extender refuses Liked Songs: the radios of a few liked songs instead.
- p.tracks.shuffled().take(3).flatMap { api.getRecommendations(listOf(it.spotifyTrackId)).take(8) }
- } else runCatching { MyspotiRuntime.api.playlists.recommended(p.uri, limit = 20) }.getOrDefault(emptyList()).map(api::songOf)
- }.filter { it.spotifyTrackId !in inList }.distinctBy { it.spotifyTrackId }.shuffled()
- val shuffled = p.tracks.shuffled().let { list -> first?.let { f -> listOf(f) + (list - f) } ?: list }
- val mixed = ArrayList<SongsModel>()
- val more = recs.iterator()
- shuffled.forEachIndexed { i, s ->
- mixed += s
- if ((i + 1) % SmartShuffle.EVERY == 0 && more.hasNext()) mixed += more.next()
- }
- SmartShuffle.recommended.value = recs.map { it.spotifyTrackId }.toSet()
- // Spotify's shuffle would mix the given order again.
- SongPlayer.setShuffle(false); state.shuffle.value = false
- state.updateQueue(mixed)
- val start = mixed.first()
- SongPlayer.playSong(start.url, contextUri = p.uri, order = mixed.map { "spotify:track:${it.spotifyTrackId}" })
- state.updateSongState(start.coverUri, start.title, start.singer, true, start.id, 0, start.album)
- }
+ viewModelScope.launch { SmartShuffle.start(p, first) }
}
fun play(p: ContextPageModel, song: SongsModel, sort: TrackOrder = TrackOrder()) {
@@ -684,6 +662,54 @@ object SmartShuffle {
val on = androidx.compose.runtime.mutableStateOf<String?>(null)
/** The recommendations mixed into the playing list. */
val recommended = androidx.compose.runtime.mutableStateOf<Set<String>>(emptySet())
+
+ /** Smart shuffle can play [contextUri]: a playlist or Liked Songs. */
+ fun canPlay(contextUri: String): Boolean = contextUri.startsWith("spotify:playlist:") || contextUri.contains(":collection")
+
+ /**
+ * Smart shuffle (Spotify keeps its own for Premium): the playlist shuffled, with one of
+ * Spotify's recommendations for it after every [EVERY] songs.
+ */
+ suspend fun start(p: ContextPageModel, first: SongsModel?) {
+ val api = Graph.api
+ val state = Graph.currentSongState
+ on.value = p.uri
+ val inList = p.tracks.map { it.spotifyTrackId }.toSet()
+ val recs = withContext(Dispatchers.IO) {
+ if (p.type == "liked") {
+ // Spotify's playlist extender refuses Liked Songs: the radios of a few liked songs instead.
+ p.tracks.shuffled().take(3).flatMap { api.getRecommendations(listOf(it.spotifyTrackId)).take(8) }
+ } else runCatching { MyspotiRuntime.api.playlists.recommended(p.uri, limit = 20) }.getOrDefault(emptyList()).map(api::songOf)
+ }.filter { it.spotifyTrackId !in inList }.distinctBy { it.spotifyTrackId }.shuffled()
+ val shuffled = p.tracks.shuffled().let { list -> first?.let { f -> listOf(f) + (list - f) } ?: list }
+ if (shuffled.isEmpty()) return
+ val mixed = ArrayList<SongsModel>()
+ val more = recs.iterator()
+ shuffled.forEachIndexed { i, s ->
+ mixed += s
+ if ((i + 1) % EVERY == 0 && more.hasNext()) mixed += more.next()
+ }
+ recommended.value = recs.map { it.spotifyTrackId }.toSet()
+ // Spotify's shuffle would mix the given order again.
+ SongPlayer.setShuffle(false); state.shuffle.value = false
+ state.updateQueue(mixed)
+ val startSong = mixed.first()
+ SongPlayer.playSong(startSong.url, contextUri = p.uri, order = mixed.map { "spotify:track:${it.spotifyTrackId}" })
+ state.updateSongState(startSong.coverUri, startSong.title, startSong.singer, true, startSong.id, 0, startSong.album)
+ }
+
+ /** From the player: loads the playing list, then smart-shuffles it, the current song first. */
+ suspend fun startFor(contextUri: String, currentTrackId: String): Boolean {
+ val api = Graph.api
+ val flow = when {
+ contextUri.contains(":collection") -> api.getLikedPage()
+ contextUri.startsWith("spotify:playlist:") -> api.getPlaylistPage(contextUri.substringAfterLast(':'))
+ else -> return false
+ }
+ val page = (withContext(Dispatchers.IO) { flow.first { it !is Response.Loading } } as? Response.Success)?.data ?: return false
+ start(page, page.tracks.firstOrNull { it.spotifyTrackId == currentTrackId })
+ return true
+ }
}
enum class TrackSort(val label: Int) {
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 ee65bac2..9bd93e3a 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 kotlinx.coroutines.launch
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.runtime.setValue
@@ -836,6 +837,8 @@ fun PlayerFull(
repeat: Boolean,
queueSongs: List<SongsModel>
) {
+ val smartOn = SmartShuffle.on.value != null && SmartShuffle.on.value == SongPlayer.nowPlaying.value.contextUri
+ val smartScope = androidx.compose.runtime.rememberCoroutineScope()
@@ -851,26 +854,36 @@ fun PlayerFull(
.size(25.dp)
.drawWithContent {
drawContent()
- if (shuffle) drawCircle(com.music.spotui.ui.theme.AppAccent, radius = 2.dp.toPx(),
+ if (shuffle || smartOn) drawCircle(com.music.spotui.ui.theme.AppAccent, radius = 2.dp.toPx(),
center = androidx.compose.ui.geometry.Offset(size.width / 2, size.height + 7.dp.toPx()))
}
.pressable {
- if (shuffle) {
- playerViewModel.updateShuffleState(false)
- } else {
- playerViewModel.updateShuffleState(true)
+ // As in Spotify: off → shuffle → smart shuffle (playlists, Liked Songs) → off.
+ val ctx = SongPlayer.nowPlaying.value.contextUri
+ when {
+ smartOn -> { SmartShuffle.on.value = null; playerViewModel.updateShuffleState(false) }
+ shuffle && SmartShuffle.canPlay(ctx) -> {
+ SmartShuffle.on.value = ctx
+ android.widget.Toast.makeText(context, context.getString(R.string.smart_shuffle_on), android.widget.Toast.LENGTH_SHORT).show()
+ smartScope.launch {
+ if (!SmartShuffle.startFor(ctx, SongPlayer.currentTrackId)) {
+ SmartShuffle.on.value = null
+ android.widget.Toast.makeText(context, context.getString(R.string.page_load_failed), android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+ else -> playerViewModel.updateShuffleState(!shuffle)
}
-
}
,
- tint = if (shuffle){
+ tint = if (shuffle || smartOn){
com.music.spotui.ui.theme.AppAccent
}
else{
Color.White
},
painter = painterResource(id = R.drawable.ic_player_shuffle),
- contentDescription = stringResource(if (shuffle) R.string.notif_shuffle_disable else R.string.notif_shuffle_enable))
+ contentDescription = stringResource(when { smartOn -> R.string.notif_shuffle_disable_smart; shuffle -> R.string.notif_shuffle_disable; else -> R.string.notif_shuffle_enable }))
Icon(
modifier = Modifier
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
index 6ec951c2..a3e453eb 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt
@@ -33,6 +33,15 @@ class LyricsViewModel constructor() : ViewModel() {
private var loadedKey: String? = null
+ init {
+ // Apple's word-by-word lyrics came after the first ones: shown in their place.
+ viewModelScope.launch {
+ LyricsApi.upgrades.collect { (key, lyrics) ->
+ if (key == loadedKey && _state.value !is State.Loading) _state.value = loadedState(lyrics)
+ }
+ }
+ }
+
fun load(track: LyricsApi.Track, force: Boolean = false) {
val key = track.key
if (!force && loadedKey == key && _state.value !is State.NotFound) return
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 7da0ca7f..a7f8c0a4 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -32,7 +32,7 @@
<string name="verified_artist">Artiste vérifié</string>
<string name="lyrics_share">Partager des paroles</string>
<string name="lyrics_extra_title">Plus de sources de paroles</string>
- <string name="lyrics_extra_summary">Apple Music (mot à mot), NetEase et Genius, quand Spotify n\'a pas les paroles</string>
+ <string name="lyrics_extra_summary">NetEase et Genius, quand ni Spotify ni Apple Music n\'ont les paroles</string>
<string name="lyrics_reload">Recharger les paroles</string>
<string name="lyrics_fullscreen">Ouvrir les paroles en plein écran</string>
<string name="browse_all">Parcourir tout</string>
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 9916abfe..71f6f38e 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -32,7 +32,7 @@
<string name="verified_artist">Artista verificato</string>
<string name="lyrics_share">Condividi il testo</string>
<string name="lyrics_extra_title">Altre fonti per i testi</string>
- <string name="lyrics_extra_summary">Apple Music (parola per parola), NetEase e Genius, quando Spotify non ha il testo</string>
+ <string name="lyrics_extra_summary">NetEase e Genius, quando né Spotify né Apple Music hanno il testo</string>
<string name="lyrics_reload">Ricarica il testo</string>
<string name="lyrics_fullscreen">Apri il testo a schermo intero</string>
<string name="browse_all">Sfoglia tutto</string>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 98a572d8..09568ad2 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -32,7 +32,7 @@
<string name="verified_artist">Verified Artist</string>
<string name="lyrics_share">Share lyrics</string>
<string name="lyrics_extra_title">More lyrics sources</string>
- <string name="lyrics_extra_summary">Apple Music (word by word), NetEase and Genius, when Spotify has no lyrics</string>
+ <string name="lyrics_extra_summary">NetEase and Genius, when neither Spotify nor Apple Music has the lyrics</string>
<string name="lyrics_reload">Reload lyrics</string>
<string name="lyrics_fullscreen">Open lyrics full screen</string>
<string name="browse_all">Browse all</string>
diff --git a/docs/CHANGELOG-full.md b/docs/CHANGELOG-full.md
index aba2de48..698ad1fd 100644
--- a/docs/CHANGELOG-full.md
+++ b/docs/CHANGELOG-full.md
@@ -5,6 +5,14 @@ Every change, release by release. The short version is in [CHANGELOG.md](../CHAN
## 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.
+- **Ad blocking stays discreet**: only ad media and third-party ad servers are refused; Spotify's own ad endpoints (ad config, ad events, sponsored recommendations) are left alone, so the client looks like any other. Sponsored content is dropped from the screens instead.
+- **Transport commands** (play, pause, next, previous, skip to) run one at a time and only the newest counts; a play is checked against the page's state and sent once more when it did not take (the old song kept playing).
+- **Fades**: every skip or play lowers the sound over ~0.1 s and brings it back once the next song plays (always within 4 s): the "pop" heard in the phone's speaker is gone. Ads and user volume changes are taken into account.
+- **Smart shuffle in the player**: the shuffle button goes off → shuffle → smart shuffle on playlists and Liked Songs; the smart mix is shared with the playlist page.
+- **Lyrics**: Apple Music's word-synced lyrics (LyricsPlus) are always looked up; Spotify's show first and are replaced when Apple's arrive. The dead LyricsPlus mirror is gone; the "more sources" setting now covers NetEase and Genius.
+- **Remote control (#40)**: while another device plays, the state is read every 3 s.
+- **Sleep timer "end of track"**: based on the media uri and the clock, so episodes, local files and repeat one stop too.
+- **Artist pages** load every page of the discography (up to 300 releases).
- **Ads, continued**: an ad is recognised by its metadata too (`is_advertisement`, `ad_id`, advertiser), not only by a `spotify:ad:` uri. Home promotion shelves and sponsored cards are dropped. Sponsored recommendations and the page's ad/audience trackers (Google Tag Manager, Google Analytics, Scorecard Research, Fastly Insights) are blocked.
- **Artist discography**: the Releases page filtered on lowercase kinds while Spotify sends "ALBUM", "SINGLE"…, so it stayed empty; it also opens by artist id now, and kinds are shown translated.
- **Long names**: every line-limited text ends with "…"; home cards keep two subtitle lines so a row never jumps; shortcut tiles, category and discover grids get a fixed text height; playlist, album, artist and profile titles shrink to fit two lines (`FitText`) before being cut.