Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Downloads deleted while their list plays no longer stall it: the songs of the queue that played from the deleted files play from their source as the list's songs never downloaded do (the extensions, else Spotify), or are left out with no connection, while the song playing ends from its open file; a song whose file is gone when it starts or is sought into plays from its source the same way, or is skipped (a file of the phone), instead of leaving the player stopped, with one log line for each case [skip ci]
kota-zo034d7356c420
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.ktindex 500f1c37..4a1b880c 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@@ -166,19 +166,32 @@ object OfflineStore {File(audioDir, t.file).delete()if (t.cover.isNotBlank()) File(coverDir, t.cover).delete()writeIndex()+ deleted(listOf(t))}}fun removeAll() {synchronized(lock) {+ val all = tracks.values.toList()tracks.clear()status.clear()audioDir.listFiles()?.forEach { it.delete() }coverDir.listFiles()?.forEach { it.delete() }writeIndex()+ deleted(all)}}+ /**+ * Downloads [gone] were deleted: the local player's queue stops pointing at their files (see+ * LocalPlayer.downloadsDeleted), on the main thread. Their file, and the song each one is.+ */+ private fun deleted(gone: List<OfflineTrack>) {+ if (gone.isEmpty()) return+ val songs = gone.associate { Uri.fromFile(audioFile(it)).toString() to toSong(it) }+ android.os.Handler(android.os.Looper.getMainLooper()).post { com.music.spotui.di.LocalPlayer.downloadsDeleted(songs) }+ }+fun totalBytes(): Long = tracks.values.sumOf { it.bytes }/** A working internet connection (else downloaded songs play from the phone). */diff --git a/base/app/src/main/java/com/music/spotui/di/DeletedDownloads.kt b/base/app/src/main/java/com/music/spotui/di/DeletedDownloads.ktnew file mode 100644index 00000000..3c4d387f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/di/DeletedDownloads.kt@@ -0,0 +1,31 @@+package com.music.spotui.di++/**+ * What [LocalPlayer] does with the songs of its queue whose downloaded file was deleted while it+ * played (OfflineStore.remove, removeAll), kept pure so it is tested off-device. Such a song no+ * longer plays from the phone: it plays from its source as a song of the list that was never+ * downloaded does (the extensions, else Spotify: see LocalPlayer.onPlayerError), or, with no+ * connection (or the data saver on), it is left out of the queue. The song playing is kept: its file+ * is still open and it ends as usual.+ */+object DeletedDownloads {+ enum class Fix { KEEP, STREAM, DROP }++ /**+ * One [Fix] per queue item: [gone] holds, for each, the Spotify id of its deleted download (""+ * when it has none, an episode), or null when its download was not deleted; [current] is the+ * song playing, [online] whether a source can be reached.+ */+ fun plan(gone: List<String?>, current: Int, online: Boolean): List<Fix> = gone.mapIndexed { i, id ->+ when {+ id == null || i == current -> Fix.KEEP+ id.isBlank() || !online -> Fix.DROP+ else -> Fix.STREAM+ }+ }++ /** True when a playback error says the item's file is not there ([code]: PlaybackException's, [cause]: its cause). */+ fun isMissingFile(code: Int, cause: Throwable?): Boolean =+ code == androidx.media3.common.PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND ||+ generateSequence(cause) { it.cause }.take(8).any { it is java.io.FileNotFoundException }+}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.ktindex a96a727b..338a64bd 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@@ -130,6 +130,8 @@ object LocalPlayer {log("error ${error.errorCodeName}: ${generic(error.cause?.toString() ?: error.message.orEmpty())}")val item = p.currentMediaItem?.localConfiguration?.uri ?: returnif (item.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME) com.music.spotui.extensions.Extensions.noteAttempt(item.lastPathSegment) { it.copy(error = "${error.errorCodeName}: ${error.cause ?: error.message.orEmpty()}") }+ // A file that is gone (a download deleted while the queue played): never left stopped on it.+ if (item.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME && DeletedDownloads.isMissingFile(error.errorCode, error.cause)) return fileGone(p, item)if (item.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME) returnval t = current() ?: returnval noAudio = com.music.spotui.extensions.AudioRoute.isNoAudio(error)@@ -228,6 +230,86 @@ object LocalPlayer {prefetchNext(p)}+ /** The downloads deleted during this session, by file: the song each one is (see [downloadsDeleted]). */+ private val deletedDownloads = HashMap<String, com.music.spotui.data.entity.SongsModel>()++ /**+ * Downloads were deleted ([gone]: the song of each file, see OfflineStore.remove, removeAll): the+ * songs of the queue that played from those files play from their source, as the list's songs+ * never downloaded do (the extensions, else Spotify), or are left out offline (see+ * [DeletedDownloads]). The song playing keeps its open file and ends as usual. On the main thread.+ */+ fun downloadsDeleted(gone: Map<String, com.music.spotui.data.entity.SongsModel>) {+ val p = exo ?: return+ if (!active.value || tracks.isEmpty()) return+ deletedDownloads.putAll(gone)+ val cur = p.currentMediaItemIndex+ val plan = DeletedDownloads.plan(tracks.map { t -> gone[t.uri.toString()]?.spotifyTrackId }, cur,+ com.music.spotui.data.offline.OfflineStore.isOnline(Graph.app))+ if (plan.all { it == DeletedDownloads.Fix.KEEP }) return+ var streamed = 0; var dropped = 0; var droppedBefore = 0+ for (i in plan.indices.reversed()) when (plan[i]) {+ DeletedDownloads.Fix.STREAM -> { swap(p, i, com.music.spotui.extensions.ExtensionAudio.localTrack(gone.getValue(tracks[i].uri.toString()))); streamed++ }+ DeletedDownloads.Fix.DROP -> {+ p.removeMediaItem(i)+ val t = tracks.removeAt(i)+ queued -= t; radioSongs -= t+ unshuffled = unshuffled?.filterNot { it === t }+ dropped++; if (i < cur) droppedBefore+++ }+ DeletedDownloads.Fix.KEEP -> Unit+ }+ if (noFadeFor >= 0) noFadeFor -= droppedBefore+ log("downloads deleted while playing: $streamed songs of the queue play from their source, $dropped left out (offline or no id); ${current()?.title} ends from its open file")+ prefetchNext(p); continueIfLast(p)+ publish()+ }++ /** Puts [t] at [index] of the queue in place of the song there (same place in the queue, the shuffle and the radio). */+ private fun swap(p: ExoPlayer, index: Int, t: LocalTrack) {+ val old = tracks[index]+ p.replaceMediaItem(index, item(t))+ tracks[index] = t+ if (queued.remove(old)) queued += t+ if (radioSongs.remove(old)) radioSongs += t+ if (playingQueued === old) playingQueued = t+ unshuffled = unshuffled?.map { if (it === old) t else it }+ }++ /**+ * The file of the song the player is on is gone ([uri]: a download deleted while the queue+ * played, or a file that left the phone): never left stopped there. A deleted download plays+ * from its source (see [downloadsDeleted]); any other file is skipped, the queue stopping only+ * when the songs after it fail too (see StreamErrors).+ */+ private fun fileGone(p: ExoPlayer, uri: android.net.Uri) {+ val i = p.currentMediaItemIndex+ val t = tracks.getOrNull(i) ?: return+ val song = deletedDownloads[uri.toString()]+ ?.takeIf { it.spotifyTrackId.isNotBlank() && com.music.spotui.data.offline.OfflineStore.isOnline(Graph.app) }+ if (song != null) {+ log("${t.title}: its download was deleted, it plays from its source")+ // From where it was (a seek into a song whose file went reopens it).+ val at = p.currentPosition+ swap(p, i, com.music.spotui.extensions.ExtensionAudio.localTrack(song))+ p.seekTo(i, at); p.prepare(); p.play()+ return+ }+ // No retry: a file that is not there will not be on a second open.+ errors.alreadyRetried(uri.toString())+ when (errors.failed(uri.toString(), p.hasNextMediaItem())) {+ StreamErrors.Step.SKIP -> {+ log("skipped ${t.title}: its file is gone")+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable_skipped, t.title), android.widget.Toast.LENGTH_SHORT).show()+ p.seekToNextMediaItem(); p.prepare(); p.play()+ }+ else -> {+ log("stopped on ${t.title}: its file is gone, and the songs after it failed too or none follows")+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable, t.title), android.widget.Toast.LENGTH_LONG).show()+ }+ }+ }+/** The most a song's start read ahead is kept (less when its address expires sooner). */private const val HEAD_KEEP_MS = 10 * 60_000L@@ -278,7 +360,7 @@ object LocalPlayer {active.value = false// A page left muted by an extension's mirror must not stay silent once Spotify plays again.SongPlayer.unmuteMirror()- forgetRadio(); continues = false+ forgetRadio(); continues = false; deletedDownloads.clear()exo?.let { it.stop(); it.clearMediaItems() }tracks.clear(); unshuffled = nullqueued.clear(); playingQueued = null; radioSongs.clear()diff --git a/base/app/src/test/java/com/music/spotui/di/DeletedDownloadsTest.kt b/base/app/src/test/java/com/music/spotui/di/DeletedDownloadsTest.ktnew file mode 100644index 00000000..415eb1a7--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/di/DeletedDownloadsTest.kt@@ -0,0 +1,36 @@+package com.music.spotui.di++import androidx.media3.common.PlaybackException+import com.music.spotui.di.DeletedDownloads.Fix+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++class DeletedDownloadsTest {+ @Test fun `the song playing keeps its file, the others play from their source`() {+ assertEquals(listOf(Fix.STREAM, Fix.KEEP, Fix.STREAM, Fix.STREAM),+ DeletedDownloads.plan(listOf("a", "b", "c", "d"), current = 1, online = true))+ }++ @Test fun `songs whose download was not deleted are untouched`() {+ assertEquals(listOf(Fix.KEEP, Fix.STREAM, Fix.KEEP),+ DeletedDownloads.plan(listOf(null, "b", null), current = 0, online = true))+ }++ @Test fun `offline the deleted songs are left out`() {+ assertEquals(listOf(Fix.KEEP, Fix.DROP, Fix.KEEP),+ DeletedDownloads.plan(listOf("a", "b", null), current = 0, online = false))+ }++ @Test fun `a deleted song with no Spotify id is left out`() {+ assertEquals(listOf(Fix.KEEP, Fix.DROP), DeletedDownloads.plan(listOf("a", ""), current = 0, online = true))+ }++ @Test fun `a missing file is told by its code or its cause`() {+ assertTrue(DeletedDownloads.isMissingFile(PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND, null))+ assertTrue(DeletedDownloads.isMissingFile(PlaybackException.ERROR_CODE_IO_UNSPECIFIED,+ java.io.IOException("open failed", java.io.FileNotFoundException("/x/audio/a.enc"))))+ assertFalse(DeletedDownloads.isMissingFile(PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED, java.io.IOException("reset")))+ }+}