Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Artist pages cached for 5 min and shared with the releases page; discography and first playlist songs fetched in parallel; liked songs loaded once per session; liked-by-artist above popular tracks
kota-zoc81f1e04b359
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 880b0f3a..daea87f6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,8 @@ Each release on GitHub shows its section below. The app shows it too when it off- **Skips are about three times faster**: the next song is heard ~0.8 s after the tap instead of ~2.5 s (the next song is loaded ahead, the first tap is sent at once, a shorter fade, and the hidden Spotify page no longer redraws its home screen at every song).- **Cover back to its full size** in the player.- **Myspoti's buttons play on this phone again** when another device (the Spotify app on the same account, for instance) took playback without being picked in Myspoti: the music comes back here first, instead of driving that device (where skips, previous and volume were refused).+- **Faster artist pages and playlists**: an artist seen in the last minutes opens at once (and its releases page too), the discography and a playlist's first songs are asked for together with the page, and your liked songs load once per session instead of on every artist page.+- **Your liked songs by an artist** come first on its page, above the popular tracks.- **New languages**: German, Spanish, Portuguese and Greek, on every screen.- **Music no longer stops for a minute**: a Web Player page that stops answering is reloaded at once, and playback goes on.- **No more silent songs**: the sound comes back by itself if a skip or a muted ad left it at zero; after a skip it comes back as soon as the next song is there.diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.ktindex e0afb7b6..d01106c6 100644--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt@@ -76,12 +76,31 @@ class Api constructor(libraryRoot = null; folders.clear()facets.clear()LikedCache.tracks = null+ ArtistCache.map.clear()ScreenCache.clear()}}object LikedCache {@Volatile var tracks: List<SongsModel>? = null+ private val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)+ @Volatile private var loading: kotlinx.coroutines.Deferred<List<SongsModel>?>? = null++ /**+ * All liked songs, loaded once for the whole app (not again by every screen that needs+ * them, nor started over when that screen closes before the end).+ */+ @Synchronized+ fun loadOnce(): kotlinx.coroutines.Deferred<List<SongsModel>?> {+ tracks?.let { return kotlinx.coroutines.CompletableDeferred(it) }+ loading?.takeIf { it.isActive }?.let { return it }+ return scope.async {+ runCatching {+ Graph.api.getLikedPage().first { it is Response.Success && it.data.complete || it is Response.Error }+ .let { (it as? Response.Success)?.data?.tracks }+ }.getOrNull()?.also { if (tracks == null) tracks = it }+ }.also { loading = it }+ }/*** [head] (the newest liked songs, from Spotify) then the rest of [known] after them.@@ -425,9 +444,26 @@ class Api constructor(val uri = if (knownArtistId.isNotBlank()) "spotify:artist:$knownArtistId"else runCatching { findArtist(artistName) }.getOrNull()?.uriif (uri == null) { emit(Response.Error(context.getString(R.string.artist_not_found))); return@flow }- val page = runCatching { api.catalog.artistPage(uri) }.getOrElse {- Log.e("Api", "getArtistOverview failed", it); emit(Response.Error(it.message ?: "error")); return@flow+ // Shown again within a few minutes (back, the releases page, another tap): from memory,+ // without asking Spotify for the page and the whole discography once more.+ ArtistCache.map[uri]?.let { (at, cached) ->+ emit(Response.Success(cached))+ if (System.currentTimeMillis() - at < ArtistCache.FRESH_MS) return@flow+ }+ val firstReleases = kotlinx.coroutines.coroutineScope {+ // The discography's first page goes out with the page itself, not after it.+ val releases = async { runCatching { api.catalog.discography(uri, 0, 50) }.getOrNull() }+ val page = runCatching { api.catalog.artistPage(uri) }.getOrElse {+ releases.cancel()+ Log.e("Api", "getArtistOverview failed", it)+ return@coroutineScope null+ }+ page to releases+ } ?: run {+ if (ArtistCache.map[uri] == null) emit(Response.Error(context.getString(R.string.page_load_failed)))+ return@flow}+ val page = firstReleases.firstval avatar = big(page.artist.images)val top = page.topTracks.map { t -> songOf(t.track).let { if (it.coverUri.isBlank()) it.copy(coverUri = avatar) else it } to t.playcount }SongPlayer.registerContext(top.map { it.first.url }, uri)@@ -445,26 +481,36 @@ class Api constructor(relatedArtists = page.related.map(::artistOf),)emit(Response.Success(model))+ ArtistCache.map[uri] = System.currentTimeMillis() to model// The overview carries only part of the discography: the whole list follows.// Every page of it (big artists have hundreds of singles), up to a sane cap.val all = runCatching {val out = ArrayList<app.myspoti.api.Album>()- var offset: Int? = 0+ val first = firstReleases.second.await()+ var offset: Int? = if (first != null) { out += first.items; first.nextOffset.takeIf { first.items.isNotEmpty() } } else 0while (offset != null && out.size < DISCOGRAPHY_MAX) {- val page = api.catalog.discography(uri, offset, 50)- if (page.items.isEmpty()) break- out += page.items- offset = page.nextOffset+ val next = api.catalog.discography(uri, offset, 50)+ if (next.items.isEmpty()) break+ out += next.items+ offset = next.nextOffset}out}.getOrNull().orEmpty()val known = page.popularReleases.map { it.uri }.toSet()if (all.any { it.uri !in known }) {val merged = (page.popularReleases + all).distinctBy { it.uri }.sortedByDescending { it.releaseDate.orEmpty() }- emit(Response.Success(model.copy(popularReleases = merged.map(::albumOf))))+ val full = model.copy(popularReleases = merged.map(::albumOf))+ ArtistCache.map[uri] = System.currentTimeMillis() to full+ emit(Response.Success(full))}}+ /** Artist pages shown lately, by artist uri, with when they were loaded. */+ private object ArtistCache {+ const val FRESH_MS = 5 * 60_000L+ val map = java.util.concurrent.ConcurrentHashMap<String, Pair<Long, ArtistOverviewModel>>()+ }+// ── Albums and playlists ──private fun dateLabel(iso: String?): String {@@ -591,7 +637,12 @@ class Api constructor(emit(Response.Loading())if (!ready()) { emit(Response.Error(notSignedIn())); return@flow }val uri = "spotify:playlist:$playlistId"+ // The first songs are asked for together with the playlist's details, not after them.+ val firstPage = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.currentCoroutineContext()).async(Dispatchers.IO) {+ runCatching { api.playlists.tracks(uri, 0, 100) }+ }val pl = runCatching { api.playlists.playlist(uri) }.getOrElse {+ firstPage.cancel()emit(Response.Error(context.getString(R.string.playlist_not_found))); return@flow}val saves = pl.followers?.takeIf { it > 0 }?.let {@@ -612,7 +663,8 @@ class Api constructor(var offset = 0var failed = falsewhile (true) {- val page = runCatching { api.playlists.tracks(uri, offset, 100) }.getOrElse { failed = true; null } ?: break+ val result = if (offset == 0) firstPage.await() else runCatching { api.playlists.tracks(uri, offset, 100) }+ val page = result.getOrElse { failed = true; null } ?: breaksongs += page.items.map(::songOf)SongPlayer.registerContext(songs.map { it.url }, uri)val total = songs.sumOf { it.durationMs.toLong() }diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.ktindex 5b015e7d..88e26911 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt@@ -156,12 +156,9 @@ private fun ArtistOverviewContent(var likedByArtist by remember(overview.id) { mutableStateOf<List<com.music.spotui.data.entity.SongsModel>>(emptyList()) }var showLiked by remember(overview.id) { mutableStateOf(false) }LaunchedEffect(overview.id) {+ // Loaded once per session, shared by every artist page, after this page is shown.val all = com.music.spotui.data.api.Api.LikedCache.tracks- ?: runCatching {- com.music.spotui.di.Graph.api.getLikedPage()- .first { it is Response.Success && it.data.complete }- .let { (it as? Response.Success)?.data?.tracks }- }.getOrNull()+ ?: run { kotlinx.coroutines.delay(800); com.music.spotui.data.api.Api.LikedCache.loadOnce().await() }?: return@LaunchedEffectlikedByArtist = all.filter { s ->if (s.artistIds.isNotEmpty()) overview.id in s.artistIds@@ -356,45 +353,6 @@ private fun ArtistOverviewContent(}}- // ── Popular tracks ──- if (tracks.isNotEmpty()) {- item {- Text(- text = stringResource(R.string.artist_popular_tracks),- color = Color.White,- fontSize = 20.sp,- fontWeight = FontWeight.Bold,- modifier = Modifier.padding(16.dp, 8.dp, 16.dp, 4.dp),- )- }- itemsIndexed(tracks.take(if (showAllPopular) 10 else 5)) { index, item ->- com.music.spotui.ui.components.SwipeToQueue(item.song) {- PopularTrackRow(- item, index, artistViewModel,- saved = SongPlayer.library["spotify:track:${item.song.spotifyTrackId}"] ?: ("spotify:track:${item.song.spotifyTrackId}" in saved),- onToggleSaved = { on ->- SongPlayer.setTrackSaved(item.song.spotifyTrackId, on)- },- onMore = { menuSong = item.song },- onPlay = { playTrackAt(index) },- )- }- }- if (tracks.size > 5) item {- Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp)) {- Box(- modifier = Modifier- .clip(RoundedCornerShape(50))- .border(1.dp, Color.White.copy(alpha = 0.5f), RoundedCornerShape(50))- .clickable { showAllPopular = !showAllPopular }- .padding(horizontal = 20.dp, vertical = 8.dp),- ) {- Text(if (showAllPopular) stringResource(R.string.profile_bio_show_less) else stringResource(R.string.audiobook_series_see_more_button), color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Bold)- }- }- }- }-// ── Liked songs by this artist ──if (likedByArtist.isNotEmpty()) {item(key = "liked-by-artist") {@@ -441,6 +399,45 @@ private fun ArtistOverviewContent(}}+ // ── Popular tracks ──+ if (tracks.isNotEmpty()) {+ item {+ Text(+ text = stringResource(R.string.artist_popular_tracks),+ color = Color.White,+ fontSize = 20.sp,+ fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(16.dp, 8.dp, 16.dp, 4.dp),+ )+ }+ itemsIndexed(tracks.take(if (showAllPopular) 10 else 5)) { index, item ->+ com.music.spotui.ui.components.SwipeToQueue(item.song) {+ PopularTrackRow(+ item, index, artistViewModel,+ saved = SongPlayer.library["spotify:track:${item.song.spotifyTrackId}"] ?: ("spotify:track:${item.song.spotifyTrackId}" in saved),+ onToggleSaved = { on ->+ SongPlayer.setTrackSaved(item.song.spotifyTrackId, on)+ },+ onMore = { menuSong = item.song },+ onPlay = { playTrackAt(index) },+ )+ }+ }+ if (tracks.size > 5) item {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp)) {+ Box(+ modifier = Modifier+ .clip(RoundedCornerShape(50))+ .border(1.dp, Color.White.copy(alpha = 0.5f), RoundedCornerShape(50))+ .clickable { showAllPopular = !showAllPopular }+ .padding(horizontal = 20.dp, vertical = 8.dp),+ ) {+ Text(if (showAllPopular) stringResource(R.string.profile_bio_show_less) else stringResource(R.string.audiobook_series_see_more_button), color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Bold)+ }+ }+ }+ }+// ── Popular releases (discography) — vertical list, first few + "Show all" ──if (overview.popularReleases.isNotEmpty()) {item { SectionHeader(stringResource(R.string.popular_releases_section_title)) }