Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Load followed artists' releases faster and lead the New page with them

Lelonio436c52a3e11e
diff --git a/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt b/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt
index 333354f..e1f8ecf 100644
--- a/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt
+++ b/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt
@@ -38,7 +38,7 @@ class FollowedReleases(private val api: SpotifyApi, private val directory: File)
suspend fun load(force: Boolean = false, onProgress: (Int, Int) -> Unit = { _, _ -> }): Result {
val artists = artists()
- val limit = Semaphore(3)
+ val limit = Semaphore(5)
val completed = AtomicInteger()
val failed = AtomicInteger()
val cutoff = LocalDate.now().minusMonths(12)
@@ -54,7 +54,7 @@ class FollowedReleases(private val api: SpotifyApi, private val directory: File)
if (!force && cached != null && System.currentTimeMillis() - cached.savedAt in 0..CACHE_MS) {
cached.albums
} else {
- discography(id).also { write(id, it) }
+ discography(id, cutoff).also { write(id, it) }
}
} catch (e: CancellationException) {
throw e
@@ -70,25 +70,55 @@ class FollowedReleases(private val api: SpotifyApi, private val directory: File)
}.awaitAll().flatten()
}
return Result(recentReleases(albums, cutoff, LocalDate.now()), artists.size, failed.get())
+ .also { if (it.failedArtists == 0) save(it) }
}
- private suspend fun discography(id: String): List<AlbumDto> {
+ /**
+ * An artist's albums and singles from the last year, newest first.
+ *
+ * Spotify lists each group newest first, so a group is read only until a
+ * page reaches back past [cutoff]: for almost every artist that is one
+ * short page of albums and one of singles. The whole discography used to be
+ * read, fifty at a time, for every artist followed, and the row waited on
+ * the longest of them.
+ */
+ private suspend fun discography(id: String, cutoff: LocalDate): List<AlbumDto> {
val albums = mutableListOf<AlbumDto>()
- var offset = 0
- while (true) {
- val page = api.artistAlbums(id, groups = "album,single", limit = 50, offset = offset)
- if (page.next != null && offset > 0) {
- val seen = albums.map { it.uri ?: it.id }.toSet()
- check(page.items.any { (it.uri ?: it.id) !in seen }) { "Repeated artist album page" }
+ for (group in listOf("album", "single")) {
+ var offset = 0
+ while (true) {
+ val page = api.artistAlbums(id, groups = group, limit = PAGE, offset = offset)
+ albums += page.items
+ val oldest = page.items.lastOrNull()?.let { releaseDay(it.releaseDate) }
+ if (page.next == null || page.items.isEmpty() || oldest == null || oldest < cutoff) break
+ offset += page.items.size
+ check(offset < MAX_PER_GROUP) { "Artist album pages did not reach back a year" }
}
- albums += page.items
- if (page.next == null) break
- check(page.items.isNotEmpty()) { "Empty artist page with a continuation" }
- offset += page.items.size
}
return albums.distinctBy { it.uri ?: it.id }
}
+ /** What the last load found, to show while the next one runs. */
+ suspend fun saved(): Result? = withContext(Dispatchers.IO) {
+ runCatching {
+ val saved = json.decodeFromString<Saved>(File(directory, SAVED).readText())
+ Result(recentReleases(saved.albums, LocalDate.now().minusMonths(12), LocalDate.now()), saved.artistCount, 0)
+ }.getOrNull()
+ }
+
+ private suspend fun save(result: Result) = withContext(Dispatchers.IO) {
+ runCatching {
+ directory.mkdirs()
+ val temp = File(directory, "$SAVED.tmp")
+ temp.writeText(json.encodeToString(Saved.serializer(), Saved(result.albums, result.artistCount)))
+ check(temp.renameTo(File(directory, SAVED)))
+ }
+ Unit
+ }
+
+ @Serializable
+ private data class Saved(val albums: List<AlbumDto>, val artistCount: Int)
+
private suspend fun read(id: String): Entry? = withContext(Dispatchers.IO) {
runCatching { json.decodeFromString<Entry>(file(id).readText()) }.getOrNull()
}
@@ -112,6 +142,10 @@ class FollowedReleases(private val api: SpotifyApi, private val directory: File)
companion object {
private const val CACHE_MS = 6 * 60 * 60 * 1_000L
+ private const val PAGE = 20
+ /** Past this, an artist's pages are not in the order they should be. */
+ private const val MAX_PER_GROUP = 200
+ private const val SAVED = "last-result.json"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 320f00f..30ce173 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -360,6 +360,16 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
_followedReleases.value = _followedReleases.value.copy(loading = true, completed = 0, error = null)
followedReleaseJob = viewModelScope.launch {
try {
+ // The last answer straight away, while this one is worked out:
+ // reading every followed artist takes seconds, and the row and
+ // the cards at the top waited on it with nothing to show.
+ if (_followedReleases.value.albums.isEmpty()) {
+ followedReleaseRepository.saved()?.let { saved ->
+ _followedReleases.value = _followedReleases.value.copy(
+ albums = saved.albums, artistCount = saved.artistCount,
+ )
+ }
+ }
val result = followedReleaseRepository.load(force) { done, total ->
_followedReleases.value = _followedReleases.value.copy(completed = done, artistCount = total)
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
index 5d0b192..1ccb446 100644
--- a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
@@ -84,14 +84,39 @@ fun NewScreen(
/** The same menu every other list of songs in the app opens. */
onSongMenu: (CatalogTrack) -> Unit,
) {
- if ((followed.loading && followed.albums.isEmpty()) ||
- (page.loading && page.hero.isEmpty() && page.songs.isEmpty() && shelves.isEmpty() && followed.albums.isEmpty())
- ) {
+ // Not held for the followed artists: reading all of them takes seconds,
+ // and the whole page stood behind a spinner for the one row that needs it.
+ // That row has an outline of its own while it comes.
+ if (page.loading && page.hero.isEmpty() && page.songs.isEmpty() && shelves.isEmpty() && followed.albums.isEmpty()) {
Box(Modifier.fillMaxSize().padding(contentPadding), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
return
}
+ // The big cards are the newest records by artists this listener follows.
+ // The catalogue's picks only fill the places those leave empty: an account
+ // that follows few artists, or the first visit, before they have been read.
+ // The ones up there leave the row below, so no cover is on screen twice.
+ val followedItems = remember(followed.albums) {
+ followed.albums.map { album ->
+ SearchItem(
+ uri = album.uri ?: "spotify:album:${album.id}",
+ title = album.name,
+ subtitle = album.artists.joinToString(", ") { it.name },
+ artworkUrl = album.images.firstOrNull()?.url,
+ )
+ }
+ }
+ val heroFollowed = remember(followedItems) { followedItems.take(HERO_CARDS) }
+ val heroItems = remember(heroFollowed, page.hero) {
+ val taken = heroFollowed.mapTo(mutableSetOf()) { it.uri }
+ heroFollowed + page.hero.filter { it.uri !in taken }.take(HERO_CARDS - heroFollowed.size)
+ }
+ val heroFollowedUris = remember(heroFollowed) { heroFollowed.mapTo(mutableSetOf()) { it.uri } }
+ val shelfFollowed = remember(followedItems, heroFollowedUris) {
+ followedItems.filter { it.uri !in heroFollowedUris }
+ }
+
LazyColumn(
contentPadding = PaddingValues(
top = contentPadding.calculateTopPadding() + 8.dp,
@@ -107,8 +132,8 @@ fun NewScreen(
)
}
- if (page.hero.isNotEmpty()) {
- item(contentType = "hero") { HeroPager(page.hero, onOpen) }
+ if (heroItems.isNotEmpty()) {
+ item(contentType = "hero") { HeroPager(heroItems, heroFollowedUris, onOpen) }
}
if (page.songs.isNotEmpty()) {
@@ -118,26 +143,18 @@ fun NewScreen(
item(contentType = "songs") { SongPages(page.songs, onSongMenu, onPlaySong) }
}
- if (followed.albums.isNotEmpty() || followed.error != null || followed.loaded) {
+ if (followed.albums.isNotEmpty() || followed.error != null || followed.loaded || followed.loading) {
item(key = "followedHeading", contentType = "shelfHeading") {
Heading(stringResource(R.string.new_from_followed_artists))
}
- if (followed.albums.isNotEmpty()) {
+ if (shelfFollowed.isNotEmpty()) {
item(key = "followedShelf", contentType = "shelfRow") {
- Shelf(
- followed.albums.map { album ->
- SearchItem(
- uri = album.uri ?: "spotify:album:${album.id}",
- title = album.name,
- subtitle = album.artists.joinToString(", ") { it.name },
- artworkUrl = album.images.firstOrNull()?.url,
- )
- },
- onOpen,
- )
+ Shelf(shelfFollowed, onOpen)
}
+ } else if (followed.loading && followed.albums.isEmpty()) {
+ item(key = "followedSkeleton", contentType = "skeleton") { SkeletonRow() }
}
- if (followed.error != null || followed.failedArtists > 0 || followed.albums.isEmpty()) {
+ if (followed.error != null || followed.failedArtists > 0 || (followed.loaded && followed.albums.isEmpty())) {
item(key = "followedStatus", contentType = "status") {
Column(Modifier.padding(horizontal = 20.dp, vertical = 12.dp)) {
Text(
@@ -223,6 +240,9 @@ fun NewScreen(
/** How many outlines stand in for the rows that are coming. */
private const val SKELETON_ROWS = 3
+/** How many big cards the page leads with. */
+private const val HERO_CARDS = 9
+
/**
* The records the page is leading with, one screen at a time.
*
@@ -234,7 +254,12 @@ private const val SKELETON_ROWS = 3
* somebody having chosen it.
*/
@Composable
-private fun HeroPager(items: List<SearchItem>, onOpen: (SearchItem) -> Unit) {
+private fun HeroPager(
+ items: List<SearchItem>,
+ /** The cards that are there because the listener follows the artist. */
+ followed: Set<String>,
+ onOpen: (SearchItem) -> Unit,
+) {
BoxWithConstraints {
// Almost the whole width, with the next card showing at the edge: the
// peek is what says the row can be moved.
@@ -244,18 +269,18 @@ private fun HeroPager(items: List<SearchItem>, onOpen: (SearchItem) -> Unit) {
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
items(items, key = { it.uri }) { item ->
- HeroCard(item, cardWidth) { onOpen(item) }
+ HeroCard(item, cardWidth, fromFollowed = item.uri in followed) { onOpen(item) }
}
}
}
}
@Composable
-private fun HeroCard(item: SearchItem, width: Dp, onClick: () -> Unit) {
+private fun HeroCard(item: SearchItem, width: Dp, fromFollowed: Boolean, onClick: () -> Unit) {
val shape = RoundedCornerShape(14.dp)
Column(Modifier.width(width)) {
Text(
- stringResource(R.string.new_release_tag).uppercase(),
+ stringResource(if (fromFollowed) R.string.new_release_followed_tag else R.string.new_release_tag).uppercase(),
style = MaterialTheme.typography.labelSmall,
fontSize = 11.sp,
fontWeight = FontWeight.Bold,
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 5ace5b6..e610e8b 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -533,4 +533,5 @@
<item quantity="one">%1$d ausgewählt</item>
<item quantity="other">%1$d ausgewählt</item>
</plurals>
+ <string name="new_release_followed_tag">Von deinen Künstlern</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 283ece9..24bdcab 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -539,4 +539,5 @@
<item quantity="one">%1$d seleccionada</item>
<item quantity="other">%1$d seleccionadas</item>
</plurals>
+ <string name="new_release_followed_tag">De tus artistas</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 4df0ab7..45c7329 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -533,4 +533,5 @@
<item quantity="one">%1$d sélectionné</item>
<item quantity="other">%1$d sélectionnés</item>
</plurals>
+ <string name="new_release_followed_tag">De tes artistes</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 4211030..c626817 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -548,4 +548,5 @@
<item quantity="one">%1$d चुना गया</item>
<item quantity="other">%1$d चुने गए</item>
</plurals>
+ <string name="new_release_followed_tag">आपके कलाकारों से</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 8093bcb..df98d96 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -570,4 +570,5 @@
<item quantity="one">%1$d selezionato</item>
<item quantity="other">%1$d selezionati</item>
</plurals>
+ <string name="new_release_followed_tag">Dai tuoi artisti</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 3e0ed62..a33fcf2 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -533,4 +533,5 @@
<item quantity="one">%1$d selecionada</item>
<item quantity="other">%1$d selecionadas</item>
</plurals>
+ <string name="new_release_followed_tag">Dos seus artistas</string>
</resources>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 2bc685b..6b341c5 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -562,4 +562,5 @@
<item quantity="many">Выбрано %1$d</item>
<item quantity="other">Выбрано %1$d</item>
</plurals>
+ <string name="new_release_followed_tag">От ваших исполнителей</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index ac93f12..96cf93f 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -546,4 +546,5 @@
<item quantity="one">%1$d seçildi</item>
<item quantity="other">%1$d seçildi</item>
</plurals>
+ <string name="new_release_followed_tag">Sanatçılarından</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index d002b33..e99dabe 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -597,4 +597,5 @@
<item quantity="one">%1$d selected</item>
<item quantity="other">%1$d selected</item>
</plurals>
+ <string name="new_release_followed_tag">From your artists</string>
</resources>
diff --git a/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt b/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt
index c53861c..d4c5d97 100644
--- a/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt
+++ b/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt
@@ -29,9 +29,9 @@ class FollowedReleasesTest {
assertEquals(LocalDate.of(2026, 9, 1), releaseDay("2026-09"))
}
- @Test fun walksEveryFollowedArtistAndEveryAlbumPage() = runBlocking {
+ @Test fun walksEveryFollowedArtistAndEveryRecentAlbumPage() = runBlocking {
var followPages = 0
- val offsets = mutableListOf<Pair<String, Int>>()
+ val offsets = mutableListOf<Triple<String, String, Int>>()
val api = api { name, args ->
when (name) {
"followedArtists" -> {
@@ -44,10 +44,11 @@ class FollowedReleasesTest {
}
"artistAlbums" -> {
val id = args[0] as String
+ val group = args[1] as String
val offset = args[4] as Int
- offsets += id to offset
- assertEquals("album,single", args[1])
- PageDto(listOf(album("${id}P$offset", LocalDate.now().toString())), total = 2, next = if (offset == 0) "next" else null)
+ offsets += Triple(id, group, offset)
+ assertTrue(group == "album" || group == "single")
+ PageDto(listOf(album("${id}${group}P$offset", LocalDate.now().toString(), group)), total = 2, next = if (offset == 0) "next" else null)
}
else -> error(name)
}
@@ -57,8 +58,11 @@ class FollowedReleasesTest {
val result = FollowedReleases(api, dir).load()
assertEquals(2, followPages)
assertEquals(60, result.artistCount)
- assertEquals(120, result.albums.size)
- assertEquals(setOf(0, 1), offsets.filter { it.first == "A60" }.map { it.second }.toSet())
+ assertEquals(240, result.albums.size)
+ assertEquals(
+ setOf("album" to 0, "album" to 1, "single" to 0, "single" to 1),
+ offsets.filter { it.first == "A60" }.map { it.second to it.third }.toSet(),
+ )
assertEquals(0, result.failedArtists)
} finally { dir.deleteRecursively() }
}
@@ -86,13 +90,40 @@ class FollowedReleasesTest {
val repository = FollowedReleases(api, dir)
val first = repository.load()
assertEquals(first.albums, repository.load().albums)
- assertEquals(1, albumRequests)
+ // One request for the albums, one for the singles.
+ assertEquals(2, albumRequests)
assertEquals(2, followedRequests)
+ assertEquals(first.albums, repository.saved()?.albums)
fail = true
val failed = repository.load(force = true)
assertEquals(first.albums, failed.albums)
assertEquals(1, failed.failedArtists)
- assertEquals(2, albumRequests)
+ assertEquals(3, albumRequests)
+ } finally { dir.deleteRecursively() }
+ }
+
+ @Test fun stopsReadingAGroupOnceItReachesBackAYear() = runBlocking {
+ val offsets = mutableListOf<Pair<String, Int>>()
+ val api = api { name, args ->
+ when (name) {
+ "followedArtists" -> FollowedArtistsDto(ArtistCursorPageDto(listOf(ArtistDto(id = "A1", name = "Artist"))))
+ "artistAlbums" -> {
+ val group = args[1] as String
+ val offset = args[4] as Int
+ offsets += group to offset
+ PageDto(
+ listOf(album("new$group", LocalDate.now().toString(), group), album("old$group", "2019-05-01", group)),
+ total = 400, next = "more",
+ )
+ }
+ else -> error(name)
+ }
+ }
+ val dir = Files.createTempDirectory("followed-releases-test").toFile()
+ try {
+ val result = FollowedReleases(api, dir).load()
+ assertEquals(listOf("album" to 0, "single" to 0), offsets)
+ assertEquals(setOf("newalbum", "newsingle"), result.albums.map { it.id }.toSet())
} finally { dir.deleteRecursively() }
}