Skip to content

Native Android client for Spotify, built with Jetpack Compose

Second audit: an account's downloads are only stamped for another account once moved aside, a folder already parked is kept under another name, a failed move leaves everything in place, and an account signing in again resumes its own download queues; a safe write never loses the old file and covers the download queues; a song kept from fading no longer blocks the fade of another list's song; the queue sync waits for a slow Spotify queue and drops a stale plan; Android Auto keeps its last 30 pages and forgets them on sign-out; a Cast connection that fails closes its socket and a failed discovery can start again

kota-zo2dc6461e8d09
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt b/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
index 943fa81e..23a8aa56 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
@@ -44,10 +44,16 @@ class CastChannel(
fun open(timeoutMs: Int = 5000) {
val ctx = SSLContext.getInstance("TLS").apply { init(null, arrayOf(AnyCertificate), java.security.SecureRandom()) }
val s = ctx.socketFactory.createSocket() as SSLSocket
- s.connect(InetSocketAddress(host, port), timeoutMs)
- s.soTimeout = 0
- s.tcpNoDelay = true
- s.startHandshake()
+ try {
+ s.connect(InetSocketAddress(host, port), timeoutMs)
+ s.soTimeout = 0
+ s.tcpNoDelay = true
+ s.startHandshake()
+ } catch (e: Exception) {
+ // Not connected: the socket is closed here, nothing else holds it.
+ runCatching { s.close() }
+ throw e
+ }
socket = s
out = BufferedOutputStream(s.outputStream)
lastHeard = System.currentTimeMillis()
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt b/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
index 1b539446..1b20b135 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
@@ -33,14 +33,19 @@ object CastDiscovery {
/** Starts looking (each [start] wants one [stop]). Main thread. */
fun start(context: Context) {
if (users++ > 0) return
- val m = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: return
+ // No discovery on this phone: counted as not started, so a later start tries again.
+ val m = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: run { users = 0; return }
nsd = m
// Found anew each time: a device switched off since is not offered.
devices.clear()
val l = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = log("looking for Cast devices")
override fun onDiscoveryStopped(serviceType: String) = log("stopped looking for Cast devices")
- override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) = log("discovery failed to start (error $errorCode)")
+ override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) = main.post {
+ log("discovery failed to start (error $errorCode)")
+ // Not running: a later start begins it again.
+ if (listener === this) { listener = null; users = 0 }
+ }.let { }
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
override fun onServiceFound(info: NsdServiceInfo) = main.post { waiting.addLast(info); next() }.let { }
override fun onServiceLost(info: NsdServiceInfo) = main.post {
@@ -49,7 +54,7 @@ object CastDiscovery {
}
listener = l
runCatching { m.discoverServices(TYPE, NsdManager.PROTOCOL_DNS_SD, l) }
- .onFailure { log("discovery not available: ${it.javaClass.simpleName}"); listener = null }
+ .onFailure { log("discovery not available: ${it.javaClass.simpleName}"); listener = null; users = 0 }
}
fun stop() {
diff --git a/base/app/src/main/java/com/music/spotui/data/SafeWrite.kt b/base/app/src/main/java/com/music/spotui/data/SafeWrite.kt
index ad490bfd..3b30f64e 100644
--- a/base/app/src/main/java/com/music/spotui/data/SafeWrite.kt
+++ b/base/app/src/main/java/com/music/spotui/data/SafeWrite.kt
@@ -7,8 +7,8 @@ import java.io.IOException
/**
* Replaces [file] with [text] whole or not at all: written to a temporary file next to it, flushed
* to the disk, then moved over it. A move that fails (the target in the way on some file systems)
- * is tried once more after deleting the target; failing again, the old file is left as it was and
- * an [IOException] says so, instead of the app carrying on with a state it never saved.
+ * is tried once more with the old file moved aside first, and put back if that fails too: the old
+ * file is never lost, and an [IOException] says the new text was not saved.
*/
fun writeTextSafely(file: File, text: String) {
file.parentFile?.mkdirs()
@@ -18,7 +18,12 @@ fun writeTextSafely(file: File, text: String) {
out.fd.sync()
}
if (tmp.renameTo(file)) return
- if (file.delete() && tmp.renameTo(file)) return
+ val old = File(file.parentFile, file.name + ".old")
+ old.delete()
+ if (!file.exists() || file.renameTo(old)) {
+ if (tmp.renameTo(file)) { old.delete(); return }
+ if (old.exists()) old.renameTo(file)
+ }
tmp.delete()
throw IOException("could not replace ${file.name}")
}
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineAccounts.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineAccounts.kt
index 3c4aa73a..11eb65f3 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineAccounts.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineAccounts.kt
@@ -37,11 +37,11 @@ object OfflineAccounts {
// Whose they are is unknown (never signed in online since): kept aside, never given to anyone.
val key = owner ?: "unclaimed-${System.currentTimeMillis()}"
stopDownloads(dir)
- val to = parked(context, key)
- withContext(Dispatchers.IO) {
- to.parentFile?.mkdirs()
- if (to.exists()) to.deleteRecursively()
- if (!dir.renameTo(to)) Logbook.log("offline: downloads not put aside for sign-out")
+ val moved = withContext(Dispatchers.IO) { putAside(dir, parked(context, key)) }
+ if (!moved) {
+ // Still in place and still stamped with their account: the next sign-in puts them aside.
+ Logbook.log("offline: downloads not put aside for sign-out")
+ return@withLock
}
reopen(context)
Logbook.log("offline: downloads put aside for sign-out")
@@ -59,23 +59,38 @@ object OfflineAccounts {
}
// Another account's downloads are in place (a sign-out that could not put them aside), or none.
stopDownloads(dir)
- withContext(Dispatchers.IO) {
- if (owner != null) {
- val to = parked(context, owner)
- to.parentFile?.mkdirs()
- if (to.exists()) to.deleteRecursively()
- dir.renameTo(to)
- } else {
- dir.deleteRecursively()
- }
+ val ready = withContext(Dispatchers.IO) {
+ // This account's stamp only goes on an emptied folder or its own: downloads that could not
+ // be moved keep their own account's stamp, never this one.
+ val cleared = if (owner != null) putAside(dir, parked(context, owner)) else dir.deleteRecursively()
+ if (!cleared) return@withContext false
val back = parked(context, key)
if (back.isDirectory && !back.renameTo(dir)) Logbook.log("offline: this account's downloads could not be brought back")
stamp(dir, key)
+ true
+ }
+ if (!ready) {
+ Logbook.log("offline: the other account's downloads could not be put aside")
+ reopen(context)
+ return@withLock
}
reopen(context)
+ // Its queues came back with its folder: they go on where they stopped.
+ OfflineDownloader.resumePending()
+ PodcastDownloader.resumePending()
Logbook.log("offline: this account's downloads in place (${OfflineStore.tracks.size} songs)")
}
+ /**
+ * Moves [dir] to [to]. A folder already there (left by an earlier sign-out that went wrong) is
+ * kept under another name rather than deleted. False when the move failed: [dir] is untouched.
+ */
+ private fun putAside(dir: File, to: File): Boolean {
+ to.parentFile?.mkdirs()
+ if (to.exists() && !to.renameTo(File(to.parentFile, "${to.name}-${System.currentTimeMillis()}"))) return false
+ return dir.renameTo(to)
+ }
+
private fun stamp(dir: File, key: String) {
dir.mkdirs()
runCatching { com.music.spotui.data.writeTextSafely(File(dir, OWNER), key) }
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 321a4d7e..0bff6970 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
@@ -244,7 +244,7 @@ object OfflineDownloader {
runCatching {
val a = JSONArray()
pending.values.forEach { a.put(it.toJson()) }
- OfflineStore.pendingFile.writeText(a.toString())
+ com.music.spotui.data.writeTextSafely(OfflineStore.pendingFile, a.toString())
}
}
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt
index 0520a490..e6875436 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt
@@ -184,7 +184,7 @@ object PodcastDownloader {
runCatching {
val a = JSONArray()
pending.values.forEach { a.put(it.toJson()) }
- OfflineStore.podcastPendingFile.writeText(a.toString())
+ com.music.spotui.data.writeTextSafely(OfflineStore.podcastPendingFile, a.toString())
}
}
diff --git a/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt b/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
index 640546d8..d42b2eff 100644
--- a/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
+++ b/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
@@ -66,8 +66,15 @@ object AutoBrowser {
private const val KEY_PLAYABLE = "android.media.browse.CONTENT_STYLE_PLAYABLE_HINT"
private const val KEY_GROUP = "android.media.browse.CONTENT_STYLE_GROUP_TITLE_HINT"
- // Contexts recently listed, so a tap plays with the right queue.
- private val pages = java.util.concurrent.ConcurrentHashMap<String, ContextPageModel>()
+ // Contexts recently listed, so a tap plays with the right queue: the last few only, in the order used.
+ private val pages: MutableMap<String, ContextPageModel> = java.util.Collections.synchronizedMap(
+ object : LinkedHashMap<String, ContextPageModel>(16, 0.75f, true) {
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, ContextPageModel>) = size > MAX_PAGES
+ })
+ private const val MAX_PAGES = 30
+
+ /** The account signs out: nothing it listed stays for the next one. */
+ fun clearSession() = pages.clear()
private val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO)
/**
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index d571062c..a3fbf175 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -114,6 +114,8 @@ object LocalPlayer {
override fun onMediaItemTransition(mediaItem: androidx.media3.common.MediaItem?, reason: Int) {
// Anything but the transition the fade itself makes (a skip, a tap in the queue) ends the fade.
if (!startingFade) endFade()
+ // The song kept from fading out is left behind: the next one fades as usual.
+ if (p.currentMediaItemIndex != noFadeFor) noFadeFor = -1
// A song to play again that the player went past by itself: put back, never followed.
if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO && wentPastRepeat(p, p.previousMediaItemIndex)) return
if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT) startsAtZero(p)
@@ -246,6 +248,8 @@ object LocalPlayer {
// Spotify's queued songs (the account's: maybe queued on another device or install) play first.
val (all, fromSpotify) = QueueSync.withSpotifyQueue(list, index.coerceIn(0, list.lastIndex))
tracks.clear(); tracks.addAll(all); unshuffled = null
+ // An index kept from fading belonged to the list before: this one fades from its first song.
+ noFadeFor = -1
queued.clear(); playingQueued = null; radioSongs.clear()
queued += fromSpotify
listName = context ?: Graph.app.getString(app.myspoti.engine.R.string.local_files_title)
diff --git a/base/app/src/main/java/com/music/spotui/di/QueueSync.kt b/base/app/src/main/java/com/music/spotui/di/QueueSync.kt
index 9d637115..17d9b3fb 100644
--- a/base/app/src/main/java/com/music/spotui/di/QueueSync.kt
+++ b/base/app/src/main/java/com/music/spotui/di/QueueSync.kt
@@ -41,7 +41,7 @@ object QueueSync {
/** How many of each uri the sync queued on Spotify (or took from there): the ones it may take out again. */
private val owned = HashMap<String, Int>()
/** The local queue's songs at the last edit seen (see [localChanged]). */
- private var lastLocal: List<String> = emptyList()
+ @Volatile private var lastLocal: List<String> = emptyList()
/** The local player's queue as published (main thread): synced when it changed. */
fun localChanged(queued: List<String>) {
@@ -75,16 +75,22 @@ object QueueSync {
}
private suspend fun reconcile(local: List<String>, spare: String?) {
- val q = api.player.queue.value ?: return
+ // Spotify slow to send its queue: waited for a moment rather than this edit dropped.
+ val q = api.player.queue.value ?: withTimeoutOrNull(QUEUE_ECHO_MS * 2) { api.player.queue.first { it != null } }
+ ?: return log("not synced: Spotify sent no queue")
val items = q.queued.filter { it.kind == ItemKind.TRACK && it.uri.startsWith(TRACK_PREFIX) }
val plan = synchronized(owned) { QueueSyncRules.plan(local, items.map { it.uri }, HashMap(owned), spare) }
if (plan.empty) return
+ // A newer local edit, or the mirror gone meanwhile: this plan is stale, the next sync does it.
+ fun stale() = local != lastLocal || !usable()
+ if (stale()) return
if (plan.remove.isNotEmpty()) {
val gone = plan.remove.map(items::get)
api.player.removeFromQueue(gone)
synchronized(owned) { gone.forEach { take(it.uri, 1) } }
}
for (insert in plan.inserts) for (batch in insert.uris.chunked(BATCH)) {
+ if (stale()) return
val before = insert.beforeIndex?.let(items::get)
if (before == null) api.player.addToQueue(batch) else api.player.insertInQueue(batch, before)
synchronized(owned) { batch.forEach { owned[it] = (owned[it] ?: 0) + 1 } }
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 7601967b..55d3a285 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
@@ -45,6 +45,7 @@ object SessionActions {
app.getSharedPreferences(name, android.content.Context.MODE_PRIVATE).edit().clear().apply()
}
com.music.spotui.data.local.ListenHistory.clear()
+ AutoBrowser.clearSession()
_signedOut.value = true
MyspotiRuntime.host.logout()
}