Skip to content

Native Android client for Spotify, built with Jetpack Compose

Playlist pickers open at once after a restart, and the Library catches up with a playlist no longer in it

kota-zob16f0a36cc58
diff --git a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt
index d0f88ae9..45f416de 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt
@@ -4,6 +4,8 @@ import app.myspoti.api.LibraryFilter
import app.myspoti.api.MediaKind
import app.myspoti.api.best
import app.myspoti.host.android.MyspotiRuntime
+import org.json.JSONArray
+import org.json.JSONObject
/**
* A playlist the user can add tracks to, for the "Add to playlist" pickers. With a
@@ -37,14 +39,47 @@ object EditablePlaylists {
private const val ROOT = "root"
/** What [loadWithCovers] gave last, or null. */
- fun cachedWithCovers(): List<EditablePlaylist>? = shown[ALL]
+ fun cachedWithCovers(): List<EditablePlaylist>? = kept(ALL)
/** What [level] gave last for [folderUri], or null. */
- fun cachedLevel(folderUri: String?): List<EditablePlaylist>? = shown[folderUri ?: ROOT]
+ fun cachedLevel(folderUri: String?): List<EditablePlaylist>? = kept(folderUri ?: ROOT)
+
+ private const val PREF = "playlist_pickers"
+ private fun prefs() = com.music.spotui.di.Graph.app.getSharedPreferences(PREF, android.content.Context.MODE_PRIVATE)
+
+ /**
+ * The last list, from the disk after a restart. Kept in memory only, every first picker of a
+ * session waited for the whole library (reported: 5-6 s of "Loading playlists", on the build
+ * that showed the last list at once).
+ */
+ private fun kept(key: String): List<EditablePlaylist>? =
+ shown[key] ?: prefs().getString(key, null)?.let(::decodeList)?.also { shown[key] = it }
+
+ private fun keep(key: String, list: List<EditablePlaylist>) {
+ if (shown.put(key, list) != list) prefs().edit().putString(key, encodeList(list)).apply()
+ }
+
+ internal fun encodeList(list: List<EditablePlaylist>): String = JSONArray().apply {
+ list.forEach { p ->
+ put(JSONObject().put("id", p.id).put("name", p.name).put("count", p.trackCount)
+ .put("image", p.imageUrl ?: JSONObject.NULL).put("folder", p.folderUri ?: JSONObject.NULL))
+ }
+ }.toString()
+
+ /** Null when unreadable: the list is read from Spotify as if never kept. */
+ internal fun decodeList(raw: String): List<EditablePlaylist>? = runCatching {
+ val a = JSONArray(raw)
+ (0 until a.length()).map { i ->
+ val o = a.getJSONObject(i)
+ EditablePlaylist(o.getString("id"), o.getString("name"), o.getInt("count"),
+ o.optString("image").takeUnless { o.isNull("image") }, o.optString("folder").takeUnless { o.isNull("folder") })
+ }
+ }.getOrNull()
/** Sign-out: nothing of the account's playlists is kept. */
fun clear() {
shown.clear(); covers.clear(); ids = null
+ prefs().edit().clear().apply()
}
suspend fun ids(): Set<String> {
@@ -66,10 +101,10 @@ object EditablePlaylists {
*/
suspend fun loadWithCovers(): List<EditablePlaylist> {
// Not read (offline, the page reloading): the last list rather than none.
- val list = load().ifEmpty { return shown[ALL].orEmpty() }
+ val list = load().ifEmpty { return cachedWithCovers().orEmpty() }
if (list.any { it.imageUrl == null && !covers.containsKey("spotify:playlist:${it.id}") }) covers.putAll(libraryCovers())
return list.map { if (it.imageUrl != null) it else it.copy(imageUrl = covers["spotify:playlist:${it.id}"]) }
- .also { shown[ALL] = it }
+ .also { keep(ALL, it) }
}
/** Playlist uri → cover, as the library shows them, folders included. */
@@ -101,17 +136,18 @@ object EditablePlaylists {
*/
suspend fun level(folderUri: String?): List<EditablePlaylist> {
val api = MyspotiRuntime.api
- val editable = runCatching { api.playlists.editable() }.getOrNull()?.associateBy { it.uri } ?: return shown[folderUri ?: ROOT] ?: load()
+ val editable = runCatching { api.playlists.editable() }.getOrNull()?.associateBy { it.uri } ?: return cachedLevel(folderUri) ?: load()
val items = ArrayList<app.myspoti.api.LibraryItem>()
- runCatching {
+ val read = runCatching {
var offset = 0
repeat(40) {
val page = api.library.items(filter = LibraryFilter.ALL, folderUri = folderUri, offset = offset, limit = 50)
items += page.items
offset = page.nextOffset ?: return@runCatching
}
- }.onFailure { if (items.isEmpty()) return shown[folderUri ?: ROOT] ?: if (folderUri == null) load() else emptyList() }
- return items.mapNotNull { item ->
+ }
+ if (read.isFailure && items.isEmpty()) return cachedLevel(folderUri) ?: if (folderUri == null) load() else emptyList()
+ val list = items.mapNotNull { item ->
when (item.kind) {
MediaKind.FOLDER -> EditablePlaylist(item.uri, item.name, item.count ?: 0, null, folderUri = item.uri)
MediaKind.PLAYLIST -> editable[item.uri]?.let {
@@ -120,6 +156,10 @@ object EditablePlaylists {
}
else -> null
}
- }.also { shown[folderUri ?: ROOT] = it }
+ }
+ // A read cut short does not replace the whole list (reported: not all the playlists shown).
+ if (read.isFailure) return cachedLevel(folderUri) ?: list
+ keep(folderUri ?: ROOT, list)
+ return list
}
}
diff --git a/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.kt b/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.kt
index fddaf22a..bb297b76 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.kt
@@ -117,6 +117,10 @@ object LibraryEdits {
reloadSoon()
}
+ /** The Library still lists a playlist Spotify says is not in it: a list older than the answer. */
+ internal fun listedButNotSaved(uri: String, saved: Set<String>, listed: List<com.music.spotui.data.entity.LibraryEntry>): Boolean =
+ uri !in saved && listed.any { it.uri == uri }
+
/** A change written elsewhere (a Blend joined): the library is read again a few times, the first read can still be the old one. */
fun reloadSoon() {
scope.launch { for (wait in longArrayOf(1_500, 3_500, 7_000)) { delay(wait); _reloads.tryEmit(Unit) } }
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 50b3f27a..a86d9cf6 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
@@ -355,6 +355,15 @@ class ContextViewModel(
val saved = SongPlayer.libraryContains(uris)
savedUris.value = saved
contextSaved.value = p.uri in saved
+ // Reported: a playlist in the Library with an empty heart, nothing to take it out with,
+ // until a pull-to-refresh of the Library. The list catches up by itself.
+ if (p.type == "playlist") {
+ val listed = withContext(Dispatchers.IO) { com.music.spotui.data.preferences.getCachedLibraryEntries(Graph.app) }
+ if (com.music.spotui.data.api.LibraryEdits.listedButNotSaved(p.uri, saved, listed)) {
+ app.myspoti.host.android.Logbook.log("library: ${p.uri} listed but not saved, the list is read again")
+ com.music.spotui.data.api.LibraryEdits.reloadSoon()
+ }
+ }
}
// A11: Spotify refuses an edit to a list the user cannot change, so the entry is only
// offered where it would work (own and collaborative playlists, as Spotify itself).
diff --git a/base/app/src/test/java/com/music/spotui/data/api/EditablePlaylistsTest.kt b/base/app/src/test/java/com/music/spotui/data/api/EditablePlaylistsTest.kt
new file mode 100644
index 00000000..4e9e02e3
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/EditablePlaylistsTest.kt
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+package com.music.spotui.data.api
+
+import com.music.spotui.data.entity.LibraryEntry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class EditablePlaylistsTest {
+ @Test fun aKeptListComesBackAsItWas() {
+ val list = listOf(
+ EditablePlaylist("a", "Road \"trip\"", 12, "https://i/a"),
+ EditablePlaylist("spotify:user:u:folder:f", "Folder", 3, null, folderUri = "spotify:user:u:folder:f"),
+ EditablePlaylist("b", "No cover", 0, null),
+ )
+ assertEquals(list, EditablePlaylists.decodeList(EditablePlaylists.encodeList(list)))
+ }
+
+ @Test fun anUnreadableListIsNoList() {
+ assertNull(EditablePlaylists.decodeList("not json"))
+ }
+
+ private fun entry(uri: String) = LibraryEntry(spotifyId = uri.substringAfterLast(':'), name = "", subtitle = "", coverUri = "", isPlaylist = true, uri = uri)
+
+ @Test fun aListedPlaylistSpotifyDoesNotCountIsAnOldList() {
+ val p = "spotify:playlist:p"
+ assertTrue(LibraryEdits.listedButNotSaved(p, emptySet(), listOf(entry(p))))
+ assertFalse(LibraryEdits.listedButNotSaved(p, setOf(p), listOf(entry(p))))
+ assertFalse(LibraryEdits.listedButNotSaved(p, emptySet(), listOf(entry("spotify:playlist:q"))))
+ }
+}