Skip to content

Native Android client for Spotify, built with Jetpack Compose

Artist pages: latest release and release order by full release date, not the year alone; playlists show their Spotify local files (#80), played from the device when a matching file is there

kota-zo8db60c6648e5
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt
index 48a783c2..2aa4e5ae 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt
@@ -9,6 +9,7 @@ import app.myspoti.api.Artist
import app.myspoti.api.ArtistRef
import app.myspoti.api.Image
import app.myspoti.api.ItemKind
+import app.myspoti.api.LocalFile
import app.myspoti.api.NowPlaying
import app.myspoti.api.Page
import app.myspoti.api.PlayerRestrictions
@@ -53,7 +54,16 @@ internal fun track(d: JsonElement?, uid: String? = null): Track? {
/** A playlist row: a track, or an episode shaped as a `Track` (show name as the artist, show/episode art as the album). */
internal fun playlistItem(d: JsonElement?, uid: String? = null): Track? {
- if (d.str("uri")?.startsWith("spotify:episode:") != true) return track(d, uid)
+ val uri = d.str("uri")
+ // A local file (#80): its tags are in the uri; the row's own name and duration win when it has them.
+ if (uri != null && LocalFile.isLocal(uri)) {
+ val local = LocalFile.track(uri, uid) ?: return null
+ return local.copy(
+ name = d.str("name")?.takeIf { it.isNotBlank() } ?: local.name,
+ durationMs = d.long("trackDuration.totalMilliseconds") ?: d.long("duration.totalMilliseconds") ?: local.durationMs,
+ )
+ }
+ if (uri?.startsWith("spotify:episode:") != true) return track(d, uid)
val e = episode(d) ?: return null
val cover = e.images.ifEmpty { e.show?.images.orEmpty() }
return Track(
diff --git a/base/api/src/main/kotlin/app/myspoti/api/LocalFile.kt b/base/api/src/main/kotlin/app/myspoti/api/LocalFile.kt
new file mode 100644
index 00000000..848551b9
--- /dev/null
+++ b/base/api/src/main/kotlin/app/myspoti/api/LocalFile.kt
@@ -0,0 +1,39 @@
+package app.myspoti.api
+
+import java.net.URLDecoder
+
+/**
+ * A "local file" of a Spotify playlist: a song the user's desktop app added from its own disk.
+ * Spotify keeps only its tags, in the uri: `spotify:local:{artist}:{album}:{title}:{seconds}`,
+ * URL-encoded (a space is `+`, a colon `%3A`), any part possibly empty.
+ */
+object LocalFile {
+ const val PREFIX = "spotify:local:"
+
+ fun isLocal(uri: Uri): Boolean = uri.startsWith(PREFIX)
+
+ /**
+ * The row for [uri], or null when it is not a local file. [uid] is the playlist row's id.
+ * It is not playable from Spotify (the file lives on another device), hence `playable = false`.
+ */
+ fun track(uri: Uri, uid: String? = null): Track? {
+ if (!isLocal(uri)) return null
+ val parts = uri.removePrefix(PREFIX).split(':')
+ fun decode(s: String) = runCatching { URLDecoder.decode(s, "UTF-8") }.getOrDefault(s)
+ fun part(i: Int) = decode(parts.getOrNull(i).orEmpty())
+ val artist = part(0)
+ val album = part(1)
+ // A title is the last-but-one part; an unencoded colon in it must not shift the duration.
+ val seconds = parts.lastOrNull()?.toLongOrNull()
+ val title = if (parts.size >= 4 && seconds != null) parts.subList(2, parts.size - 1).joinToString(":") { decode(it) } else part(2)
+ return Track(
+ uri = uri,
+ name = title,
+ durationMs = (seconds ?: 0L) * 1000,
+ artists = if (artist.isBlank()) emptyList() else listOf(ArtistRef("", artist)),
+ album = if (album.isBlank()) null else AlbumRef("", album),
+ playable = false,
+ uid = uid,
+ )
+ }
+}
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.kt
index 6f321f87..40378a10 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
@@ -8,6 +8,7 @@ import app.myspoti.api.Album
import app.myspoti.api.Artist
import app.myspoti.api.Image
import app.myspoti.api.LibraryFilter
+import app.myspoti.api.LocalFile
import app.myspoti.api.MediaCard
import app.myspoti.api.MediaKind
import app.myspoti.api.MyspotiApi
@@ -29,6 +30,8 @@ import com.music.spotui.data.entity.PodcastModel
import com.music.spotui.data.entity.SearchResults
import com.music.spotui.data.entity.ShowPage
import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.data.local.LocalFileMatch
+import com.music.spotui.data.local.LocalMusic
import com.music.spotui.di.Graph
import com.music.spotui.di.SongPlayer
import kotlinx.coroutines.async
@@ -166,6 +169,20 @@ class Api constructor(
playable = t.playable,
rowUid = t.uid.orEmpty(),
)
+ // A local file of the user's computer: the uri holds its tags, nothing else. Greyed out
+ // until [LocalFileMatch] finds the same song on this device.
+ if (LocalFile.isLocal(t.uri)) return SongsModel(
+ id = stableId("local:${t.uri}"),
+ title = t.name.take(128),
+ album = t.album?.name.orEmpty(),
+ singer = singer,
+ coverUri = "",
+ url = t.uri,
+ durationMs = t.durationMs.toInt(),
+ addedAt = t.addedAt.orEmpty(),
+ playable = false,
+ rowUid = t.uid.orEmpty(),
+ )
return SongsModel(
id = stableId("track:$id"),
title = t.name.take(128),
@@ -184,6 +201,12 @@ class Api constructor(
)
}
+ /** [songs] with the playlist's local files played from this device's own copy, when there is one. */
+ private suspend fun withDeviceFiles(songs: List<SongsModel>): List<SongsModel> {
+ if (songs.none { it.url.startsWith(LocalFileMatch.SPOTIFY_PREFIX) }) return songs
+ return LocalFileMatch.resolve(songs, LocalMusic.tracks(context))
+ }
+
private fun episodeSong(e: app.myspoti.api.Episode): SongsModel {
val id = e.uri.substringAfterLast(':')
val show = e.show?.name ?: "Podcast"
@@ -212,7 +235,7 @@ class Api constructor(
artists = a.artists.joinToString(", ") { it.name },
coverUri = cover(a.images),
name = a.name,
- time = a.releaseDate?.take(4).orEmpty(),
+ time = a.releaseDate?.take(10).orEmpty(),
type = a.type,
)
@@ -628,7 +651,8 @@ class Api constructor(
headerImage = big(page.headerImages).ifBlank { avatar },
avatarImage = avatar,
topTracks = top.map { (song, plays) -> ArtistTrackUi(song, plays) },
- popularReleases = page.popularReleases.map(::albumOf),
+ // Newest first (the sort is stable: same-day releases keep Spotify's order).
+ popularReleases = page.popularReleases.sortedByDescending { it.releaseDate.orEmpty().take(10) }.map(::albumOf),
appearsOn = page.appearsOn.map(::albumOf),
relatedArtists = page.related.map(::artistOf),
)
@@ -650,7 +674,7 @@ class Api constructor(
}.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() }
+ val merged = (page.popularReleases + all).distinctBy { it.uri }.sortedByDescending { it.releaseDate.orEmpty().take(10) }
val full = model.copy(popularReleases = merged.map(::albumOf))
ArtistCache.map[uri] = System.currentTimeMillis() to full
emit(Response.Success(full))
@@ -947,7 +971,7 @@ class Api constructor(
}
val first = firstPage.await().getOrElse { failed = true; null }
if (first != null) {
- songs += first.items.map(::songOf)
+ songs += withDeviceFiles(first.items.map(::songOf))
val offsets = generateSequence(first.nextOffset) { (it + PLAYLIST_PAGE).takeIf { n -> n < first.total } }.toList()
emit(publish(done = offsets.isEmpty()))
if (offsets.isNotEmpty()) {
@@ -958,7 +982,7 @@ class Api constructor(
for ((i, job) in jobs.withIndex()) {
val page = job.await()
if (page == null) { failed = true; jobs.drop(i + 1).forEach { it.cancel() }; break }
- songs += page.items.map(::songOf)
+ songs += withDeviceFiles(page.items.map(::songOf))
val last = i == jobs.lastIndex
if (last || System.currentTimeMillis() - lastEmit >= PLAYLIST_EMIT_MS) {
emit(publish(done = last)); lastEmit = System.currentTimeMillis()
@@ -993,7 +1017,7 @@ class Api constructor(
var offset = 0
while (true) {
val page = runCatching { api.playlists.tracks(uri, offset, 100) }.getOrNull() ?: break
- songs += page.items.map(::songOf)
+ songs += withDeviceFiles(page.items.map(::songOf))
SongPlayer.registerContext(songs.map { it.url }, uri)
emit(Response.Success(songs.toList()))
offset = page.nextOffset ?: break
diff --git a/base/app/src/main/java/com/music/spotui/data/entity/AlbumsModel.kt b/base/app/src/main/java/com/music/spotui/data/entity/AlbumsModel.kt
index 429d914f..09f9b669 100644
--- a/base/app/src/main/java/com/music/spotui/data/entity/AlbumsModel.kt
+++ b/base/app/src/main/java/com/music/spotui/data/entity/AlbumsModel.kt
@@ -6,6 +6,8 @@ data class AlbumsModel(
val artists : String,
val coverUri : String,
val name : String,
+ // Release date as Spotify gives it: "2024-05-17", or just "2024" when only the year is known.
+ // Sorts as text, newest last; [year] is what the screens show.
val time : String,
// Release kind from Spotify: "album", "single", "compilation"... Empty when unknown.
val type : String = "",
@@ -13,4 +15,7 @@ data class AlbumsModel(
val spotifyId : String = "",
){
constructor() : this( -1,"" ,"" ,"", "")
+
+ /** The release year ("2024"), or empty when the date is unknown. */
+ val year : String get() = time.take(4)
}
diff --git a/base/app/src/main/java/com/music/spotui/data/local/LocalFileMatch.kt b/base/app/src/main/java/com/music/spotui/data/local/LocalFileMatch.kt
new file mode 100644
index 00000000..d9d003ca
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalFileMatch.kt
@@ -0,0 +1,58 @@
+package com.music.spotui.data.local
+
+import com.music.spotui.data.entity.SongsModel
+
+/**
+ * Spotify playlists can hold "local files" of the user's computer (`spotify:local:...`), known by
+ * their tags only. When the same song is among this device's files, the row plays from there.
+ */
+object LocalFileMatch {
+ /** A playlist row that is a Spotify local file nothing on this device matched. */
+ val SongsModel.isUnmatchedLocal: Boolean get() = url.startsWith(SPOTIFY_PREFIX)
+
+ /** A playlist row that is a file of this device (its play key is `local:<content uri>`). */
+ val SongsModel.isDeviceFile: Boolean get() = url.startsWith(DEVICE_PREFIX)
+
+ const val SPOTIFY_PREFIX = "spotify:local:"
+ const val DEVICE_PREFIX = "local:"
+
+ /** The play key of a device file, as the player names it. */
+ fun key(track: LocalTrack) = DEVICE_PREFIX + track.uri
+
+ /** Lengths this close are the same song: Spotify keeps whole seconds, the tags are not exact. */
+ private const val TOLERANCE_MS = 3_000L
+
+ private fun norm(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
+
+ /**
+ * The device file for [song]: same title, and same artist when both say one; the closest
+ * length wins, and a length off by more than [TOLERANCE_MS] is another recording.
+ */
+ fun find(song: SongsModel, files: List<LocalTrack>): LocalTrack? {
+ val title = norm(song.title)
+ if (title.isEmpty()) return null
+ val artist = norm(song.singer)
+ return files.asSequence()
+ .filter { norm(it.title) == title }
+ .filter { artist.isEmpty() || norm(it.artist).let { a -> a.isEmpty() || a in artist || artist in a } }
+ .filter { song.durationMs <= 0 || it.durationMs <= 0 || kotlin.math.abs(it.durationMs - song.durationMs) <= TOLERANCE_MS }
+ .minByOrNull { if (song.durationMs > 0) kotlin.math.abs(it.durationMs - song.durationMs) else 0L }
+ }
+
+ /** [songs] with their local-file rows switched to the matching device files, where there are. */
+ fun resolve(songs: List<SongsModel>, files: List<LocalTrack>): List<SongsModel> {
+ if (files.isEmpty() || songs.none { it.isUnmatchedLocal }) return songs
+ return songs.map { s ->
+ if (!s.isUnmatchedLocal) s else find(s, files)?.let { f ->
+ s.copy(
+ id = (key(f).hashCode() and 0x7fffffff),
+ url = key(f),
+ coverUri = f.artUri.toString(),
+ album = s.album.ifBlank { f.album },
+ durationMs = if (s.durationMs > 0) s.durationMs else f.durationMs.toInt(),
+ playable = true,
+ )
+ } ?: s
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.kt
index 150e0256..10256082 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveArtistScreen.kt
@@ -109,7 +109,7 @@ private val TrackColumnMaxWidth = 400.dp
private fun grouped(n: Long): String = "%,d".format(n)
/** "2024" or "2024-05-17" -> "2024". */
-private fun releaseYear(album: AlbumsModel): String = album.time.take(4)
+private fun releaseYear(album: AlbumsModel): String = album.year
/** "2024 · Single": what a release card says under its name. */
@Composable
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.kt
index 64c454be..0e24435b 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
@@ -691,7 +691,7 @@ private fun ReleaseCard(album: AlbumsModel, onClick: () -> Unit) {
Spacer(Modifier.height(6.dp))
Text(text = album.name, color = AppText, fontSize = 13.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
Text(
- text = album.time.ifBlank { album.artists }.let { if (album.time.isNotBlank()) "${album.time} • Album" else it },
+ text = album.year.ifBlank { album.artists }.let { if (album.year.isNotBlank()) "${album.year} • Album" else it },
color = AppMuted,
fontSize = 11.sp,
maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
@@ -754,7 +754,7 @@ private fun ShowAllButton(onClick: () -> Unit) {
}
/** Release-year helper: Spotify release dates come as "2024" or "2024-05-17". */
-private fun releaseYear(album: AlbumsModel): String = album.time.take(4)
+private fun releaseYear(album: AlbumsModel): String = album.year
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index 48da8787..da37e178 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -446,6 +446,26 @@ class ContextViewModel(
}
fun play(p: ContextPageModel, song: SongsModel, sort: TrackOrder = TrackOrder()) {
+ // Local files of the playlist (Spotify holds their tags only): one found on this device
+ // plays from there, with the other such files of the list; one not found cannot play,
+ // the next song that can does.
+ with(com.music.spotui.data.local.LocalFileMatch) {
+ val sorted = sort.apply(p.tracks)
+ if (song.isUnmatchedLocal) {
+ val after = sorted.drop(sorted.indexOfFirst { it.id == song.id && it.rowUid == song.rowUid } + 1)
+ val next = (after + sorted).firstOrNull { !it.isUnmatchedLocal } ?: return
+ return play(p, next, sort)
+ }
+ if (song.isDeviceFile) {
+ viewModelScope.launch {
+ val files = com.music.spotui.data.local.LocalMusic.tracks(Graph.app).associateBy { key(it) }
+ val list = sorted.mapNotNull { files[it.url] }
+ val at = list.indexOfFirst { key(it) == song.url }.coerceAtLeast(0)
+ if (list.isNotEmpty()) com.music.spotui.di.LocalPlayer.play(list, at, shuffle = state.shuffle.value, context = p.name, contextUri = p.uri)
+ }
+ return
+ }
+ }
// No connection (the Web Player cannot stream), or the data saver on mobile data:
// the page's downloaded songs play from the phone. Online, a downloaded song also plays
// from its file when the whole list is downloaded (it used to stream anyway).
@@ -484,7 +504,7 @@ class ContextViewModel(
if (p.type == "liked" || p.type == "liked-artist") SongPlayer.registerLikedSongs(p.tracks.map { it.url })
// Sorted by the user: Spotify plays the list in that order, not the playlist's. An
// artist's liked songs are a part of Liked Songs: always given, so only they play.
- val order = if (sort.isCustom && p.type != "liked-artist") null else sort.apply(p.tracks).map { "spotify:track:${it.spotifyTrackId}" }
+ val order = if (sort.isCustom && p.type != "liked-artist") null else sort.apply(p.tracks).filter { it.spotifyTrackId.isNotBlank() }.map { "spotify:track:${it.spotifyTrackId}" }
if (order != null) state.updateQueue(sort.apply(p.tracks))
// The audio-source extensions were asked already (or the phone is offline): Spotify plays.
SongPlayer.playSong(song.url, contextUri = p.uri, order = order, askExtensions = false)