Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Keep resolved playlists on disk, and check them with one request
Lelonio575680952882
diff --git a/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin b/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.binindex 5824847..f856c4c 100644--- a/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin+++ b/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin@@ -2,27 +2,27 @@ C/C++ Structured Logca_/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/additional_project_files.txtCA-?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint �����3 ��߈�3`+?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint ��ƌ�3 ��߈�3`^-\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build.json �����3� ��߈�3e+\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build.json ��ƌ�3� ��߈�3ec-a/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build_mini.json �����3� ��߈�3R+a/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build_mini.json ��ƌ�3� ��߈�3RP-N/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja �����3� ��߈�3V+N/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja ��ƌ�3� ��߈�3VT-R/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja.txt �����3[+R/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja.txt ��ƌ�3[Y-W/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build_file_index.txt �����3 @ ��߈�3\+W/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build_file_index.txt ��ƌ�3 @ ��߈�3\Z-X/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json �����3֚ ��߈�3`+X/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json ��ƌ�3֚ ��߈�3`^-\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json.bin �����3 �" ��߈�3f+\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json.bin ��ƌ�3 �" ��߈�3fd-b/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/metadata_generation_command.txt �����3+b/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/metadata_generation_command.txt ��ƌ�3� ��߈�3YW-U/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/prefab_config.json �����3 ( ��߈�3^+U/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/prefab_config.json ��ƌ�3 ( ��߈�3^\-Z/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/symbol_folder_index.txt �����3 Y ��߈�3D+Z/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/symbol_folder_index.txt ��ƌ�3 Y ��߈�3DB-@/Users/emanuele/Progetto Spotify/app/src/main/cpp/CMakeLists.txt �����3 � �Ȅ��3\ No newline at end of file+@/Users/emanuele/Progetto Spotify/app/src/main/cpp/CMakeLists.txt ��ƌ�3 � �Ȅ��3\ No newline at end of filediff --git a/app/src/main/java/dev/emanuele/spot/SpotApplication.kt b/app/src/main/java/dev/emanuele/spot/SpotApplication.ktindex 9f645ef..5fdfb3b 100644--- a/app/src/main/java/dev/emanuele/spot/SpotApplication.kt+++ b/app/src/main/java/dev/emanuele/spot/SpotApplication.kt@@ -3,6 +3,7 @@ package dev.emanuele.spotimport android.app.Applicationimport dev.emanuele.spot.auth.TokenStoreimport dev.emanuele.spot.auth.WebApiAccount+import dev.emanuele.spot.data.ContextCacheStoreimport dev.emanuele.spot.data.PlaylistOrderStoreimport dev.emanuele.spot.data.PreferencesStoreimport dev.emanuele.spot.data.RecentStore@@ -26,6 +27,9 @@ class SpotApplication : Application() {val playlistOrder: PlaylistOrderStore by lazy { PlaylistOrderStore(this) }val preferences: PreferencesStore by lazy { PreferencesStore(this) }+ /** Track lists already resolved, so reopening a playlist is not a reload. */+ val contextCache: ContextCacheStore by lazy { ContextCacheStore(this) }+/*** The user's own Spotify application. Web API calls go through it so they* are metered against a quota nobody else shares — see [WebApiAccount].diff --git a/app/src/main/java/dev/emanuele/spot/data/ContextCacheStore.kt b/app/src/main/java/dev/emanuele/spot/data/ContextCacheStore.ktnew file mode 100644index 0000000..952b9e5--- /dev/null+++ b/app/src/main/java/dev/emanuele/spot/data/ContextCacheStore.kt@@ -0,0 +1,92 @@+package dev.emanuele.spot.data++import android.content.Context+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.io.File++/**+ * Resolved track lists, kept on disk between runs.+ *+ * The in-memory cache above this only helps while the app is alive, and a+ * playlist of a thousand tracks is a dozen Web API pages: every cold start paid+ * for all of them, and the user watched the rows arrive a hundred at a time.+ *+ * Spotify stamps a playlist with a `snapshot_id` that changes whenever its+ * contents do, which is what makes a cache honest here rather than a gamble: one+ * small request says whether the twelve big ones are needed at all. Albums have+ * no such stamp and need none — an album does not gain tracks.+ *+ * One file per context. A single blob would have to be rewritten in full every+ * time any playlist changed, and would be read in full to open one.+ */+class ContextCacheStore(context: Context) {++ @Serializable+ data class Entry(+ val tracks: List<CatalogTrack>,+ /** Spotify's stamp for the version this was read from; null for albums. */+ val snapshotId: String? = null,+ val savedAt: Long = 0,+ )++ private val dir = File(context.applicationContext.cacheDir, DIR_NAME)+ private val json = Json { ignoreUnknownKeys = true }++ suspend fun read(uri: String): Entry? = withContext(Dispatchers.IO) {+ val file = fileFor(uri)+ if (!file.exists()) return@withContext null+ // A half-written or outdated file is not worth a crash: dropping it+ // costs one reload, and the next save repairs it.+ runCatching { json.decodeFromString(Entry.serializer(), file.readText()) }+ .onFailure { file.delete() }+ .getOrNull()+ ?.takeIf { it.savedAt > System.currentTimeMillis() - MAX_AGE_MS }+ }++ suspend fun write(uri: String, tracks: List<CatalogTrack>, snapshotId: String?) =+ withContext(Dispatchers.IO) {+ if (tracks.isEmpty()) return@withContext+ dir.mkdirs()+ val entry = Entry(tracks, snapshotId, System.currentTimeMillis())+ runCatching { fileFor(uri).writeText(json.encodeToString(Entry.serializer(), entry)) }+ trim()+ }++ suspend fun remove(uri: String) = withContext(Dispatchers.IO) {+ fileFor(uri).delete()+ Unit+ }++ suspend fun clear() = withContext(Dispatchers.IO) {+ dir.deleteRecursively()+ Unit+ }++ /** Oldest files go first, so a browsing session cannot fill the disk. */+ private fun trim() {+ val files = dir.listFiles()?.sortedByDescending { it.lastModified() } ?: return+ files.drop(MAX_ENTRIES).forEach { it.delete() }+ }++ // Hashed rather than sanitised: a URI is not a legal file name, and any+ // escaping scheme would have to survive URIs that differ only in a character+ // it escapes.+ private fun fileFor(uri: String) = File(dir, "${uri.hashCode().toUInt().toString(16)}.json")++ private companion object {+ const val DIR_NAME = "contexts"+ const val MAX_ENTRIES = 40++ /**+ * Old entries are dropped rather than trusted indefinitely.+ *+ * The snapshot check covers playlists exactly, but an album can be+ * relinked and an artist's top tracks change with no stamp to notice it+ * by, so nothing is kept for more than a week.+ */+ const val MAX_AGE_MS = 7L * 24 * 60 * 60 * 1000+ }+}diff --git a/app/src/main/java/dev/emanuele/spot/data/SpotifyApi.kt b/app/src/main/java/dev/emanuele/spot/data/SpotifyApi.ktindex 8ecc6e7..0b85521 100644--- a/app/src/main/java/dev/emanuele/spot/data/SpotifyApi.kt+++ b/app/src/main/java/dev/emanuele/spot/data/SpotifyApi.kt@@ -53,6 +53,21 @@ interface SpotifyApi {@Query("market") market: String = "from_token",): PageDto<PlaylistTrackDto>+ /**+ * The playlist's version stamp, and nothing else.+ *+ * `snapshot_id` changes whenever the contents do, so this one small request+ * answers "is the copy on disk still right?" — which is what lets a+ * thousand-track playlist open without re-reading a dozen pages of it.+ * `fields` keeps the response to the two values that matter instead of the+ * whole playlist with its first hundred tracks inside.+ */+ @GET("v1/playlists/{id}")+ suspend fun playlistSnapshot(+ @Path("id") playlistId: String,+ @Query("fields") fields: String = "snapshot_id,tracks(total)",+ ): PlaylistSnapshotDto+/*** Albums and singles released recently.*@@ -179,6 +194,15 @@ data class SavedTrackDto(val track: TrackDto,)+@Serializable+data class PlaylistSnapshotDto(+ @SerialName("snapshot_id") val snapshotId: String? = null,+ val tracks: TotalDto? = null,+)++@Serializable+data class TotalDto(val total: Int = 0)+@Serializabledata class PlaylistTrackDto(/** Null for episodes and for tracks removed from the catalogue. */diff --git a/app/src/main/java/dev/emanuele/spot/ui/MainViewModel.kt b/app/src/main/java/dev/emanuele/spot/ui/MainViewModel.ktindex 9f92db0..8e24c12 100644--- a/app/src/main/java/dev/emanuele/spot/ui/MainViewModel.kt+++ b/app/src/main/java/dev/emanuele/spot/ui/MainViewModel.kt@@ -11,6 +11,7 @@ import dev.emanuele.spot.data.RemoveTracksRequestDtoimport dev.emanuele.spot.data.TrackUriDtoimport dev.emanuele.spot.data.CatalogPlaylistimport dev.emanuele.spot.data.CatalogTrack+import dev.emanuele.spot.data.ContextCacheStoreimport dev.emanuele.spot.data.SearchItemimport dev.emanuele.spot.data.TransferRequestDtoimport dev.emanuele.spot.data.SearchResults@@ -528,6 +529,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {container.tokenStore.clear()container.recentStore.clear()container.playlistOrder.clear()+ // Somebody else's library must not be sitting in the cache when the+ // next account signs in.+ contextCache.clear()+ viewModelScope.launch { container.contextCache.clear() }_playlist.value = PlaylistState()_feed.value = FeedState()_state.value = UiState.LoggedOut@@ -644,10 +649,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {* replaces it only when it has the whole thing, so reopening never takes a* finished list away and rebuilds it in front of the user.*/- private val contextCache = object : LinkedHashMap<String, List<CatalogTrack>>(0, 0.75f, true) {- override fun removeEldestEntry(eldest: Map.Entry<String, List<CatalogTrack>>) =- size > CONTEXT_CACHE_SIZE- }+ private val contextCache =+ object : LinkedHashMap<String, ContextCacheStore.Entry>(0, 0.75f, true) {+ override fun removeEldestEntry(eldest: Map.Entry<String, ContextCacheStore.Entry>) =+ size > CONTEXT_CACHE_SIZE+ }fun openPlaylist(playlist: CatalogPlaylist) {// Reopening one counts as opening it, and that is exactly the playlist@@ -663,14 +669,30 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {kind = kind,)- val cached = contextCache[playlist.uri].orEmpty()- _playlist.value = base.copy(tracks = cached, loading = cached.isEmpty())+ val remembered = contextCache[playlist.uri]+ _playlist.value = base.copy(+ tracks = remembered?.tracks.orEmpty(),+ loading = remembered == null,+ )playlistJob = viewModelScope.launch {+ // The disk copy, if this run has not opened the playlist yet. Read+ // before anything is asked of the network: the whole point is that a+ // list already known appears at once rather than filling in.+ val entry = remembered ?: container.contextCache.read(playlist.uri)?.also {+ contextCache[playlist.uri] = it+ _playlist.value = base.copy(tracks = it.tracks, loading = false)+ }+ val cached = entry?.tracks.orEmpty()+runCatching {if (kind == DetailKind.ARTIST) {val (tracks, albums) = loadArtist(playlist.uri)_playlist.value = base.copy(tracks = tracks, albums = albums)+ } else if (cached.isNotEmpty() && isUnchanged(playlist.uri, entry?.snapshotId)) {+ // Nothing to do: one small request said the copy on screen+ // is the current one.+ _playlist.value = base.copy(tracks = cached, loadingMore = false)} else {loadContextInto(base, playlist.uri, showProgress = cached.isEmpty())}@@ -685,6 +707,24 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}+ /**+ * Whether the stored copy of a playlist is still the current one.+ *+ * Spotify changes a playlist's `snapshot_id` whenever its contents do, so+ * this is one request against a dozen. False for anything without a stored+ * stamp — an album, a list read through the access point — which simply+ * means it is refreshed as before, silently, behind what is already shown.+ */+ private suspend fun isUnchanged(uri: String, snapshotId: String?): Boolean {+ if (snapshotId == null) return false+ if (!container.webApi.isReady || !uri.startsWith("spotify:playlist:")) return false+ return runCatching {+ container.api.playlistSnapshot(uri.substringAfterLast(':')).snapshotId == snapshotId+ }+ .onFailure { android.util.Log.w(TAG, "snapshot check failed: ${describe(it)}") }+ .getOrDefault(false)+ }+/*** Removes a track from the playlist currently open.*@@ -718,9 +758,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}- /** Drops a context from the cache so the next open re-reads it. */+ /** Drops a context from both caches so the next open re-reads it. */private fun invalidateContext(uri: String) {contextCache.remove(uri)+ viewModelScope.launch { container.contextCache.remove(uri) }}/**@@ -747,8 +788,22 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val tracks = viaWebApi ?: accessPointTracks(base, uri, showProgress)- contextCache[uri] = tracks_playlist.value = base.copy(tracks = tracks, loadingMore = false)++ // Stamped with the version it was read from, so the next open can ask+ // one question instead of reading it all again. Without a stamp the+ // entry still saves — it just gets refreshed silently every time.+ val snapshotId = snapshotOf(uri)+ contextCache[uri] = ContextCacheStore.Entry(tracks, snapshotId)+ container.contextCache.write(uri, tracks, snapshotId)+ }++ /** The playlist's current version stamp, or null if it has none to give. */+ private suspend fun snapshotOf(uri: String): String? {+ if (!container.webApi.isReady || !uri.startsWith("spotify:playlist:")) return null+ return runCatching {+ container.api.playlistSnapshot(uri.substringAfterLast(':')).snapshotId+ }.getOrNull()}/** Null when this is not something the Web API can page through. */