Skip to content

Native Android client for Spotify, built with Jetpack Compose

Rest of the second audit: Cast closes the connections it is serving when it stops; a download part must be the bytes asked for (Content-Range checked, nothing past them kept) and a file with no length in its header is checked against its own metadata; the Recap counts every credited artist (split only when names and ids agree) and reads the history once; the glass follows the page five times a second while it is used and once a second at rest; the Immersive bar and mini player step aside while the keyboard is up [skip ci]

kota-zo03d97747d0e5
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastServer.kt b/base/app/src/main/java/com/music/spotui/cast/CastServer.kt
index 617444f7..ed522a80 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastServer.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastServer.kt
@@ -63,12 +63,17 @@ object CastServer {
return before != null
}
+ /** The connections being served: closed with the server, so no byte goes out once Cast stops. */
+ private val open = java.util.concurrent.ConcurrentHashMap.newKeySet<Socket>()
+
@Synchronized
fun stop() {
server?.let { runCatching { it.close() }; log("server stopped") }
server = null
token = ""
entries.clear()
+ open.toList().forEach { runCatching { it.close() } }
+ open.clear()
}
/** The address of [e] on this server (the older entries are forgotten: their address dies). */
@@ -133,6 +138,11 @@ object CastServer {
}
private fun serve(c: Socket) {
+ open += c
+ try { serveOpen(c) } finally { open -= c }
+ }
+
+ private fun serveOpen(c: Socket) {
c.use { socket ->
socket.soTimeout = 20_000
val input = BufferedInputStream(socket.getInputStream())
diff --git a/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt b/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt
index b76b2618..f931c237 100644
--- a/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt
+++ b/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt
@@ -21,8 +21,20 @@ object ListenHistory {
val cover: String,
val playedMs: Long,
val source: Source,
+ /** Each credited artist on its own, for the top artists; just the line's first one for older listens. */
+ val artists: List<String> = listOf(artist.substringBefore(",").trim()),
)
+ /**
+ * The artists of a song credited as [line] ("A, B") with [ids] artist ids: split only when the
+ * names and the ids agree in number, so a name with a comma in it ("Tyler, The Creator", one id)
+ * stays whole.
+ */
+ fun artistsOf(line: String, ids: List<String>): List<String> {
+ val names = line.split(", ").map { it.trim() }.filter { it.isNotEmpty() }
+ return if (ids.size > 1 && names.size == ids.size) names else listOf(line.trim()).filter { it.isNotEmpty() }
+ }
+
const val MIN_PLAYED_MS = 30_000L
private var file: File? = null
private val lock = Any()
@@ -37,22 +49,35 @@ object ListenHistory {
val line = JSONObject()
.put("at", listen.atMs).put("key", listen.key).put("title", listen.title).put("artist", listen.artist)
.put("album", listen.album).put("cover", listen.cover).put("ms", listen.playedMs).put("src", listen.source.name)
+ .put("artists", org.json.JSONArray(listen.artists))
.toString()
- synchronized(lock) { f.appendText(line + "\n") }
+ synchronized(lock) {
+ f.appendText(line + "\n")
+ loaded?.let { loaded = it + listen }
+ }
}
+ /** The history as last read, kept while the file only grows by [record]: not read again for every screen. */
+ private var loaded: List<Listen>? = null
+
fun all(): List<Listen> = synchronized(lock) {
+ loaded?.let { return it }
val f = file?.takeIf { it.exists() } ?: return emptyList()
- f.readLines().mapNotNull { line ->
+ val list = f.readLines().mapNotNull { line ->
runCatching {
val o = JSONObject(line)
- Listen(o.getLong("at"), o.getString("key"), o.getString("title"), o.optString("artist"), o.optString("album"),
- o.optString("cover"), o.getLong("ms"), Source.valueOf(o.optString("src", "SPOTIFY")))
+ val artist = o.optString("artist")
+ val artists = o.optJSONArray("artists")?.let { a -> List(a.length()) { a.getString(it) } }?.filter { it.isNotBlank() }
+ Listen(o.getLong("at"), o.getString("key"), o.getString("title"), artist, o.optString("album"),
+ o.optString("cover"), o.getLong("ms"), Source.valueOf(o.optString("src", "SPOTIFY")),
+ artists?.ifEmpty { null } ?: listOf(artist.substringBefore(",").trim()))
}.getOrNull()
}
+ loaded = list
+ list
}
- fun clear() = synchronized(lock) { file?.delete() }
+ fun clear() = synchronized(lock) { loaded = null; file?.delete() }
data class Ranked(val name: String, val subtitle: String, val cover: String, val count: Int, val minutes: Long)
@@ -101,6 +126,14 @@ object ListenHistory {
}
}
+ /** Every credited artist of a listen counts it, not only the first one on the line. */
+ internal fun rankArtists(list: List<Listen>): List<Ranked> = list
+ .flatMap { l -> l.artists.filter { it.isNotBlank() }.map { it to l } }
+ .groupBy({ it.first }, { it.second })
+ .map { (name, l) -> Ranked(name, "", l.first().cover, l.size, l.sumOf { it.playedMs } / 60_000) }
+ .sortedWith(compareByDescending<Ranked> { it.count }.thenByDescending { it.minutes })
+ .take(10)
+
/** Totals and top lists for listens since [sinceMs]. */
fun recap(sinceMs: Long): Recap {
val list = all().filter { it.atMs >= sinceMs }
@@ -114,7 +147,7 @@ object ListenHistory {
minutes = list.sumOf { it.playedMs } / 60_000,
bySource = list.groupBy { it.source }.mapValues { (_, l) -> l.sumOf { it.playedMs } / 60_000 },
topTracks = rank({ it.title + "\u0000" + it.artist }, { it.artist }).map { it.copy(name = it.name.substringBefore('\u0000')) },
- topArtists = rank({ it.artist.substringBefore(",").trim() }, { "" }),
+ topArtists = rankArtists(list),
topAlbums = rank({ it.album }, { it.artist }),
)
}
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
index 0bff6970..a0b54931 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
@@ -434,7 +434,17 @@ object OfflineDownloader {
} finally {
extractor.release()
}
- if (seconds > 0) checkLength(seconds, meta)
+ // No length in the track's header (some MP3 streams): the file's own metadata is asked next.
+ val known = seconds.takeIf { it > 0 } ?: runCatching {
+ android.media.MediaMetadataRetriever().let { r ->
+ try {
+ r.setDataSource(file.path)
+ r.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull()?.div(1000)
+ } finally { r.release() }
+ }
+ }.getOrNull()?.takeIf { it > 0 }
+ if (known != null) checkLength(known, meta)
+ else Log.w(TAG, "${meta.title}: length of the file unknown, not compared with the song's")
}
private fun checkLength(seconds: Long, meta: Meta) {
@@ -522,6 +532,13 @@ object OfflineDownloader {
if (code !in 200..299) throw IOException("stream HTTP $code")
val full = code != 206 // server ignored Range → the whole body, from byte 0
if (full) output.setLength(0)
+ // A part must be the one asked for: bytes from elsewhere in the file would be
+ // written at the wrong place and make a file that plays wrong.
+ if (!full) {
+ val span = contentRangeSpan(conn.response.header("Content-Range"))
+ if (span == null || span.first != position || span.last > end)
+ throw IOException("stream sent ${conn.response.header("Content-Range") ?: "no Content-Range"} for bytes $position-$end")
+ }
if (total <= 0) total = contentRangeTotal(conn.response.header("Content-Range")) ?: -1L
output.seek(output.length())
val expected = if (full) -1L else end - position + 1
@@ -531,8 +548,11 @@ object OfflineDownloader {
while (true) {
val n = input.read(buf)
if (n < 0) break
- output.write(buf, 0, n)
- got += n
+ // Never more than the part asked for, whatever the server sends after it.
+ val keep = if (expected >= 0) minOf(n.toLong(), expected - got).toInt() else n
+ output.write(buf, 0, keep)
+ got += keep
+ if (expected in 0..got) break
}
}
if (full) done = true
@@ -606,6 +626,14 @@ object OfflineDownloader {
}
/** "bytes 0-99/1234" → 1234; null when absent or "*". */
+ /** "bytes 100-199/1234" → 100..199; null when absent or not that shape. */
+ fun contentRangeSpan(header: String?): LongRange? {
+ val m = Regex("""^\s*bytes\s+(\d+)-(\d+)/(\d+|\*)\s*$""", RegexOption.IGNORE_CASE).find(header ?: return null) ?: return null
+ val first = m.groupValues[1].toLongOrNull() ?: return null
+ val last = m.groupValues[2].toLongOrNull() ?: return null
+ return if (last >= first) first..last else null
+ }
+
fun contentRangeTotal(header: String?): Long? =
header?.substringAfterLast('/', "")?.trim()?.toLongOrNull()?.takeIf { it > 0 }
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 dd0dc262..2dabc533 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
@@ -744,6 +744,7 @@ object SongPlayer {
listenSong?.let { s ->
com.music.spotui.data.local.ListenHistory.record(com.music.spotui.data.local.ListenHistory.Listen(
System.currentTimeMillis(), listenKey, s.title, s.singer, s.album, s.coverUri, listenPlayedMs, listenSource,
+ com.music.spotui.data.local.ListenHistory.artistsOf(s.singer, s.artistIds),
))
}
listenKey = key; listenSong = song; listenSource = source; listenPlayedMs = 0
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt
index 4c1e15d9..f3c92b56 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/ImmersiveChrome.kt
@@ -10,6 +10,8 @@ package com.music.spotui.ui.immersive.shell
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
@@ -165,6 +167,9 @@ fun ImmersiveBottomChrome(
) {
val tabs = rememberTabNavigation(navController)
if (tabs.fullScreen) return
+ // The keyboard is up (a search, a name to type): the bar and the mini player would sit on it or
+ // over the results right above it, so they step aside until it goes.
+ if (WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0) return
// Large windows (tablets, foldables, DeX): the tab bar and the mini player side by side in one
// floating row, centred, each at its own capped width; there is room, so it never folds.
if (com.music.spotui.ui.components.windowSize().large) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt
index fcd50592..d10ebe58 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/shell/backdrop/backdrops/LayerBackdropModifier.kt
@@ -66,7 +66,25 @@ private class LayerBackdropElement(
private class LayerBackdropNode(
var backdrop: LayerBackdrop
-) : DrawModifierNode, GlobalPositionAwareModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode, Modifier.Node() {
+) : DrawModifierNode, GlobalPositionAwareModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode,
+ androidx.compose.ui.node.PointerInputModifierNode, Modifier.Node() {
+
+ /** Until when the page counts as being used (a touch on it, see [onPointerEvent]): the glass follows it closely. */
+ private var activeUntil = 0L
+
+ // Seen first and never consumed: a scroll, a swipe of a row of cards or a tap is what changes the
+ // page without it redrawing itself, so the glass is refreshed quickly for a while after one.
+ override fun onPointerEvent(
+ pointerEvent: androidx.compose.ui.input.pointer.PointerEvent,
+ pass: androidx.compose.ui.input.pointer.PointerEventPass,
+ bounds: androidx.compose.ui.unit.IntSize,
+ ) {
+ if (pass == androidx.compose.ui.input.pointer.PointerEventPass.Initial) {
+ activeUntil = android.os.SystemClock.uptimeMillis() + ACTIVE_MS
+ }
+ }
+
+ override fun onCancelPointerInput() = Unit
override fun ContentDrawScope.draw() {
// Vendored change: record once and composite, rather than upstream's
@@ -116,7 +134,7 @@ private class LayerBackdropNode(
// Only then: a page animating on its own (a playing row) does not keep the blur running.
// Past that, the same holds for anything that changes without the page itself redrawing (a
// cover that loads late, a row of cards scrolled sideways, an animated header): the glass
- // is redrawn a few times a second so it never keeps an old picture of the page for long.
+ // is redrawn a few times a second while the page is being used, once a second at rest.
// Driven by frames, so nothing runs while the app is in the background.
coroutineScope.launch {
val end = android.os.SystemClock.uptimeMillis() + SETTLE_MS
@@ -124,8 +142,9 @@ private class LayerBackdropNode(
androidx.compose.runtime.withFrameNanos { }
(registeredIn ?: backdrop).moves++
}
+ activeUntil = android.os.SystemClock.uptimeMillis() + ACTIVE_MS
while (true) {
- kotlinx.coroutines.delay(REFRESH_MS)
+ kotlinx.coroutines.delay(if (android.os.SystemClock.uptimeMillis() < activeUntil) REFRESH_MS else IDLE_REFRESH_MS)
androidx.compose.runtime.withFrameNanos { }
(registeredIn ?: backdrop).moves++
}
@@ -157,5 +176,11 @@ private class LayerBackdropNode(
/** How long a page that just arrived keeps redrawing the glass as it fills in. */
private const val SETTLE_MS = 3_000L
-/** How often, once settled, the glass is redrawn over what the page shows now. */
+/** How often, once settled, the glass is redrawn over what the page shows now while it is used. */
private const val REFRESH_MS = 200L
+
+/** How often at rest (nothing touched for [ACTIVE_MS]). */
+private const val IDLE_REFRESH_MS = 1_000L
+
+/** How long after arriving, or after a touch, the page counts as being used. */
+private const val ACTIVE_MS = 15_000L
diff --git a/base/app/src/test/java/com/music/spotui/data/local/ListenHistoryArtistsTest.kt b/base/app/src/test/java/com/music/spotui/data/local/ListenHistoryArtistsTest.kt
new file mode 100644
index 00000000..772fde71
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/local/ListenHistoryArtistsTest.kt
@@ -0,0 +1,22 @@
+package com.music.spotui.data.local
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class ListenHistoryArtistsTest {
+ @Test
+ fun splitsOnlyWhenNamesAndIdsAgree() {
+ assertEquals(listOf("A", "B"), ListenHistory.artistsOf("A, B", listOf("1", "2")))
+ assertEquals(listOf("Tyler, The Creator"), ListenHistory.artistsOf("Tyler, The Creator", listOf("1")))
+ assertEquals(listOf("A, B"), ListenHistory.artistsOf("A, B", emptyList()))
+ }
+
+ @Test
+ fun everyCreditedArtistCountsTheListen() {
+ fun l(artists: List<String>) = ListenHistory.Listen(0, "k", "t", artists.joinToString(", "), "", "", 60_000, ListenHistory.Source.SPOTIFY, artists)
+ val top = ListenHistory.rankArtists(listOf(l(listOf("A", "B")), l(listOf("B")), l(listOf("C"))))
+ assertEquals("B", top.first().name)
+ assertEquals(2, top.first().count)
+ assertEquals(setOf("A", "B", "C"), top.map { it.name }.toSet())
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt b/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt
index bbf926b8..5fefcaa6 100644
--- a/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt
+++ b/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt
@@ -12,6 +12,14 @@ class OfflineDownloaderTest {
assertNull(OfflineDownloader.contentRangeTotal(null))
}
+ @Test fun contentRangeSpanReadsThePartSent() {
+ assertEquals(100L..199L, OfflineDownloader.contentRangeSpan("bytes 100-199/1234"))
+ assertEquals(0L..99L, OfflineDownloader.contentRangeSpan("Bytes 0-99/*"))
+ assertNull(OfflineDownloader.contentRangeSpan("bytes 199-100/1234"))
+ assertNull(OfflineDownloader.contentRangeSpan("bytes */1234"))
+ assertNull(OfflineDownloader.contentRangeSpan(null))
+ }
+
@Test fun normalizeIsrcAcceptsDashesAndCase() {
assertEquals("USUM71703861", OfflineDownloader.normalizeIsrc("us-um7-17-03861"))
assertEquals("FRZ039800212", OfflineDownloader.normalizeIsrc("FR Z03 98 00212"))