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
Show who made the song, and let the song load first
Leloniofd6d5849ed91
diff --git a/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyCredits.kt b/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyCredits.ktnew file mode 100644index 0000000..364364e--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/spotify/SpotifyCredits.kt@@ -0,0 +1,104 @@+package dev.lelonio.square.backend.spotify++import dev.lelonio.square.nativecore.NativeBridge+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okhttp3.OkHttpClient+import okhttp3.Request+import org.json.JSONObject++/**+ * Who made a track, as Spotify's own clients show it.+ *+ * The same list that sits behind "Show credits" there: who performed it, who+ * wrote it, who produced it, and whose recording it is. It comes from an+ * endpoint of the account's own, so the listener's token is all it needs, and+ * it is asked for only when somebody opens the panel — nothing about playing a+ * song requires knowing who engineered it.+ */+object SpotifyCredits {++ private val http = OkHttpClient()++ /** One group of people with the same job on this track. */+ data class Role(val title: String, val people: List<Person>)++ data class Person(+ val name: String,+ /** "main artist", "composer", "lyricist" — what they did, when it is said. */+ val subroles: List<String>,+ /** Their artist page, for the ones who have one. */+ val uri: String?,+ )++ data class Credits(+ val title: String,+ val roles: List<Role>,+ /** The label, as Spotify names it: "Sony Music", "Tattica s.r.l.". */+ val sources: List<String>,+ ) {+ val isEmpty: Boolean get() = roles.all { it.people.isEmpty() } && sources.isEmpty()+ }++ /**+ * Null when the track has none, when the account cannot be asked, or when+ * anything at all goes wrong: this is a panel, not a feature to fail over.+ */+ suspend fun of(trackUri: String): Credits? = withContext(Dispatchers.IO) {+ val id = trackUri.substringAfterLast(':').takeIf { it.isNotEmpty() }+ ?: return@withContext null+ val token = NativeBridge.accessToken() ?: return@withContext null++ runCatching {+ val request = Request.Builder()+ .url("$HOST/track-credits-view/v0/experimental/$id/credits")+ .header("authorization", "Bearer $token")+ .header("accept", "application/json")+ .build()++ http.newCall(request).execute().use { response ->+ if (!response.isSuccessful) return@withContext null+ parse(JSONObject(response.body?.string().orEmpty()))+ }+ }+ .onFailure { android.util.Log.i(TAG, "no credits for $trackUri: ${it.message}") }+ .getOrNull()+ }++ private fun parse(body: JSONObject): Credits {+ val roles = body.optJSONArray("roleCredits").let { array ->+ (0 until (array?.length() ?: 0)).mapNotNull { index ->+ val group = array?.optJSONObject(index) ?: return@mapNotNull null+ val people = group.optJSONArray("artists").let { artists ->+ (0 until (artists?.length() ?: 0)).mapNotNull { at ->+ val person = artists?.optJSONObject(at) ?: return@mapNotNull null+ val name = person.optString("name").takeIf { it.isNotEmpty() }+ ?: return@mapNotNull null+ Person(+ name = name,+ subroles = person.optJSONArray("subroles").let { list ->+ (0 until (list?.length() ?: 0)).mapNotNull { role ->+ list?.optString(role)?.takeIf { it.isNotEmpty() }+ }+ },+ uri = person.optString("uri").takeIf { it.startsWith("spotify:artist:") },+ )+ }+ }+ Role(title = group.optString("roleTitle"), people = people)+ .takeIf { it.people.isNotEmpty() }+ }+ }++ val sources = body.optJSONArray("sourceNames").let { list ->+ (0 until (list?.length() ?: 0)).mapNotNull { at ->+ list?.optString(at)?.takeIf { it.isNotEmpty() }+ }+ }++ return Credits(body.optString("trackTitle"), roles, sources)+ }++ private const val HOST = "https://spclient.wg.spotify.com"+ private const val TAG = "SquareCredits"+}diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex 602ef7b..3b72fd2 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -256,7 +256,8 @@ fun SquareApp(// The session as it was left, so the player has something to draw before// the media controller connects. Read once, off the saved queue.val seed = remember(context) { savedPlaybackSeed(context) }- val local by rememberPlaybackState(player, seed)+ val localState = rememberPlaybackState(player, seed)+ val local by localState/*** Playback on another of the account's devices, when there is any.@@ -399,7 +400,10 @@ fun SquareApp(// Asked once per track: almost no song has a video, and the answer is two// catalogue calls rather than something the account volunteers.- LaunchedEffect(playback.mediaId) { viewModel.lookUpVideo(playback.mediaId) }+ LaunchedEffect(playback.mediaId) {+ awaitAudible(localState)+ viewModel.lookUpVideo(playback.mediaId)+ }val devices by viewModel.devices.collectAsStateWithLifecycle()val addToPlaylist by viewModel.addToPlaylist.collectAsStateWithLifecycle()val trackSort by viewModel.trackSort.collectAsStateWithLifecycle()@@ -553,10 +557,17 @@ fun SquareApp(val uri = playback.mediaIdcanvas = nullif (uri != null && backend == dev.lelonio.square.backend.BackendId.SPOTIFY) {+ // After the song, not beside it: a Canvas is a video, and fetching+ // one while the track is still arriving takes the connection the+ // track needs. See awaitAudible.+ awaitAudible(localState)canvas = Catalog.canvas(uri)}}+ val credits by viewModel.credits.collectAsStateWithLifecycle()+ val creditsLoading by viewModel.creditsLoading.collectAsStateWithLifecycle()+var lyrics by remember { mutableStateOf<Lyrics?>(null) }var lyricsLoading by remember { mutableStateOf(false) }@@ -572,6 +583,9 @@ fun SquareApp(lyrics = nullif (uri == null) return@LaunchedEffectlyricsLoading = true+ // Behind the song as well; see awaitAudible. The panel shows its own+ // spinner meanwhile, so the wait is visible rather than blank.+ awaitAudible(localState)lyrics = runCatching {(context.applicationContext as dev.lelonio.square.SquareApplication).activeBackend@@ -1540,6 +1554,9 @@ fun SquareApp(queue = queue,lyrics = lyrics,lyricsLoading = lyricsLoading,+ credits = credits,+ creditsLoading = creditsLoading,+ onWantCredits = viewModel::loadCredits,onPlayQueueItem = { player?.seekTo(it, 0L) },reverb = reverb,// Speed and pitch are set as a pair because@@ -2403,3 +2420,27 @@ private fun BarSearchField(}}}++/**+ * Waits for the song to be playing before fetching what surrounds it.+ *+ * Everything the player shows around a track — the Canvas clip above all, which+ * is a video, plus the lyrics and the question of whether there is a music+ * video — is worth having and worth nothing at all until the song is audible.+ * Asked for the moment the track changes, they compete with the audio for the+ * same connection, and on a slow one that is the difference between a song+ * starting now and starting in three seconds.+ *+ * Bounded, because a track that never gets going must not hold them for ever:+ * after this, they are fetched anyway.+ */+private suspend fun awaitAudible(+ state: androidx.compose.runtime.State<dev.lelonio.square.ui.player.PlaybackState>,+) {+ kotlinx.coroutines.withTimeoutOrNull(AUDIBLE_TIMEOUT_MS) {+ snapshotFlow { state.value.isBuffering }.first { !it }+ }+}++/** How long the extras wait for the song; see [awaitAudible]. */+private const val AUDIBLE_TIMEOUT_MS = 5_000Ldiff --git a/app/src/main/java/dev/lelonio/square/ui/player/CreditsView.kt b/app/src/main/java/dev/lelonio/square/ui/player/CreditsView.ktnew file mode 100644index 0000000..ad8255d--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/player/CreditsView.kt@@ -0,0 +1,124 @@+package dev.lelonio.square.ui.player++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import dev.lelonio.square.R+import dev.lelonio.square.backend.spotify.SpotifyCredits+import dev.lelonio.square.ui.theme.Ink+import dev.lelonio.square.ui.theme.InkDim++/**+ * Who made the song, in the player's own slot.+ *+ * The same three groups Spotify lists — who played it, who wrote it, who+ * produced it — and the label underneath. Names only: this is a page to read+ * once, not a place to navigate from, and every name that has an artist page+ * already has a row in the queue or a line under the title that opens it.+ */+@Composable+fun CreditsView(+ credits: SpotifyCredits.Credits?,+ loading: Boolean,+ modifier: Modifier = Modifier,+) {+ Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ when {+ loading && credits == null -> CircularProgressIndicator(+ color = Ink,+ strokeWidth = 2.dp,+ )++ credits == null || credits.isEmpty -> Text(+ stringResource(R.string.credits_none),+ style = MaterialTheme.typography.bodyMedium,+ color = InkDim,+ textAlign = TextAlign.Center,+ modifier = Modifier.padding(horizontal = 40.dp),+ )++ else -> Column(+ Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 28.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(18.dp),+ ) {+ credits.roles.forEach { role ->+ Column(Modifier.fillMaxWidth()) {+ Text(+ role.title.localised(),+ style = MaterialTheme.typography.labelLarge,+ color = InkDim,+ )+ role.people.forEach { person ->+ Text(+ person.name,+ style = MaterialTheme.typography.titleMedium,+ color = Ink,+ modifier = Modifier.padding(top = 4.dp),+ )+ // "main artist", "composer": what they did on this+ // track, when the credit says so.+ person.subroles+ .takeIf { it.isNotEmpty() }+ ?.joinToString(", ")+ ?.let {+ Text(+ it,+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ )+ }+ }+ }+ }++ credits.sources.takeIf { it.isNotEmpty() }?.let { sources ->+ Column(Modifier.fillMaxWidth()) {+ Text(+ stringResource(R.string.credits_source),+ style = MaterialTheme.typography.labelLarge,+ color = InkDim,+ )+ Text(+ sources.joinToString(" · "),+ style = MaterialTheme.typography.bodyMedium,+ color = Ink,+ modifier = Modifier.padding(top = 4.dp),+ )+ }+ }+ }+ }+ }+}++/**+ * The three groups in the app's language.+ *+ * Spotify names them in English whatever the account's language is, and these+ * three cover every track that has credits at all; anything else it invents is+ * shown as it arrives rather than dropped.+ */+@Composable+private fun String.localised(): String = when (lowercase()) {+ "performers" -> stringResource(R.string.credits_performers)+ "writers" -> stringResource(R.string.credits_writers)+ "producers" -> stringResource(R.string.credits_producers)+ else -> this+}diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.ktindex 0ecca14..4b08302 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt@@ -59,6 +59,8 @@ import com.adamglin.phosphoricons.fill.SlidersHorizontalimport com.adamglin.phosphoricons.fill.TextAlignLeftimport com.adamglin.phosphoricons.fill.VinylRecordimport com.adamglin.phosphoricons.regular.VinylRecord+import com.adamglin.phosphoricons.fill.Info+import com.adamglin.phosphoricons.regular.Infoimport com.adamglin.phosphoricons.regular.X/** Which panel is open below the transport controls. */@@ -68,6 +70,9 @@ enum class PlayerPanel {LYRICS,EFFECTS,+ /** Who made the track: performers, writers, producers, and the label. */+ INFO,+/*** The Connect device list and the playlist picker.*@@ -124,7 +129,9 @@ fun PlayerPanelSection(.collectAsStateWithLifecycle()val effectsOn = speed != 1f || pitch != 1f || reverb > 0f- val views = remember { listOf(PlayerPanel.NONE, PlayerPanel.LYRICS, PlayerPanel.EFFECTS) }+ val views = remember {+ listOf(PlayerPanel.NONE, PlayerPanel.LYRICS, PlayerPanel.EFFECTS, PlayerPanel.INFO)+ }val selected = views.indexOf(panel).coerceAtLeast(0)// Stable, or LiquidBottomTabs throws away the state it keys on this and// the indicator stops animating; see the note in SquareApp.@@ -168,6 +175,12 @@ fun PlayerPanelSection(selected = selected == 2,marked = effectsOn,) { onSelect(PlayerPanel.EFFECTS) }+ PanelTab(+ icon = PhosphorIcons.Regular.Info,+ activeIcon = PhosphorIcons.Fill.Info,+ label = stringResource(R.string.credits),+ selected = selected == 3,+ ) { onSelect(PlayerPanel.INFO) }}}diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.ktindex 5c5a7d3..ec96ff6 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt@@ -138,7 +138,9 @@ private const val PAUSED_DIM = 0.55f* back here as a full-bleed backdrop.*//** What occupies the middle of the player. */-private enum class Stage { COVER, LYRICS, EFFECTS, QUEUE, DEVICES, ADD_TO_PLAYLIST, CANVAS, VIDEO }+private enum class Stage {+ COVER, LYRICS, EFFECTS, INFO, QUEUE, DEVICES, ADD_TO_PLAYLIST, CANVAS, VIDEO+}@UnstableApi@Composable@@ -156,6 +158,11 @@ fun PlayerScreen(queue: List<QueueEntry>,lyrics: dev.lelonio.square.data.Lyrics?,lyricsLoading: Boolean,+ /** Who made the track, for the credits panel; null until it is asked for. */+ credits: dev.lelonio.square.backend.spotify.SpotifyCredits.Credits?,+ creditsLoading: Boolean,+ /** Asked for when the credits panel is opened, and not before. */+ onWantCredits: (String?) -> Unit,onPlayQueueItem: (Int) -> Unit,/** The music video for this track, when the catalogue has one. */videoFileId: String? = null,@@ -252,6 +259,13 @@ fun PlayerScreen() {var panel by remember { mutableStateOf(PlayerPanel.NONE) }+ // The one panel whose contents are fetched rather than already here, and+ // the one nobody opens for most songs. Asking on open keeps a request per+ // track from being made for a page most listeners never see.+ LaunchedEffect(panel, state.mediaId) {+ if (panel == PlayerPanel.INFO) onWantCredits(state.mediaId)+ }+// How far the track-change swipe has been dragged, when the clip stands in// for the cover. Written from the gesture and read only inside a// graphicsLayer, so following the finger costs a redraw of one layer rather@@ -509,6 +523,7 @@ fun PlayerScreen(targetState = when (panel) {PlayerPanel.LYRICS -> Stage.LYRICSPlayerPanel.EFFECTS -> Stage.EFFECTS+ PlayerPanel.INFO -> Stage.INFOPlayerPanel.QUEUE -> Stage.QUEUEPlayerPanel.DEVICES -> Stage.DEVICESPlayerPanel.ADD_TO_PLAYLIST -> Stage.ADD_TO_PLAYLIST@@ -580,6 +595,12 @@ fun PlayerScreen(// controls. A panel that pushed the transport// around every time it opened was the reason// this screen never sat still.+ Stage.INFO -> CreditsView(+ credits = credits,+ loading = creditsLoading,+ modifier = Modifier.fillMaxSize(),+ )+Stage.EFFECTS -> Box(Modifier.fillMaxSize(),contentAlignment = Alignment.Center,@@ -1132,6 +1153,7 @@ private fun TopBar(targetState = when (panel) {PlayerPanel.LYRICS -> stringResource(R.string.lyrics)PlayerPanel.EFFECTS -> stringResource(R.string.effects)+ PlayerPanel.INFO -> stringResource(R.string.credits)PlayerPanel.QUEUE -> stringResource(R.string.queued)PlayerPanel.DEVICES -> stringResource(R.string.play_on)PlayerPanel.ADD_TO_PLAYLIST -> stringResource(R.string.add_to_playlist)