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.

Shelves of Spotify's own, and skeletons while they arrive

Lelonioe4648fbc316c
diff --git a/app/src/main/java/dev/lelonio/square/data/Gateway.kt b/app/src/main/java/dev/lelonio/square/data/Gateway.kt
index 907fd9c..d6530b1 100644
--- a/app/src/main/java/dev/lelonio/square/data/Gateway.kt
+++ b/app/src/main/java/dev/lelonio/square/data/Gateway.kt
@@ -113,6 +113,58 @@ class Gateway(private val keys: PathfinderKeys) {
.getOrNull()
}
+ /**
+ * One page of Spotify's own browse, as rows.
+ *
+ * The home query answers with what this account is shown when it opens the
+ * app; this answers with what the catalogue has to offer — new releases
+ * chosen for the listener, the editors' playlists, the charts, the daily
+ * mixes — which is a different question and a much larger answer. Pages are
+ * addressed by uri: see BrowsePages.
+ *
+ * Null when the gateway will not answer, which is the ordinary case for a
+ * retired hash; every caller draws its page without it.
+ */
+ suspend fun browsePage(uri: String, sections: Int = BROWSE_SECTIONS): String? {
+ keys.refresh()
+ return runCatching {
+ query(
+ operation = "browsePage",
+ hash = keys.browsePage,
+ // Exactly the shape the web player sends, values included; see
+ // the note on search.
+ variables = """{"pagePagination":{"offset":0,"limit":$sections},""" +
+ """"sectionPagination":{"offset":0,"limit":$BROWSE_ITEMS},""" +
+ """"uri":"$uri","browseEndUserIntegration":"INTEGRATION_WEB_PLAYER",""" +
+ """"includeEpisodeContentRatingsV2":true}""",
+ )
+ }
+ .onFailure { android.util.Log.i(TAG, "browse page unavailable: ${it.message}") }
+ .getOrNull()
+ }
+
+ /**
+ * One row of a browse page, past the handful the page itself carries.
+ *
+ * The page answers with ten items a row and says how many there are — a
+ * thousand, for the new releases picked for a listener — so a row worth
+ * scrolling is this query, not that one.
+ */
+ suspend fun browseSection(uri: String, offset: Int, limit: Int = BROWSE_PAGE): String? {
+ keys.refresh()
+ return runCatching {
+ query(
+ operation = "browseSection",
+ hash = keys.browseSection,
+ variables = """{"pagination":{"offset":$offset,"limit":$limit},""" +
+ """"uri":"$uri","browseEndUserIntegration":"INTEGRATION_WEB_PLAYER",""" +
+ """"includeEpisodeContentRatingsV2":true}""",
+ )
+ }
+ .onFailure { android.util.Log.i(TAG, "browse section unavailable: ${it.message}") }
+ .getOrNull()
+ }
+
/**
* Reads a list to its end.
*
@@ -173,10 +225,25 @@ class Gateway(private val keys: PathfinderKeys) {
*/
const val PAGE = 200
- /** What one page of each kind of search result holds, as the web player asks. */
- const val SEARCH_LIMIT = 10
+ /**
+ * What one page of each kind of search result holds.
+ *
+ * Twenty rather than the ten the web player's overview asks for — that
+ * is the size it uses itself the moment you open one of the categories,
+ * so it is still a page shape this endpoint sees all day, and it is the
+ * difference between four songs under a heading and a list worth
+ * scrolling.
+ */
+ const val SEARCH_LIMIT = 20
/** And how many of the best of everything it asks for; see [search]. */
- const val TOP_RESULTS = 5
+ const val TOP_RESULTS = 8
+
+ /** How many rows of a browse page to read, and how much of each. */
+ const val BROWSE_SECTIONS = 10
+ const val BROWSE_ITEMS = 10
+
+ /** And how much of a single row, when one is read on its own. */
+ const val BROWSE_PAGE = 20
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt b/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt
index 4e29e29..706c47e 100644
--- a/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt
@@ -46,6 +46,13 @@ class PathfinderKeys(context: Context) {
/** And for `searchDesktop`, which is what the search box asks. */
val search: String get() = prefs.getString(KEY_SEARCH, null) ?: DEFAULT_SEARCH
+ /** And for `browsePage`, which is a whole page of Spotify's own browse. */
+ val browsePage: String get() = prefs.getString(KEY_BROWSE_PAGE, null) ?: DEFAULT_BROWSE_PAGE
+
+ /** And `browseSection`, for reading one of that page's rows past its first few. */
+ val browseSection: String
+ get() = prefs.getString(KEY_BROWSE_SECTION, null) ?: DEFAULT_BROWSE_SECTION
+
/** The web client version the gateway is told about. */
val appVersion: String get() = prefs.getString(KEY_VERSION, null) ?: DEFAULT_VERSION
@@ -76,6 +83,10 @@ class PathfinderKeys(context: Context) {
?.let { edit.putString(KEY_LIBRARY, it) }
body.optString("search").takeIf { it.length == HASH_LENGTH }
?.let { edit.putString(KEY_SEARCH, it) }
+ body.optString("browsePage").takeIf { it.length == HASH_LENGTH }
+ ?.let { edit.putString(KEY_BROWSE_PAGE, it) }
+ body.optString("browseSection").takeIf { it.length == HASH_LENGTH }
+ ?.let { edit.putString(KEY_BROWSE_SECTION, it) }
body.optString("appVersion").takeIf { it.isNotEmpty() }
?.let { edit.putString(KEY_VERSION, it) }
edit.apply()
@@ -91,6 +102,8 @@ class PathfinderKeys(context: Context) {
const val KEY_PLAYLIST = "playlist"
const val KEY_LIBRARY = "library"
const val KEY_SEARCH = "search"
+ const val KEY_BROWSE_PAGE = "browse_page"
+ const val KEY_BROWSE_SECTION = "browse_section"
const val KEY_VERSION = "app_version"
const val KEY_CHECKED = "checked_at"
@@ -115,6 +128,10 @@ class PathfinderKeys(context: Context) {
"134337999233cc6fdd6b1e6dbf94841409f04a946c5c7b744b09ba0dfe5a85ed"
const val DEFAULT_SEARCH =
"db61238974d27839a136c9dc02bfdbe3fab7635f21cf85976ebff9a1ee281345"
+ const val DEFAULT_BROWSE_PAGE =
+ "f5c4e6d668f5716464a231c1cc8b22c1cbf6ad68b09929fd7de813a30581298b"
+ const val DEFAULT_BROWSE_SECTION =
+ "b13c1cccbfcb6947753c2613411b3566485c21fd5f36d80a80bb64be61ba2d51"
const val DEFAULT_VERSION = "1.2.97.155.g5dd0dcaf-development"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
index b3e9634..4a2bf1f 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -94,7 +94,11 @@ interface SpotifyApi {
* what they actually played.
*/
@GET("v1/browse/new-releases")
- suspend fun newReleases(@Query("limit") limit: Int = 12): NewReleasesDto
+ suspend fun newReleases(
+ @Query("limit") limit: Int = 12,
+ /** Fifty at a time is this endpoint's maximum, so more means paging. */
+ @Query("offset") offset: Int = 0,
+ ): NewReleasesDto
/** Needs the `user-top-read` scope; 403 without it. */
@GET("v1/me/top/artists")
@@ -339,7 +343,8 @@ interface SpotifyApi {
suspend fun search(
@Query("q") query: String,
@Query("type") type: String = "track,album,artist,playlist",
- @Query("limit") limit: Int = 20,
+ /** Fifty is this endpoint's maximum, and the fallback should not be thinner. */
+ @Query("limit") limit: Int = 40,
): SearchDto
}
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyBrowse.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyBrowse.kt
new file mode 100644
index 0000000..d3add06
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyBrowse.kt
@@ -0,0 +1,124 @@
+package dev.lelonio.square.data
+
+import org.json.JSONObject
+
+/**
+ * Spotify's own browse pages, read as rows.
+ *
+ * The personalised home answers "what should this account see when it opens the
+ * app". This answers a different and much larger question — what the catalogue
+ * has to offer right now — and it is where the client's own Browse gets the new
+ * releases chosen for a listener, the editors' playlists, the charts and the
+ * daily mixes. The two overlap in places, which is why the pages that use this
+ * drop anything the home already showed.
+ *
+ * Read exactly as forgivingly as [SpotifyHome], and for the same reason: this
+ * is a private interface, so an unrecognised row is skipped rather than treated
+ * as a failure.
+ */
+object SpotifyBrowse {
+
+ /**
+ * The pages worth asking for, by the uri Spotify addresses them with.
+ *
+ * These are stable identifiers — the same ones the web client puts in its
+ * own links — and they name a page rather than its contents, so what comes
+ * back is whatever the catalogue holds today.
+ */
+ object Pages {
+ /** New releases: the albums out now, and the ones picked for this account. */
+ const val NEW_RELEASES = "spotify:page:0JQ5DAqbMKFz6FAsUtgAab"
+
+ /** Made for you: the daily mixes, the DJ, the day's own list, on repeat. */
+ const val MADE_FOR_YOU = "spotify:page:0JQ5DAt0tbjZptfcdMSKl3"
+
+ /** Charts: what is being played most, by country and worldwide. */
+ const val CHARTS = "spotify:page:0JQ5DAudkNjCgYMM0TZXDw"
+
+ /** Music: the front page of browse, which leads with discovery. */
+ const val MUSIC = "spotify:page:0JQ5DAqbMKFSi39LMRT0Cy"
+ }
+
+ fun parse(json: String): List<HomeShelf> = runCatching {
+ val sections = JSONObject(json)
+ .getJSONObject("data")
+ .getJSONObject("browse")
+ .getJSONObject("sections")
+ .getJSONArray("items")
+
+ (0 until sections.length()).mapNotNull { index ->
+ shelf(sections.getJSONObject(index))
+ }
+ }.getOrDefault(emptyList())
+
+ private fun shelf(section: JSONObject): HomeShelf? {
+ val data = section.optJSONObject("data") ?: return null
+ val title = data.optJSONObject("title")?.optString("transformedLabel").orEmpty()
+ if (title.isEmpty()) return null
+
+ val items = section.optJSONObject("sectionItems")?.optJSONArray("items") ?: return null
+ val entries = (0 until items.length()).mapNotNull { index ->
+ entry(items.getJSONObject(index))
+ }
+ return if (entries.isEmpty()) null else HomeShelf(title, entries)
+ }
+
+ /**
+ * One card of a row.
+ *
+ * Playlists and albums only. A browse page also carries links to other
+ * browse pages — the grid of categories — and those are a page this app has
+ * no screen for; a tile that cannot be opened is worse than a gap.
+ */
+ private fun entry(item: JSONObject): CatalogPlaylist? {
+ val uri = item.optString("uri")
+ if (uri.isEmpty() || uri == Catalog.DJ_URI) return null
+ val data = item.optJSONObject("content")?.optJSONObject("data") ?: return null
+
+ return when (data.optString("__typename")) {
+ "Playlist" -> CatalogPlaylist(
+ uri = uri,
+ name = data.optString("name"),
+ artworkUrl = firstSource(data.optJSONObject("images")),
+ )
+
+ "Album" -> CatalogPlaylist(
+ uri = uri,
+ name = data.optString("name"),
+ artworkUrl = sources(data.optJSONObject("coverArt")),
+ )
+
+ else -> null
+ }
+ }
+
+ /** The `images { items { sources } }` shape a playlist's artwork arrives in. */
+ private fun firstSource(images: JSONObject?): String? {
+ val items = images?.optJSONArray("items") ?: return null
+ val first = items.optJSONObject(0) ?: return null
+ return sources(first)
+ }
+
+ /**
+ * The largest of the sizes offered, or the only one.
+ *
+ * A cover arrives as three prints of the same picture and the tiles here
+ * are drawn at a hundred and fifty dp on a screen three times that dense,
+ * so the small print is a blur and the large one is what to ask for.
+ */
+ private fun sources(holder: JSONObject?): String? {
+ val list = holder?.optJSONArray("sources") ?: return null
+ var best: String? = null
+ var bestWidth = -1
+ for (index in 0 until list.length()) {
+ val source = list.optJSONObject(index) ?: continue
+ val url = source.optString("url").takeIf { it.isNotEmpty() } ?: continue
+ val width = source.optInt("width", 0)
+ if (best == null || width > bestWidth) {
+ best = url
+ bestWidth = width
+ }
+ }
+ return best
+ }
+}
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 e8b5c5b..77cc9a3 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -35,6 +35,9 @@ import dev.lelonio.square.nativecore.NativeBridge
import dev.lelonio.square.playback.BuiltInPresets
import dev.lelonio.square.playback.EffectPreset
import dev.lelonio.square.playback.PlaybackService
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.currentCoroutineContext
@@ -311,11 +314,26 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
_newPage.value = _newPage.value.copy(loading = true)
newPageJob = viewModelScope.launch {
+ // Three pages rather than one. Fifty is what this endpoint will
+ // answer with at a time, and one page of it is two shelves' worth
+ // on a page that is meant to be browsed — the whole complaint about
+ // this tab was that it ended almost as soon as it started.
val albums = runCatching {
- container.api.newReleases(limit = NEW_RELEASES).albums?.items.orEmpty()
+ withContext(Dispatchers.IO) {
+ coroutineScope {
+ (0 until NEW_PAGES).map { page ->
+ async {
+ container.api
+ .newReleases(limit = NEW_RELEASES, offset = page * NEW_RELEASES)
+ .albums?.items.orEmpty()
+ }
+ }.awaitAll().flatten()
+ }
+ }
}
.onFailure { android.util.Log.w(TAG, "new releases unavailable: ${describe(it)}") }
.getOrDefault(emptyList())
+ .distinctBy { it.uri }
.sortedByDescending { it.releaseDate.orEmpty() }
val week = java.time.LocalDate.now().minusDays(7).toString()
@@ -333,7 +351,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// because "new" without "to you" is a catalogue. The global list is
// the fallback for an account too young to have artists of its own.
val mine = _feed.value.fromYourArtists
- val hero = (if (mine.isNotEmpty()) mine else thisWeek + rest).take(HERO_RELEASES)
+ // Turned over daily, like the radio page's stations: the six the
+ // page leads with are drawn from a list that changes slowly, and
+ // showing the same six until it does made a page that is supposed
+ // to be about what is out look like it had stopped.
+ val leading = (if (mine.isNotEmpty()) mine else thisWeek + rest)
+ val hero = leading.turnedDaily().take(HERO_RELEASES)
_newPage.value = NewPage(
hero = hero,
@@ -349,10 +372,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// it does not come out of the account's own quota.
if (!awaitEngine()) return@launch
val songs = withContext(Dispatchers.IO) {
- (thisWeek + rest).take(NEW_SONGS).mapNotNull { album ->
- runCatching {
- Catalog.tracks(Catalog.contextTrackUris(album.uri).take(1)).firstOrNull()
- }.getOrNull()
+ coroutineScope {
+ (thisWeek + rest).turnedDaily().take(NEW_SONGS).map { album ->
+ async {
+ runCatching {
+ Catalog.tracks(Catalog.contextTrackUris(album.uri).take(1)).firstOrNull()
+ }.getOrNull()
+ }
+ }.awaitAll().filterNotNull()
}
}
_newPage.value = _newPage.value.copy(songs = songs)
@@ -539,6 +566,21 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /**
+ * The same list, started at a different place each day.
+ *
+ * Not a shuffle: a page that rearranges itself every time it is opened is
+ * not richer, it is unreadable. This moves the starting point once a day,
+ * so a list that Spotify itself only recomputes weekly still shows
+ * something different when the tab is opened tomorrow.
+ */
+ private fun <T> List<T>.turnedDaily(): List<T> {
+ if (size < 2) return this
+ val day = java.time.LocalDate.now().toEpochDay().toInt()
+ val from = Math.floorMod(day * DAILY_TURN, size)
+ return drop(from) + take(from)
+ }
+
private suspend fun topTracks(range: String): List<CatalogTrack> = runCatching {
container.api.topTracks(timeRange = range).items.map { it.toCatalogTrack() }
}.onFailure { android.util.Log.w(TAG, "top tracks ($range) unavailable: ${describe(it)}") }
@@ -554,10 +596,21 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
*/
private suspend fun freshFromArtists(artists: List<SearchItem>): List<SearchItem> {
val cutoff = java.time.LocalDate.now().minusMonths(12).toString()
- return artists.take(FRESH_ARTISTS).flatMap { artist ->
- runCatching {
- container.api.artistAlbums(artist.uri.substringAfterLast(':'), limit = 6).items
- }.getOrDefault(emptyList())
+ // All of them at once. One request per artist is what this costs
+ // whatever happens, but asked in turn a dozen of them is several
+ // seconds of the home page waiting on a shelf that is not even the
+ // first thing on it.
+ return coroutineScope {
+ artists.take(FRESH_ARTISTS).map { artist ->
+ async(Dispatchers.IO) {
+ runCatching {
+ container.api.artistAlbums(
+ artist.uri.substringAfterLast(':'),
+ limit = 6,
+ ).items
+ }.getOrDefault(emptyList())
+ }
+ }.awaitAll().flatten()
}
.filter { (it.releaseDate ?: "") >= cutoff }
.sortedByDescending { it.releaseDate }
@@ -2232,6 +2285,87 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
*/
val homeShelves: StateFlow<List<HomeShelf>> = _homeShelves.asStateFlow()
+ private val _newBrowse = MutableStateFlow<List<dev.lelonio.square.data.HomeShelf>>(emptyList())
+
+ /** Spotify's own new-releases page, as rows; see SpotifyBrowse. */
+ val newBrowse: StateFlow<List<dev.lelonio.square.data.HomeShelf>> = _newBrowse.asStateFlow()
+
+ private val _radioBrowse =
+ MutableStateFlow<List<dev.lelonio.square.data.HomeShelf>>(emptyList())
+
+ /** And its "made for you" and charts pages, which is what a radio tab is. */
+ val radioBrowse: StateFlow<List<dev.lelonio.square.data.HomeShelf>> = _radioBrowse.asStateFlow()
+
+ private var browseJob: Job? = null
+
+ private val _browseLoading = MutableStateFlow(false)
+
+ /**
+ * Whether the browse rows are still on their way.
+ *
+ * The two tabs draw an outline of what is coming rather than growing a row
+ * at a time under the reader's thumb: a page that assembles itself while
+ * being read moves what is being looked at.
+ */
+ val browseLoading: StateFlow<Boolean> = _browseLoading.asStateFlow()
+
+ /**
+ * Reads Spotify's own browse pages for the two tabs that show them.
+ *
+ * Kept apart from the personalised home on purpose. Both come off the same
+ * gateway, but home answers "what should this account see on opening the
+ * app" — which is the home page's question, and putting its answer on two
+ * more tabs is how those tabs ended up repeating it. These pages answer
+ * what the catalogue is offering: the releases picked for this listener,
+ * the editors' lists, the charts, the mixes.
+ *
+ * Whatever the home page is already showing is dropped here, by title: the
+ * two do overlap, and a row that appears twice in one app is worse than a
+ * row that appears once.
+ */
+ fun loadBrowse() {
+ if (browseJob?.isActive == true) return
+ if (_newBrowse.value.isNotEmpty() && _radioBrowse.value.isNotEmpty()) return
+
+ _browseLoading.value = true
+ browseJob = viewModelScope.launch {
+ val onHome = _homeShelves.value.map { it.title.lowercase() }.toSet()
+ suspend fun page(uri: String) = withContext(Dispatchers.IO) {
+ container.gateway.browsePage(uri)
+ ?.let { dev.lelonio.square.data.SpotifyBrowse.parse(it) }
+ .orEmpty()
+ .filter { it.title.lowercase() !in onHome }
+ }
+
+ val releases = page(dev.lelonio.square.data.SpotifyBrowse.Pages.NEW_RELEASES)
+ if (releases.isNotEmpty()) _newBrowse.value = releases
+
+ // Two pages behind one tab: the mixes made for this listener, and
+ // the charts, which are the other half of what a radio is for.
+ val mixes = page(dev.lelonio.square.data.SpotifyBrowse.Pages.MADE_FOR_YOU)
+ val charts = page(dev.lelonio.square.data.SpotifyBrowse.Pages.CHARTS)
+ val forRadio = (mixes + charts).distinctBy { it.title.lowercase() }
+ if (forRadio.isNotEmpty()) _radioBrowse.value = forRadio
+
+ android.util.Log.i(
+ TAG,
+ "browse: ${releases.size} rows for new, ${forRadio.size} for radio",
+ )
+ _browseLoading.value = false
+ }
+ }
+
+ /**
+ * Asks for the personalised shelves if they are not already here.
+ *
+ * The home page loads them with the library; the two browse tabs show them
+ * too and can be opened without ever visiting home — on a cold start
+ * straight into Radio, for instance.
+ */
+ fun ensureHomeShelves() {
+ if (_homeShelves.value.isEmpty()) loadHomeShelves()
+ }
+
private fun loadHomeShelves() = viewModelScope.launch {
val keys = container.pathfinderKeys
keys.refresh()
@@ -3879,7 +4013,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
const val TAG = "SquareUi"
/** Artists asked for new records on the home page; one request each. */
- const val FRESH_ARTISTS = 6
+ const val FRESH_ARTISTS = 14
+
+ /** How far the daily turn moves; a prime, so it works through the list. */
+ const val DAILY_TURN = 7
/** A page of saved albums; the API's own maximum. */
const val ALBUM_PAGE = 50
@@ -3891,13 +4028,16 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
const val FEED_ROW = 12
/** Records asked of Spotify's own new-releases list for the New tab. */
- const val NEW_RELEASES = 40
+ const val NEW_RELEASES = 50
+
+ /** How many of those pages to read; see loadNewPage. */
+ const val NEW_PAGES = 3
/** How many of them the page leads with, drawn large. */
const val HERO_RELEASES = 6
/** And how many are opened for a song to put in the list under them. */
- const val NEW_SONGS = 10
+ const val NEW_SONGS = 18
/**
* How long a header holds its picture back for the other catalogue.
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index 74add76..7cbc4dc 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -315,7 +315,15 @@ private val TAB_ROUTES =
setOf(Routes.HOME, Routes.NEW, Routes.RADIO, Routes.LIBRARY, Routes.SEARCH)
/** How many stations the radio tab offers. Enough to scroll, few enough to read. */
-private const val RADIO_SEEDS = 14
+private const val RADIO_SEEDS = 36
+
+/**
+ * How far the radio page's order moves each day.
+ *
+ * A prime, so a list of any length works its way through all of itself rather
+ * than landing on the same few starting points.
+ */
+private const val DAILY_TURN = 7
/**
* Decode size of the page backdrop, in pixels.
@@ -549,10 +557,36 @@ fun SquareApp(
}
}
- val radioSeeds = remember(feed.topTracks, feed.allTimeTracks) {
- (feed.topTracks + feed.allTimeTracks)
- .filter { it.uri.startsWith("spotify:track:") }
+ // Everything the account has actually touched, one station per artist.
+ //
+ // It used to be the two lists of top tracks and nothing else, and those are
+ // computed monthly at best: the page was the same fourteen names for weeks
+ // at a time. These sources move at different speeds — what was played this
+ // hour, what was searched for, what came out this week, what is on repeat
+ // this month, what has been on repeat for years — so between them there is
+ // always something the page did not show yesterday.
+ // Spotify's own browse pages, one tab each; see loadBrowse. Filtering the
+ // home page's rows into these two tabs was the first attempt and it only
+ // moved the same rows around the app.
+ val newShelves by viewModel.newBrowse.collectAsStateWithLifecycle()
+ val browseLoading by viewModel.browseLoading.collectAsStateWithLifecycle()
+ val radioShelves by viewModel.radioBrowse.collectAsStateWithLifecycle()
+
+ val radioSeeds = remember(recent, searchHistory, newPage.songs, feed.topTracks, feed.allTimeTracks) {
+ (recent + feed.topTracks + searchHistory + newPage.songs + feed.allTimeTracks)
+ .filter { it.uri.startsWith("spotify:track:") && it.artist.isNotBlank() }
.distinctBy { it.artist.lowercase() }
+ // Turned over daily rather than shuffled: a page that rearranges
+ // itself every time it is opened is not richer, it is unreadable.
+ // The same list, started at a different name each day.
+ .let { seeds ->
+ if (seeds.isEmpty()) seeds
+ else {
+ val day = java.time.LocalDate.now().toEpochDay().toInt()
+ val from = Math.floorMod(day * DAILY_TURN, seeds.size)
+ seeds.drop(from) + seeds.take(from)
+ }
+ }
.take(RADIO_SEEDS)
}
val playlistOrder by viewModel.playlistOrder.collectAsStateWithLifecycle()
@@ -1350,9 +1384,14 @@ fun SquareApp(
}
composable(Routes.NEW) {
- LaunchedEffect(Unit) { viewModel.loadNewPage() }
+ LaunchedEffect(Unit) {
+ viewModel.loadNewPage()
+ viewModel.loadBrowse()
+ }
NewScreen(
page = newPage,
+ shelves = newShelves,
+ shelvesLoading = browseLoading,
contentPadding = listPadding,
onPlaySong = { tracks, index ->
onPlay(tracks, index, null, false, newLabel, 0L)
@@ -1369,10 +1408,17 @@ fun SquareApp(
}
composable(Routes.RADIO) {
+ LaunchedEffect(Unit) { viewModel.loadBrowse() }
RadioScreen(
seeds = radioSeeds,
+ shelves = radioShelves,
+ shelvesLoading = browseLoading,
loading = feed.loading,
contentPadding = listPadding,
+ onOpenMix = { mix ->
+ viewModel.openContext(mix.uri, mix.name, mix.artworkUrl)
+ navController.navigate(Routes.PLAYLIST)
+ },
onOpen = { seed ->
scope.launch {
val tracks = viewModel.radioFor(seed.uri)
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 532b834..ba4012b 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
@@ -55,11 +55,23 @@ import dev.lelonio.square.ui.theme.InkDim
@Composable
fun NewScreen(
page: MainViewModel.NewPage,
+ /**
+ * Spotify's own rows, as it lays them out for this account.
+ *
+ * The rest of this page is built out of the catalogue-wide list of what
+ * came out, which is the same for everyone and moves once a week. These are
+ * assembled per listener and change daily, and they are the reason the tab
+ * has something to say on a Tuesday.
+ */
+ shelves: List<dev.lelonio.square.data.HomeShelf>,
+ /** Whether those rows are still coming; see SkeletonRow. */
+ shelvesLoading: Boolean,
contentPadding: PaddingValues,
onOpen: (SearchItem) -> Unit,
onPlaySong: (List<CatalogTrack>, Int) -> Unit,
) {
- val empty = page.hero.isEmpty() && page.thisWeek.isEmpty() && page.recent.isEmpty()
+ val empty = page.hero.isEmpty() && page.thisWeek.isEmpty() &&
+ page.recent.isEmpty() && shelves.isEmpty()
if (empty) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
if (page.loading) {
@@ -108,12 +120,53 @@ fun NewScreen(
songRows(page.songs, onPlaySong)
}
+ // The outline of what is coming, while it is coming.
+ if (shelvesLoading && shelves.isEmpty()) {
+ items(
+ count = SKELETON_ROWS,
+ key = { "skeleton $it" },
+ contentType = { "skeleton" },
+ ) {
+ SkeletonRow()
+ }
+ }
+
+ // Spotify's own rows, under its own headings: they are titled for this
+ // listener and renaming them would be this app pretending to have
+ // assembled them.
+ shelves.forEach { shelf ->
+ item(key = "shelf ${shelf.title}", contentType = "shelfHeading") {
+ Heading(shelf.title)
+ }
+ item(key = "shelfRow ${shelf.title}", contentType = "shelfRow") {
+ Shelf(
+ shelf.items.map { entry ->
+ SearchItem(
+ uri = entry.uri,
+ title = entry.name,
+ subtitle = "",
+ artworkUrl = entry.artworkUrl,
+ )
+ },
+ onOpen,
+ )
+ }
+ }
+
if (page.thisWeek.isNotEmpty()) {
item(contentType = "weekHeading") { Heading(stringResource(R.string.new_this_week)) }
item(contentType = "week") { Shelf(page.thisWeek, onOpen) }
}
- if (page.recent.isNotEmpty()) {
+ // The catalogue-wide list of what came out, and only when Spotify's
+ // own picked one is not here.
+ //
+ // The two are the same shelf twice: theirs is chosen for this listener
+ // and ours is what the market got, and on a page that shows both, the
+ // reader sees "new releases" and "new releases for you" one under the
+ // other with half the same covers. Ours is the fallback for an account
+ // the gateway will not answer for.
+ if (page.recent.isNotEmpty() && shelves.isEmpty()) {
item(contentType = "recentHeading") {
Heading(stringResource(R.string.new_releases_title))
}
@@ -122,6 +175,9 @@ fun NewScreen(
}
}
+/** How many outlines stand in for the rows that are coming. */
+private const val SKELETON_ROWS = 3
+
/** The songs, one row each, played as a list rather than one at a time. */
private fun LazyListScope.songRows(
songs: List<CatalogTrack>,
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
index 28cec09..409a067 100644
--- a/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/RadioScreen.kt
@@ -10,9 +10,12 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items as rowItems
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -57,11 +60,24 @@ import dev.lelonio.square.ui.theme.InkDim
fun RadioScreen(
/** Seeds, already reduced to one per artist by the caller. */
seeds: List<CatalogTrack>,
+ /**
+ * Spotify's own mixes and stations, as it makes them for this account.
+ *
+ * The grid below is built here — one station per artist the account plays —
+ * and it can only ever be as varied as what has been listened to. These are
+ * assembled on their side, out of things the listener has not played yet,
+ * and they change from one day to the next.
+ */
+ shelves: List<dev.lelonio.square.data.HomeShelf>,
+ /** Whether those rows are still coming; see SkeletonRow. */
+ shelvesLoading: Boolean,
loading: Boolean,
contentPadding: PaddingValues,
onOpen: (CatalogTrack) -> Unit,
+ /** Opens one of Spotify's own, which is a context rather than a seed. */
+ onOpenMix: (dev.lelonio.square.data.CatalogPlaylist) -> Unit,
) {
- if (seeds.isEmpty()) {
+ if (seeds.isEmpty() && shelves.isEmpty() && !shelvesLoading) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
if (loading) {
CircularProgressIndicator(strokeWidth = 2.dp)
@@ -98,21 +114,96 @@ fun RadioScreen(
)
}
- item(span = { GridItemSpan(maxLineSpan) }) {
- Text(
- stringResource(R.string.stations_for_you),
- style = MaterialTheme.typography.titleLarge,
- fontWeight = FontWeight.Bold,
- modifier = Modifier.padding(bottom = 2.dp),
- )
+ // The outline of what is coming, while it is coming.
+ if (shelvesLoading && shelves.isEmpty()) {
+ items(
+ count = SKELETON_ROWS,
+ span = { GridItemSpan(maxLineSpan) },
+ key = { "skeleton $it" },
+ contentType = { "skeleton" },
+ ) {
+ SkeletonRow(tiles = 3)
+ }
}
- items(seeds, key = { it.uri }) { seed ->
- StationTile(seed) { onOpen(seed) }
+ // Spotify's own first, under its own headings: they are titled for
+ // this listener, and they are the half of the page that is new every
+ // day rather than as old as the listening behind it.
+ shelves.forEach { shelf ->
+ item(span = { GridItemSpan(maxLineSpan) }, key = "shelf ${shelf.title}") {
+ Text(
+ shelf.title,
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(bottom = 2.dp),
+ )
+ }
+ item(span = { GridItemSpan(maxLineSpan) }, key = "row ${shelf.title}") {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ rowItems(shelf.items, key = { it.uri }) { mix ->
+ MixTile(mix) { onOpenMix(mix) }
+ }
+ }
+ }
+ }
+
+ if (seeds.isNotEmpty()) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Text(
+ stringResource(R.string.stations_for_you),
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(top = 18.dp, bottom = 2.dp),
+ )
+ }
+
+ items(seeds, key = { it.uri }) { seed ->
+ StationTile(seed) { onOpen(seed) }
+ }
}
}
}
+/** How many outlines stand in for the rows that are coming. */
+private const val SKELETON_ROWS = 2
+
+/**
+ * One of Spotify's own mixes, in a row rather than in the grid.
+ *
+ * Smaller than a station tile and named under the cover instead of over it:
+ * these arrive with names their covers already carry — "Daily Mix 1", "Radio di
+ * Madame" — and printing the name twice over the artwork is how a page of tiles
+ * turns into a page of labels.
+ */
+@Composable
+private fun MixTile(
+ mix: dev.lelonio.square.data.CatalogPlaylist,
+ onClick: () -> Unit,
+) {
+ Column(
+ Modifier
+ .width(146.dp)
+ .pressable(onClick, pressedScale = 0.97f),
+ ) {
+ Artwork(
+ url = mix.artworkUrl,
+ title = mix.name,
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(1f),
+ corner = 12.dp,
+ decodeSize = 146.dp,
+ )
+ Text(
+ mix.name,
+ style = MaterialTheme.typography.bodyMedium,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 8.dp),
+ )
+ }
+}
+
/**
* A station, drawn as the thing it plays rather than as a list icon.
*
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/Skeleton.kt b/app/src/main/java/dev/lelonio/square/ui/browse/Skeleton.kt
new file mode 100644
index 0000000..d782277
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/Skeleton.kt
@@ -0,0 +1,102 @@
+package dev.lelonio.square.ui.browse
+
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+
+/**
+ * The shape of a row that has not arrived yet.
+ *
+ * Rows read off Spotify's own browse take a moment, and until now they simply
+ * appeared: a page that grows a row at a time under the reader's thumb moves
+ * what is being looked at, and on a slow connection it reads as the tab having
+ * finished when it has not. An outline says the same thing without lying about
+ * either — this much is coming, it is not here yet.
+ *
+ * Breathing rather than sweeping: a highlight travelling across a placeholder is
+ * a second animation on a screen whose whole business is glass, and it draws the
+ * eye to the one part of the page with nothing to see.
+ */
+@Composable
+fun SkeletonRow(
+ /** How wide the tiles are, matched to the row this stands in for. */
+ tile: Dp = 146.dp,
+ tiles: Int = 4,
+ modifier: Modifier = Modifier,
+) {
+ val breath = rememberInfiniteTransition(label = "skeleton")
+ val alpha by breath.animateFloat(
+ initialValue = 0.5f,
+ targetValue = 1f,
+ animationSpec = infiniteRepeatable(
+ animation = tween(BreathMs),
+ repeatMode = RepeatMode.Reverse,
+ ),
+ label = "skeletonBreath",
+ )
+
+ Column(modifier.alpha(alpha)) {
+ // Where the heading will be.
+ Box(
+ Modifier
+ .padding(start = 20.dp, top = 26.dp, bottom = 12.dp)
+ .width(168.dp)
+ .height(20.dp)
+ .clip(RoundedCornerShape(6.dp))
+ .background(Bone),
+ )
+ Row(
+ Modifier.padding(horizontal = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ ) {
+ repeat(tiles) {
+ Column(Modifier.width(tile)) {
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .aspectRatio(1f)
+ .clip(RoundedCornerShape(10.dp))
+ .background(Bone),
+ )
+ Box(
+ Modifier
+ .padding(top = 10.dp)
+ .fillMaxWidth(0.72f)
+ .height(12.dp)
+ .clip(RoundedCornerShape(4.dp))
+ .background(Bone),
+ )
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Barely there on purpose: this is a placeholder for something, not a thing.
+ * At any more it reads as a row of blank tiles that failed to load.
+ */
+private val Bone = Color.White.copy(alpha = 0.07f)
+
+private const val BreathMs = 900
diff --git a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
index e62ca22..7f7f76e 100644
--- a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
@@ -444,5 +444,12 @@ private val SelectedFilm = androidx.compose.ui.graphics.Color.White.copy(alpha =
*/
private val BadgeFilm = androidx.compose.ui.graphics.Color.White.copy(alpha = 0.16f)
-/** How many of each kind the combined page shows before the chips take over. */
-private const val TOP_RESULTS = 4
+/**
+ * How many of each kind the combined page shows before the chips take over.
+ *
+ * Four was a taste of each kind and nothing to read: a search for an artist
+ * answered with four songs, four albums and four playlists on a screen that
+ * holds far more. The filters above are still where a long list of one kind
+ * belongs, but the page they sit on should be worth scrolling first.
+ */
+private const val TOP_RESULTS = 8