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.

Put Liked Songs in the library, and let playlists be pinned

Lelonio764df61aa830
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 8a93ffc..b32c86c 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -35,6 +35,11 @@ class SquareApplication : Application() {
/** Which playlists were opened most recently, for ordering the home page. */
val playlistOrder: PlaylistOrderStore by lazy { PlaylistOrderStore(this) }
+
+ /** Playlists the listener keeps at the top of the library; this device's own. */
+ val pinnedPlaylists: dev.lelonio.square.data.PinnedPlaylistStore by lazy {
+ dev.lelonio.square.data.PinnedPlaylistStore(this)
+ }
val preferences: PreferencesStore by lazy { PreferencesStore(this) }
/** Which file the engine asks Spotify for. */
diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
index 72bfde4..c25766b 100644
--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
@@ -11,6 +11,8 @@ import dev.lelonio.square.data.SearchResults
import dev.lelonio.square.data.toCatalogTrack
import dev.lelonio.square.data.toResults
import dev.lelonio.square.nativecore.NativeBridge
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
import dev.lelonio.square.playback.AudioOutput
import dev.lelonio.square.playback.LibrespotPlayer
import dev.lelonio.square.playback.PlayQueue
@@ -77,8 +79,33 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
)
}
+ /**
+ * The account's Liked Songs, which Spotify keeps outside the playlists.
+ *
+ * It behaves like one everywhere it matters — a name, a cover, a list to
+ * open and play — so it is put at the head of the library rather than given
+ * a screen of its own, with the same purple cover Spotify's own clients use.
+ */
+ private suspend fun likedSongs(): CatalogPlaylist? {
+ val uri = withContext(Dispatchers.IO) {
+ runCatching { NativeBridge.collectionUri() }.getOrDefault("")
+ }
+ if (uri.isEmpty()) return null
+ return CatalogPlaylist(
+ uri = uri,
+ name = container.getString(dev.lelonio.square.R.string.liked_songs),
+ artworkUrl = LIKED_SONGS_COVER,
+ )
+ }
+
/** The access point first, the Web API when `rootlist` fails; see MainViewModel. */
override suspend fun playlists(): List<CatalogPlaylist> =
+ likedSongs().let { liked ->
+ listOfNotNull(liked) +
+ rootlist().filterNot { it.uri == liked?.uri || it.uri == Catalog.DJ_URI }
+ }
+
+ private suspend fun rootlist(): List<CatalogPlaylist> =
runCatching { Catalog.playlists() }
.recoverCatching {
check(container.webApi.isReady) { it.message ?: "rootlist non disponibile" }
@@ -108,9 +135,35 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
container.webApi.isReady && uri.startsWith("spotify:playlist:") ->
webApiPlaylistTracks(uri.substringAfterLast(':'))
+ // Liked Songs is not a context the access point will resolve: asked for
+ // it answers 503, so this is the one list that has to come from the Web
+ // API and therefore needs the user's own application.
+ uri.endsWith(":collection") -> {
+ check(container.webApi.isReady) {
+ "i brani che ti piacciono richiedono la tua applicazione Spotify"
+ }
+ savedTracks()
+ }
+
else -> Catalog.tracks(Catalog.contextTrackUris(uri))
}
+ /** Everything the account has saved, newest first, a page at a time. */
+ private suspend fun savedTracks(): List<CatalogTrack> {
+ val loaded = mutableListOf<CatalogTrack>()
+ var offset = 0
+ while (true) {
+ val page = container.api.savedTracks(limit = WEB_API_PAGE, offset = offset)
+ loaded += page.items.mapNotNull { saved ->
+ saved.track
+ .takeIf { it.isPlayable != false && it.uri.startsWith("spotify:track:") }
+ ?.toCatalogTrack(saved.addedAt)
+ }
+ offset += page.items.size
+ if (page.items.isEmpty() || offset >= page.total) return loaded
+ }
+ }
+
private suspend fun webApiPlaylistTracks(id: String): List<CatalogTrack> {
val loaded = mutableListOf<CatalogTrack>()
var offset = 0
@@ -190,5 +243,14 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
private companion object {
/** The Web API's own maximum page size for playlist tracks. */
const val WEB_API_PAGE = 100
+
+ /**
+ * The purple heart Spotify's own clients draw for Liked Songs.
+ *
+ * A fixed asset of theirs rather than anything account-specific, and
+ * the only way to have this row look like the row it stands for: it is
+ * not a playlist, so no cover comes back for it anywhere.
+ */
+ const val LIKED_SONGS_COVER = "https://misc.scdn.co/liked-songs/liked-songs-640.png"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
index c3f18aa..afb3809 100644
--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt
+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
@@ -176,7 +176,7 @@ object Catalog {
* no track list to open, and opening it is the one thing a row in a library
* promises. The same id for every account.
*/
- private const val DJ_URI = "spotify:playlist:37i9dQZF1EYkqdzj48dyYq"
+ const val DJ_URI = "spotify:playlist:37i9dQZF1EYkqdzj48dyYq"
/** The account's own playlists. */
suspend fun playlists(): List<CatalogPlaylist> = withContext(Dispatchers.IO) {
diff --git a/app/src/main/java/dev/lelonio/square/data/PinnedPlaylistStore.kt b/app/src/main/java/dev/lelonio/square/data/PinnedPlaylistStore.kt
new file mode 100644
index 0000000..d8da3c1
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/PinnedPlaylistStore.kt
@@ -0,0 +1,71 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * The playlists the listener has pinned to the top of their library.
+ *
+ * Kept here rather than on the account: Spotify has no such concept, so there
+ * is nothing to send and nothing to read back. That also means the pins belong
+ * to this device, which is the honest behaviour for something the service does
+ * not know about.
+ *
+ * Ordered, oldest pin first, so the shelf at the top does not rearrange itself
+ * every time another playlist is pinned.
+ */
+class PinnedPlaylistStore(context: Context) {
+
+ private val prefs = context.applicationContext
+ .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
+
+ private val _pinned = MutableStateFlow(load())
+
+ /** URIs in the order they were pinned. */
+ val pinned: StateFlow<List<String>> = _pinned.asStateFlow()
+
+ fun isPinned(uri: String): Boolean = uri in _pinned.value
+
+ fun toggle(uri: String) {
+ val current = _pinned.value
+ val updated = if (uri in current) {
+ current - uri
+ } else {
+ (current + uri).takeLast(LIMIT)
+ }
+ _pinned.value = updated
+ prefs.edit().putString(KEY_PINNED, updated.joinToString(SEPARATOR)).commit()
+ }
+
+ private fun load(): List<String> =
+ prefs.getString(KEY_PINNED, null)
+ ?.split(SEPARATOR)
+ ?.filter { it.isNotBlank() }
+ .orEmpty()
+
+ private companion object {
+ const val FILE_NAME = "square_pinned_playlists"
+ const val KEY_PINNED = "pinned"
+
+ /** A URI contains no whitespace, so this can never appear inside one. */
+ const val SEPARATOR = "\n"
+
+ /** Enough that nobody meets it; a guard against a runaway list. */
+ const val LIMIT = 50
+ }
+}
+
+/**
+ * Lifts the pinned playlists to the front, whatever the sort underneath.
+ *
+ * The sort the listener chose still applies: this only says which rows come
+ * first, and pinning is an instruction the sort has no business overruling.
+ */
+fun List<CatalogPlaylist>.withPinnedFirst(pinned: List<String>): List<CatalogPlaylist> {
+ if (pinned.isEmpty()) return this
+ val rank = pinned.withIndex().associate { (index, uri) -> uri to index }
+ val (top, rest) = partition { rank.containsKey(it.uri) }
+ return top.sortedBy { rank.getValue(it.uri) } + rest
+}
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 a903dee..a251334 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -24,6 +24,14 @@ interface SpotifyApi {
@GET("v1/me")
suspend fun me(): UserDto
+ /**
+ * Whether each of these tracks is in the account's Liked Songs.
+ *
+ * The answers come back in the order asked, as bare booleans.
+ */
+ @GET("v1/me/tracks/contains")
+ suspend fun tracksAreSaved(@Query("ids") ids: String): List<Boolean>
+
@GET("v1/me/tracks")
suspend fun savedTracks(
@Query("limit") limit: Int = 50,
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt
index 1143d8d..f5e4202 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyHome.kt
@@ -64,6 +64,10 @@ object SpotifyHome {
private fun entry(item: JSONObject): CatalogPlaylist? {
val uri = item.optString("uri")
if (uri.isEmpty()) return null
+ // The DJ is a stream Spotify generates as you listen, not a list: it has
+ // no tracks to resolve, so opening it here only ever showed a blank
+ // page. It is kept out of the library for the same reason.
+ if (uri == Catalog.DJ_URI) return null
val content = item.optJSONObject("content") ?: return null
val data = content.optJSONObject("data") ?: return null
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
index 68186be..46a7e23 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
@@ -39,6 +39,7 @@ import com.kyant.backdrop.Backdrop
import dev.lelonio.square.R
import dev.lelonio.square.data.CatalogPlaylist
import dev.lelonio.square.data.sortedByRecentlyOpened
+import dev.lelonio.square.data.withPinnedFirst
import dev.lelonio.square.ui.MainViewModel
import dev.lelonio.square.ui.components.Artwork
import dev.lelonio.square.ui.glass.LiquidButton
@@ -48,6 +49,8 @@ import dev.lelonio.square.ui.theme.Ink
import dev.lelonio.square.ui.theme.InkDim
import dev.lelonio.square.ui.theme.softShadow
import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Fill
+import com.adamglin.phosphoricons.fill.PushPin
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.ListBullets
import com.adamglin.phosphoricons.regular.Plus
@@ -82,6 +85,8 @@ fun LibraryScreen(
onOpenPlaylist: (CatalogPlaylist) -> Unit,
/** URIs most recently opened first; see PlaylistOrderStore. */
playlistOrder: List<String>,
+ /** URIs the listener pinned to the top; see PinnedPlaylistStore. */
+ pinned: List<String> = emptyList(),
/** False when the source cannot be written to; see MusicBackend. */
canEdit: Boolean = false,
onCreatePlaylist: () -> Unit = {},
@@ -124,7 +129,7 @@ fun LibraryScreen(
var layout by remember { mutableStateOf(Layout.GRID) }
var order by remember { mutableStateOf(Order.RECENT) }
- val playlists = remember(state.playlists, playlistOrder, order) {
+ val playlists = remember(state.playlists, playlistOrder, pinned, order) {
when (order) {
Order.RECENT -> state.playlists.sortedByRecentlyOpened(playlistOrder)
Order.NAME -> state.playlists.sortedWith(
@@ -134,6 +139,9 @@ fun LibraryScreen(
// rootlist arrives in.
Order.ADDED -> state.playlists
}
+ // Pinning outranks the sort: it is the one instruction the
+ // listener gave about this list themselves.
+ .withPinnedFirst(pinned)
}
Column(Modifier.fillMaxSize()) {
@@ -167,6 +175,7 @@ fun LibraryScreen(
items(playlists, key = { it.uri }) { playlist ->
GridTile(
playlist,
+ pinned = playlist.uri in pinned,
onClick = { onOpenPlaylist(playlist) },
onLongClick = if (canEdit) {
{ onPlaylistMenu(playlist) }
@@ -185,6 +194,7 @@ fun LibraryScreen(
items(playlists, key = { it.uri }) { playlist ->
ListRow(
playlist,
+ pinned = playlist.uri in pinned,
onClick = { onOpenPlaylist(playlist) },
onLongClick = if (canEdit) {
{ onPlaylistMenu(playlist) }
@@ -311,6 +321,7 @@ private fun Header(
@Composable
private fun GridTile(
playlist: CatalogPlaylist,
+ pinned: Boolean,
onClick: () -> Unit,
onLongClick: (() -> Unit)?,
) {
@@ -327,19 +338,25 @@ private fun GridTile(
corner = 20.dp,
decodeSize = 220.dp,
)
- Text(
- playlist.name,
- style = MaterialTheme.typography.titleMedium,
- maxLines = 2,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.padding(top = 10.dp, start = 2.dp, end = 2.dp),
- )
+ Row(
+ Modifier.padding(top = 10.dp, start = 2.dp, end = 2.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ if (pinned) PinMark(Modifier.padding(end = 6.dp))
+ Text(
+ playlist.name,
+ style = MaterialTheme.typography.titleMedium,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
}
}
@Composable
private fun ListRow(
playlist: CatalogPlaylist,
+ pinned: Boolean,
onClick: () -> Unit,
onLongClick: (() -> Unit)?,
) {
@@ -374,9 +391,21 @@ private fun ListRow(
.padding(start = 16.dp)
.weight(1f),
)
+ if (pinned) PinMark()
}
}
+/** The quiet mark on a pinned row. Small: the position is the message. */
+@Composable
+private fun PinMark(modifier: Modifier = Modifier) {
+ Icon(
+ PhosphorIcons.Fill.PushPin,
+ contentDescription = stringResource(R.string.pinned),
+ tint = InkDim,
+ modifier = modifier.size(14.dp),
+ )
+}
+
/** A glass pill, for the handful of places that need a button at all. */
@Composable
private fun GlassAction(label: String, backdrop: Backdrop, onClick: () -> Unit) {
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index fa55652..15145a7 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -230,4 +230,10 @@
<string name="effect_quality_high_note">Am besten für Musik und am anspruchsvollsten für den Akku.</string>
<string name="effect_quality_light">Leicht</string>
<string name="effect_quality_light_note">Das Telefon übernimmt. Schonender für ältere Geräte, rauer bei Anschlägen.</string>
+ <string name="liked_songs">Lieblingssongs</string>
+ <string name="pinned">Angeheftet</string>
+ <string name="pin">Oben anheften</string>
+ <string name="unpin">Lösen</string>
+ <string name="cover_aura">Farbanimation</string>
+ <string name="radio">Radio</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index cf6b362..5bdb560 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -230,4 +230,10 @@
<string name="effect_quality_high_note">La mejor con música y la que más batería consume.</string>
<string name="effect_quality_light">Ligera</string>
<string name="effect_quality_light_note">Lo hace el teléfono. Más amable con los equipos antiguos, más áspera en los ataques.</string>
+ <string name="liked_songs">Tus me gusta</string>
+ <string name="pinned">Fijada</string>
+ <string name="pin">Fijar arriba</string>
+ <string name="unpin">Quitar de arriba</string>
+ <string name="cover_aura">Animación de color</string>
+ <string name="radio">Radio</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 6fc3193..85383d0 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -230,4 +230,10 @@
<string name="effect_quality_high_note">La meilleure sur la musique, et la plus gourmande en batterie.</string>
<string name="effect_quality_light">Légère</string>
<string name="effect_quality_light_note">Le téléphone s’en charge. Plus douce pour les appareils anciens, plus rêche sur les attaques.</string>
+ <string name="liked_songs">Titres likés</string>
+ <string name="pinned">Épinglée</string>
+ <string name="pin">Épingler en haut</string>
+ <string name="unpin">Désépingler</string>
+ <string name="cover_aura">Animation colorée</string>
+ <string name="radio">Radio</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index bd11e91..285ed66 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -231,4 +231,10 @@
<string name="effect_quality_high_note">La migliore sulla musica, e la più esigente per la batteria.</string>
<string name="effect_quality_light">Leggera</string>
<string name="effect_quality_light_note">Se ne occupa il telefono. Più gentile con i dispositivi vecchi, più ruvida sugli attacchi.</string>
+ <string name="liked_songs">Brani che ti piacciono</string>
+ <string name="pinned">Fissata</string>
+ <string name="pin">Fissa in alto</string>
+ <string name="unpin">Togli dall\'alto</string>
+ <string name="cover_aura">Animazione a colori</string>
+ <string name="radio">Radio</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index fe07d5b..52a2a4d 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -230,4 +230,10 @@
<string name="effect_quality_high_note">A melhor com música e a mais exigente para a bateria.</string>
<string name="effect_quality_light">Leve</string>
<string name="effect_quality_light_note">O telefone é que trata disso. Melhor para aparelhos antigos, mais áspera nos ataques.</string>
+ <string name="liked_songs">Músicas curtidas</string>
+ <string name="pinned">Fixada</string>
+ <string name="pin">Fixar no topo</string>
+ <string name="unpin">Desafixar</string>
+ <string name="cover_aura">Animação de cores</string>
+ <string name="radio">Rádio</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 030b380..3c87f19 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -251,4 +251,10 @@
<string name="effect_quality_high_note">Best on music, and the heaviest on the battery.</string>
<string name="effect_quality_light">Light</string>
<string name="effect_quality_light_note">The phone does the work. Kinder to older devices, rougher on attacks.</string>
+ <string name="liked_songs">Liked Songs</string>
+ <string name="pinned">Pinned</string>
+ <string name="pin">Pin to the top</string>
+ <string name="unpin">Unpin</string>
+ <string name="cover_aura">Colour animation</string>
+ <string name="radio">Radio</string>
</resources>