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.

Likes through the library, artists without the Web API, more lyrics (#19)

Hector Zambranofd06eae633ba
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 8b68eb1..0eff15d 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -50,8 +50,8 @@ android {
// cpal's Android host is AAudio, which the ndk crate gates at API 26.
minSdk = 26
targetSdk = 35
- versionCode = 29
- versionName = "2.2.3"
+ versionCode = 30
+ versionName = "2.2.4"
buildConfigField("boolean", "VERBOSE_LOG", "false")
ndk {
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 83166f8..8f341e6 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -55,3 +55,7 @@
# the fully qualified class name.
-keepclasseswithmembernames class dev.lelonio.square.playback.Stretcher { native <methods>; }
-keep class dev.lelonio.square.playback.Stretcher { *; }
+
+# Preserve readable line numbers and stack traces in release builds
+-renamesourcefileattribute SourceFile
+-keepattributes SourceFile,LineNumberTable
diff --git a/app/src/main/baseline-prof.txt b/app/src/main/baseline-prof.txt
index 6dac8d9..43b5c2f 100644
--- a/app/src/main/baseline-prof.txt
+++ b/app/src/main/baseline-prof.txt
@@ -1,3 +1,7 @@
+# Baseline Profile for Square
+# Pre-compiles critical code ahead of time (AOT) to eliminate JIT pauses,
+# reduce cold-start latency, and maintain 60-120 FPS during initial gestures.
+#
# What to compile ahead of time, so the first fold of the bar is as smooth as
# the tenth.
#
@@ -6,15 +10,21 @@
# whole app to compile ahead of time on the phone took the same cold gesture
# from 43% dropped frames and 85ms at the 90th percentile to 28% and 57 — the
# same numbers a warm run gives. These rules ship that head start.
-#
-# Coarse on purpose. A generated profile would name individual methods, and it
-# would be out of date the next time the UI changes; the drawing and animation
-# packages are small enough that compiling them whole costs little and keeps
-# being right.
-# The whole interface, not a chosen part of it. The first version named the
-# glass, the player and the shared components, and left out the screens: home,
-# library and search are where the scrolling happens, so the one gesture the
-# profile exists for was running interpreted anyway.
-HSPLdev/lelonio/square/ui/**->**(**)**
-HSPLdev/lelonio/square/playback/**->**(**)**
-HSPLdev/lelonio/square/data/**->**(**)**
+
+# 1. Preload application and UI classes
+Ldev/lelonio/square/**;
+
+# 2. Jetpack Compose UI methods with complete signatures (Composer, bitmask, and return types)
+# Explicit signature with parameters and types ensures the AOT compiler does not silently discard the profile.
+HSPLdev/lelonio/square/ui/**;->*(**Landroidx/compose/runtime/Composer;*)V
+HSPLdev/lelonio/square/ui/**;->*(**Landroidx/compose/runtime/Composer;I)V
+HSPLdev/lelonio/square/ui/**;->*(**Landroidx/compose/runtime/Composer;II)V
+HSPLdev/lelonio/square/ui/**;->*(Landroidx/compose/runtime/Composer;I)V
+HSPLdev/lelonio/square/ui/**;->*(Landroidx/compose/runtime/Composer;II)V
+HSPLdev/lelonio/square/ui/**;->*(**Landroidx/compose/runtime/Composer;*)Lkotlin/Unit;
+HSPLdev/lelonio/square/ui/**;->*(**Landroidx/compose/runtime/Composer;*)**
+
+# 3. Whole UI, playback, and data layers
+HSPLdev/lelonio/square/ui/**;->*(**)**
+HSPLdev/lelonio/square/playback/**;->*(**)**
+HSPLdev/lelonio/square/data/**;->*(**)**
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 45cf052..5f4cd8a 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -141,6 +141,11 @@ class SquareApplication : Application(), ImageLoaderFactory {
/** Which playlists were opened most recently, for ordering the home page. */
val playlistOrder: PlaylistOrderStore by lazy { PlaylistOrderStore(this) }
+ /** Tracks the listener has liked ("Tus me gusta"). */
+ val likedStore: dev.lelonio.square.data.LikedStore by lazy {
+ dev.lelonio.square.data.LikedStore(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)
@@ -229,10 +234,23 @@ class SquareApplication : Application(), ImageLoaderFactory {
.build()
}
+ /**
+ * The account's country code (e.g. "ES", "MX", "US"), drawn from the authenticated
+ * account profile and cached in preferences. If the profile hasn't been fetched yet,
+ * falls back to the device's locale country, or "from_token".
+ */
+ val userCountry: String
+ get() = preferences.userCountry?.takeIf { it.length == 2 }?.uppercase()
+ ?: java.util.Locale.getDefault().country.takeIf { it.length == 2 }?.uppercase()
+ ?: "US"
+
val api: SpotifyApi by lazy {
ApiFactory.create(
tokens = webApi.tokens,
+ fallbackTokens = tokenStore,
+ nativeToken = { dev.lelonio.square.nativecore.NativeBridge.accessToken() },
baseClient = sharedHttpClient,
+ countryProvider = { userCountry },
debug = BuildConfig.DEBUG,
)
}
diff --git a/app/src/main/java/dev/lelonio/square/auth/SpotifyOAuth.kt b/app/src/main/java/dev/lelonio/square/auth/SpotifyOAuth.kt
index d6eec56..31eb6a8 100644
--- a/app/src/main/java/dev/lelonio/square/auth/SpotifyOAuth.kt
+++ b/app/src/main/java/dev/lelonio/square/auth/SpotifyOAuth.kt
@@ -11,11 +11,16 @@ import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
+import java.io.IOException
import java.net.InetAddress
+import java.net.InetSocketAddress
import java.net.ServerSocket
+import java.net.SocketException
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.job
/**
* Authorization Code + PKCE against Spotify's accounts service.
@@ -99,6 +104,17 @@ object SpotifyOAuth {
private val http = OkHttpClient()
private val random = SecureRandom()
+ @Volatile
+ private var activeReceiver: LoopbackReceiver? = null
+ private val authLock = Any()
+
+ fun cancelActiveAuthorization() {
+ synchronized(authLock) {
+ activeReceiver?.close()
+ activeReceiver = null
+ }
+ }
+
data class Tokens(
val accessToken: String,
val refreshToken: String?,
@@ -129,7 +145,20 @@ object SpotifyOAuth {
val challenge = challengeFor(verifier)
val state = randomState()
- LoopbackReceiver(REDIRECT_PORT, context.getString(R.string.browser_return)).use { receiver ->
+ // Cancel any pending receiver from an abandoned or previous attempt before binding
+ cancelActiveAuthorization()
+
+ val receiver = LoopbackReceiver(REDIRECT_PORT, context.getString(R.string.browser_return))
+ synchronized(authLock) {
+ activeReceiver = receiver
+ }
+
+ // When the coroutine completes or is cancelled, immediately unblock accept() by closing the socket
+ coroutineContext.job.invokeOnCompletion {
+ receiver.close()
+ }
+
+ receiver.use {
val redirectUri = receiver.redirectUri
// The port is ephemeral, so without this there is no way to tell a
// listener that never accepted from a browser that refused to load
@@ -252,8 +281,35 @@ private class LoopbackReceiver(port: Int, private val doneMessage: String) : Aut
* through it leaves nothing listening on `127.0.0.1` — which is the literal
* Spotify's registered redirect URIs use, and the browser then fails the
* redirect with ERR_CONNECTION_REFUSED.
+ *
+ * Enables SO_REUSEADDR and retries binding if the port was recently in TIME_WAIT.
*/
- private val server = ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"))
+ private val server: ServerSocket
+
+ init {
+ var boundServer: ServerSocket? = null
+ var lastEx: IOException? = null
+ for (attempt in 1..5) {
+ try {
+ boundServer = ServerSocket().apply {
+ reuseAddress = true
+ bind(InetSocketAddress(InetAddress.getByName("127.0.0.1"), port), 1)
+ soTimeout = REDIRECT_TIMEOUT_MS
+ }
+ break
+ } catch (e: IOException) {
+ lastEx = e
+ if (attempt < 5) {
+ try {
+ Thread.sleep(120L * attempt)
+ } catch (_: InterruptedException) {
+ break
+ }
+ }
+ }
+ }
+ server = boundServer ?: throw (lastEx ?: IOException("Unable to bind loopback on port $port"))
+ }
/** The one line the browser shows once the redirect lands, in the app's language. */
private val response: String = buildString {
@@ -269,13 +325,15 @@ private class LoopbackReceiver(port: Int, private val doneMessage: String) : Aut
val redirectUri: String =
"http://${server.inetAddress.hostAddress}:${server.localPort}/login"
- init {
- // If the user abandons the browser we must not leak the thread forever.
- server.soTimeout = REDIRECT_TIMEOUT_MS
- }
-
fun awaitRedirect(): Callback {
- val socket = server.accept()
+ val socket = try {
+ server.accept()
+ } catch (e: SocketException) {
+ if (server.isClosed) {
+ throw CancellationException("OAuth loopback receiver was closed", e)
+ }
+ throw e
+ }
socket.use {
val reader = it.getInputStream().bufferedReader()
val requestLine = reader.readLine() ?: error("empty redirect request")
@@ -302,6 +360,6 @@ private class LoopbackReceiver(port: Int, private val doneMessage: String) : Aut
}
private companion object {
- const val REDIRECT_TIMEOUT_MS = 5 * 60 * 1000
+ const val REDIRECT_TIMEOUT_MS = 2 * 60 * 1000
}
}
diff --git a/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt b/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt
index 7fc58ed..c088d3a 100644
--- a/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt
+++ b/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt
@@ -141,6 +141,18 @@ class TokenStore(
}
}
+ /**
+ * Forces an immediate token refresh against Spotify's accounts service,
+ * bypassing any unexpired cached token. Used on HTTP 401 Unauthorized.
+ */
+ suspend fun forceRefresh(): String = refreshLock.withLock {
+ val refreshToken = prefs.getString(KEY_REFRESH, null)
+ ?: error("not logged in")
+ val tokens = SpotifyOAuth.refresh(refreshToken, clientId())
+ save(tokens)
+ tokens.accessToken
+ }
+
private fun currentIfFresh(): String? {
val token = prefs.getString(KEY_ACCESS, null) ?: return null
val expiresAt = prefs.getLong(KEY_EXPIRES_AT, 0)
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 d6feceb..29befd1 100644
--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
@@ -130,7 +130,9 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
override suspend fun playlists(): List<CatalogPlaylist> =
likedSongs().let { liked ->
listOfNotNull(liked) +
- rootlist().filterNot { it.uri == liked?.uri || it.uri == Catalog.DJ_URI }
+ rootlist().filterNot {
+ it.uri == liked?.uri || it.uri == Catalog.DJ_URI || it.uri.startsWith("spotify:station:")
+ }
}
private suspend fun rootlist(): List<CatalogPlaylist> =
@@ -155,9 +157,23 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
*/
override suspend fun tracksOf(uri: String): List<CatalogTrack> = when {
uri.startsWith("spotify:artist:") -> {
- check(container.webApi.isReady) { "un artista richiede la tua applicazione Spotify" }
- container.api.artistTopTracks(uri.substringAfterLast(':')).tracks
- .map { it.toCatalogTrack() }
+ val id = uri.substringAfterLast(':')
+ val apiTracks = if (container.webApi.isReady) {
+ runCatching {
+ container.api.artistTopTracks(id, market = container.userCountry).tracks
+ .map { it.toCatalogTrack() }
+ }.getOrNull()?.takeIf { it.isNotEmpty() }
+ } else null
+
+ if (apiTracks != null) {
+ apiTracks
+ } else {
+ val webTracks = runCatching {
+ dev.lelonio.square.data.SpotifyWebArtist.fetch(id, container.sharedHttpClient, container.resources)?.tracks
+ }.getOrNull()?.takeIf { it.isNotEmpty() }
+
+ webTracks ?: Catalog.tracks(Catalog.contextTrackUris(uri).take(10))
+ }
}
// Spotify's own gateway first, for both of the lists it answers for:
@@ -207,7 +223,7 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
val loaded = mutableListOf<CatalogTrack>()
var offset = 0
while (true) {
- val page = container.api.playlistTracks(id, limit = WEB_API_PAGE, offset = offset)
+ val page = container.api.playlistTracks(id, limit = WEB_API_PAGE, offset = offset, market = container.userCountry)
// Episodes and delisted tracks arrive as a null track, and an
// unplayable one is something the engine could only skip.
loaded += page.items.mapNotNull { item ->
diff --git a/app/src/main/java/dev/lelonio/square/backend/lyrics/LrcLib.kt b/app/src/main/java/dev/lelonio/square/backend/lyrics/LrcLib.kt
index 8ff291a..a23b6e7 100644
--- a/app/src/main/java/dev/lelonio/square/backend/lyrics/LrcLib.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/lyrics/LrcLib.kt
@@ -22,7 +22,11 @@ import org.json.JSONObject
*/
object LrcLib {
- private val http = OkHttpClient()
+ private val http = OkHttpClient.Builder()
+ .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
+ .readTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
+ .callTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
+ .build()
/**
* @param durationMs used to tell versions apart — a single, an album cut and
@@ -32,28 +36,83 @@ object LrcLib {
suspend fun lyrics(title: String, artist: String, durationMs: Long): Lyrics? =
withContext(Dispatchers.IO) {
val cleaned = title.songTitle()
- val body = get(url(cleaned, artist, durationMs))
- // Retry without the duration before giving up: YouTube's own
- // duration includes any silence at the end of the upload, so an
- // exact-length match misses tracks LrcLib really does have.
- ?: get(url(cleaned, artist, durationMs = null))
- ?: return@withContext null
+ val primary = artist.primaryArtist()
- val json = runCatching { JSONObject(body) }.getOrNull() ?: return@withContext null
+ // 1. Exact match with cleaned title, full artist and duration
+ var body = get(url(cleaned, artist, durationMs))
- json.optString("syncedLyrics").takeIf { it.isNotBlank() }?.let { synced ->
- return@withContext parseLrc(synced)
+ // 2. Exact match with primary artist and duration
+ if (body == null && primary != artist) {
+ body = get(url(cleaned, primary, durationMs))
}
- json.optString("plainLyrics").takeIf { it.isNotBlank() }?.let { plain ->
- return@withContext Lyrics(
- lines = plain.lines()
- .filter { it.isNotBlank() }
- .map { LyricLine(startTimeMs = null, text = it.trim()) },
- synced = false,
- )
+
+ // 3. Exact match with primary artist without duration
+ if (body == null) {
+ body = get(url(cleaned, primary, durationMs = null))
+ }
+
+ if (body != null) {
+ parseJson(body)?.let { return@withContext it }
}
- null
+
+ // 4. Fallback search via /api/search when exact lookup misses
+ search(cleaned, primary, durationMs)
+ }
+
+ private fun parseJson(body: String): Lyrics? {
+ val json = runCatching { JSONObject(body) }.getOrNull() ?: return null
+
+ json.optString("syncedLyrics").takeIf { it.isNotBlank() }?.let { synced ->
+ return parseLrc(synced)
+ }
+ json.optString("plainLyrics").takeIf { it.isNotBlank() }?.let { plain ->
+ return parsePlain(plain)
}
+ return null
+ }
+
+ private fun parsePlain(plain: String): Lyrics = Lyrics(
+ lines = plain.lines()
+ .filter { it.isNotBlank() }
+ .map { LyricLine(startTimeMs = null, text = it.trim()) },
+ synced = false,
+ )
+
+ private fun search(title: String, artist: String, durationMs: Long): Lyrics? {
+ val query = "$title $artist".trim()
+ val searchUrl = "https://lrclib.net/api/search?q=" + java.net.URLEncoder.encode(query, "UTF-8")
+ val raw = get(searchUrl) ?: return null
+ val array = runCatching { org.json.JSONArray(raw) }.getOrNull() ?: return null
+ if (array.length() == 0) return null
+
+ val targetSec = durationMs / 1000.0
+ var bestSynced: Lyrics? = null
+ var bestPlain: Lyrics? = null
+ var minDiff = Double.MAX_VALUE
+
+ for (i in 0 until array.length().coerceAtMost(10)) {
+ val item = array.optJSONObject(i) ?: continue
+ val synced = item.optString("syncedLyrics").takeIf { it.isNotBlank() }
+ val plain = item.optString("plainLyrics").takeIf { it.isNotBlank() }
+ if (synced == null && plain == null) continue
+
+ val itemDuration = item.optDouble("duration", 0.0)
+ val diff = if (targetSec > 0 && itemDuration > 0) kotlin.math.abs(itemDuration - targetSec) else 0.0
+
+ if (synced != null) {
+ if (diff <= 4.0 && diff < minDiff) {
+ minDiff = diff
+ bestSynced = parseLrc(synced)
+ } else if (bestSynced == null) {
+ bestSynced = parseLrc(synced)
+ }
+ } else if (plain != null && bestPlain == null && diff <= 5.0) {
+ bestPlain = parsePlain(plain)
+ }
+ }
+
+ return bestSynced ?: bestPlain
+ }
private fun url(title: String, artist: String, durationMs: Long?): String = buildString {
append("https://lrclib.net/api/get?track_name=")
@@ -73,7 +132,7 @@ object LrcLib {
.header("User-Agent", USER_AGENT)
.build()
http.newCall(request).execute().use { response ->
- if (!response.isSuccessful) null else response.body?.string()
+ if (!response.isSuccessful) null else response.body.string()
}
}.getOrNull()
diff --git a/app/src/main/java/dev/lelonio/square/backend/lyrics/LyricsOvh.kt b/app/src/main/java/dev/lelonio/square/backend/lyrics/LyricsOvh.kt
new file mode 100644
index 0000000..daf04dc
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/backend/lyrics/LyricsOvh.kt
@@ -0,0 +1,70 @@
+package dev.lelonio.square.backend.lyrics
+
+import dev.lelonio.square.data.LyricLine
+import dev.lelonio.square.data.Lyrics
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import org.json.JSONObject
+import java.net.URLEncoder
+import java.util.concurrent.TimeUnit
+
+/**
+ * Fallback lyrics provider using the free and open Lyrics.ovh REST API.
+ *
+ * Useful for contemporary or regional tracks (e.g. Latin releases) that
+ * have not yet been synced to LRCLIB or Spotify Musixmatch.
+ */
+object LyricsOvh {
+
+ private val http = OkHttpClient.Builder()
+ .connectTimeout(4, TimeUnit.SECONDS)
+ .readTimeout(4, TimeUnit.SECONDS)
+ .callTimeout(6, TimeUnit.SECONDS)
+ .build()
+
+ private const val BASE_URL = "https://api.lyrics.ovh/v1"
+ private const val USER_AGENT = "SquareMusicApp/1.0"
+
+ suspend fun lyrics(title: String, artist: String, durationMs: Long): Lyrics? =
+ withContext(Dispatchers.IO) {
+ val cleanedTitle = title.songTitle()
+ if (cleanedTitle.isBlank()) return@withContext null
+
+ // Try each candidate artist (e.g. combined "CORKIDI, Alex Ponce", primary "CORKIDI", and featured "Alex Ponce")
+ val candidates = artist.allArtists()
+
+ for (candidate in candidates) {
+ val rawLyrics = fetch(cleanedTitle, candidate)
+ if (!rawLyrics.isNullOrBlank()) {
+ val lines = rawLyrics.lines()
+ .filter { it.isNotBlank() }
+ .map { LyricLine(startTimeMs = null, text = it.trim()) }
+ if (lines.isNotEmpty()) {
+ return@withContext Lyrics(lines, synced = false)
+ }
+ }
+ }
+
+ null
+ }
+
+ private fun fetch(title: String, artist: String): String? = runCatching {
+ val encodedArtist = URLEncoder.encode(artist, "UTF-8")
+ val encodedTitle = URLEncoder.encode(title, "UTF-8")
+ val url = "$BASE_URL/$encodedArtist/$encodedTitle"
+
+ val request = Request.Builder()
+ .url(url)
+ .header("User-Agent", USER_AGENT)
+ .build()
+
+ http.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) return null
+ val body = response.body.string()
+ val json = JSONObject(body)
+ json.optString("lyrics").takeIf { it.isNotBlank() }
+ }
+ }.getOrNull()
+}
diff --git a/app/src/main/java/dev/lelonio/square/backend/lyrics/NetEase.kt b/app/src/main/java/dev/lelonio/square/backend/lyrics/NetEase.kt
new file mode 100644
index 0000000..e4b8c91
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/backend/lyrics/NetEase.kt
@@ -0,0 +1,145 @@
+package dev.lelonio.square.backend.lyrics
+
+import dev.lelonio.square.data.LyricLine
+import dev.lelonio.square.data.Lyrics
+import java.net.URLEncoder
+import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import org.json.JSONObject
+
+/**
+ * High-accuracy synchronized LRC lyrics provider backed by NetEase Cloud Music's
+ * extensive global library.
+ *
+ * Provides millisecond-accurate timestamps for millions of tracks that might be missing
+ * or unsynced on Spotify and LRCLIB.
+ */
+object NetEase {
+
+ private val http = OkHttpClient.Builder()
+ .callTimeout(4, TimeUnit.SECONDS)
+ .build()
+
+ private const val SEARCH_URL = "https://music.163.com/api/search/pc"
+ private const val LYRIC_URL = "https://music.163.com/api/song/lyric"
+ private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ private const val COOKIE = "os=pc; NMTID=00OAVK3xqDG726ITU6jopU6jF2yMk0AAAGCO8l1BA;"
+
+ suspend fun lyrics(
+ title: String,
+ artist: String,
+ durationMs: Long,
+ ): Lyrics? = withContext(Dispatchers.IO) {
+ val cleanTitle = title.songTitle()
+ val artists = artist.allArtists()
+
+ for (candidateArtist in artists) {
+ val result = query(cleanTitle, candidateArtist, durationMs)
+ if (result != null) return@withContext result
+ }
+
+ // If not found with separate artists, try cleanTitle alone
+ if (artists.size > 1) {
+ query(cleanTitle, "", durationMs)?.let { return@withContext it }
+ }
+
+ null
+ }
+
+ private fun query(title: String, artist: String, durationMs: Long): Lyrics? {
+ val q = if (artist.isBlank()) title else "$title $artist"
+ val searchEncoded = runCatching { URLEncoder.encode(q, "UTF-8") }.getOrNull() ?: return null
+ val searchReq = Request.Builder()
+ .url("$SEARCH_URL?s=$searchEncoded&type=1&offset=0&limit=5")
+ .header("User-Agent", USER_AGENT)
+ .header("Referer", "https://music.163.com")
+ .header("Cookie", COOKIE)
+ .build()
+
+ val searchBody = runCatching {
+ http.newCall(searchReq).execute().use { resp ->
+ if (resp.isSuccessful) resp.body.string() else null
+ }
+ }.getOrNull() ?: return null
+
+ val root = runCatching { JSONObject(searchBody) }.getOrNull() ?: return null
+ val songs = root.optJSONObject("result")?.optJSONArray("songs") ?: return null
+ if (songs.length() == 0) return null
+
+ var bestSongId: Long? = null
+ var minDiff = Long.MAX_VALUE
+
+ val targetArtistLower = artist.lowercase().trim()
+ val hasTargetArtist = targetArtistLower.isNotEmpty()
+
+ for (i in 0 until songs.length().coerceAtMost(10)) {
+ val song = songs.optJSONObject(i) ?: continue
+ val id = song.optLong("id")
+ if (id <= 0) continue
+
+ val songArtists = (0 until (song.optJSONArray("artists")?.length() ?: 0)).mapNotNull {
+ song.optJSONArray("artists")?.optJSONObject(it)?.optString("name")?.lowercase()
+ }
+ val matchesArtist = !hasTargetArtist || songArtists.any { it.contains(targetArtistLower) || targetArtistLower.contains(it) }
+
+ // If we have a target artist, skip songs that don't match it
+ if (hasTargetArtist && !matchesArtist) continue
+
+ val songDur = song.optLong("duration", 0L)
+ val diff = if (durationMs > 0 && songDur > 0) kotlin.math.abs(songDur - durationMs) else 0L
+
+ if (diff < minDiff) {
+ minDiff = diff
+ bestSongId = id
+ }
+ }
+
+ // Only accept if duration is close (within 8 seconds) or duration wasn't specified
+ if (durationMs > 0 && minDiff > 8000L && bestSongId != null) {
+ return null
+ }
+
+ val targetId = bestSongId ?: return null
+ val lyricReq = Request.Builder()
+ .url("$LYRIC_URL?id=$targetId&lv=1&kv=1&tv=-1")
+ .header("User-Agent", USER_AGENT)
+ .header("Referer", "https://music.163.com")
+ .build()
+
+ val lyricBody = runCatching {
+ http.newCall(lyricReq).execute().use { resp ->
+ if (resp.isSuccessful) resp.body.string() else null
+ }
+ }.getOrNull() ?: return null
+
+ val lyricRoot = runCatching { JSONObject(lyricBody) }.getOrNull() ?: return null
+ val rawLrc = lyricRoot.optJSONObject("lrc")?.optString("lyric")?.takeIf { it.isNotBlank() }
+ ?: return null
+
+ return parseLrc(rawLrc)
+ }
+
+ private fun parseLrc(raw: String): Lyrics? {
+ val lines = raw.lines().mapNotNull { line ->
+ val match = LRC_LINE.find(line) ?: return@mapNotNull null
+ val (minutes, seconds, fraction, text) = match.destructured
+ val startMs = minutes.toLong() * 60_000 +
+ seconds.toLong() * 1_000 +
+ fraction.padEnd(3, '0').take(3).toLong()
+
+ val cleanText = text.trim()
+ // Filter out metadata lines like [00:00.00] 作曲 : ...
+ if (cleanText.startsWith("作词") || cleanText.startsWith("作曲") || cleanText.startsWith("编曲")) {
+ return@mapNotNull null
+ }
+ LyricLine(startTimeMs = startMs, text = cleanText)
+ }.filter { it.text.isNotBlank() }
+
+ return lines.takeIf { it.isNotEmpty() }?.let { Lyrics(it, synced = true) }
+ }
+
+ private val LRC_LINE = Regex("\\[(\\d{1,2}):(\\d{2})[.:](\\d{2,3})\\](.*)")
+}
diff --git a/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt b/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt
index bf7e9be..4c19a43 100644
--- a/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/lyrics/SpotifyLyrics.kt
@@ -27,6 +27,11 @@ object SpotifyLyrics {
private val json = Json { ignoreUnknownKeys = true }
+ private class Cached(val lyrics: Lyrics?)
+
+ /** Fast session cache so repeat views or replay during playback cost 0ms and 0 network. */
+ private val sessionCache = object : android.util.LruCache<String, Cached>(64) {}
+
/**
* @param allowNetwork false offline, where the only lyrics are the kept ones.
*/
@@ -39,9 +44,21 @@ object SpotifyLyrics {
): Lyrics? {
if (!allowNetwork) return kept(uri)
+ sessionCache.get(uri)?.let { return it.lyrics }
+
+ kept(uri)?.let {
+ sessionCache.put(uri, Cached(it))
+ return it
+ }
+
val found = Amll.lyrics(uri)
?: Lossless.lyrics(title, artist, durationMs)
?: Catalog.lyrics(uri)
+ ?: LrcLib.lyrics(title, artist, durationMs)
+ ?: NetEase.lyrics(title, artist, durationMs)
+ ?: LyricsOvh.lyrics(title, artist, durationMs)
+
+ sessionCache.put(uri, Cached(found))
return withContext(Dispatchers.IO) {
// Nothing found is an answer worth keeping too, so a downloaded
@@ -49,7 +66,7 @@ object SpotifyLyrics {
// queue; see DownloadExtras.note.
if (found == null) {
DownloadExtras.note("lyrics", uri)
- return@withContext kept(uri)
+ return@withContext null
}
runCatching { DownloadExtras.rememberLyrics(uri, json.encodeToString(found)) }
found
diff --git a/app/src/main/java/dev/lelonio/square/backend/lyrics/TrackTitle.kt b/app/src/main/java/dev/lelonio/square/backend/lyrics/TrackTitle.kt
index 84b8107..24bdbc1 100644
--- a/app/src/main/java/dev/lelonio/square/backend/lyrics/TrackTitle.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/lyrics/TrackTitle.kt
@@ -9,11 +9,67 @@ package dev.lelonio.square.backend.lyrics
* want the same cleaning.
*/
internal fun String.songTitle(): String =
- replace(NOISE, "").replace(WHITESPACE, " ").trim()
+ replace(NOISE, "")
+ .replace(FEAT_NOISE, "")
+ .replace(EDITION_NOISE, "")
+ .replace(WHITESPACE, " ")
+ .trim()
+
+/**
+ * Extracts the lead artist from collaboration strings like "Artist A, Artist B"
+ * or "Artist A feat. Artist B", which lyrics databases often file under the primary name.
+ */
+internal fun String.primaryArtist(): String =
+ split(',', '&', '/', ';')
+ .firstOrNull { it.isNotBlank() }
+ ?.replace(FEAT_TRAILING, "")
+ ?.trim()
+ ?.ifEmpty { this.trim() }
+ ?: this.trim()
+
+/**
+ * Extracts all distinct artists from collaboration strings like "Artist A, Artist B",
+ * "Artist A & Artist B", or "Artist A feat. Artist B".
+ */
+internal fun String.allArtists(): List<String> {
+ val candidates = mutableListOf<String>()
+ val raw = this.trim()
+ if (raw.isNotBlank()) candidates += raw
+
+ val splitArtists = split(',', '&', '/', ';')
+ .flatMap { part ->
+ part.split(Regex("\\s+(?:feat|ft)\\.?\\s+", RegexOption.IGNORE_CASE))
+ }
+ .map { it.trim() }
+ .filter { it.isNotBlank() }
+
+ for (artist in splitArtists) {
+ if (artist !in candidates) {
+ candidates += artist
+ }
+ }
+ return candidates
+}
private val NOISE = Regex(
"\\((?:official|lyric|audio|video|visualizer|hd|4k|mv|m/v)[^)]*\\)" +
"|\\[[^\\]]*(?:official|lyric|audio|video|remaster|hd|4k)[^\\]]*\\]",
RegexOption.IGNORE_CASE,
)
+
+private val FEAT_NOISE = Regex(
+ "\\s*\\((?:feat|ft)\\.?\\s+[^)]+\\)|\\s*\\[(?:feat|ft)\\.?\\s+[^\\]]+\\]",
+ RegexOption.IGNORE_CASE,
+)
+
+private val FEAT_TRAILING = Regex(
+ "\\s+(?:feat|ft)\\.?\\s+.*",
+ RegexOption.IGNORE_CASE,
+)
+
+private val EDITION_NOISE = Regex(
+ "\\s*-\\s*(?:(?:\\d{4}\\s+)?remaster(?:ed)?|live(?:\\s+at\\s+[^\\-]+)?|anniversary(?:\\s+edition)?|deluxe(?:\\s+edition)?|radio\\s+edit|mono|stereo|bonus\\s+track).*",
+ RegexOption.IGNORE_CASE,
+)
+
private val WHITESPACE = Regex("\\s+")
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
index 7303690..4e38068 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
@@ -9,10 +9,15 @@ import dev.lelonio.square.backend.PlaybackHost
import dev.lelonio.square.backend.SearchLabels
import dev.lelonio.square.backend.lyrics.LrcLib
import dev.lelonio.square.backend.lyrics.Lossless
+import dev.lelonio.square.backend.lyrics.LyricsOvh
import dev.lelonio.square.data.CatalogPlaylist
import dev.lelonio.square.data.CatalogTrack
+import dev.lelonio.square.data.Lyrics
import dev.lelonio.square.data.SearchItem
import dev.lelonio.square.data.SearchResults
+import dev.lelonio.square.download.DownloadExtras
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.encodeToString
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -334,13 +339,27 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
* smaller of the two, so it is asked first and LrcLib carries the rest of
* the catalogue as it did before.
*/
+ private val lyricsJson = Json { ignoreUnknownKeys = true }
+
override suspend fun lyrics(
uri: String,
title: String,
artist: String,
durationMs: Long,
- ) = Lossless.lyrics(title, artist, durationMs)
- ?: LrcLib.lyrics(title, artist, durationMs)
+ ): Lyrics? {
+ DownloadExtras.lyrics(uri)?.let { raw ->
+ runCatching { lyricsJson.decodeFromString<Lyrics>(raw) }.getOrNull()?.let { return it }
+ }
+
+ val found = Lossless.lyrics(title, artist, durationMs)
+ ?: LrcLib.lyrics(title, artist, durationMs)
+ ?: LyricsOvh.lyrics(title, artist, durationMs)
+
+ if (found != null) {
+ runCatching { DownloadExtras.rememberLyrics(uri, lyricsJson.encodeToString(found)) }
+ }
+ return found
+ }
override val canEditPlaylists: Boolean
get() = account.isSignedIn
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt
new file mode 100644
index 0000000..af77f15
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeFadeController.kt
@@ -0,0 +1,140 @@
+package dev.lelonio.square.backend.youtube
+
+import androidx.media3.common.MediaItem
+import androidx.media3.common.Player
+import androidx.media3.exoplayer.ExoPlayer
+import dev.lelonio.square.data.CrossfadeStore
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlin.math.PI
+import kotlin.math.sin
+
+/**
+ * Manages smooth volume transitions (fade out / fade in) between tracks on YouTube Music.
+ *
+ * ExoPlayer plays gapless sequentially; this controller applies equal-power volume
+ * shaping as a track nears its end, and smoothly ramps the next track up upon transition.
+ */
+class YouTubeFadeController(
+ private val player: ExoPlayer,
+ private val crossfadeStore: CrossfadeStore?,
+) : Player.Listener {
+
+ private val scope = CoroutineScope(Dispatchers.Main.immediate)
+ private var tickerJob: Job? = null
+ private var rampJob: Job? = null
+ private var isFadingOut = false
+
+ init {
+ player.addListener(this)
+ }
+
+ override fun onPlaybackStateChanged(playbackState: Int) {
+ if (playbackState == Player.STATE_READY && player.playWhenReady) {
+ startTicker()
+ } else if (playbackState == Player.STATE_ENDED || playbackState == Player.STATE_IDLE) {
+ stopTicker()
+ resetVolume()
+ }
+ }
+
+ override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
+ if (playWhenReady && player.playbackState == Player.STATE_READY) {
+ startTicker()
+ } else {
+ stopTicker()
+ }
+ }
+
+ override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
+ isFadingOut = false
+ val fadeMs = crossfadeStore?.durationMs() ?: 0
+ if (fadeMs > 0) {
+ rampUp(minOf(fadeMs / 2, 1500))
+ } else {
+ resetVolume()
+ }
+ }
+
+ override fun onPositionDiscontinuity(
+ oldPosition: Player.PositionInfo,
+ newPosition: Player.PositionInfo,
+ reason: Int,
+ ) {
+ if (reason == Player.DISCONTINUITY_REASON_SEEK) {
+ isFadingOut = false
+ resetVolume()
+ }
+ }
+
+ private fun startTicker() {
+ if (tickerJob?.isActive == true) return
+ tickerJob = scope.launch {
+ while (isActive) {
+ checkFade()
+ delay(80)
+ }
+ }
+ }
+
+ private fun stopTicker() {
+ tickerJob?.cancel()
+ tickerJob = null
+ }
+
+ private fun checkFade() {
+ val fadeMs = crossfadeStore?.durationMs() ?: 0
+ if (fadeMs <= 0) {
+ if (player.volume != 1f) player.volume = 1f
+ return
+ }
+
+ if (rampJob?.isActive == true) return
+
+ val duration = player.duration
+ val position = player.currentPosition
+ if (duration <= 0 || position <= 0 || duration <= fadeMs) return
+
+ val remaining = duration - position
+ if (remaining in 1..fadeMs) {
+ isFadingOut = true
+ val x = remaining.toFloat() / fadeMs.toFloat()
+ // Equal-power curve: sin(x * pi / 2) so remaining=fadeMs -> 1.0, remaining=0 -> 0.0
+ val volume = sin(x * (PI.toFloat() / 2f)).coerceIn(0f, 1f)
+ player.volume = volume
+ } else if (!isFadingOut && player.volume < 1f) {
+ player.volume = 1f
+ }
+ }
+
+ private fun rampUp(durationMs: Int) {
+ rampJob?.cancel()
+ if (durationMs <= 0) {
+ resetVolume()
+ return
+ }
+ player.volume = 0f
+ rampJob = scope.launch {
+ val steps = 20
+ val stepDelay = (durationMs / steps).toLong().coerceAtLeast(10L)
+ for (i in 1..steps) {
+ if (!isActive) break
+ val x = i.toFloat() / steps.toFloat()
+ // Equal-power fade in
+ val volume = sin(x * (PI.toFloat() / 2f)).coerceIn(0f, 1f)
+ player.volume = volume
+ delay(stepDelay)
+ }
+ player.volume = 1f
+ }
+ }
+
+ private fun resetVolume() {
+ rampJob?.cancel()
+ player.volume = 1f
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
index 8f3c0fc..487eae5 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt
@@ -23,29 +23,47 @@ import org.schabi.newpipe.extractor.stream.StreamInfo
@UnstableApi
object YouTubePlayerFactory {
- fun create(host: PlaybackHost): Player = ExoPlayer.Builder(host.context, renderers(host))
- .setMediaSourceFactory(
- DefaultMediaSourceFactory(
- ResolvingDataSource.Factory(
- DefaultHttpDataSource.Factory(),
- YouTubeStreamResolver(),
+ fun create(host: PlaybackHost): Player {
+ val loadControl = androidx.media3.exoplayer.DefaultLoadControl.Builder()
+ .setBufferDurationsMs(
+ /* minBufferMs = */ 30_000,
+ /* maxBufferMs = */ 60_000,
+ /* bufferForPlaybackMs = */ 500,
+ /* bufferForPlaybackAfterRebufferMs = */ 1_500,
+ )
+ .setPrioritizeTimeOverSizeThresholds(true)
+ .build()
+
+ val crossfadeStore = (host.context.applicationContext as? dev.lelonio.square.SquareApplication)?.crossfade
+
+ return ExoPlayer.Builder(host.context, renderers(host))
+ .setMediaSourceFactory(
+ DefaultMediaSourceFactory(
+ ResolvingDataSource.Factory(
+ DefaultHttpDataSource.Factory(),
+ YouTubeStreamResolver(),
+ ),
),
- ),
- )
- .setHandleAudioBecomingNoisy(true)
- // Ducks and pauses for whatever else wants the speaker. The Spotify
- // path gets this from its own output; ExoPlayer will not ask for focus
- // at all unless it is told to handle it.
- .setAudioAttributes(
- androidx.media3.common.AudioAttributes.Builder()
- .setUsage(androidx.media3.common.C.USAGE_MEDIA)
- .setContentType(androidx.media3.common.C.AUDIO_CONTENT_TYPE_MUSIC)
- .build(),
- /* handleAudioFocus = */ true,
- )
- .setLooper(host.looper)
- .build()
- .apply { addAnalyticsListener(Diagnostics) }
+ )
+ .setLoadControl(loadControl)
+ .setHandleAudioBecomingNoisy(true)
+ // Ducks and pauses for whatever else wants the speaker. The Spotify
+ // path gets this from its own output; ExoPlayer will not ask for focus
+ // at all unless it is told to handle it.
+ .setAudioAttributes(
+ androidx.media3.common.AudioAttributes.Builder()
+ .setUsage(androidx.media3.common.C.USAGE_MEDIA)
+ .setContentType(androidx.media3.common.C.AUDIO_CONTENT_TYPE_MUSIC)
+ .build(),
+ /* handleAudioFocus = */ true,
+ )
+ .setLooper(host.looper)
+ .build()
+ .apply {
+ addAnalyticsListener(Diagnostics)
+ YouTubeFadeController(this, crossfadeStore)
+ }
+ }
/** Temporary: chasing a stall where the position stops with the sink idle. */
private object Diagnostics : androidx.media3.exoplayer.analytics.AnalyticsListener {
diff --git a/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt b/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
index 5238ba8..8da0265 100644
--- a/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
+++ b/app/src/main/java/dev/lelonio/square/data/ApiFactory.kt
@@ -4,6 +4,7 @@ import dev.lelonio.square.auth.TokenStore
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.OkHttpClient
import okhttp3.Interceptor
import okhttp3.Response
@@ -39,15 +40,21 @@ object ApiFactory {
*/
fun create(
tokens: TokenStore,
+ fallbackTokens: TokenStore? = null,
+ nativeToken: (() -> String?)? = null,
baseClient: OkHttpClient? = null,
+ countryProvider: (() -> String)? = null,
debug: Boolean = false,
): SpotifyApi {
- val client = (baseClient?.newBuilder() ?: OkHttpClient.Builder())
- .addInterceptor(AuthInterceptor(tokens))
+ val clientBuilder = (baseClient?.newBuilder() ?: OkHttpClient.Builder())
+ .addInterceptor(AuthInterceptor(tokens, fallbackTokens, nativeToken))
.addInterceptor(RateLimitInterceptor())
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.apply {
+ if (countryProvider != null) {
+ addInterceptor(MarketInterceptor(countryProvider))
+ }
if (debug) {
addInterceptor(
okhttp3.logging.HttpLoggingInterceptor().setLevel(
@@ -56,16 +63,55 @@ object ApiFactory {
)
}
}
- .build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
- .client(client)
+ .client(clientBuilder.build())
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
.create(SpotifyApi::class.java)
}
+ /**
+ * Injects the listener's account market into Spotify catalog endpoints when
+ * no explicit market parameter is present.
+ *
+ * Without a market parameter on endpoints like playlist tracks or album tracks,
+ * Spotify returns the raw catalog item without regional track relinking, which
+ * causes tracks to appear unplayable or missing for users outside the US.
+ */
+ private class MarketInterceptor(
+ private val countryProvider: () -> String,
+ ) : Interceptor {
+ override fun intercept(chain: Interceptor.Chain): Response {
+ val request = chain.request()
+ val url = request.url
+ val path = url.encodedPath
+
+ if (url.queryParameter("market") == null && shouldAddMarket(path)) {
+ val raw = countryProvider()
+ val country = raw.takeIf { it.length == 2 && it.all(Char::isLetter) && it != "from_token" }
+ ?: java.util.Locale.getDefault().country.takeIf { it.length == 2 && it.all(Char::isLetter) }
+ ?: "US"
+ val newUrl = url.newBuilder()
+ .addQueryParameter("market", country.uppercase())
+ .build()
+ return chain.proceed(request.newBuilder().url(newUrl).build())
+ }
+ return chain.proceed(request)
+ }
+
+ private fun shouldAddMarket(path: String): Boolean {
+ return (path.startsWith("/v1/playlists/") && path.endsWith("/tracks")) ||
+ (path.startsWith("/v1/artists/") && path.endsWith("/top-tracks")) ||
+ (path.startsWith("/v1/artists/") && path.endsWith("/albums")) ||
+ path.startsWith("/v1/albums/") ||
+ path.startsWith("/v1/tracks/") ||
+ path == "/v1/search"
+ }
+ }
+
+
/**
* Waits out a single 429 when Spotify says how long to wait.
*
@@ -109,38 +155,110 @@ object ApiFactory {
private companion object {
/**
- * Spotify's back-offs on this client id run to tens of seconds.
- * Blocking a background OkHttp thread that long is cheaper than
- * showing an error the user can only answer by tapping retry —
- * which costs another request against the same quota.
+ * Short back-offs (<=3s) can be waited out safely.
+ * Longer back-offs should not block OkHttp dispatcher threads so that
+ * subsequent requests and fallbacks can proceed without hanging the UI.
*/
- const val MAX_WAIT_SECONDS = 90L
+ const val MAX_WAIT_SECONDS = 3L
const val TAG = "SquareApi"
}
}
- private class AuthInterceptor(private val tokens: TokenStore) : Interceptor {
+ private class AuthInterceptor(
+ private val tokens: TokenStore,
+ private val fallbackTokens: TokenStore? = null,
+ private val nativeToken: (() -> String?)? = null,
+ ) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
- // OkHttp interceptors are blocking by contract and always run on a
- // background thread, so bridging into the suspending token store
- // with runBlocking is safe here.
- //
- // Everything must leave as an IOException: OkHttp's async dispatcher
- // only routes IOException to onFailure and rethrows anything else on
- // its own thread, which takes the whole process down instead of
- // failing the one call.
- val token = try {
- runBlocking { tokens.validAccessToken() }
+ try {
+ return proceedWithAuth(chain)
} catch (e: IOException) {
throw e
} catch (e: Exception) {
- throw IOException("could not obtain a Spotify access token", e)
+ throw IOException("AuthInterceptor failed: ${e.message}", e)
}
+ }
- val request = chain.request().newBuilder()
- .header("Authorization", "Bearer $token")
- .build()
- return chain.proceed(request)
+ private fun proceedWithAuth(chain: Interceptor.Chain): Response {
+ val candidates = buildList<Candidate> {
+ if (tokens.isLoggedIn) {
+ add(Candidate("webApi", tokens))
+ }
+ if (fallbackTokens?.isLoggedIn == true) {
+ add(Candidate("account", fallbackTokens))
+ }
+ if (nativeToken != null) {
+ add(Candidate("native", null, nativeToken))
+ }
+ }
+
+ if (candidates.isEmpty()) {
+ throw IOException("No Spotify access token available; user is not logged in")
+ }
+
+ var lastResponse: Response? = null
+
+ for ((index, candidate) in candidates.withIndex()) {
+ val token = runCatching {
+ runBlocking { candidate.getToken() }
+ }.getOrNull()
+
+ if (token == null) continue
+
+ val request = chain.request().newBuilder()
+ .header("Authorization", "Bearer $token")
+ .build()
+
+ android.util.Log.i("SquareApi", "-> ${request.method} ${request.url} [candidate: ${candidate.name}]")
+ var response = chain.proceed(request)
+ android.util.Log.i("SquareApi", "<- ${response.code} ${request.url} [candidate: ${candidate.name}]")
+ if (!response.isSuccessful) {
+ val peek = runCatching { response.peekBody(512).string() }.getOrNull()
+ android.util.Log.w("SquareApi", "<- error body: $peek")
+ }
+
+ // If 401 Unauthorized, try forcing an immediate refresh on this token store once
+ if (response.code == 401 && candidate.store != null) {
+ val refreshed = runCatching {
+ runBlocking { candidate.store.forceRefresh() }
+ }.getOrNull()
+ if (refreshed != null) {
+ response.close()
+ val retryRequest = chain.request().newBuilder()
+ .header("Authorization", "Bearer $refreshed")
+ .build()
+ response = chain.proceed(retryRequest)
+ }
+ }
+
+ // If successful or an expected response (not 401 Unauthorized and not 403 Forbidden when candidates remain), return it.
+ // 429 Rate Limited is handled by RateLimitInterceptor waiting out backoff; switching credentials on 429 risks account flagging.
+ if (response.isSuccessful || (response.code != 401 && response.code != 403)) {
+ return response
+ }
+
+ val hasMoreCandidates = index < candidates.lastIndex
+ if (hasMoreCandidates) {
+ android.util.Log.w("SquareApi", "HTTP ${response.code} with ${candidate.name} token; closing response and trying next candidate")
+ response.close()
+ } else {
+ lastResponse = response
+ }
+ }
+
+ return lastResponse ?: chain.proceed(chain.request())
+ }
+
+ private class Candidate(
+ val name: String,
+ val store: TokenStore?,
+ val supplier: (() -> String?)? = null,
+ ) {
+ suspend fun getToken(): String? = when {
+ store != null -> store.validAccessToken()
+ supplier != null -> supplier.invoke()
+ else -> null
+ }
}
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt b/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt
index c5c51ec..85a2095 100644
--- a/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt
+++ b/app/src/main/java/dev/lelonio/square/data/AppleCatalog.kt
@@ -84,8 +84,14 @@ object AppleCatalog {
"apple-catalog-v7",
android.content.Context.MODE_PRIVATE,
)
+ // Stored weakly: this object lives for the process lifetime and must not
+ // hold a strong reference to anything from a Context chain.
+ connectivityRef = java.lang.ref.WeakReference(
+ context.applicationContext.getSystemService(android.net.ConnectivityManager::class.java),
+ )
}
+
private fun remembered(key: String): String? {
val prefs = store ?: return null
val row = prefs.getString(key, null) ?: return null
@@ -108,9 +114,34 @@ object AppleCatalog {
* remembered as one: the answer offline is "not here yet", not "there is
* none", and caching the first would keep the picture away for the rest of
* the run.
+ *
+ * Also gated on the connection being unmetered (Wi-Fi or ethernet). Apple's
+ * catalogue exists to enrich the visual experience — the app works correctly
+ * without it — and reaching out for large editorial photos over mobile data
+ * is not a trade the listener has agreed to. A cached answer is always used
+ * regardless of connection type; only a live lookup is skipped.
*/
- private fun mayAsk(): Boolean =
- !dev.lelonio.square.playback.OfflineMode.active.value
+ private fun mayAsk(): Boolean {
+ if (dev.lelonio.square.playback.OfflineMode.active.value) return false
+ // Check metered status via the connectivity service.
+ val connectivity = connectivityRef?.get()
+ if (connectivity != null) {
+ val caps = connectivity.activeNetwork
+ ?.let(connectivity::getNetworkCapabilities)
+ // If we cannot determine the connection type, err on the side of
+ // caution and allow the request (same behaviour as before this check).
+ if (caps != null &&
+ !caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
+ ) {
+ return false
+ }
+ }
+ return true
+ }
+
+ /** Held weakly so AppleCatalog (an object) does not leak a Context. */
+ private var connectivityRef: java.lang.ref.WeakReference<android.net.ConnectivityManager>? = null
+
private fun remember(key: String, value: String) {
store?.edit()?.putString(key, System.currentTimeMillis().toString() + "\n" + value)?.apply()
diff --git a/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
index 8297196..d2de12e 100644
--- a/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
@@ -437,6 +437,36 @@ class DownloadStore(context: Context) {
}
}
+ /** Adds one track to the automatic download of liked songs. */
+ suspend fun addLiked(track: CatalogTrack) {
+ val existing = _owners.value[LIKED].orEmpty()
+ if (existing.contains(track.uri)) return
+ writeLock.withLock {
+ ensureLoaded()
+ val current = _index.value
+ publish(
+ current.copy(
+ owners = current.owners + (LIKED to existing + track.uri),
+ tracks = current.tracks + (track.uri to track),
+ failures = current.failures - track.uri,
+ ),
+ )
+ save()
+ }
+ }
+
+ /** Removes one track from the automatic download of liked songs. */
+ suspend fun removeLiked(trackUri: String) {
+ val existing = _owners.value[LIKED].orEmpty()
+ if (!existing.contains(trackUri)) return
+ writeLock.withLock {
+ ensureLoaded()
+ val current = _index.value
+ publish(current.copy(owners = current.owners + (LIKED to existing - trackUri)))
+ save()
+ }
+ }
+
/**
* Forgets an owner. What it was alone in wanting is left for [pruneOrphans].
*
@@ -460,7 +490,10 @@ class DownloadStore(context: Context) {
// ---------------------------------------------------- what the queue says
fun onProgress(trackUri: String, fraction: Float) {
- _progress.value = _progress.value + (trackUri to fraction.coerceIn(0f, 1f))
+ val current = _progress.value[trackUri]
+ val clamped = fraction.coerceIn(0f, 1f)
+ if (current != null && Math.abs(clamped - current) < 0.01f && clamped < 1f) return
+ _progress.value = _progress.value + (trackUri to clamped)
}
/**
@@ -533,7 +566,7 @@ class DownloadStore(context: Context) {
val claimed = current.owners.values.flatten().toSet()
val orphaned = current.files.keys.filterNot(claimed::contains)
- val strandedTracks = current.tracks.keys.filterNot(claimed::contains)
+ val strandedTracks = current.tracks.keys.filterNot { claimed.contains(it) || current.files.containsKey(it) }
if (orphaned.isEmpty() && strandedTracks.isEmpty()) return@withLock emptyList()
publish(
diff --git a/app/src/main/java/dev/lelonio/square/data/LikedStore.kt b/app/src/main/java/dev/lelonio/square/data/LikedStore.kt
new file mode 100644
index 0000000..95a9dab
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/LikedStore.kt
@@ -0,0 +1,79 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+/**
+ * Tracks the listener has liked ("Tus me gusta").
+ *
+ * Persisted on this device and updated whenever a heart is added or removed,
+ * so the notification, the lock screen and the player share one state without
+ * waiting on a network round-trip.
+ */
+class LikedStore(context: Context) {
+
+ private val prefs = context.applicationContext
+ .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val saveLock = Mutex()
+
+ private val _liked = MutableStateFlow(load())
+ val likedTracks: StateFlow<Set<String>> = _liked.asStateFlow()
+
+ fun isLiked(uri: String?): Boolean = uri != null && uri in _liked.value
+
+ fun seed(uris: Collection<String>) {
+ if (uris.isEmpty()) return
+ val updated = _liked.value + uris
+ if (updated.size != _liked.value.size) {
+ _liked.value = updated
+ save(updated)
+ }
+ }
+
+ fun add(uri: String) {
+ if (uri in _liked.value) return
+ val updated = _liked.value + uri
+ _liked.value = updated
+ save(updated)
+ }
+
+ fun remove(uri: String) {
+ if (uri !in _liked.value) return
+ val updated = _liked.value - uri
+ _liked.value = updated
+ save(updated)
+ }
+
+ fun toggle(uri: String): Boolean {
+ val nowLiked = uri !in _liked.value
+ if (nowLiked) add(uri) else remove(uri)
+ return nowLiked
+ }
+
+ private fun load(): Set<String> =
+ prefs.getStringSet(KEY_LIKED, null)?.toSet() ?: emptySet()
+
+ private fun save(tracks: Set<String>) {
+ val snapshot = tracks.toSet()
+ scope.launch {
+ saveLock.withLock {
+ prefs.edit().putStringSet(KEY_LIKED, snapshot).apply()
+ }
+ }
+ }
+
+ private companion object {
+ const val FILE_NAME = "square_liked_tracks"
+ const val KEY_LIKED = "liked_tracks"
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
index 9979b5f..81afad7 100644
--- a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
+++ b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
@@ -41,7 +41,7 @@ object LocalLibrary {
*/
const val CONTEXT_URI = "local:files"
- fun isLocalContext(uri: String?): Boolean = uri == CONTEXT_URI
+ fun isLocalContext(uri: String?): Boolean = uri == CONTEXT_URI || uri == DownloadStore.SINGLES
/**
* What the shelf carries where a playlist carries a cover URL.
diff --git a/app/src/main/java/dev/lelonio/square/data/PlaylistOrderStore.kt b/app/src/main/java/dev/lelonio/square/data/PlaylistOrderStore.kt
index cecb719..e8365de 100644
--- a/app/src/main/java/dev/lelonio/square/data/PlaylistOrderStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PlaylistOrderStore.kt
@@ -66,8 +66,23 @@ class PlaylistOrderStore(context: Context) {
* A fixed shelf rather than a playlist among playlists; see LocalLibrary.
*/
fun List<CatalogPlaylist>.withLocalFilesFirst(): List<CatalogPlaylist> {
- val local = firstOrNull { LocalLibrary.isLocalContext(it.uri) } ?: return this
- return listOf(local) + filterNot { it.uri == local.uri }
+ val local = firstOrNull { it.uri == LocalLibrary.CONTEXT_URI }
+ val downloads = firstOrNull { it.uri == DownloadStore.SINGLES }
+ val head = listOfNotNull(local, downloads).distinctBy { it.uri }
+ if (head.isEmpty()) return this
+ val headUris = head.map { it.uri }.toSet()
+ return head + filterNot { it.uri in headUris }
+}
+
+/**
+ * Moves the "Liked Songs" playlist (Spotify collection, URI ends with ":collection")
+ * right after the fixed shelves (local files and downloads).
+ */
+fun List<CatalogPlaylist>.withLikedSecond(): List<CatalogPlaylist> {
+ val liked = firstOrNull { it.uri.endsWith(":collection") } ?: return this
+ val without = filterNot { it.uri == liked.uri }
+ val fixedCount = without.takeWhile { it.uri == LocalLibrary.CONTEXT_URI || it.uri == DownloadStore.SINGLES }.size
+ return without.take(fixedCount) + listOf(liked) + without.drop(fixedCount)
}
fun List<CatalogPlaylist>.sortedByRecentlyOpened(order: List<String>): List<CatalogPlaylist> {
diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
index b1dff07..7195432 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -84,6 +84,29 @@ class PreferencesStore(context: Context) {
prefs.edit().putBoolean(KEY_CANVAS, value).apply()
}
+ private val _autoplayInfinite = MutableStateFlow(prefs.getBoolean(KEY_AUTOPLAY_INFINITE, false))
+
+ /** Whether playback automatically appends similar tracks when reaching queue end. */
+ val autoplayInfinite: StateFlow<Boolean> = _autoplayInfinite.asStateFlow()
+
+ fun setAutoplayInfinite(value: Boolean) {
+ _autoplayInfinite.value = value
+ prefs.edit().putBoolean(KEY_AUTOPLAY_INFINITE, value).apply()
+ }
+
+ private val _trimSilence = MutableStateFlow(prefs.getBoolean(KEY_TRIM_SILENCE, true))
+
+ /** Whether trailing silence triggers early crossfade. */
+ val trimSilence: StateFlow<Boolean> = _trimSilence.asStateFlow()
+
+ fun setTrimSilence(value: Boolean) {
+ _trimSilence.value = value
+ prefs.edit().putBoolean(KEY_TRIM_SILENCE, value).apply()
+ runCatching {
+ dev.lelonio.square.nativecore.NativeBridge.setTrimSilence(value)
+ }
+ }
+
/**
* Whether the player was open when the app was last left.
*
@@ -162,6 +185,18 @@ class PreferencesStore(context: Context) {
prefs.edit().putString(KEY_SKIPPED_UPDATE, value).apply()
}
+ /** The account's country code, saved from the Spotify profile. */
+ val userCountry: String?
+ get() = prefs.getString(KEY_USER_COUNTRY, null)
+
+ fun setUserCountry(value: String?) {
+ if (value.isNullOrBlank()) {
+ prefs.edit().remove(KEY_USER_COUNTRY).apply()
+ } else {
+ prefs.edit().putString(KEY_USER_COUNTRY, value).apply()
+ }
+ }
+
private companion object {
const val FILE_NAME = "square_preferences"
const val KEY_TRACK_SORT = "track_sort"
@@ -169,11 +204,14 @@ class PreferencesStore(context: Context) {
const val KEY_DEVICE_ID = "device_id"
const val KEY_ONBOARDED = "onboarded"
const val KEY_CANVAS = "canvas_enabled"
+ const val KEY_AUTOPLAY_INFINITE = "autoplay_infinite"
+ const val KEY_TRIM_SILENCE = "trim_silence"
const val KEY_PLAYER_OPEN = "player_open"
const val KEY_BACKEND = "backend"
const val KEY_PROFILE_NAME = "profile_name"
const val KEY_PROFILE_ART = "profile_art"
const val KEY_LAST_UPDATE_CHECK = "last_update_check"
const val KEY_SKIPPED_UPDATE = "skipped_update"
+ const val KEY_USER_COUNTRY = "user_country"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/RecentStore.kt b/app/src/main/java/dev/lelonio/square/data/RecentStore.kt
index 122a703..f904456 100644
--- a/app/src/main/java/dev/lelonio/square/data/RecentStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/RecentStore.kt
@@ -36,7 +36,9 @@ class RecentStore(context: Context) {
* which is what makes the section useless in practice.
*/
suspend fun record(track: CatalogTrack) = withContext(Dispatchers.IO) {
+ if (track.name.isBlank()) return@withContext
val updated = (listOf(track) + _tracks.value.filterNot { it.uri == track.uri })
+ .filter { it.name.isNotBlank() }
.take(LIMIT)
_tracks.value = updated
prefs.edit()
@@ -51,7 +53,9 @@ class RecentStore(context: Context) {
private fun load(): List<CatalogTrack> {
val raw = prefs.getString(KEY_TRACKS, null) ?: return emptyList()
- return runCatching { json.decodeFromString(serializer, raw) }.getOrDefault(emptyList())
+ return runCatching { json.decodeFromString(serializer, raw) }
+ .getOrDefault(emptyList())
+ .filter { it.name.isNotBlank() }
}
private companion object {
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 ad3bfa0..a52c167 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -2,6 +2,9 @@ package dev.lelonio.square.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody
+import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
@@ -144,7 +147,7 @@ interface SpotifyApi {
@GET("v1/artists/{id}/top-tracks")
suspend fun artistTopTracks(
@Path("id") artistId: String,
- @Query("market") market: String = "from_token",
+ @Query("market") market: String,
): TopTracksDto
@GET("v1/artists/{id}/albums")
@@ -152,8 +155,12 @@ interface SpotifyApi {
@Path("id") artistId: String,
@Query("include_groups") groups: String = "album,single",
@Query("limit") limit: Int = 20,
+ @Query("market") market: String? = null,
): PageDto<AlbumDto>
+ @GET("v1/artists/{id}/related-artists")
+ suspend fun artistRelatedArtists(@Path("id") artistId: String): RelatedArtistsDto
+
/**
* The three below exist for one field each: the picture at the top of a
* page opened by name alone.
@@ -281,12 +288,14 @@ interface SpotifyApi {
suspend fun followArtists(
@Query("type") type: String = "artist",
@Query("ids") ids: String,
+ @Body request: IdsDto = IdsDto(ids.split(",").map { it.trim() }),
)
- @DELETE("v1/me/following")
+ @HTTP(method = "DELETE", path = "v1/me/following", hasBody = true)
suspend fun unfollowArtists(
@Query("type") type: String = "artist",
@Query("ids") ids: String,
+ @Body request: IdsDto = IdsDto(ids.split(",").map { it.trim() }),
)
@GET("v1/me/following/contains")
@@ -314,7 +323,10 @@ interface SpotifyApi {
* button on the page, two endpoints underneath.
*/
@PUT("v1/playlists/{id}/followers")
- suspend fun followPlaylist(@Path("id") playlistId: String)
+ suspend fun followPlaylist(
+ @Path("id") playlistId: String,
+ @Body request: FollowPlaylistRequestDto = FollowPlaylistRequestDto(),
+ )
@GET("v1/playlists/{id}/followers/contains")
suspend fun playlistIsFollowed(
@@ -322,19 +334,56 @@ interface SpotifyApi {
@Query("ids") userIds: String,
): List<Boolean>
- /** Saves tracks to Liked Songs, which is what the heart in the player says. */
+ companion object {
+ val EMPTY_BODY: RequestBody = ByteArray(0).toRequestBody("application/json".toMediaType())
+ }
+
+ /** Unified Spotify Library endpoints (matching fastpotify) */
+ @PUT("v1/me/library")
+ suspend fun saveToLibrary(
+ @Query("uris") uris: String,
+ @Body body: RequestBody = EMPTY_BODY,
+ )
+
+ @DELETE("v1/me/library")
+ suspend fun removeFromLibrary(@Query("uris") uris: String)
+
+ @GET("v1/me/library/contains")
+ suspend fun libraryContains(@Query("uris") uris: String): List<Boolean>
+
+ /** Saves tracks to Liked Songs (Canciones que te gustan). */
@PUT("v1/me/tracks")
- suspend fun saveTracks(@Query("ids") ids: String)
+ suspend fun saveTracks(
+ @Query("ids") ids: String,
+ @Body body: RequestBody = EMPTY_BODY,
+ )
- /** And takes them out again, which is the heart pressed a second time. */
+ @PUT("v1/me/tracks")
+ suspend fun saveTracksWithBody(
+ @Body request: IdsDto,
+ )
+
+ /** And takes them out again. */
@DELETE("v1/me/tracks")
- suspend fun removeSavedTracks(@Query("ids") ids: String)
+ suspend fun removeSavedTracks(
+ @Query("ids") ids: String,
+ )
+
+ @HTTP(method = "DELETE", path = "v1/me/tracks", hasBody = true)
+ suspend fun removeSavedTracksWithBody(
+ @Body request: IdsDto,
+ )
@PUT("v1/me/albums")
- suspend fun saveAlbums(@Query("ids") ids: String)
+ suspend fun saveAlbums(
+ @Query("ids") ids: String,
+ @Body body: RequestBody = EMPTY_BODY,
+ )
@DELETE("v1/me/albums")
- suspend fun removeAlbums(@Query("ids") ids: String)
+ suspend fun removeAlbums(
+ @Query("ids") ids: String,
+ )
@GET("v1/me/albums/contains")
suspend fun albumsAreSaved(@Query("ids") ids: String): List<Boolean>
@@ -350,6 +399,13 @@ interface SpotifyApi {
): SearchDto
}
+
+@Serializable
+data class IdsDto(val ids: List<String>)
+
+@Serializable
+data class FollowPlaylistRequestDto(val public: Boolean = false)
+
@Serializable
data class AddTracksRequestDto(val uris: List<String>)
@@ -379,6 +435,7 @@ data class UserDto(
@SerialName("display_name") val displayName: String? = null,
/** `premium` or `free`; the engine only works for the former. */
val product: String? = null,
+ val country: String? = null,
val images: List<ImageDto> = emptyList(),
)
@@ -475,6 +532,9 @@ data class AlbumDto(
@Serializable
data class TopTracksDto(val tracks: List<TrackDto> = emptyList())
+@Serializable
+data class RelatedArtistsDto(val artists: List<ArtistDto> = emptyList())
+
/** One entry of the account's play history: the track and where it was played from. */
@Serializable
data class PlayHistoryDto(
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyWebArtist.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyWebArtist.kt
new file mode 100644
index 0000000..bf7adb1
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyWebArtist.kt
@@ -0,0 +1,279 @@
+package dev.lelonio.square.data
+
+import android.content.res.Resources
+import android.util.Base64
+import dev.lelonio.square.R
+import dev.lelonio.square.ui.MainViewModel.ArtistPage
+import dev.lelonio.square.ui.MainViewModel.ArtistRelease
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.Locale
+import java.util.concurrent.ConcurrentHashMap
+
+/**
+ * Resolves artist top tracks, albums, singles, followers, and monthly listeners
+ * directly from Spotify's web player artist entity.
+ *
+ * Spotify's public Web API rate-limits librespot's shared client ID (HTTP 429)
+ * for users without a custom developer app. Spotify's web player CDN renders
+ * the full artist entity into the page HTML without authentication or API quota limits,
+ * providing the top 5 tracks, all albums, singles/EPs, monthly listeners, and bio.
+ */
+object SpotifyWebArtist {
+ private const val TAG = "SpotifyWebArtist"
+ private val scriptRegex = Regex("<script[^>]*>(.*?)</script>", RegexOption.DOT_MATCHES_ALL)
+
+ /** Session cache to prevent redundant scrapes across multiple callers. */
+ private val sessionCache = ConcurrentHashMap<String, ArtistPage>()
+
+ fun clearCache() {
+ sessionCache.clear()
+ }
+
+ suspend fun fetch(
+ artistId: String,
+ client: OkHttpClient,
+ resources: Resources? = null,
+ ): ArtistPage? = withContext(Dispatchers.IO) {
+ sessionCache[artistId]?.let { return@withContext it }
+
+ val url = "https://open.spotify.com/artist/$artistId"
+ val request = Request.Builder()
+ .url(url)
+ .header(
+ "User-Agent",
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
+ )
+ .header("Accept-Language", Locale.getDefault().language)
+ .build()
+
+ runCatching {
+ client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) {
+ android.util.Log.w(TAG, "HTTP ${response.code} for artist $artistId")
+ return@withContext null
+ }
+ val html = response.body?.string() ?: return@withContext null
+ val page = parseHtml(html, artistId, resources)
+ if (page != null) {
+ sessionCache[artistId] = page
+ }
+ page
+ }
+ }.onFailure {
+ android.util.Log.w(TAG, "Failed to load web artist $artistId: ${it.message}")
+ }.getOrNull()
+ }
+
+ fun parseHtml(html: String, artistId: String, resources: Resources? = null): ArtistPage? {
+ val matches = scriptRegex.findAll(html)
+ for (match in matches) {
+ val content = match.groupValues[1].trim()
+ if (content.length < 500 || !content.startsWith("eyJ")) continue
+
+ val decoded = runCatching {
+ val bytes = Base64.decode(content, Base64.DEFAULT)
+ String(bytes, Charsets.UTF_8)
+ }.getOrNull() ?: continue
+
+ if (!decoded.contains(artistId)) continue
+
+ val root = runCatching { JSONObject(decoded) }.getOrNull() ?: continue
+ val items = root.optJSONObject("entities")?.optJSONObject("items") ?: continue
+ val artistKey = "spotify:artist:$artistId"
+ val artistData = items.optJSONObject(artistKey)
+ ?: items.keys().asSequence().firstOrNull { it.startsWith("spotify:artist:") }?.let { items.optJSONObject(it) }
+ ?: continue
+
+ return parseArtistData(artistData, artistId, resources)
+ }
+ return null
+ }
+
+ private fun parseArtistData(data: JSONObject, artistId: String, resources: Resources?): ArtistPage {
+ val profile = data.optJSONObject("profile")
+ val name = profile?.optString("name").orEmpty()
+ val biography = profile?.optJSONObject("biography")?.optString("text")
+
+ val stats = data.optJSONObject("stats")
+ val followersCount = stats?.optInt("followers") ?: 0
+ val monthlyListenersCount = stats?.optLong("monthlyListeners") ?: 0L
+
+ val monthlyListenersFormatted = if (monthlyListenersCount > 0) {
+ val locale = Locale.getDefault()
+ val formattedCount = when {
+ monthlyListenersCount >= 1_000_000 -> String.format(locale, "%.1f M", monthlyListenersCount / 1_000_000.0)
+ monthlyListenersCount >= 1_000 -> String.format(locale, "%.1f K", monthlyListenersCount / 1_000.0)
+ else -> String.format(locale, "%,d", monthlyListenersCount)
+ }
+ if (resources != null) {
+ val quantity = monthlyListenersCount.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+ resources.getQuantityString(R.plurals.monthly_listeners, quantity, formattedCount)
+ } else {
+ formattedCount
+ }
+ } else null
+
+ val visuals = data.optJSONObject("visuals")
+ val avatarUrl = extractBestImage(visuals?.optJSONObject("avatarImage")?.optJSONArray("sources"), 320)
+
+ val disco = data.optJSONObject("discography")
+
+ // Parse top tracks (strictly top 5)
+ val topTracksArray = disco?.optJSONObject("topTracks")?.optJSONArray("items")
+ val tracks = mutableListOf<CatalogTrack>()
+ if (topTracksArray != null) {
+ for (i in 0 until topTracksArray.length()) {
+ val item = topTracksArray.optJSONObject(i) ?: continue
+ val track = item.optJSONObject("track") ?: continue
+ val uri = track.optString("uri")
+ if (!uri.startsWith("spotify:track:")) continue
+
+ val trackName = track.optString("name")
+ val albumObj = track.optJSONObject("albumOfTrack")
+ val albumName = albumObj?.optString("name").orEmpty()
+ val coverArt = extractBestImage(albumObj?.optJSONObject("coverArt")?.optJSONArray("sources"), 300)
+
+ val artistsArray = track.optJSONObject("artists")?.optJSONArray("items")
+ val credited = mutableListOf<CatalogArtist>()
+ if (artistsArray != null) {
+ for (j in 0 until artistsArray.length()) {
+ val aObj = artistsArray.optJSONObject(j) ?: continue
+ val aName = aObj.optJSONObject("profile")?.optString("name").orEmpty()
+ if (aName.isNotEmpty()) {
+ credited.add(CatalogArtist(aName, aObj.optString("uri").takeIf { it.isNotEmpty() }))
+ }
+ }
+ }
+
+ val explicit = track.optJSONObject("contentRating")?.optString("label") == "EXPLICIT"
+
+ // Extract real duration from Spotify entity:
+ // Typically duration.totalMilliseconds or trackDuration.totalMilliseconds or duration_ms
+ val durationMs = track.optJSONObject("duration")?.optLong("totalMilliseconds")
+ ?: track.optJSONObject("trackDuration")?.optLong("totalMilliseconds")
+ ?: track.optLong("durationMs")
+ ?: track.optLong("duration_ms")
+ ?: track.optLong("duration")
+ ?: 0L
+
+ tracks.add(
+ CatalogTrack(
+ uri = uri,
+ name = trackName,
+ artist = credited.joinToString(", ") { it.name },
+ artistUri = credited.firstOrNull()?.uri,
+ artists = credited,
+ album = albumName,
+ durationMs = durationMs,
+ explicit = explicit,
+ artworkUrl = coverArt,
+ ),
+ )
+ }
+ }
+
+ data class ReleaseEntry(val item: SearchItem, val year: Int)
+
+ fun extractReleases(sectionKey: String): List<SearchItem> {
+ val section = disco?.optJSONObject(sectionKey)
+ val items = section?.optJSONArray("items") ?: return emptyList()
+ val list = mutableListOf<ReleaseEntry>()
+ for (i in 0 until items.length()) {
+ val group = items.optJSONObject(i) ?: continue
+ val releases = group.optJSONObject("releases")?.optJSONArray("items") ?: continue
+ for (j in 0 until releases.length()) {
+ val rel = releases.optJSONObject(j) ?: continue
+ val uri = rel.optString("uri")
+ if (!uri.startsWith("spotify:album:")) continue
+
+ val title = rel.optString("name")
+ val type = rel.optString("type")
+ val yearInt = rel.optJSONObject("date")?.optInt("year")?.takeIf { it > 0 }
+ ?: rel.optString("date").take(4).toIntOrNull()
+ ?: 0
+ val yearStr = if (yearInt > 0) yearInt.toString() else ""
+
+ val label = when (type) {
+ "SINGLE" -> resources?.getString(R.string.single) ?: "Single"
+ "ALBUM" -> resources?.getString(R.string.album) ?: "Album"
+ "COMPILATION" -> resources?.getString(R.string.compilation) ?: "Compilation"
+ else -> ""
+ }
+ val subtitle = if (label.isNotEmpty() && yearStr.isNotEmpty()) "$label • $yearStr" else yearStr.ifEmpty { label }
+ val cover = extractBestImage(rel.optJSONObject("coverArt")?.optJSONArray("sources"), 300)
+
+ list.add(
+ ReleaseEntry(
+ item = SearchItem(
+ uri = uri,
+ title = title,
+ subtitle = subtitle,
+ artworkUrl = cover,
+ ),
+ year = yearInt,
+ ),
+ )
+ }
+ }
+ return list.distinctBy { it.item.title.lowercase() }
+ .sortedByDescending { it.year }
+ .map { it.item }
+ }
+
+ val albumsList = extractReleases("albums") + extractReleases("compilations")
+ val singlesList = extractReleases("singles")
+
+ val latestObj = disco?.optJSONObject("latest")
+ val latestRelease = if (latestObj != null) {
+ val lUri = latestObj.optString("uri")
+ if (lUri.startsWith("spotify:album:")) {
+ val lTitle = latestObj.optString("name")
+ val lDate = latestObj.optJSONObject("date")?.optInt("year")?.takeIf { it > 0 }?.toString()
+ ?: latestObj.optString("date").take(4)
+ val lCover = extractBestImage(latestObj.optJSONObject("coverArt")?.optJSONArray("sources"), 300)
+ val totalCount = latestObj.optJSONObject("tracks")?.optInt("totalCount") ?: 1
+ ArtistRelease(
+ uri = lUri,
+ title = lTitle,
+ artworkUrl = lCover,
+ releaseDate = lDate,
+ trackCount = totalCount,
+ )
+ } else null
+ } else null
+
+ return ArtistPage(
+ playlists = emptyList(),
+ tracks = tracks.take(5),
+ latest = latestRelease,
+ albums = albumsList,
+ singles = singlesList,
+ appearsOn = emptyList(),
+ relatedArtists = emptyList(),
+ followers = followersCount,
+ genres = emptyList(),
+ monthlyListeners = monthlyListenersFormatted,
+ name = name.takeIf { it.isNotEmpty() },
+ artworkUrl = avatarUrl,
+ biography = biography,
+ )
+ }
+
+ private fun extractBestImage(sources: JSONArray?, preferredWidth: Int): String? {
+ if (sources == null || sources.length() == 0) return null
+ var fallback: String? = null
+ for (i in 0 until sources.length()) {
+ val src = sources.optJSONObject(i) ?: continue
+ val url = src.optString("url").takeIf { it.isNotEmpty() } ?: continue
+ val width = src.optInt("width")
+ if (width in (preferredWidth - 40)..(preferredWidth + 60)) return url
+ if (fallback == null) fallback = url
+ }
+ return fallback
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/util/SpotifyLinkParser.kt b/app/src/main/java/dev/lelonio/square/data/util/SpotifyLinkParser.kt
new file mode 100644
index 0000000..c7a4856
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/util/SpotifyLinkParser.kt
@@ -0,0 +1,56 @@
+package dev.lelonio.square.data.util
+
+sealed class SpotifyLink(val rawId: String) {
+ abstract val uri: String
+
+ data class Track(val id: String) : SpotifyLink(id) {
+ override val uri: String get() = "spotify:track:$id"
+ }
+ data class Album(val id: String) : SpotifyLink(id) {
+ override val uri: String get() = "spotify:album:$id"
+ }
+ data class Playlist(val id: String) : SpotifyLink(id) {
+ override val uri: String get() = "spotify:playlist:$id"
+ }
+ data class Artist(val id: String) : SpotifyLink(id) {
+ override val uri: String get() = "spotify:artist:$id"
+ }
+}
+
+object SpotifyLinkParser {
+ private val HTTP_REGEX = Regex(
+ """https?://(?:open\.)?spotify\.com/(?:intl-[a-zA-Z]+/)?(track|album|playlist|artist)/([a-zA-Z0-9]+)""",
+ RegexOption.IGNORE_CASE,
+ )
+ private val URI_REGEX = Regex(
+ """spotify:(track|album|playlist|artist):([a-zA-Z0-9]+)""",
+ RegexOption.IGNORE_CASE,
+ )
+
+ fun parse(input: String): SpotifyLink? {
+ val trimmed = input.trim()
+ val httpMatch = HTTP_REGEX.find(trimmed)
+ if (httpMatch != null) {
+ val type = httpMatch.groupValues[1].lowercase()
+ val id = httpMatch.groupValues[2]
+ return create(type, id)
+ }
+ val uriMatch = URI_REGEX.find(trimmed)
+ if (uriMatch != null) {
+ val type = uriMatch.groupValues[1].lowercase()
+ val id = uriMatch.groupValues[2]
+ return create(type, id)
+ }
+ return null
+ }
+
+ private fun create(type: String, id: String): SpotifyLink? {
+ return when (type) {
+ "track" -> SpotifyLink.Track(id)
+ "album" -> SpotifyLink.Album(id)
+ "playlist" -> SpotifyLink.Playlist(id)
+ "artist" -> SpotifyLink.Artist(id)
+ else -> null
+ }
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt b/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt
index bc42c71..17b353a 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt
@@ -31,6 +31,9 @@ object DownloadEvents {
val progress: SharedFlow<Progress> = _progress.asSharedFlow()
+ private val lastEmitMs = java.util.concurrent.ConcurrentHashMap<String, Long>()
+ private val lastFraction = java.util.concurrent.ConcurrentHashMap<String, Float>()
+
/**
* Takes a download event off the engine's event channel.
*
@@ -41,7 +44,16 @@ object DownloadEvents {
PROGRESS -> {
// Per mille on the wire: the event carries one number, and a
// fraction would not have survived the trip as a long.
- _progress.tryEmit(Progress(uri, (value / 1000f).coerceIn(0f, 1f)))
+ // Throttled to prevent flooding Compose with dozens of recompositions/sec.
+ val fraction = (value / 1000f).coerceIn(0f, 1f)
+ val now = System.currentTimeMillis()
+ val last = lastEmitMs[uri] ?: 0L
+ val prev = lastFraction[uri] ?: 0f
+ if (now - last >= 150L || (fraction - prev) >= 0.02f || fraction >= 0.99f) {
+ lastEmitMs[uri] = now
+ lastFraction[uri] = fraction
+ _progress.tryEmit(Progress(uri, fraction))
+ }
true
}
@@ -49,6 +61,8 @@ object DownloadEvents {
// it — but the ring should reach the end before the row changes shape,
// and the last progress tick lands a chunk short of the whole.
DONE -> {
+ lastEmitMs.remove(uri)
+ lastFraction.remove(uri)
_progress.tryEmit(Progress(uri, 1f))
true
}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
index a3083dc..0bdaf26 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
@@ -148,7 +148,7 @@ object DownloadExtras {
fun note(kind: String, uri: String) = remember(kind, uri, "")
/** Whether this song has been asked about at all, answer or not. */
- fun asked(kind: String, uri: String): Boolean = fileFor(kind, uri)?.exists() == true
+ fun asked(kind: String, uri: String): Boolean = look(kind, uri)?.exists() == true
/**
* Artist descriptions are kept for anyone with a downloaded track, so the
@@ -170,7 +170,7 @@ object DownloadExtras {
}
private fun recall(kind: String, uri: String): String? {
- val file = fileFor(kind, uri) ?: return null
+ val file = look(kind, uri) ?: return null
return runCatching { file.takeIf(File::exists)?.readText() }
.getOrNull()
?.takeIf { it.isNotBlank() }
@@ -189,8 +189,18 @@ object DownloadExtras {
if (kind == "art") artCache.computeIfAbsent(url) { Kept(look(kind, it)) }.value
else look(kind, url)
- private fun look(kind: String, key: String): File? =
- fileFor(kind, key)?.takeIf(File::exists)
+ private fun look(kind: String, key: String): File? {
+ val file = fileFor(kind, key) ?: return null
+ if (file.exists()) return file
+ val old = oldFileFor(kind, key)
+ if (old != null && old.exists()) {
+ if (old.renameTo(file)) {
+ return file
+ }
+ return old
+ }
+ return null
+ }
/**
* Answers about covers, remembered.
@@ -386,6 +396,7 @@ object DownloadExtras {
fun forget(trackUri: String) {
listOf("lyrics", "canvas", ART).forEach { kind ->
fileFor(kind, trackUri)?.let { runCatching { it.delete() } }
+ oldFileFor(kind, trackUri)?.let { runCatching { it.delete() } }
}
}
@@ -420,28 +431,47 @@ object DownloadExtras {
fun sweep(trackUris: Collection<String>, coverUrls: Collection<String>) {
if (root == null) return
- val keepLyrics = trackUris.mapNotNullTo(mutableSetOf()) { fileFor("lyrics", it)?.name }
- val keepCanvas = trackUris.mapNotNullTo(mutableSetOf()) { fileFor("canvas", it)?.name }
- val keepApple = trackUris.mapNotNullTo(mutableSetOf()) { fileFor(ART, it)?.name }
- val keepArt = coverUrls.mapNotNullTo(mutableSetOf()) { fileFor("art", it)?.name }
+ val keepLyrics = trackUris.flatMapTo(mutableSetOf()) { uri ->
+ look("lyrics", uri)
+ listOfNotNull(fileFor("lyrics", uri)?.name, oldFileFor("lyrics", uri)?.name)
+ }
+ val keepCanvas = trackUris.flatMapTo(mutableSetOf()) { uri ->
+ look("canvas", uri)
+ listOfNotNull(fileFor("canvas", uri)?.name, oldFileFor("canvas", uri)?.name)
+ }
+ val keepApple = trackUris.flatMapTo(mutableSetOf()) { uri ->
+ look(ART, uri)
+ listOfNotNull(fileFor(ART, uri)?.name, oldFileFor(ART, uri)?.name)
+ }
+ val keepArt = coverUrls.flatMapTo(mutableSetOf()) { url ->
+ look("art", url)
+ listOfNotNull(fileFor("art", url)?.name, oldFileFor("art", url)?.name)
+ }
// The tall pictures are named by the answers that point at them, the
// same way the Canvas videos are: read while those answers are still
// here to be read.
trackUris.forEach { uri ->
art(uri)?.toList()?.filterNotNull()?.forEach { url ->
+ look("art", url)
fileFor("art", url)?.let { keepArt += it.name }
+ oldFileFor("art", url)?.let { keepArt += it.name }
}
}
// Read before the Canvas answers are pruned: a video is named after the
// URL inside the answer that points at it, so the answers are the only
// way to know which videos are still wanted.
- val keepVideo = trackUris.mapNotNullTo(mutableSetOf()) { uri ->
- recall("canvas", uri)
+ val keepVideo = trackUris.flatMapTo(mutableSetOf()) { uri ->
+ val url = recall("canvas", uri)
?.let { raw -> runCatching { JSONObject(raw).optString("url") }.getOrNull() }
?.takeIf { it.isNotBlank() }
- ?.let { fileFor("video", it)?.name }
+ if (url != null) {
+ look("video", url)
+ listOfNotNull(fileFor("video", url)?.name, oldFileFor("video", url)?.name)
+ } else {
+ emptyList()
+ }
}
forgetArtAnswers()
@@ -469,12 +499,51 @@ object DownloadExtras {
val root = root ?: return null
// Hashed rather than sanitised: a URI is not a legal file name, and any
// escaping scheme would have to survive the characters it escapes.
+ //
+ // A 64-bit FNV-1a hash rather than String.hashCode() (32-bit): the 32-bit
+ // space has ~4 billion values, and the birthday-paradox collision probability
+ // for a 10,000-item library is already ~1 %. At 64 bits the probability is
+ // negligible across any library size the app will encounter in practice.
+ val name = fnv1a64((if (kind == "art") coverKey(key) else key)).toString(16)
+ val extension = when (kind) {
+ "art" -> "jpg"
+ "video" -> "mp4"
+ else -> "json"
+ }
+ return File(File(root, kind), "$name.$extension")
+ }
+
+ private fun oldFileFor(kind: String, key: String): File? {
+ val root = root ?: return null
val name = (if (kind == "art") coverKey(key) else key).hashCode().toUInt().toString(16)
val extension = when (kind) {
- "art" -> "jpg"
+ "art" -> "jpg"
"video" -> "mp4"
- else -> "json"
+ else -> "json"
}
return File(File(root, kind), "$name.$extension")
}
+
+ /**
+ * 64-bit FNV-1a hash of a string, encoded as its UTF-8 bytes.
+ *
+ * Non-cryptographic, fast, and well-distributed for short keys like URIs and
+ * image URLs. Returns an unsigned Long so the hex representation is always
+ * positive and always 16 characters wide.
+ */
+ private fun fnv1a64(input: String): ULong {
+ var hash = FNV_OFFSET_BASIS
+ for (byte in input.encodeToByteArray()) {
+ hash = hash xor byte.toULong()
+ hash *= FNV_PRIME
+ }
+ return hash
+ }
+
}
+
+/** FNV-1a 64-bit offset basis. */
+private val FNV_OFFSET_BASIS = 14695981039346656037UL
+
+/** FNV-1a 64-bit prime. */
+private const val FNV_PRIME = 1099511628211UL
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
index 52fcca7..7139cdd 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
@@ -18,8 +18,12 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Semaphore
+import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import org.json.JSONObject
@@ -54,6 +58,7 @@ class DownloadQueue(
val running: Boolean = false,
val done: Int = 0,
val total: Int = 0,
+ val currentTitle: String? = null,
/** Why nothing is happening, when nothing is happening. */
val waiting: Waiting? = null,
/**
@@ -72,6 +77,7 @@ class DownloadQueue(
private val appContext = context.applicationContext
private val connectivity = appContext.getSystemService(ConnectivityManager::class.java)
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val extrasSemaphore = Semaphore(1)
private val _status = MutableStateFlow(Status())
val status: StateFlow<Status> = _status.asStateFlow()
@@ -192,8 +198,9 @@ class DownloadQueue(
continue
}
- publish(waiting = null)
val batch = pending.take(PARALLEL)
+ val currentUri = batch.firstOrNull()
+ publish(waiting = null, currentTrackUri = currentUri)
val outcomes = batch
.map { uri -> async { attempt(uri) } }
.awaitAll()
@@ -251,9 +258,15 @@ class DownloadQueue(
.toList()
if (missing.isEmpty()) return false
- for ((uri, url) in missing) {
- coversTried += uri
- DownloadExtras.keep(url, "art")
+ missing.chunked(4).forEach { chunk ->
+ coroutineScope {
+ chunk.map { (uri, url) ->
+ async {
+ coversTried += uri
+ DownloadExtras.keep(url, "art")
+ }
+ }.awaitAll()
+ }
delay(COVER_GAP_MS)
}
return true
@@ -269,16 +282,20 @@ class DownloadQueue(
.toList()
if (missing.isEmpty()) return false
- for (uri in missing) {
- coversTried += uri
- val cover = runCatching { NativeBridge.downloadState(uri) }
- .getOrNull()
- ?.let { runCatching { JSONObject(it).optString("coverUrl") }.getOrNull() }
- ?.takeIf { it.isNotBlank() }
- ?: continue
- DownloadExtras.keep(cover, "art")
- // No audio key is asked for here, so the pace that keeps the key
- // limiter happy does not apply: this is an ordinary CDN image.
+ missing.chunked(4).forEach { chunk ->
+ coroutineScope {
+ chunk.map { uri ->
+ async {
+ coversTried += uri
+ val cover = runCatching { NativeBridge.downloadState(uri) }
+ .getOrNull()
+ ?.let { runCatching { JSONObject(it).optString("coverUrl") }.getOrNull() }
+ ?.takeIf { it.isNotBlank() }
+ ?: return@async
+ DownloadExtras.keep(cover, "art")
+ }
+ }.awaitAll()
+ }
delay(COVER_GAP_MS)
}
return true
@@ -386,7 +403,23 @@ class DownloadQueue(
// [gap].
noteKeyWait(runCatching { JSONObject(sidecar).optLong("keyWaitMs", 0L) }.getOrDefault(0L))
store.onCompleted(trackUri, recordOf(sidecar, kbps))
- keepExtras(trackUri, sidecar)
+
+ // Essential cover kept immediately for thumbnail (lightweight, ~30KB)
+ val cover = runCatching { JSONObject(sidecar).optString("coverUrl") }
+ .getOrNull()
+ ?.takeIf { it.isNotBlank() }
+ ?: store.trackOf(trackUri)?.artworkUrl
+ if (cover != null) {
+ runCatching { DownloadExtras.keep(cover, "art") }
+ }
+
+ // Heavy extras (lyrics, canvas video, apple art) run sequentially in the background
+ // with a semaphore to prevent network/CPU saturation that slows down the UI.
+ scope.launch {
+ extrasSemaphore.withPermit {
+ keepRemainingExtras(trackUri)
+ }
+ }
return Outcome.DONE
}
@@ -406,40 +439,20 @@ class DownloadQueue(
/**
* Everything a downloaded song carries besides the song: the sleeve, the
* tall picture, the words and the Canvas.
- *
- * Everything here fails quietly. A track with no lyrics is the ordinary
- * case, a Canvas that will not fetch is a still cover, and neither is worth
- * failing a download that has already succeeded — the music is on the
- * phone, which is what was asked for.
- *
- * Each half is skipped when it has already been asked about, so this is
- * also what the backfill runs: a song downloaded by a build that had none
- * of this ends up with all of it, and a song that has it is left alone.
*/
private suspend fun keepExtras(trackUri: String, sidecar: String) {
- runCatching {
- // The cover first, and deliberately. It is a few tens of kilobytes
- // and it is the one extra that is missed the moment it is absent —
- // a song playing with a blank tile in the notification. The Canvas
- // below is megabytes of video; behind it, covers arrived at about
- // one a minute.
- //
- // The size the engine recorded is the large one, which is what the
- // player screen wants. The row thumbnail finds it too: covers are
- // keyed on the picture rather than the size. See DownloadExtras.
- val cover = runCatching { JSONObject(sidecar).optString("coverUrl") }
- .getOrNull()
- ?.takeIf { it.isNotBlank() }
- ?: store.trackOf(trackUri)?.artworkUrl
- // The sidecar's cover comes from the engine's own metadata, which
- // does not always carry one; the catalogue's does. Without either,
- // a downloaded song plays offline with a drawn tile where its
- // sleeve should be.
- val kept = cover?.let { DownloadExtras.keep(it, "art") }
- if (kept == null) {
- android.util.Log.i("SquareDownloads", "no cover kept for $trackUri")
- }
+ val cover = runCatching { JSONObject(sidecar).optString("coverUrl") }
+ .getOrNull()
+ ?.takeIf { it.isNotBlank() }
+ ?: store.trackOf(trackUri)?.artworkUrl
+ if (cover != null) {
+ runCatching { DownloadExtras.keep(cover, "art") }
+ }
+ keepRemainingExtras(trackUri)
+ }
+ private suspend fun keepRemainingExtras(trackUri: String) {
+ runCatching {
val track = store.trackOf(trackUri)
// The words. Asking is the whole of the keeping: the chain the
@@ -569,15 +582,16 @@ class DownloadQueue(
val capabilities = manager.activeNetwork
?.let(manager::getNetworkCapabilities)
?: return Link.NONE
- if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
- return Link.NONE
- }
- // Not validated means a captive portal or a network that is up but goes
- // nowhere. Treated as no network, because that is what it is for us.
- if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
+ val hasInternet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
+ val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
+ val isEthernet = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
+ val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
+
+ if (!hasInternet && !validated && !isWifi && !isEthernet && !isCellular) {
return Link.NONE
}
- return if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
+ return if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) || isWifi || isEthernet) {
Link.UNMETERED
} else {
Link.METERED
@@ -585,22 +599,26 @@ class DownloadQueue(
}
/** Null when downloading may go ahead, otherwise what it is waiting for. */
- private fun allowed(): Waiting? = when (_link.value) {
- Link.NONE -> Waiting.NETWORK
- Link.METERED -> if (settings.wifiOnly.value) Waiting.WIFI else null
- Link.UNMETERED -> null
+ private fun allowed(): Waiting? {
+ if (dev.lelonio.square.playback.OfflineMode.active.value) return Waiting.NETWORK
+ return when (_link.value) {
+ Link.NONE -> Waiting.NETWORK
+ Link.METERED -> if (settings.wifiOnly.value) Waiting.WIFI else null
+ Link.UNMETERED -> null
+ }
}
private suspend fun awaitAllowed() {
- // The setting can change as well as the link, and a StateFlow of one
- // will not report the other. Combining them would mean building a flow
- // for a wait that ends either way, so this simply waits on whichever
- // moves and re-asks.
- val before = _link.value
- val wifiBefore = settings.wifiOnly.value
- while (_link.value == before && settings.wifiOnly.value == wifiBefore) {
- delay(NETWORK_POLL_MS)
- }
+ // Suspend without polling: combine state flows and resume the
+ // moment conditions permit downloading.
+ combine(_link, settings.wifiOnly, dev.lelonio.square.playback.OfflineMode.active) { link, wifiOnly, offline ->
+ if (offline) return@combine false
+ when (link) {
+ Link.NONE -> false
+ Link.METERED -> !wifiOnly
+ Link.UNMETERED -> true
+ }
+ }.first { allowed -> allowed }
}
private fun holdWatch() {
@@ -616,13 +634,15 @@ class DownloadQueue(
runCatching { connectivity?.unregisterNetworkCallback(networkCallback) }
}
- private fun publish(waiting: Waiting?) {
+ private fun publish(waiting: Waiting?, currentTrackUri: String? = null) {
val wanted = store.owners.value.values.flatten().toSet()
val files = store.files.value
+ val trackTitle = currentTrackUri?.let { store.trackOf(it)?.name }?.takeIf { it.isNotBlank() }
_status.value = Status(
running = true,
done = wanted.count(files::containsKey),
total = wanted.size,
+ currentTitle = trackTitle,
waiting = waiting,
)
}
@@ -676,7 +696,7 @@ class DownloadQueue(
*/
const val THROTTLED_WAIT_MS = 20_000L
- const val NETWORK_POLL_MS = 1_500L
+
/** How long to leave the engine alone before asking it again. */
const val ENGINE_POLL_MS = 3_000L
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadService.kt b/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
index 06e5bec..2d6be4f 100644
--- a/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
@@ -125,6 +125,12 @@ class DownloadService : android.app.Service() {
}
private fun build(status: DownloadQueue.Status): Notification {
+ val percent = if (status.total > 0) {
+ ((status.done.toFloat() / status.total) * 100).toInt().coerceIn(0, 100)
+ } else 0
+ val countText = getString(R.string.download_progress_count, status.done, status.total)
+ val progressText = "$countText ($percent%)"
+
val text = when {
status.waiting == DownloadQueue.Waiting.WIFI ->
getString(R.string.download_waiting_wifi)
@@ -134,7 +140,8 @@ class DownloadService : android.app.Service() {
getString(R.string.download_waiting_engine)
// The music is all here; what is left is what goes beside it.
status.extras -> getString(R.string.download_extras)
- else -> getString(R.string.download_progress_count, status.done, status.total)
+ !status.currentTitle.isNullOrBlank() -> "${status.currentTitle} · $progressText"
+ else -> progressText
}
val stop = PendingIntent.getService(
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index 9f837ba..fc3b5f1 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -188,6 +188,7 @@ object NativeBridge {
* called — no gap, no restart.
*/
fun setBitrate(bitrateKbps: Int) = nativeSetBitrate(bitrateKbps)
+ fun setTrimSilence(enabled: Boolean) = nativeSetTrimSilence(enabled)
/**
* Builds a new session, player and Connect device, keeping everything else.
@@ -450,6 +451,7 @@ object NativeBridge {
private external fun nativeSetQuality(bitrateKbps: Int, crossfadeMs: Int)
private external fun nativeSetBitrate(bitrateKbps: Int)
+ private external fun nativeSetTrimSilence(enabled: Boolean)
private external fun nativeReconnect()
private external fun nativePlaybackElsewhere(): Boolean
private external fun nativePublishContext(positionMs: Int): Boolean
diff --git a/app/src/main/java/dev/lelonio/square/playback/BandwidthWatch.kt b/app/src/main/java/dev/lelonio/square/playback/BandwidthWatch.kt
index 5ca2672..abf0f2e 100644
--- a/app/src/main/java/dev/lelonio/square/playback/BandwidthWatch.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/BandwidthWatch.kt
@@ -72,6 +72,17 @@ class BandwidthWatch(
}
}
+ /**
+ * A track load failed over the network (e.g. timeout or unavailable).
+ */
+ fun loadFailed(uri: String? = null) {
+ if (uri != null && loadingUri != null && loadingUri != uri) return
+ Log.i(TAG, "track load failed for ${uri ?: loadingUri}, stepping down")
+ loadingUri = null
+ loadStartedAt = 0L
+ stepDown()
+ }
+
/**
* The music stopped while it meant to be playing.
*
@@ -116,11 +127,6 @@ class BandwidthWatch(
/**
* A load slower than this is taken as a link that cannot keep up.
- *
- * Generous on purpose: it also covers the access point answering, the
- * key exchange and the first seconds of audio, and none of that is
- * instant even on a good connection. What it must not do is fire on a
- * link that is merely ordinary.
*/
const val SLOW_LOAD_MS = 6_000L
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index 8a252dc..8534696 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -743,6 +743,12 @@ class LibrespotPlayer(
// anyway would talk over it.
if (!focus.requestFocus()) return Futures.immediateVoidFuture()
wantPlay = true
+ this.playWhenReady = true
+ if (playbackState == Player.STATE_IDLE) {
+ playbackState = Player.STATE_READY
+ }
+ invalidateState()
+
// Pressed before there is an engine to press it on. Remembered
// rather than sent: the queue goes over the moment the access point
// answers, and it goes over playing.
@@ -752,14 +758,24 @@ class LibrespotPlayer(
invalidateState()
return Futures.immediateVoidFuture()
}
- // Play is where a reconnection is worth waiting for. The engine has
- // no queue of its own, so a rebuilt device knows nothing until the
- // queue is handed over again, and resuming is exactly the moment
- // the user is willing to wait a handshake for.
- if (deviceGone) {
+
+ // If no track is currently loaded but queue exists, load the queue.
+ // Otherwise, unpause the existing loaded track immediately via NativeBridge.play().
+ if (currentMediaItem == null && queue.items.isNotEmpty()) {
pushQueue(startPlaying = true, positionMs = positionMs.toInt())
} else {
- engine("play") { NativeBridge.play() }
+ var playFailed = false
+ engine("play") {
+ try {
+ NativeBridge.play()
+ } catch (e: Throwable) {
+ playFailed = true
+ throw e
+ }
+ }
+ if (playFailed && queue.items.isNotEmpty()) {
+ pushQueue(startPlaying = true, positionMs = positionMs.toInt())
+ }
}
// After the engine, not before: waking the output is a call into
// the audio server that took most of a tenth of a second here, and
@@ -768,13 +784,12 @@ class LibrespotPlayer(
onPlaybackActive(true)
} else {
wantPlay = false
- engine("pause") { NativeBridge.pause() }
+ this.playWhenReady = false
onPlaybackActive(false)
focus.abandonFocus()
+ engine("pause") { NativeBridge.pause() }
+ invalidateState()
}
- // Do not update local state here: the engine confirms via onEvent, and
- // reporting "playing" before audio actually starts makes the seek bar
- // run ahead of the sound.
return Futures.immediateVoidFuture()
}
diff --git a/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt b/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt
index afde699..4a5e311 100644
--- a/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt
@@ -26,8 +26,10 @@ import dev.lelonio.square.ui.EXTRA_CONTEXT_LABEL
import dev.lelonio.square.ui.EXTRA_CONTEXT_ORDERED
import dev.lelonio.square.ui.EXTRA_CONTEXT_URI
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
import kotlinx.coroutines.guava.future
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -103,13 +105,17 @@ class MediaBrowseTree(
player: androidx.media3.common.Player,
/**
* The shade has room for two buttons beside the transport and is looked
- * at rather than operated: repeat is a setting people change once,
- * while radio is a thing to do with the song on screen. The car keeps
- * repeat, because there it is the mode a driver actually reaches for.
+ * at rather than operated: the shade shows a heart to add to Liked Songs
+ * (Tus me gusta) instead of repeat, which is a setting people change once.
+ * The car keeps repeat, because there it is the mode a driver actually reaches for.
*/
radioInsteadOfRepeat: Boolean = false,
- ): ImmutableList<CommandButton> =
- ImmutableList.of(
+ isLiked: Boolean? = null,
+ ): ImmutableList<CommandButton> {
+ val currentUri = player.currentMediaItem?.mediaId
+ val liked = isLiked ?: app.likedStore.isLiked(currentUri)
+
+ return ImmutableList.of(
CommandButton.Builder(
if (player.shuffleModeEnabled) {
CommandButton.ICON_SHUFFLE_ON
@@ -121,9 +127,12 @@ class MediaBrowseTree(
.setDisplayName(strings.getString(R.string.shuffle))
.build(),
if (radioInsteadOfRepeat) {
- CommandButton.Builder(CommandButton.ICON_RADIO)
- .setSessionCommand(SessionCommand(CMD_RADIO, Bundle.EMPTY))
- .setDisplayName(strings.getString(R.string.radio))
+ CommandButton.Builder()
+ .setIconResId(if (liked) R.drawable.ic_heart_filled else R.drawable.ic_heart_outline)
+ .setSessionCommand(SessionCommand(CMD_LIKE, Bundle.EMPTY))
+ .setDisplayName(
+ strings.getString(if (liked) R.string.remove_from_liked else R.string.liked_songs),
+ )
.build()
} else {
CommandButton.Builder(
@@ -140,6 +149,7 @@ class MediaBrowseTree(
.build()
},
)
+ }
override fun onConnect(
session: MediaSession,
@@ -150,6 +160,7 @@ class MediaBrowseTree(
.add(SessionCommand(CMD_SHUFFLE, Bundle.EMPTY))
.add(SessionCommand(CMD_REPEAT, Bundle.EMPTY))
.add(SessionCommand(CMD_RADIO, Bundle.EMPTY))
+ .add(SessionCommand(CMD_LIKE, Bundle.EMPTY))
.build()
return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
@@ -183,17 +194,98 @@ class MediaBrowseTree(
startRadio(session)
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
}
+ CMD_LIKE -> {
+ toggleLike(session)
+ return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
+ }
else -> return Futures.immediateFuture(
SessionResult(SessionResult.RESULT_ERROR_NOT_SUPPORTED),
)
}
- // Redrawn at once. The button carries the state, so a press that left
- // the old icon up read as a press that had not landed.
- session.setCustomLayout(layoutFor(player))
+ // Redrawn at once on each controller so their layouts (car vs shade) remain distinct.
+ session.connectedControllers.forEach { ctrl ->
+ session.setCustomLayout(
+ ctrl,
+ layoutFor(
+ player,
+ radioInsteadOfRepeat = session.isMediaNotificationController(ctrl),
+ ),
+ )
+ }
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
}
+ private fun toggleLike(session: MediaSession) {
+ val player = session.player
+ val uri = player.currentMediaItem?.mediaId ?: return
+ if (!uri.startsWith("spotify:track:")) return
+
+ val nowLiked = app.likedStore.toggle(uri)
+ val id = uri.substringAfterLast(':')
+
+ // Redraw immediately on all connected controllers so the heart flips without latency
+ session.connectedControllers.forEach { ctrl ->
+ session.setCustomLayout(
+ ctrl,
+ layoutFor(
+ player,
+ radioInsteadOfRepeat = session.isMediaNotificationController(ctrl),
+ isLiked = nowLiked,
+ ),
+ )
+ }
+
+ scope.launch {
+ val callResult = runCatching {
+ if (nowLiked) {
+ app.api.saveToLibrary("spotify:track:$id", dev.lelonio.square.data.SpotifyApi.EMPTY_BODY)
+ } else {
+ app.api.removeFromLibrary("spotify:track:$id")
+ }
+ }
+ callResult.onSuccess {
+ android.util.Log.i(TAG, "toggleLike remote sync OK for $id (nowLiked=$nowLiked)")
+ }.onFailure { ex ->
+ android.util.Log.w(TAG, "toggleLike remote sync failed for $id: ${ex.message}", ex)
+ app.likedStore.toggle(uri)
+ val revertedLiked = !nowLiked
+ session.connectedControllers.forEach { ctrl ->
+ session.setCustomLayout(
+ ctrl,
+ layoutFor(
+ player,
+ radioInsteadOfRepeat = session.isMediaNotificationController(ctrl),
+ isLiked = revertedLiked,
+ ),
+ )
+ }
+ }
+
+ if (callResult.isSuccess && app.downloadSettings.downloadLikedSongs.value) {
+ if (nowLiked) {
+ val meta = player.currentMediaItem?.mediaMetadata
+ val track = app.downloads.trackOf(uri) ?: CatalogTrack(
+ uri = uri,
+ name = meta?.title?.toString().orEmpty(),
+ artist = meta?.artist?.toString().orEmpty(),
+ album = meta?.albumTitle?.toString().orEmpty(),
+ durationMs = meta?.durationMs ?: 0L,
+ artworkUrl = meta?.artworkUri?.toString(),
+ )
+ app.downloads.addLiked(track)
+ dev.lelonio.square.download.DownloadService.start(app)
+ } else {
+ app.downloads.removeLiked(uri)
+ app.downloads.pruneOrphans().forEach { orphanUri ->
+ runCatching { NativeBridge.removeDownload(orphanUri) }
+ dev.lelonio.square.download.DownloadExtras.forget(orphanUri)
+ }
+ }
+ }
+ }
+ }
+
/**
* A station from what is playing, without a screen to ask anything of.
*
@@ -544,6 +636,7 @@ class MediaBrowseTree(
const val CMD_SHUFFLE = "dev.lelonio.square.SHUFFLE"
const val CMD_REPEAT = "dev.lelonio.square.REPEAT"
const val CMD_RADIO = "dev.lelonio.square.RADIO"
+ const val CMD_LIKE = "dev.lelonio.square.LIKE"
const val ID_ROOT = "sq/root"
const val ID_PLAYLISTS = "sq/playlists"
diff --git a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
index 9e33891..ac42e33 100644
--- a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
@@ -74,6 +74,7 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
pending?.cancel()
if (connected) {
OfflineMode.setNoSession(false)
+ OfflineMode.setSlow(false)
return
}
pending = scope.launch {
@@ -84,20 +85,12 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
}
/**
- * Whether there is a link that actually reaches the internet.
+ * Whether there is an active link that can carry traffic.
*
- * `NET_CAPABILITY_VALIDATED` rather than merely connected: a Wi-Fi that has
- * not passed its own check — a captive portal, a router with no line behind
- * it — is a network to the system and nothing at all to this app.
- */
- /**
- * What the system says is carrying the traffic, for the log.
- *
- * Which transport it is matters: reporting "up" with everything switched
- * off means this is reading something that is not the listener's
- * connection — a tunnel, a tether, a link the system has not torn down yet
- * — and the name of it is the difference between a wrong answer and a
- * wrong question.
+ * Wi-Fi, Ethernet, Cellular and VPNs are treated as connected without strictly
+ * requiring NET_CAPABILITY_VALIDATED, because Android's captive portal check
+ * (Google 204 probe) frequently fails or is blocked on local/regional networks
+ * despite having working internet.
*/
private fun describe(): String {
val network = connectivity?.activeNetwork ?: return "no active network"
@@ -119,8 +112,13 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
private fun connected(): Boolean {
val network = connectivity?.activeNetwork ?: return false
val capabilities = connectivity.getNetworkCapabilities(network) ?: return false
- return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
- capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ val hasInternet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
+ val isWifi = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
+ val isEthernet = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
+ val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
+ val isVpn = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
+
+ return hasInternet && (isWifi || isEthernet || isCellular || isVpn)
}
private companion object {
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 0b3876b..3183bf4 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -45,6 +45,109 @@ class PlaybackService : MediaLibraryService() {
private var engineStarted = false
private lateinit var container: dev.lelonio.square.SquareApplication
+ private lateinit var browseTree: MediaBrowseTree
+
+ private fun redrawButtons() {
+ val live = session ?: return
+ live.connectedControllers.forEach { controller ->
+ live.setCustomLayout(
+ controller,
+ browseTree.layoutFor(
+ player,
+ radioInsteadOfRepeat = live.isMediaNotificationController(controller),
+ ),
+ )
+ }
+ }
+
+ private var autoplayInFlight = false
+ private var lastAutoplayTrackUri: String? = null
+
+ private val buttonsListener = object : androidx.media3.common.Player.Listener {
+ override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = redrawButtons()
+
+ override fun onRepeatModeChanged(repeatMode: Int) = redrawButtons()
+
+ override fun onMediaItemTransition(
+ mediaItem: androidx.media3.common.MediaItem?,
+ reason: Int,
+ ) {
+ redrawButtons()
+ maybeTriggerAutoplay(mediaItem)
+ }
+
+ override fun onPlaybackStateChanged(playbackState: Int) {
+ if (playbackState == androidx.media3.common.Player.STATE_READY) {
+ maybeTriggerAutoplay(player.currentMediaItem)
+ }
+ }
+ }
+
+ private fun maybeTriggerAutoplay(mediaItem: androidx.media3.common.MediaItem?) {
+ if (!::container.isInitialized) return
+ if (!container.preferences.autoplayInfinite.value) return
+ if (player.repeatMode != androidx.media3.common.Player.REPEAT_MODE_OFF) return
+
+ val current = mediaItem ?: player.currentMediaItem ?: return
+ val currentUri = current.mediaId
+ if (!currentUri.startsWith("spotify:track:")) return
+
+ val currentIdx = player.currentMediaItemIndex
+ val totalCount = player.mediaItemCount
+ val remaining = totalCount - currentIdx - 1
+ if (remaining > 2) return
+
+ val toAdd = (AUTOPLAY_QUEUE_CAP - remaining).coerceAtLeast(0)
+ if (toAdd <= 0) return
+
+ if (autoplayInFlight || currentUri == lastAutoplayTrackUri) return
+ autoplayInFlight = true
+ lastAutoplayTrackUri = currentUri
+
+ scope.launch(Dispatchers.IO) {
+ try {
+ val id = currentUri.substringAfterLast(':')
+ val stationUri = "spotify:station:track:$id"
+ val stationTrackUris = dev.lelonio.square.data.Catalog.contextTrackUris(stationUri)
+ val catalogTracks = dev.lelonio.square.data.Catalog.tracks(stationTrackUris)
+ withContext(Dispatchers.Main) {
+ val currentUris = (0 until player.mediaItemCount)
+ .mapNotNull { player.getMediaItemAt(it).mediaId }
+ .toSet()
+ val newTracks = catalogTracks.filter { it.uri !in currentUris }.take(toAdd)
+ if (newTracks.isNotEmpty()) {
+ val items = newTracks.map { track ->
+ androidx.media3.common.MediaItem.Builder()
+ .setMediaId(track.uri)
+ .setUri(track.uri)
+ .setMediaMetadata(
+ androidx.media3.common.MediaMetadata.Builder()
+ .setTitle(track.name)
+ .setArtist(track.artist)
+ .setAlbumTitle(track.album)
+ .setDurationMs(track.durationMs.takeIf { it > 0 })
+ .setArtworkUri(
+ track.artworkUrl?.let { url ->
+ dev.lelonio.square.download.DownloadExtras.fileOf(url, "art")
+ ?.let(android.net.Uri::fromFile)
+ ?: android.net.Uri.parse(url)
+ }
+ )
+ .build()
+ )
+ .build()
+ }
+ android.util.Log.i(TAG, "Autoplay: appending ${items.size} tracks for $currentUri (queue cap: $AUTOPLAY_QUEUE_CAP)")
+ player.addMediaItems(items)
+ }
+ }
+ } catch (t: Throwable) {
+ android.util.Log.w(TAG, "Autoplay: failed to fetch tracks for $currentUri", t)
+ } finally {
+ autoplayInFlight = false
+ }
+ }
+ }
/** Whatever the active backend plays through. */
private lateinit var player: androidx.media3.common.Player
@@ -96,7 +199,7 @@ class PlaybackService : MediaLibraryService() {
crossfade = container.crossfade
player = buildPlayer(container.preferences.backend.value)
- val browseTree = MediaBrowseTree(this, scope, ::ensurePlayerFor)
+ browseTree = MediaBrowseTree(this, scope, ::ensurePlayerFor)
session = MediaLibrarySession.Builder(this, player, browseTree)
// Without this the notification is inert to a tap: Media3 has no way
// to know which activity owns the session. `SINGLE_TOP` so an app
@@ -130,32 +233,15 @@ class PlaybackService : MediaLibraryService() {
.apply { setSmallIcon(dev.lelonio.square.R.drawable.ic_notification) },
)
- // The car's shuffle and repeat buttons carry their own state, so they
- // are redrawn whenever the mode changes here — from the app, from a
- // headset, or from another Connect device.
- player.addListener(object : androidx.media3.common.Player.Listener {
- override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = redrawButtons()
-
- override fun onRepeatModeChanged(repeatMode: Int) = redrawButtons()
-
- /**
- * Per controller, because the two layouts differ: the shade shows
- * radio where the car shows repeat, and one blanket update would
- * hand every controller the same pair.
- */
- private fun redrawButtons() {
- val live = session ?: return
- live.connectedControllers.forEach { controller ->
- live.setCustomLayout(
- controller,
- browseTree.layoutFor(
- player,
- radioInsteadOfRepeat = live.isMediaNotificationController(controller),
- ),
- )
- }
+ // The notification and car buttons carry their own state (shuffle, repeat,
+ // and heart/like), so they are redrawn whenever the mode or track changes.
+ player.addListener(buttonsListener)
+
+ scope.launch {
+ container.likedStore.likedTracks.collect {
+ redrawButtons()
}
- })
+ }
// Already read by the application object, and harmless twice: `load`
// returns at once once the file is open.
@@ -604,7 +690,9 @@ class PlaybackService : MediaLibraryService() {
librespot = null
playerKind = kind
player = buildPlayer(kind)
+ player.addListener(buttonsListener)
session?.player = player
+ redrawButtons()
// The queue on disk belongs to this player when it is the one being
// restored into — leaving it out is what made a local song paused
// at closing time impossible to start again: the screen had it, the
@@ -627,7 +715,9 @@ class PlaybackService : MediaLibraryService() {
librespot = parked
playerKind = kind
player = parked
+ player.addListener(buttonsListener)
session?.player = player
+ redrawButtons()
if (restore) restoreQueue()
observeForSaving()
return
@@ -655,7 +745,9 @@ class PlaybackService : MediaLibraryService() {
dev.lelonio.square.backend.youtube.YouTubeVideoMode.reset()
player = buildPlayer(kind)
+ player.addListener(buttonsListener)
session?.player = player
+ redrawButtons()
followReverb()
// The engine is what the Spotify player plays through, so it is started
// whatever brought us here — without this, coming back from a local file
@@ -1195,6 +1287,8 @@ class PlaybackService : MediaLibraryService() {
artworkUrl = metadata.artworkUri?.toString(),
)
}
+ val currentTrack = tracks.getOrNull(player.currentMediaItemIndex)
+ if (currentTrack != null && currentTrack.name.isBlank()) return
val extras = player.currentMediaItem?.mediaMetadata?.extras
playbackStore.save(
SavedPlayback(
@@ -1392,6 +1486,9 @@ class PlaybackService : MediaLibraryService() {
companion object {
private const val TAG = "PlaybackService"
+ /** Maximum upcoming tracks to buffer in queue for autoplay. */
+ private const val AUTOPLAY_QUEUE_CAP = 10
+
/** How often the position is written back while playing. */
private const val SAVE_INTERVAL_MS = 10_000L
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index 8709a6d..efab7f0 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -85,6 +85,7 @@ class MainActivity : ComponentActivity() {
player = controller,
onPlay = ::play,
onEnqueue = ::enqueue,
+ onEnqueueAll = ::enqueueAll,
openPlayer = openPlayer,
link = link,
)
@@ -341,6 +342,21 @@ class MainActivity : ComponentActivity() {
}
}
+ /**
+ * Appends multiple tracks to the end of the queue (used for continuous Autoplay).
+ */
+ private fun enqueueAll(tracks: List<CatalogTrack>) {
+ val player = controller ?: return
+ if (tracks.isEmpty()) return
+ val wasEmpty = player.mediaItemCount == 0
+ val items = tracks.map { toMediaItem(it, playNext = false) }
+ player.addMediaItems(items)
+ if (wasEmpty) {
+ player.prepare()
+ player.play()
+ }
+ }
+
private fun toMediaItem(
track: CatalogTrack,
contextUri: String? = null,
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 93fb214..a32dc20 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -14,9 +14,11 @@ import dev.lelonio.square.backend.HomeRow
import dev.lelonio.square.backend.SearchLabels
import dev.lelonio.square.R
import dev.lelonio.square.data.Catalog
+import dev.lelonio.square.data.SpotifyApi
import dev.lelonio.square.data.DownloadStore
import dev.lelonio.square.download.DownloadService
import dev.lelonio.square.data.AddTracksRequestDto
+import dev.lelonio.square.data.IdsDto
import dev.lelonio.square.data.RemoveTracksRequestDto
import dev.lelonio.square.data.TrackUriDto
import dev.lelonio.square.data.CatalogPlaylist
@@ -43,6 +45,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.Dispatchers
+import retrofit2.HttpException
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
@@ -57,6 +60,9 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.isActive
+import java.util.concurrent.ConcurrentHashMap
/**
* Login gate and library browsing.
@@ -161,6 +167,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val appearsOn: List<SearchItem> = emptyList(),
/** The playlists Spotify built around them, "This Is" first. */
val artistPlaylists: List<SearchItem> = emptyList(),
+ /** Fans also like / related artists. */
+ val relatedArtists: List<SearchItem> = emptyList(),
+ /** Whether the artist is verified. */
+ val verified: Boolean = true,
+ /** Formatted monthly listeners string, e.g. "14.3 M oyentes mensuales". */
+ val monthlyListeners: String? = null,
/**
* The record they put out last, for the card under the artist's photo.
*
@@ -1014,11 +1026,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
trackUri = trackUri,
trackTitle = trackTitle,
playlists = (_state.value as? UiState.Ready)?.playlists.orEmpty(),
- liked = trackUri != null && trackUri in _liked.value,
+ liked = trackUri != null && container.likedStore.isLiked(trackUri),
error = when {
trackUri?.startsWith("spotify:track:") != true ->
string(R.string.track_cannot_be_added)
- !container.webApi.isReady ->
+ !container.webApi.isReady && !container.tokenStore.isLoggedIn ->
string(R.string.connect_app_in_settings)
else -> null
},
@@ -1053,29 +1065,33 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// and pressing it twice is how everything else undoes a like.
val unsaving = toLibrary && current.liked
+ if (toLibrary) {
+ _addToPlaylist.value = current.copy(
+ busy = playlist.uri,
+ done = null,
+ removed = null,
+ error = null,
+ )
+ toggleLike(trackUri, current.trackTitle, playlistName = playlist.name)
+ return
+ }
+
_addToPlaylist.value =
current.copy(busy = playlist.uri, done = null, removed = null, error = null)
viewModelScope.launch {
runCatching {
- when {
- unsaving -> container.api.removeSavedTracks(trackUri.substringAfterLast(':'))
- toLibrary -> container.api.saveTracks(trackUri.substringAfterLast(':'))
- else -> container.api.addToPlaylist(id, AddTracksRequestDto(listOf(trackUri)))
- }
+ container.api.addToPlaylist(id, AddTracksRequestDto(listOf(trackUri)))
}
.onSuccess {
_addToPlaylist.value = _addToPlaylist.value.copy(
busy = null,
- done = if (unsaving) null else playlist.name,
- removed = if (unsaving) playlist.name else null,
- liked = toLibrary && !unsaving,
+ done = playlist.name,
+ removed = null,
)
// Known at once, rather than when that playlist is next
// read: the tick is about the track, and the track is in a
// playlist from this moment.
- if (unsaving) _liked.value = _liked.value - trackUri
- else if (toLibrary) _liked.value = _liked.value + trackUri
- else _inPlaylists.value = _inPlaylists.value + trackUri
+ _inPlaylists.value = _inPlaylists.value + trackUri
// The detail screen holds a list resolved before this track
// was in it; if that is the playlist just written to, read
// it again.
@@ -1084,22 +1100,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
.onFailure {
android.util.Log.e(TAG, "add to playlist failed: ${chain(it)}", it)
- // The same 403 the followed artists take, for the same
- // reason: an application connected before a permission was
- // asked for holds a token that will never be allowed to do
- // this. Saying the playlist is not yours would be a lie
- // about Liked Songs, which is nobody else's.
val forbidden = describe(it).contains("403")
if (forbidden) _webApi.value = _webApi.value.copy(expired = true)
_addToPlaylist.value = _addToPlaylist.value.copy(
busy = null,
error = when {
forbidden -> string(R.string.permission_needed)
- unsaving -> string(R.string.unlike_failed)
- toLibrary -> string(R.string.like_failed)
- // A playlist the account follows but does not own is
- // the one failure worth naming: it looks identical
- // to the user's own in every list the app draws.
else -> string(R.string.add_failed, playlist.name)
},
)
@@ -1158,6 +1164,30 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
return
}
+ val spotifyLink = dev.lelonio.square.data.util.SpotifyLinkParser.parse(query)
+ if (spotifyLink != null) {
+ searchJob = viewModelScope.launch {
+ _search.value = _search.value.copy(loading = true, error = null)
+ runCatching {
+ resolveSpotifyLink(spotifyLink)
+ }.onSuccess { results ->
+ currentCoroutineContext().ensureActive()
+ _search.value = _search.value.copy(
+ loading = false,
+ results = results,
+ needsSetup = false,
+ loadingMore = false,
+ exhausted = true,
+ )
+ }.onFailure {
+ if (it is kotlinx.coroutines.CancellationException) throw it
+ android.util.Log.e(TAG, "resolve link failed: ${chain(it)}", it)
+ _search.value = _search.value.copy(loading = false, error = describe(it))
+ }
+ }
+ return
+ }
+
searchJob = viewModelScope.launch {
delay(SEARCH_DEBOUNCE_MS)
_search.value = _search.value.copy(loading = true, error = null)
@@ -1198,6 +1228,64 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ private suspend fun resolveSpotifyLink(link: dev.lelonio.square.data.util.SpotifyLink): SearchResults =
+ withContext(Dispatchers.IO) {
+ when (link) {
+ is dev.lelonio.square.data.util.SpotifyLink.Track -> {
+ val trackDto = runCatching { container.api.track(link.id) }.getOrNull()
+ if (trackDto != null) {
+ SearchResults(tracks = listOf(trackDto.toCatalogTrack()))
+ } else {
+ val tracks = runCatching { Catalog.tracks(listOf(link.uri)) }.getOrDefault(emptyList())
+ SearchResults(tracks = tracks)
+ }
+ }
+ is dev.lelonio.square.data.util.SpotifyLink.Album -> {
+ val tracks = runCatching { container.activeBackend.tracksOf(link.uri) }.getOrDefault(emptyList())
+ val albumDto = runCatching { container.api.album(link.id) }.getOrNull()
+ val first = tracks.firstOrNull()
+ val title = albumDto?.name ?: first?.album ?: string(R.string.album)
+ val subtitle = albumDto?.artists?.joinToString { it.name }
+ ?: first?.artist.orEmpty()
+ val artworkUrl = albumDto?.images?.firstOrNull()?.url ?: first?.artworkUrl
+ val albumItem = SearchItem(
+ uri = link.uri,
+ title = title,
+ subtitle = subtitle,
+ artworkUrl = artworkUrl,
+ )
+ SearchResults(albums = listOf(albumItem), tracks = tracks)
+ }
+ is dev.lelonio.square.data.util.SpotifyLink.Playlist -> {
+ val playlistDto = runCatching { container.api.playlist(link.id) }.getOrNull()
+ val tracks = runCatching { container.activeBackend.tracksOf(link.uri) }.getOrDefault(emptyList())
+ val title = playlistDto?.name ?: string(R.string.playlist)
+ val subtitle = playlistDto?.description.orEmpty().ifBlank { string(R.string.playlist) }
+ val artworkUrl = playlistDto?.images?.firstOrNull()?.url ?: tracks.firstOrNull()?.artworkUrl
+ val item = SearchItem(
+ uri = link.uri,
+ title = title,
+ subtitle = subtitle,
+ artworkUrl = artworkUrl,
+ )
+ SearchResults(playlists = listOf(item), tracks = tracks)
+ }
+ is dev.lelonio.square.data.util.SpotifyLink.Artist -> {
+ val artistDto = runCatching { container.api.artist(link.id) }.getOrNull()
+ val tracks = runCatching { container.activeBackend.tracksOf(link.uri) }.getOrDefault(emptyList())
+ val title = artistDto?.name ?: tracks.firstOrNull()?.artist ?: string(R.string.artist)
+ val artworkUrl = artistDto?.images?.firstOrNull()?.url ?: tracks.firstOrNull()?.artworkUrl
+ val item = SearchItem(
+ uri = link.uri,
+ title = title,
+ subtitle = string(R.string.artist),
+ artworkUrl = artworkUrl,
+ )
+ SearchResults(artists = listOf(item), tracks = tracks)
+ }
+ }
+ }
+
/**
* The next page of the same search, appended.
*
@@ -1306,14 +1394,18 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* token is only valid for the application it was issued to, so the Web API
* needs its own even though it is the same Spotify account behind both.
*/
- fun connectWebApi() = viewModelScope.launch {
- val clientId = _webApi.value.clientId.trim()
- if (clientId.isEmpty()) {
- _webApi.value = _webApi.value.copy(error = string(R.string.enter_client_id))
- return@launch
- }
+ private var webApiJob: Job? = null
+
+ fun connectWebApi() {
+ webApiJob?.takeIf { it.isActive }?.let { return }
+ webApiJob = viewModelScope.launch {
+ val clientId = _webApi.value.clientId.trim()
+ if (clientId.isEmpty()) {
+ _webApi.value = _webApi.value.copy(error = string(R.string.enter_client_id))
+ return@launch
+ }
- _webApi.value = _webApi.value.copy(connecting = true, error = null, expired = false)
+ _webApi.value = _webApi.value.copy(connecting = true, error = null, expired = false)
container.webApi.setClientId(clientId)
runCatching {
// Search needs no scope — it reads public catalogue data — but the
@@ -1352,19 +1444,24 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
),
)
}
- .onSuccess {
- container.webApi.tokens.save(it)
- _webApi.value = _webApi.value.copy(connecting = false, connected = true)
- _search.value = _search.value.copy(needsSetup = false)
- // The feed could not have loaded before this point.
- loadFeed()
- // Re-run whatever the user had already typed.
- _search.value.query.takeIf { q -> q.isNotBlank() }?.let(::onSearchQuery)
+ .onSuccess { tokens ->
+ runCatching {
+ container.webApi.tokens.save(tokens)
+ _webApi.value = _webApi.value.copy(connecting = false, connected = true)
+ _search.value = _search.value.copy(needsSetup = false)
+ // The feed could not have loaded before this point.
+ loadFeed()
+ // Re-run whatever the user had already typed.
+ _search.value.query.takeIf { q -> q.isNotBlank() }?.let(::onSearchQuery)
+ }.onFailure { ex ->
+ android.util.Log.e(TAG, "post-login setup failed: ${chain(ex)}", ex)
+ }
}
.onFailure {
android.util.Log.e(TAG, "web api login failed: ${chain(it)}", it)
_webApi.value = _webApi.value.copy(connecting = false, error = describe(it))
}
+ }
}
fun disconnectWebApi() {
@@ -1670,24 +1767,42 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
- fun logIn() = viewModelScope.launch {
- _state.value = UiState.Loading
- runCatching { SpotifyOAuth.authorize(getApplication()) }
- .onSuccess {
- container.tokenStore.save(it)
- // The service was created before this session existed, so it has
- // to be told to authenticate the native engine now.
- PlaybackService.connect(getApplication())
- refresh()
- }
- .onFailure {
- android.util.Log.e(TAG, "login failed: ${chain(it)}", it)
- _state.value = UiState.Failed(describe(it))
- }
+ private var loginJob: Job? = null
+
+ fun logIn() {
+ loginJob?.takeIf { it.isActive }?.let { return }
+ loginJob = viewModelScope.launch {
+ _state.value = UiState.Loading
+ runCatching { SpotifyOAuth.authorize(getApplication()) }
+ .onSuccess {
+ container.tokenStore.save(it)
+ // The service was created before this session existed, so it has
+ // to be told to authenticate the native engine now.
+ PlaybackService.connect(getApplication())
+ refresh()
+ }
+ .onFailure {
+ if (it is kotlinx.coroutines.CancellationException) return@launch
+ android.util.Log.e(TAG, "login failed: ${chain(it)}", it)
+ _state.value = UiState.Failed(describe(it))
+ }
+ }
+ }
+
+ /** Retries login if not signed in yet, or refreshes the library if signed in. */
+ fun retryFailed() {
+ if (!container.spotifySignedIn && container.activeBackend.id == BackendId.SPOTIFY) {
+ logIn()
+ } else {
+ refresh()
+ }
}
fun logOut() {
+ loginJob?.cancel()
+ SpotifyOAuth.cancelActiveAuthorization()
container.tokenStore.clear()
+ container.webApi.disconnect()
// The engine's own credential too, or the next launch would log itself
// back in with it and signing out would mean nothing.
dev.lelonio.square.auth.EngineCredentials.clear(getApplication())
@@ -1905,22 +2020,15 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// ninety on the phone is a shelf that lies. The playlists are listed
// beside it either way, so this is the one place that answers "what can
// I play right now" without picking through them.
- val shelf = container.downloads.files.value.keys.takeIf { it.isNotEmpty() }?.let {
- CatalogPlaylist(
- uri = DownloadStore.SINGLES,
- name = string(R.string.downloaded_tracks),
- artworkUrl = dev.lelonio.square.ui.components.DOWNLOADS_COVER,
- )
- }
- val everything = listOfNotNull(shelf) + labelled
- if (everything.isEmpty()) return null
+ val everything = labelled
+ if (everything.isEmpty() && container.downloads.files.value.isEmpty()) return null
android.util.Log.i(TAG, "offline library: ${everything.size} downloaded")
// The name and the picture from the last time there was a connection.
// They cost nothing to keep and their absence reads as being signed
// out, which is not what has happened.
val (name, avatar) = container.preferences.profile()
- // The phone's own files belong here as much as they do online.
+ // The downloaded music shelf belongs here as much as it does online.
return UiState.Ready(name, withLocalFiles(everything), avatarUrl = avatar)
}
@@ -1936,16 +2044,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
withLocalFiles(container.activeBackend.playlists())
/**
- * The phone's own music, at the head of whichever library is on screen.
- *
- * Not a third service to switch to: a file on this phone is there whether
- * the listener is on Spotify or on YouTube Music, exactly as it is in
- * Spotify's own client, so it belongs in both libraries rather than behind
- * a setting that swaps one for the other.
- *
- * Shown whether or not the permission has been given. Hiding it until then
- * would leave the listener nowhere to say yes: the shelf is where the
- * asking happens.
+ * The phone's own music and downloaded music, at the head of whichever library is on screen.
*/
private fun withLocalFiles(playlists: List<CatalogPlaylist>): List<CatalogPlaylist> =
listOf(
@@ -1954,7 +2053,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
name = string(R.string.local_files),
artworkUrl = LocalLibrary.COVER,
),
- ) + playlists.filterNot { it.uri == LocalLibrary.CONTEXT_URI }
+ CatalogPlaylist(
+ uri = DownloadStore.SINGLES,
+ name = string(R.string.downloaded_tracks),
+ artworkUrl = dev.lelonio.square.ui.components.DOWNLOADS_COVER,
+ ),
+ ) + playlists.filterNot { it.uri == DownloadStore.SINGLES || it.uri == LocalLibrary.CONTEXT_URI }
.distinctBy { it.uri }
/** Covers already looked up, so a second visit to the home page is free. */
@@ -1992,8 +2096,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** The account's own Spotify id, once the profile has been read. */
private var meId: String? = null
+ /** The account's country, for endpoints that require market code. */
+ private val userCountry: String get() = container.userCountry
- private fun loadProfile() = viewModelScope.launch {
+ fun loadProfile() = viewModelScope.launch {
if (!container.webApi.isReady) return@launch
runCatching { container.api.me() }
.onSuccess { profile ->
@@ -2007,6 +2113,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// list mine. The id, not the display name — two accounts can
// be called the same thing and only one of them owns it.
meId = profile.id
+ profile.country?.takeIf { it.isNotBlank() }?.let {
+ container.preferences.setUserCountry(it.uppercase())
+ }
// And kept on disk, for the next time there is no network to
// ask with; see [offlineLibrary].
container.preferences.setProfile(
@@ -2061,6 +2170,16 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
fun setOnboarded(value: Boolean) = container.preferences.setOnboarded(value)
+ /** Infinite autoplay: whether to fetch similar tracks when queue reaches the end. */
+ val autoplayInfinite: StateFlow<Boolean> get() = container.preferences.autoplayInfinite
+
+ fun setAutoplayInfinite(value: Boolean) = container.preferences.setAutoplayInfinite(value)
+
+ /** Silence trimming: whether to trim trailing silence during crossfade. */
+ val trimSilence: StateFlow<Boolean> get() = container.preferences.trimSilence
+
+ fun setTrimSilence(value: Boolean) = container.preferences.setTrimSilence(value)
+
/**
* Loads a playlist's tracks.
*
@@ -2182,7 +2301,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* than showing a state nobody checked.
*/
private suspend fun savedState(uri: String): Boolean? {
- if (!container.webApi.isReady) return null
+ if (!container.webApi.isReady && !container.tokenStore.isLoggedIn) return null
val id = uri.substringAfterLast(':')
return runCatching {
when {
@@ -2266,17 +2385,22 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val kind = kindOf(uri)
val id = uri.substringAfterLast(':')
- if (container.webApi.isReady) {
- runCatching {
- when (kind) {
- DetailKind.ARTIST -> container.api.artist(id).name
- DetailKind.ALBUM -> container.api.album(id).name
- DetailKind.PLAYLIST -> container.api.playlist(id).name
- }
+ val apiName = runCatching {
+ when (kind) {
+ DetailKind.ARTIST -> if (container.webApi.isReady) container.api.artist(id).name else null
+ DetailKind.ALBUM -> if (container.webApi.isReady) container.api.album(id).name else null
+ DetailKind.PLAYLIST -> if (container.webApi.isReady) container.api.playlist(id).name else null
}
- .onFailure { android.util.Log.w(TAG, "no name for $uri: ${describe(it)}") }
- .getOrNull()
- ?.let { return it }
+ }
+ .onFailure { android.util.Log.w(TAG, "no name for $uri: ${describe(it)}") }
+ .getOrNull()
+
+ if (!apiName.isNullOrEmpty()) return apiName
+
+ if (kind == DetailKind.ARTIST) {
+ runCatching {
+ dev.lelonio.square.data.SpotifyWebArtist.fetch(id, container.sharedHttpClient, getApplication<SquareApplication>().resources)?.name
+ }.getOrNull()?.takeIf { it.isNotEmpty() }?.let { return it }
}
// The Web API answers 404 for everything Spotify generates itself — the
@@ -2323,11 +2447,13 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
suspend fun retryOnline(): Boolean {
container.downloadSettings.setOfflineMode(false)
withContext(Dispatchers.IO) {
+ runCatching { NativeBridge.setOfflineOnly(false) }
runCatching { NativeBridge.reconnect() }
.onFailure { android.util.Log.w(TAG, "retry failed: ${describe(it)}") }
}
- val offline = runCatching { NativeBridge.isOffline }.getOrDefault(true)
+ val offline = runCatching { NativeBridge.isOffline }.getOrDefault(false)
dev.lelonio.square.playback.OfflineMode.setNoSession(offline)
+ dev.lelonio.square.playback.OfflineMode.setSlow(false)
if (!offline) {
// The library was built from the download index while there was no
// session; now there is one, and it is a different library.
@@ -2510,7 +2636,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// Liked Songs is not one of the playlists, and the player says so with
// a heart rather than a tick.
if (contextUri.endsWith(":collection")) {
- _liked.value = _liked.value + tracks.map { it.uri }
+ container.likedStore.seed(tracks.map { it.uri })
// Just read, so nothing missing from it is saved. The seeding
// below is left to run: it is the tick's half that this says
// nothing about.
@@ -2521,20 +2647,177 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
_inPlaylists.value = _inPlaylists.value + tracks.map { it.uri }
}
- private val _liked = MutableStateFlow<Set<String>>(emptySet())
-
/**
* Tracks known to be in Liked Songs.
*
- * Read from the list itself wherever possible rather than asked about one
- * track at a time. Spotify will answer "is this saved?" for a single URI,
- * and asking that once a song for as long as the music plays is both a
- * request the app does not need — it has usually read the whole list
- * already — and a pattern nothing but a machine produces. So the copy of
- * Liked Songs on disk answers first, and the network only hears about the
- * tracks it cannot.
+ * Delegated to the persistent [LikedStore] so state survives app restarts
+ * and stays in lockstep with the notification and car controllers.
*/
- val likedTracks: StateFlow<Set<String>> = _liked.asStateFlow()
+ val likedTracks: StateFlow<Set<String>> = container.likedStore.likedTracks
+
+ /**
+ * Direct toggle for Liked Songs ("Tus me gusta").
+ *
+ * Flips local state immediately for zero-latency UI response, syncs with Spotify
+ * in the background, and keeps offline downloads updated if enabled.
+ */
+ fun toggleLike(
+ trackUri: String?,
+ trackTitle: String? = null,
+ artist: String? = null,
+ artworkUrl: String? = null,
+ playlistName: String? = null,
+ ) {
+ if (trackUri == null || !trackUri.startsWith("spotify:track:")) return
+ val nowLiked = container.likedStore.toggle(trackUri)
+ val id = trackUri.substringAfterLast(':')
+
+ if (_addToPlaylist.value.trackUri == trackUri) {
+ _addToPlaylist.value = _addToPlaylist.value.copy(liked = nowLiked)
+ }
+
+ // Build or find the CatalogTrack for immediate local collection update
+ val resolvedTrack = _playlist.value.tracks.find { it.uri == trackUri }
+ ?: contextCache.values.firstNotNullOfOrNull { entry -> entry.tracks.find { it.uri == trackUri } }
+ ?: CatalogTrack(
+ uri = trackUri,
+ name = trackTitle.orEmpty().ifEmpty { "Track" },
+ artist = artist.orEmpty(),
+ artworkUrl = artworkUrl,
+ )
+
+ // Immediately update Liked Songs in memory and disk cache
+ val colUri = runCatching { NativeBridge.collectionUri() }.getOrNull()?.takeIf { it.isNotEmpty() }
+ val targetUris = (contextCache.keys.filter { it.endsWith(":collection") } + listOfNotNull(colUri)).toSet()
+ for (cUri in targetUris) {
+ val cachedEntry = contextCache[cUri]
+ if (cachedEntry != null) {
+ val updatedList = if (nowLiked) {
+ listOf(resolvedTrack) + cachedEntry.tracks.filterNot { it.uri == trackUri }
+ } else {
+ cachedEntry.tracks.filterNot { it.uri == trackUri }
+ }
+ contextCache[cUri] = cachedEntry.copy(tracks = updatedList)
+ viewModelScope.launch {
+ container.contextCache.write(cUri, updatedList, cachedEntry.snapshotId)
+ }
+ } else if (cUri.isNotEmpty()) {
+ viewModelScope.launch {
+ val diskEntry = container.contextCache.read(cUri)
+ if (diskEntry != null) {
+ val updatedList = if (nowLiked) {
+ listOf(resolvedTrack) + diskEntry.tracks.filterNot { it.uri == trackUri }
+ } else {
+ diskEntry.tracks.filterNot { it.uri == trackUri }
+ }
+ contextCache[cUri] = diskEntry.copy(tracks = updatedList)
+ container.contextCache.write(cUri, updatedList, diskEntry.snapshotId)
+ }
+ }
+ }
+ }
+
+ // If currently viewing Liked Songs screen, update UI tracks immediately
+ if (_playlist.value.uri?.endsWith(":collection") == true || (_playlist.value.uri != null && _playlist.value.uri == colUri)) {
+ val currentTracks = _playlist.value.tracks
+ val updated = if (nowLiked) {
+ listOf(resolvedTrack) + currentTracks.filterNot { it.uri == trackUri }
+ } else {
+ currentTracks.filterNot { it.uri == trackUri }
+ }
+ _playlist.value = _playlist.value.copy(tracks = updated)
+ }
+
+ viewModelScope.launch {
+ val syncResult = runCatching {
+ if (nowLiked) {
+ container.api.saveToLibrary("spotify:track:$id", SpotifyApi.EMPTY_BODY)
+ } else {
+ container.api.removeFromLibrary("spotify:track:$id")
+ }
+ }.onSuccess {
+ android.util.Log.i(TAG, "toggleLike remote sync succeeded for $id (nowLiked=$nowLiked)")
+ if (_addToPlaylist.value.trackUri == trackUri) {
+ _addToPlaylist.value = _addToPlaylist.value.copy(
+ busy = null,
+ done = if (nowLiked) playlistName ?: string(R.string.liked_songs) else null,
+ removed = if (!nowLiked) playlistName ?: string(R.string.liked_songs) else null,
+ liked = nowLiked,
+ error = null,
+ )
+ }
+ }.onFailure { ex ->
+ android.util.Log.w(TAG, "toggleLike remote sync failed for $id: ${ex.message}", ex)
+ // Revert local state because Spotify call failed
+ container.likedStore.toggle(trackUri)
+ val revertedLiked = !nowLiked
+
+ val forbidden = describe(ex).contains("403") || (ex as? retrofit2.HttpException)?.code() == 403
+ if (forbidden) _webApi.value = _webApi.value.copy(expired = true)
+
+ val errorMsg = when {
+ forbidden -> string(R.string.permission_needed)
+ nowLiked -> string(R.string.like_failed)
+ else -> string(R.string.unlike_failed)
+ }
+
+ if (_addToPlaylist.value.trackUri == trackUri) {
+ _addToPlaylist.value = _addToPlaylist.value.copy(
+ busy = null,
+ done = null,
+ removed = null,
+ liked = revertedLiked,
+ error = errorMsg,
+ )
+ } else {
+ viewModelScope.launch(kotlinx.coroutines.Dispatchers.Main) {
+ android.widget.Toast.makeText(getApplication(), errorMsg, android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+
+ // Revert Liked Songs in memory and disk cache
+ val colUriRevert = runCatching { NativeBridge.collectionUri() }.getOrNull()?.takeIf { it.isNotEmpty() }
+ val targetUrisRevert = (contextCache.keys.filter { it.endsWith(":collection") } + listOfNotNull(colUriRevert)).toSet()
+ for (cUri in targetUrisRevert) {
+ val cachedEntry = contextCache[cUri]
+ if (cachedEntry != null) {
+ val updatedList = if (revertedLiked) {
+ listOf(resolvedTrack) + cachedEntry.tracks.filterNot { it.uri == trackUri }
+ } else {
+ cachedEntry.tracks.filterNot { it.uri == trackUri }
+ }
+ contextCache[cUri] = cachedEntry.copy(tracks = updatedList)
+ launch {
+ container.contextCache.write(cUri, updatedList, cachedEntry.snapshotId)
+ }
+ }
+ }
+
+ if (_playlist.value.uri?.endsWith(":collection") == true || (_playlist.value.uri != null && _playlist.value.uri == colUriRevert)) {
+ val currentTracks = _playlist.value.tracks
+ val updated = if (revertedLiked) {
+ listOf(resolvedTrack) + currentTracks.filterNot { it.uri == trackUri }
+ } else {
+ currentTracks.filterNot { it.uri == trackUri }
+ }
+ _playlist.value = _playlist.value.copy(tracks = updated)
+ }
+ }
+
+ if (syncResult.isSuccess && container.downloadSettings.downloadLikedSongs.value) {
+ if (nowLiked) {
+ container.downloads.addLiked(resolvedTrack)
+ dev.lelonio.square.download.DownloadService.start(container)
+ } else {
+ container.downloads.removeLiked(trackUri)
+ container.downloads.pruneOrphans().forEach {
+ runCatching { NativeBridge.removeDownload(it) }
+ dev.lelonio.square.download.DownloadExtras.forget(it)
+ }
+ }
+ }
+ }
+ }
/** Tracks already asked about, saved or not, so each is asked once. */
private val likedAsked = mutableSetOf<String>()
@@ -2559,7 +2842,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (uri == null || !uri.startsWith("spotify:track:")) return
viewModelScope.launch {
seedMembership()
- if (uri in _liked.value || likedListTrusted) return@launch
+ if (container.likedStore.isLiked(uri) || likedListTrusted) return@launch
if (!likedAsked.add(uri)) return@launch
likedPending += uri
@@ -2595,7 +2878,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val liked = collection.takeIf { it.isNotEmpty() }
?.let { contextCache[it] ?: container.contextCache.read(it) }
if (liked != null) {
- _liked.value = _liked.value + liked.tracks.map { it.uri }
+ container.likedStore.seed(liked.tracks.map { it.uri })
// Never downwards: this run may already have read the list itself,
// which is fresher than anything on disk.
likedListTrusted = likedListTrusted ||
@@ -2624,12 +2907,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
return
}
val saved = uris.filterIndexed { index, _ -> answers.getOrNull(index) == true }
- if (saved.isNotEmpty()) _liked.value = _liked.value + saved
+ if (saved.isNotEmpty()) container.likedStore.seed(saved)
}
/** The same question through the listener's own application. */
private suspend fun webApiSaved(uris: List<String>): List<Boolean>? {
- if (!container.webApi.isReady) return null
+ if (!container.webApi.isReady && !container.tokenStore.isLoggedIn) return null
return runCatching {
container.api.tracksAreSaved(uris.joinToString(",") { it.substringAfterLast(':') })
}
@@ -2643,6 +2926,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
size > CONTEXT_CACHE_SIZE
}
+ private val artistPageCache =
+ object : LinkedHashMap<String, ArtistPage>(0, 0.75f, true) {
+ override fun removeEldestEntry(eldest: Map.Entry<String, ArtistPage>) =
+ size > 30
+ }
+
// ------------------------------------------------------------ downloads
/** What is on the phone, per track; see DownloadStore. */
@@ -2834,6 +3123,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** And when it goes, so does everything behind it. */
fun detailClosed() {
pageOnScreen = false
+ playlistJob?.cancel()
+ _playlist.value = PlaylistState()
clearPageHistory()
}
@@ -2844,7 +3135,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* the page underneath is then a tab, not another detail.
*/
fun popPage(): Boolean {
- val previous = pageStack.removeLastOrNull() ?: return false
+ while (pageStack.isNotEmpty() && pageStack.last().uri == _playlist.value.uri) {
+ pageStack.removeLast()
+ }
+ val previous = pageStack.removeLastOrNull()
+ if (previous == null) {
+ playlistJob?.cancel()
+ return false
+ }
playlistJob?.cancel()
_playlist.value = previous
_hasPreviousPage.value = pageStack.isNotEmpty()
@@ -2872,16 +3170,17 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// should be instant.
_playlist.value
.takeIf {
- pageOnScreen && it.uri != null && it.uri != playlist.uri &&
- it.tracks.isNotEmpty()
+ pageOnScreen && it.uri != null && it.uri != playlist.uri
}
?.let {
- pageStack.addLast(it)
- // Deep enough to walk back through a listening session, short
- // enough that a thousand-track playlist is not held forever.
- while (pageStack.size > PAGE_HISTORY) pageStack.removeFirst()
- _hasPreviousPage.value = true
- _pageDepth.value = pageStack.size
+ if (pageStack.lastOrNull()?.uri != it.uri) {
+ pageStack.addLast(it)
+ // Deep enough to walk back through a listening session, short
+ // enough that a thousand-track playlist is not held forever.
+ while (pageStack.size > PAGE_HISTORY) pageStack.removeFirst()
+ _hasPreviousPage.value = true
+ _pageDepth.value = pageStack.size
+ }
}
// A station reopens as the list it already is; see [showStation].
@@ -2895,29 +3194,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// the home page should keep at the front.
container.playlistOrder.record(playlist.uri)
- // The phone's own music answers for itself: no service to ask, no
- // snapshot to compare, and nothing worth keeping on disk about files
- // that are already on disk.
- if (LocalLibrary.isLocalContext(playlist.uri)) {
+ if (playlist.uri == LocalLibrary.CONTEXT_URI) {
openLocalFiles(playlist)
return
}
- // The shelf of downloaded songs is not a context at all: its uri
- // belongs to this app rather than to Spotify, and asking the access
- // point to resolve it answered "invalid argument". This app keeps the
- // list, so this app answers for it — online as much as offline, and
- // with everything on the phone rather than only the loose songs.
+ // The shelf of downloaded songs contains all songs downloaded to the phone.
if (playlist.uri == DownloadStore.SINGLES) {
- // Newest first: a shelf of everything is read from the top, and
- // what was just downloaded is what somebody came looking for.
- openDownloadedContext(
- playlist,
- container.downloads.files.value
- .entries
- .sortedByDescending { it.value.downloadedAt }
- .map { it.key },
- )
+ openDownloadedTracks(playlist)
return
}
@@ -2946,11 +3230,32 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
kind = kind,
)
+ val rememberedArtist = if (kind == DetailKind.ARTIST) artistPageCache[playlist.uri] else null
val remembered = contextCache[playlist.uri]
- publishPlaylist(base.copy(
- tracks = remembered?.tracks.orEmpty(),
- loading = remembered == null,
- ))
+ if (rememberedArtist != null) {
+ publishPlaylist(base.copy(
+ name = base.name.ifEmpty { rememberedArtist.name.orEmpty() },
+ artworkUrl = base.artworkUrl ?: rememberedArtist.artworkUrl,
+ tracks = rememberedArtist.tracks.take(5),
+ latest = rememberedArtist.latest,
+ albums = rememberedArtist.albums,
+ singles = rememberedArtist.singles,
+ appearsOn = rememberedArtist.appearsOn,
+ artistPlaylists = rememberedArtist.playlists,
+ relatedArtists = rememberedArtist.relatedArtists,
+ verified = true,
+ monthlyListeners = rememberedArtist.monthlyListeners,
+ followers = rememberedArtist.followers,
+ genres = rememberedArtist.genres,
+ notes = base.notes ?: rememberedArtist.biography,
+ loading = false,
+ ))
+ } else {
+ publishPlaylist(base.copy(
+ tracks = remembered?.tracks.orEmpty(),
+ loading = remembered == null,
+ ))
+ }
playlistJob = viewModelScope.launch {
// Opened by URI alone, from a tap on the player's text: there was no
@@ -2965,7 +3270,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (base.name.isEmpty()) launch {
val name = nameOf(playlist.uri) ?: return@launch
base = base.copy(name = name)
- if (_playlist.value.uri == playlist.uri) {
+ if (isActive && _playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(name = name)
}
}
@@ -2988,7 +3293,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
mine = mine,
byline = details.owner.orEmpty(),
)
- if (_playlist.value.uri == playlist.uri) {
+ if (isActive && _playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(
description = text.orEmpty().ifEmpty { _playlist.value.description },
mine = mine,
@@ -3000,7 +3305,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// Whether it is already kept, for the button that keeps it.
if (kind != DetailKind.ARTIST) launch {
val kept = savedState(playlist.uri) ?: return@launch
- if (_playlist.value.uri == playlist.uri) {
+ if (isActive && _playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(saved = kept)
}
base = base.copy(saved = kept)
@@ -3014,7 +3319,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (kind == DetailKind.ARTIST || kind == DetailKind.ALBUM) {
if (!dev.lelonio.square.playback.OfflineMode.active.value) {
base = base.copy(heroPending = true)
- if (_playlist.value.uri == playlist.uri) {
+ if (isActive && _playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(heroPending = true)
}
}
@@ -3024,7 +3329,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (base.artworkUrl == null) launch {
val art = artworkFor(playlist.uri, kind) ?: return@launch
base = base.copy(artworkUrl = art)
- if (_playlist.value.uri == playlist.uri) {
+ if (isActive && _playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(artworkUrl = art)
}
}
@@ -3039,27 +3344,38 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
val cached = entry?.tracks.orEmpty()
- runCatching {
+ try {
if (!playlist.uri.startsWith("spotify:")) {
// Another backend's context. Resolved in one call rather
// than page by page: the Spotify paths below are built
// around the Web API's paging and the access point's
// per-track lookups, neither of which exists here.
val tracks = container.activeBackend.tracksOf(playlist.uri)
- publishPlaylist(base.copy(tracks = tracks, loading = false))
+ if (isActive && _playlist.value.uri == playlist.uri) {
+ publishPlaylist(base.copy(tracks = tracks, loading = false))
+ }
} else if (kind == DetailKind.ARTIST) {
- val page = loadArtist(playlist.uri)
+ val page = loadArtist(playlist.uri, base.name.ifEmpty { playlist.name })
+ if (!isActive || _playlist.value.uri != playlist.uri) return@launch
+ artistPageCache[playlist.uri] = page
publishPlaylist(
base.copy(
- tracks = page.tracks,
+ name = base.name.ifEmpty { page.name.orEmpty() },
+ artworkUrl = base.artworkUrl ?: page.artworkUrl,
+ tracks = page.tracks.take(5),
latest = page.latest,
albums = page.albums,
singles = page.singles,
appearsOn = page.appearsOn,
artistPlaylists = page.playlists,
+ relatedArtists = page.relatedArtists,
+ verified = true,
+ monthlyListeners = page.monthlyListeners,
followers = page.followers,
genres = page.genres,
+ notes = base.notes ?: page.biography,
following = _playlist.value.following,
+ loading = false,
),
)
@@ -3069,7 +3385,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
page.latest?.let { release ->
launch {
val kept = savedState(release.uri) ?: return@launch
- if (_playlist.value.uri == playlist.uri) {
+ if (isActive && _playlist.value.uri == playlist.uri) {
_playlist.value = _playlist.value.copy(latestSaved = kept)
}
}
@@ -3077,19 +3393,25 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
} else if (cached.isNotEmpty() && isUnchanged(playlist.uri, entry?.snapshotId)) {
// Nothing to do: one small request said the copy on screen
// is the current one.
- publishPlaylist(base.copy(tracks = cached, loadingMore = false))
+ if (isActive && _playlist.value.uri == playlist.uri) {
+ publishPlaylist(base.copy(tracks = cached, loadingMore = false))
+ }
} else {
loadContextInto(base, playlist.uri, showProgress = cached.isEmpty())
}
- }
- .onFailure {
- android.util.Log.e(TAG, "detail load failed: ${chain(it)}", it)
- // Only when there is nothing to show. A refresh that fails
- // over a list already on screen should leave the list.
+ } catch (e: CancellationException) {
+ // Cooperative cancellation: do NOT treat job cancellation as a failure or set error on the screen!
+ throw e
+ } catch (t: Throwable) {
+ android.util.Log.e(TAG, "detail load failed: ${chain(t)}", t)
+ if (isActive && _playlist.value.uri == playlist.uri) {
+ val hasCachedContent = cached.isNotEmpty() || rememberedArtist != null
+ val fallbackTracks = cached.ifEmpty { rememberedArtist?.tracks.orEmpty() }
publishPlaylist(
- if (cached.isEmpty()) base.copy(error = describe(it)) else base.copy(tracks = cached),
+ if (!hasCachedContent) base.copy(error = describe(t), loading = false) else base.copy(tracks = fallbackTracks, loading = false),
)
}
+ }
}
}
@@ -3102,10 +3424,101 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* it is the only case in the app where an empty list is something to act
* on rather than to report.
*/
+ /**
+ * All songs downloaded to this phone, sorted newest first, updated live as downloads complete.
+ */
+ private fun openDownloadedTracks(playlist: CatalogPlaylist) {
+ playlistJob?.cancel()
+ val name = playlist.name.ifEmpty { string(R.string.downloaded_tracks) }
+ val base = PlaylistState(
+ uri = DownloadStore.SINGLES,
+ name = name,
+ artworkUrl = dev.lelonio.square.ui.components.DOWNLOADS_COVER,
+ kind = DetailKind.PLAYLIST,
+ mine = false,
+ )
+
+ val resolvedInMemory = mutableMapOf<String, CatalogTrack>()
+
+ fun resolveList(uris: List<String>): List<CatalogTrack> {
+ val known = uris.mapNotNull { container.downloads.trackOf(it) ?: resolvedInMemory[it] }
+ .associateBy { it.uri }
+ return uris.map { uri ->
+ known[uri] ?: CatalogTrack(
+ uri = uri,
+ name = uri.substringAfterLast(':'),
+ artist = "",
+ )
+ }
+ }
+
+ // Snapshot of downloads right now so the user sees songs with 0 delay
+ val filesSnapshot = container.downloads.files.value
+ val uris = filesSnapshot.entries
+ .sortedByDescending { it.value.downloadedAt }
+ .map { it.key }
+
+ val missingInitial = uris.filter { container.downloads.trackOf(it) == null }
+
+ publishPlaylist(
+ base.copy(
+ tracks = resolveList(uris),
+ loading = missingInitial.isNotEmpty(),
+ ),
+ )
+
+ playlistJob = viewModelScope.launch {
+ if (missingInitial.isNotEmpty() && !dev.lelonio.square.playback.OfflineMode.active.value) {
+ runCatching {
+ val fetched = withContext(Dispatchers.IO) {
+ Catalog.tracks(missingInitial)
+ }
+ if (fetched.isNotEmpty()) {
+ fetched.forEach { resolvedInMemory[it.uri] = it }
+ publishPlaylist(base.copy(tracks = resolveList(uris), loading = false))
+ }
+ }
+ }
+
+ // Observe downloads flow in real time while this screen is open
+ container.downloads.files.collect { currentFiles ->
+ val currentUris = currentFiles.entries
+ .sortedByDescending { it.value.downloadedAt }
+ .map { it.key }
+
+ val missing = currentUris.filter { container.downloads.trackOf(it) == null && !resolvedInMemory.containsKey(it) }
+ if (missing.isNotEmpty() && !dev.lelonio.square.playback.OfflineMode.active.value) {
+ runCatching {
+ val fetched = withContext(Dispatchers.IO) {
+ Catalog.tracks(missing)
+ }
+ if (fetched.isNotEmpty()) {
+ fetched.forEach { resolvedInMemory[it.uri] = it }
+ }
+ }
+ }
+
+ publishPlaylist(
+ base.copy(
+ tracks = resolveList(currentUris),
+ loading = false,
+ ),
+ )
+ }
+ }
+ }
+
/** A downloaded list, read out of the index rather than off the network. */
private fun openDownloadedContext(playlist: CatalogPlaylist, wanted: List<String>) {
playlistJob?.cancel()
val label = container.downloads.labelOf(playlist.uri)
+ val resolvedTracks = wanted.map { uri ->
+ container.downloads.trackOf(uri) ?: CatalogTrack(
+ uri = uri,
+ name = uri.substringAfterLast(':'),
+ artist = "",
+ )
+ }
publishPlaylist(
PlaylistState(
uri = playlist.uri,
@@ -3116,7 +3529,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
DownloadStore.KIND_ARTIST -> DetailKind.ARTIST
else -> DetailKind.PLAYLIST
},
- tracks = wanted.mapNotNull(container.downloads::trackOf),
+ tracks = resolvedTracks,
),
)
}
@@ -3126,11 +3539,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val base = PlaylistState(
uri = playlist.uri,
name = playlist.name,
- // The shelf's own tile, drawn rather than fetched; see Artwork.
artworkUrl = playlist.artworkUrl ?: LocalLibrary.COVER,
kind = DetailKind.PLAYLIST,
- // Nothing here belongs to an account, so none of what a playlist
- // page offers applies: no following, no editing, no removing.
mine = false,
)
publishPlaylist(base.copy(loading = true))
@@ -3151,7 +3561,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** Called once the listener has answered the system's permission dialog. */
fun onLocalPermissionAnswered() {
val open = _playlist.value
- if (!LocalLibrary.isLocalContext(open.uri)) return
+ if (open.uri != LocalLibrary.CONTEXT_URI) return
openLocalFiles(
CatalogPlaylist(
uri = open.uri.orEmpty(),
@@ -3175,17 +3585,22 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
?.let { return it }
val id = uri.substringAfterLast(':')
- if (container.webApi.isReady) {
- val fetched = runCatching {
- when (kind) {
- DetailKind.ARTIST -> container.api.artist(id).images
- DetailKind.ALBUM -> container.api.album(id).images
- DetailKind.PLAYLIST -> container.api.playlist(id).images
- }.firstOrNull()?.url
+
+ val fetched = runCatching {
+ when (kind) {
+ DetailKind.ARTIST -> if (container.webApi.isReady) container.api.artist(id).images.firstOrNull()?.url else null
+ DetailKind.ALBUM -> if (container.webApi.isReady) container.api.album(id).images.firstOrNull()?.url else null
+ DetailKind.PLAYLIST -> if (container.webApi.isReady) container.api.playlist(id).images.firstOrNull()?.url else null
}
- .onFailure { android.util.Log.w(TAG, "no cover for $uri: ${describe(it)}") }
- .getOrNull()
- if (fetched != null) return fetched
+ }
+ .onFailure { android.util.Log.w(TAG, "no cover for $uri: ${describe(it)}") }
+ .getOrNull()
+ if (fetched != null) return fetched
+
+ if (kind == DetailKind.ARTIST) {
+ runCatching {
+ dev.lelonio.square.data.SpotifyWebArtist.fetch(id, container.sharedHttpClient, getApplication<SquareApplication>().resources)?.artworkUrl
+ }.getOrNull()?.takeIf { !it.isNullOrEmpty() }?.let { return it }
}
// The access point carries the art for the lists Spotify generates,
@@ -3343,7 +3758,30 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
.onFailure { android.util.Log.w(TAG, "paged read failed: ${describe(it)}") }
.getOrNull()
- val tracks = paged ?: accessPointTracks(base, uri, showProgress)
+ var tracks = paged ?: accessPointTracks(base, uri, showProgress)
+ if (uri.endsWith(":collection")) {
+ val priorCached = contextCache[uri]?.tracks?.takeIf { it.isNotEmpty() }
+ ?: container.contextCache.read(uri)?.tracks?.takeIf { it.isNotEmpty() }
+ if (tracks.isEmpty() && priorCached != null) {
+ tracks = priorCached
+ }
+ val localLikedUris = container.likedStore.likedTracks.value
+ val existingUris = tracks.map { it.uri }.toSet()
+ val priorPool = (priorCached.orEmpty() + contextCache.values.flatMap { it.tracks })
+ val localExtras = priorPool
+ .filter { it.uri in localLikedUris && it.uri !in existingUris }
+ .distinctBy { it.uri }
+ if (localExtras.isNotEmpty()) {
+ tracks = localExtras + tracks
+ }
+ if (tracks.isEmpty() && localLikedUris.isNotEmpty()) {
+ val loaded = runCatching { Catalog.tracks(localLikedUris.toList()) }.getOrDefault(emptyList())
+ if (loaded.isNotEmpty()) {
+ tracks = loaded
+ }
+ }
+ container.likedStore.seed(tracks.map { it.uri })
+ }
publishPlaylist(base.copy(tracks = tracks, loadingMore = false))
@@ -3389,7 +3827,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// Nothing else knows this list: the access point refuses the
// collection as a context, so without the gateway and without a
// registered application there is no answer to give.
- check(container.webApi.isReady) { string(R.string.liked_songs_failed) }
+ check(container.webApi.isReady || container.tokenStore.isLoggedIn) { string(R.string.liked_songs_failed) }
return webApiSavedTracks(base, showProgress)
}
@@ -3425,7 +3863,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val loaded = mutableListOf<CatalogTrack>()
var offset = 0
while (true) {
- val page = container.api.playlistTracks(id, limit = WEB_API_PAGE, offset = offset)
+ val page = container.api.playlistTracks(id, limit = WEB_API_PAGE, offset = offset, market = userCountry)
// Episodes and delisted tracks come back as a null track, and
// `is_playable` is false for anything the relinking could not find a
// licensed copy of here. Keeping those would put items in the queue
@@ -3605,6 +4043,54 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
)
}
+ /**
+ * Resolves the artist for a track.
+ *
+ * Prefers the track's own artistUri or first credited artist; if missing on
+ * a Spotify track, looks it up via Web API.
+ */
+ suspend fun artistOf(track: CatalogTrack): SearchItem? {
+ val directUri = track.artistUri ?: track.artists.firstOrNull()?.uri
+ val name = track.artists.firstOrNull()?.name ?: track.artist
+ if (directUri != null) {
+ return SearchItem(
+ uri = directUri,
+ title = name,
+ subtitle = "",
+ artworkUrl = null,
+ )
+ }
+ if (track.uri.startsWith("spotify:track:") && container.webApi.isReady) {
+ val id = track.uri.substringAfterLast(':')
+ val dto = runCatching { container.api.track(id) }
+ .onFailure { android.util.Log.w(TAG, "no artist for ${track.uri}: ${describe(it)}") }
+ .getOrNull()
+ val firstArtist = dto?.artists?.firstOrNull()
+ if (firstArtist?.uri != null) {
+ return SearchItem(
+ uri = firstArtist.uri,
+ title = firstArtist.name.ifBlank { name },
+ subtitle = "",
+ artworkUrl = null,
+ )
+ }
+ }
+ if (name.isNotBlank()) {
+ val hit = runCatching {
+ container.api.search(query = name, type = "artist", limit = 1).artists?.items?.firstOrNull()
+ }.getOrNull()
+ if (hit?.uri != null) {
+ return SearchItem(
+ uri = hit.uri,
+ title = hit.name,
+ subtitle = "",
+ artworkUrl = hit.images.firstOrNull()?.url,
+ )
+ }
+ }
+ return null
+ }
+
/** Called when the track changes; cached and cheap on a repeat. */
fun loadNowPlayingArt(uri: String?, title: String, album: String, artist: String) {
nowPlayingArtJob?.cancel()
@@ -3812,93 +4298,328 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* application, hence the explicit message rather than a raw 401.
*/
/** Everything an artist page shows, gathered in one go. */
- private data class ArtistPage(
+ /** Everything an artist page shows, gathered in one go. */
+ data class ArtistPage(
val tracks: List<CatalogTrack>,
val latest: ArtistRelease?,
val albums: List<SearchItem>,
val singles: List<SearchItem>,
val appearsOn: List<SearchItem>,
val playlists: List<SearchItem>,
+ val relatedArtists: List<SearchItem>,
val followers: Int,
val genres: List<String>,
+ val monthlyListeners: String?,
+ val name: String? = null,
+ val artworkUrl: String? = null,
+ val biography: String? = null,
)
- private suspend fun loadArtist(uri: String): ArtistPage {
- if (!container.webApi.isReady) {
- error(string(R.string.artist_needs_app))
- }
+ private data class BasicArtistMeta(val name: String, val artworkUrl: String?, val followers: Int)
+
+ private suspend fun fetchArtistMetadata(id: String): BasicArtistMeta? = withContext(Dispatchers.IO) {
+ val token = dev.lelonio.square.nativecore.NativeBridge.accessToken() ?: return@withContext null
+ runCatching {
+ val request = okhttp3.Request.Builder()
+ .url("https://api.spotify.com/v1/artists/$id")
+ .header("Authorization", "Bearer $token")
+ .build()
+ container.sharedHttpClient.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) return@withContext null
+ val json = org.json.JSONObject(response.body.string())
+ val name = json.optString("name").takeIf { it.isNotEmpty() } ?: return@withContext null
+ val img = json.optJSONArray("images")?.optJSONObject(0)?.optString("url")
+ val followers = json.optJSONObject("followers")?.optInt("total") ?: 0
+ BasicArtistMeta(name, img, followers)
+ }
+ }.getOrNull()
+ }
+
+ private suspend fun loadArtist(uri: String, knownName: String = ""): ArtistPage = coroutineScope {
val id = uri.substringAfterLast(':')
- val tracks = container.api.artistTopTracks(id).tracks.map { it.toCatalogTrack() }
-
- // One request for every kind of record rather than three. Spotify says
- // which shelf each one belongs on, and asking per shelf would spend the
- // account's quota three times for the same answer.
- val releases = container.api.artistAlbums(
- id,
- groups = "album,single,compilation,appears_on",
- limit = 50,
- ).items
-
- fun shelf(vararg groups: String): List<SearchItem> = releases
- .filter { it.albumGroup in groups }
- .mapNotNull { album ->
- SearchItem(
- uri = album.uri ?: return@mapNotNull null,
- title = album.name,
- subtitle = album.releaseDate?.take(4).orEmpty(),
- artworkUrl = album.images.firstOrNull()?.url,
+ val market = userCountry
+
+ // Primary: Web API if custom developer app is configured
+ if (container.webApi.isReady) {
+ val tracksDeferred = async {
+ runCatching {
+ withTimeoutOrNull(3000L) {
+ container.api.artistTopTracks(id, market = market).tracks.map { it.toCatalogTrack() }
+ }
+ }.getOrNull()?.takeIf { it.isNotEmpty() }
+ ?: runCatching {
+ withTimeoutOrNull(3000L) {
+ container.api.artistTopTracks(id, market = "from_token").tracks.map { it.toCatalogTrack() }
+ }
+ }.getOrNull()?.takeIf { it.isNotEmpty() }
+ ?: runCatching {
+ withTimeoutOrNull(3000L) {
+ container.api.artistTopTracks(id, market = "US").tracks.map { it.toCatalogTrack() }
+ }
+ }.getOrNull().orEmpty().take(5)
+ }
+ val releasesDeferred = async {
+ runCatching {
+ withTimeoutOrNull(3000L) {
+ container.api.artistAlbums(artistId = id, groups = "album,single", limit = 50, market = market).items
+ }
+ }.getOrNull()?.takeIf { it.isNotEmpty() }
+ ?: runCatching {
+ withTimeoutOrNull(3000L) {
+ container.api.artistAlbums(artistId = id, groups = "album,single", limit = 50, market = null).items
+ }
+ }.getOrNull().orEmpty()
+ }
+ val artistDeferred = async {
+ runCatching { withTimeoutOrNull(2000L) { container.api.artist(id) } }.getOrNull()
+ }
+ val followingDeferred = async {
+ runCatching { withTimeoutOrNull(2000L) { container.api.isFollowing(ids = id).firstOrNull() } }.getOrNull()
+ }
+
+ var tracks = tracksDeferred.await()
+ val releases = releasesDeferred.await()
+ val artist = artistDeferred.await()
+ val following = followingDeferred.await()
+ val resolvedName = artist?.name ?: knownName
+
+ // If Web API returned the artist info but 0 top tracks, don't leave tracks empty!
+ // Query Gateway search or native context tracks as fallback
+ if (tracks.isEmpty() && resolvedName.isNotEmpty()) {
+ val searchRes = runCatching {
+ withTimeoutOrNull(3000L) {
+ container.gateway.search(resolvedName)?.let {
+ dev.lelonio.square.data.GatewaySearch.parse(
+ it,
+ dev.lelonio.square.backend.SearchLabels(
+ artist = string(R.string.artist),
+ album = string(R.string.album),
+ playlist = string(R.string.playlist),
+ ),
+ )
+ }
+ }
+ }.getOrNull()
+
+ if (searchRes != null && searchRes.tracks.isNotEmpty()) {
+ tracks = searchRes.tracks
+ .filter { it.artists.any { a -> a.name.contains(resolvedName, ignoreCase = true) } }
+ .ifEmpty { searchRes.tracks }
+ .take(5)
+ }
+ }
+
+ if (tracks.isEmpty()) {
+ val nativeTracks = runCatching {
+ withTimeoutOrNull(3000L) {
+ Catalog.tracks(Catalog.contextTrackUris(uri).take(10))
+ }
+ }.getOrNull()
+ if (!nativeTracks.isNullOrEmpty()) {
+ tracks = nativeTracks.take(5)
+ }
+ }
+
+ if (tracks.isNotEmpty() || releases.isNotEmpty() || artist != null) {
+ if (following != null) {
+ _playlist.value = _playlist.value.let {
+ if (it.uri == uri) it.copy(following = following) else it
+ }
+ }
+
+ data class AlbumItemEntry(val item: SearchItem, val date: String)
+
+ fun shelf(vararg groups: String): List<SearchItem> = releases
+ .filter { it.albumGroup in groups }
+ .mapNotNull { album ->
+ val date = album.releaseDate.orEmpty()
+ val year = date.take(4)
+ val type = when (album.albumGroup) {
+ "single" -> if (album.totalTracks > 1) "EP" else string(R.string.single)
+ "album" -> string(R.string.album)
+ "compilation" -> string(R.string.compilation)
+ else -> ""
+ }
+ val subtitle = if (type.isNotEmpty() && year.isNotEmpty()) "$type • $year" else year.ifEmpty { type }
+ AlbumItemEntry(
+ item = SearchItem(
+ uri = album.uri ?: return@mapNotNull null,
+ title = album.name,
+ subtitle = subtitle,
+ artworkUrl = album.images.firstOrNull()?.url,
+ ),
+ date = date,
+ )
+ }
+ .distinctBy { it.item.title.lowercase() }
+ .sortedByDescending { it.date }
+ .map { it.item }
+
+ val followersCount = artist?.followers?.total ?: 0
+ val monthlyListenersFormatted = formatMonthlyListeners(followersCount.toLong())
+
+ var albumsList = shelf("album", "compilation")
+ var singlesList = shelf("single")
+
+ // If releases were empty, enrich from Gateway search if available
+ if (albumsList.isEmpty() && singlesList.isEmpty() && resolvedName.isNotEmpty()) {
+ val searchRes = runCatching {
+ withTimeoutOrNull(3000L) {
+ container.gateway.search(resolvedName)?.let {
+ dev.lelonio.square.data.GatewaySearch.parse(
+ it,
+ dev.lelonio.square.backend.SearchLabels(
+ artist = string(R.string.artist),
+ album = string(R.string.album),
+ playlist = string(R.string.playlist),
+ ),
+ )
+ }
+ }
+ }.getOrNull()
+ if (searchRes != null && searchRes.albums.isNotEmpty()) {
+ albumsList = searchRes.albums
+ }
+ }
+
+ return@coroutineScope ArtistPage(
+ playlists = emptyList(),
+ tracks = tracks,
+ latest = null,
+ albums = albumsList,
+ singles = singlesList,
+ appearsOn = emptyList(),
+ relatedArtists = emptyList(),
+ followers = followersCount,
+ genres = artist?.genres.orEmpty(),
+ monthlyListeners = monthlyListenersFormatted,
+ name = resolvedName.takeIf { it.isNotEmpty() },
+ artworkUrl = artist?.images?.firstOrNull()?.url,
)
}
- // The same record is often listed several times, once per market.
- .distinctBy { it.title.lowercase() }
- .sortedByDescending { it.subtitle }
-
- // Not fatal, either of them. The page is worth showing without the
- // number under the name, and an account whose application predates the
- // follow permissions still gets everything else.
- val artist = runCatching { container.api.artist(id) }.getOrNull()
- val following = runCatching { container.api.isFollowing(ids = id).firstOrNull() }
- .onFailure { android.util.Log.w(TAG, "cannot tell if followed: ${describe(it)}") }
- .getOrNull()
+ }
- if (following != null) {
+ // Secondary fallback: Web player entity (when Web API is not configured or rate-limited)
+ val webArtist = runCatching {
+ withTimeoutOrNull(4000L) {
+ dev.lelonio.square.data.SpotifyWebArtist.fetch(
+ id,
+ container.sharedHttpClient,
+ getApplication<SquareApplication>().resources,
+ )
+ }
+ }.onFailure {
+ android.util.Log.w(TAG, "web artist lookup failed for $id: ${describe(it)}")
+ }.getOrNull()
+
+ if (webArtist != null && (webArtist.tracks.isNotEmpty() || webArtist.albums.isNotEmpty() || webArtist.singles.isNotEmpty())) {
+ val enrichedTracks = runCatching {
+ withTimeoutOrNull(3000L) {
+ Catalog.tracks(webArtist.tracks.map { it.uri })
+ }
+ }.getOrNull()?.takeIf { it.size == webArtist.tracks.size } ?: webArtist.tracks
+
+ val isFollowed = _followedArtists.value.any { it.uri == uri }
_playlist.value = _playlist.value.let {
- if (it.uri == uri) it.copy(following = following) else it
+ if (it.uri == uri) it.copy(following = isFollowed) else it
}
+
+ return@coroutineScope webArtist.copy(tracks = enrichedTracks.take(5))
}
- // The newest thing with the artist's own name on it. Compilations and
- // the records that are somebody else's are left out: "latest release"
- // meaning a greatest-hits reissue somebody else assembled is how that
- // card ends up wrong on half the artists in the catalogue.
- val latest = releases
- .filter { it.albumGroup == "album" || it.albumGroup == "single" }
- .filter { !it.releaseDate.isNullOrBlank() }
- .maxByOrNull { it.releaseDate.orEmpty() }
- ?.let { album ->
- album.uri?.let { uri ->
- ArtistRelease(
- uri = uri,
- title = album.name,
- artworkUrl = album.images.firstOrNull()?.url,
- releaseDate = album.releaseDate.orEmpty(),
- trackCount = album.totalTracks,
- )
+ // Resolve artist name & metadata if knownName is empty
+ val meta = if (knownName.isEmpty()) withTimeoutOrNull(3000L) { fetchArtistMetadata(id) } else null
+ val searchName = knownName.ifEmpty { meta?.name.orEmpty() }.ifEmpty { webArtist?.name.orEmpty() }
+
+ // Tertiary fallback: Gateway search if web scraper fails
+ if (searchName.isNotEmpty()) {
+ val searchRes = runCatching {
+ withTimeoutOrNull(3000L) {
+ container.gateway.search(searchName)?.let {
+ dev.lelonio.square.data.GatewaySearch.parse(
+ it,
+ dev.lelonio.square.backend.SearchLabels(
+ artist = string(R.string.artist),
+ album = string(R.string.album),
+ playlist = string(R.string.playlist),
+ ),
+ )
+ }
}
+ }.getOrNull()
+
+ if (searchRes != null && (searchRes.tracks.isNotEmpty() || searchRes.albums.isNotEmpty())) {
+ val matchedTracks = searchRes.tracks
+ .filter { it.artists.any { a -> a.name.contains(searchName, ignoreCase = true) } }
+ .ifEmpty { searchRes.tracks }
+ .take(5)
+
+ val matchedAlbums = searchRes.albums
+ val isFollowed = _followedArtists.value.any { it.uri == uri }
+ _playlist.value = _playlist.value.let {
+ if (it.uri == uri) it.copy(following = isFollowed) else it
+ }
+
+ val followers = meta?.followers ?: webArtist?.followers ?: 0
+ val artwork = meta?.artworkUrl ?: webArtist?.artworkUrl
+
+ return@coroutineScope ArtistPage(
+ playlists = searchRes.playlists,
+ tracks = matchedTracks,
+ latest = null,
+ albums = matchedAlbums,
+ singles = emptyList(),
+ appearsOn = emptyList(),
+ relatedArtists = emptyList(),
+ followers = followers,
+ genres = emptyList(),
+ monthlyListeners = formatMonthlyListeners(followers.toLong()) ?: webArtist?.monthlyListeners,
+ name = searchName,
+ artworkUrl = artwork,
+ biography = webArtist?.biography,
+ )
}
+ }
- return ArtistPage(
- playlists = artistPlaylists(artist?.name.orEmpty()),
- tracks = tracks,
- latest = latest,
- albums = shelf("album", "compilation"),
- singles = shelf("single"),
- appearsOn = shelf("appears_on"),
- followers = artist?.followers?.total ?: 0,
- genres = artist?.genres.orEmpty(),
+ // Last resort: native contextTracks
+ val nativeTracks = runCatching {
+ Catalog.tracks(Catalog.contextTrackUris(uri).take(10))
+ }.getOrDefault(emptyList()).take(5)
+
+ val isFollowed = _followedArtists.value.any { it.uri == uri }
+ _playlist.value = _playlist.value.let {
+ if (it.uri == uri) it.copy(following = isFollowed) else it
+ }
+
+ ArtistPage(
+ playlists = emptyList(),
+ tracks = nativeTracks,
+ latest = null,
+ albums = emptyList(),
+ singles = emptyList(),
+ appearsOn = emptyList(),
+ relatedArtists = emptyList(),
+ followers = meta?.followers ?: 0,
+ genres = emptyList(),
+ monthlyListeners = meta?.followers?.let { formatMonthlyListeners(it.toLong()) },
+ name = searchName.takeIf { it.isNotEmpty() },
+ artworkUrl = meta?.artworkUrl,
)
}
+ private fun formatMonthlyListeners(count: Long): String? {
+ if (count <= 0) return null
+ val res = getApplication<SquareApplication>().resources
+ val locale = java.util.Locale.getDefault()
+ val formattedCount = when {
+ count >= 1_000_000 -> String.format(locale, "%.1f M", count / 1_000_000.0)
+ count >= 1_000 -> String.format(locale, "%.1f K", count / 1_000.0)
+ else -> String.format(locale, "%,d", count)
+ }
+ val quantity = count.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
+ return res.getQuantityString(R.plurals.monthly_listeners, quantity, formattedCount)
+ }
+
/**
* The playlists Spotify built around one artist.
*
@@ -3954,6 +4675,18 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val id = uri.substringAfterLast(':')
_playlist.value = _playlist.value.copy(following = !was)
+
+ if (!container.webApi.isReady) {
+ val currentList = _followedArtists.value.toMutableList()
+ if (was) {
+ currentList.removeAll { it.uri == uri }
+ } else {
+ currentList.add(SearchItem(uri = uri, title = page.name, subtitle = "", artworkUrl = page.artworkUrl))
+ }
+ _followedArtists.value = currentList
+ return@launch
+ }
+
runCatching {
if (was) container.api.unfollowArtists(ids = id) else container.api.followArtists(ids = id)
}
@@ -4107,6 +4840,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* or an empty wrapper, which is how "unknown error" screens happen.
*/
private fun describe(error: Throwable): String {
+ if (error is java.util.concurrent.CancellationException || error is CancellationException) {
+ return ""
+ }
+ if (error is java.net.BindException || error.message?.contains("EADDRINUSE") == true) {
+ return string(R.string.cannot_connect)
+ }
val parts = generateSequence(error, Throwable::cause)
.mapNotNull { it.message?.takeIf(String::isNotBlank) }
.toList()
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 a6a8d6e..89d892f 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -141,6 +141,7 @@ import com.adamglin.phosphoricons.regular.SpotifyLogo
import com.adamglin.phosphoricons.regular.YoutubeLogo
import com.adamglin.phosphoricons.regular.Export
import com.adamglin.phosphoricons.regular.Trash
+import com.adamglin.phosphoricons.regular.User
import dev.lelonio.square.data.RemoteConnect
import dev.lelonio.square.ui.player.asPlaybackState
import dev.lelonio.square.ui.player.rememberRemotePositionMs
@@ -372,6 +373,8 @@ fun SquareApp(
onPlay: (List<CatalogTrack>, Int, String?, Boolean, String, Long) -> Unit,
/** Appends one track to the end of the queue; see the swipe gesture on rows. */
onEnqueue: (CatalogTrack) -> Unit,
+ /** Appends multiple tracks to the end of the queue; used by Autoplay. */
+ onEnqueueAll: (List<CatalogTrack>) -> Unit = {},
/**
* Incremented when something outside the app asks for the player — the
* notification, for now. A counter, so a second request while the player is
@@ -649,6 +652,7 @@ fun SquareApp(
awaitAudible(localState)
viewModel.lookUpVideo(playback.mediaId)
}
+
val devices by viewModel.devices.collectAsStateWithLifecycle()
val addToPlaylist by viewModel.addToPlaylist.collectAsStateWithLifecycle()
val trackSort by viewModel.trackSort.collectAsStateWithLifecycle()
@@ -685,7 +689,12 @@ fun SquareApp(
// Once, on the first composition that has a usable Web API session. The
// ViewModel keeps what it fetched, so navigating away and back does not
// spend the quota again.
- LaunchedEffect(webApi.connected) { viewModel.loadFeed() }
+ LaunchedEffect(webApi.connected) {
+ if (webApi.connected) {
+ viewModel.loadFeed()
+ viewModel.loadProfile()
+ }
+ }
// Two layers, and the split is not optional.
//
// `pageBackdrop` records the artwork *and* the screen on top of it, and is
@@ -915,8 +924,10 @@ fun SquareApp(
) {
// 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)
+ // track needs. See awaitAudible. Only wait when playing locally.
+ if (remote == null) {
+ awaitAudible(localState)
+ }
// The copy kept beside a download first, and not only offline: it
// is the same clip, it is already here, and playing it costs
// nothing. Offline it is the only one there is — the answer names a
@@ -951,46 +962,51 @@ fun SquareApp(
// Fetched per track. Most of the catalogue has none, so a null result is an
// ordinary answer that shows an empty state rather than an error.
- LaunchedEffect(playback.mediaId) {
+ LaunchedEffect(playback.mediaId, playback.title, playback.artist) {
val uri = playback.mediaId
- lyrics = null
- lyricsFor = null
if (uri == null) {
+ lyrics = null
lyricsFor = null
return@LaunchedEffect
}
- // Behind the song as well; see awaitAudible. The panel shows its own
- // spinner meanwhile, so the wait is visible rather than blank.
- awaitAudible(localState)
+ val isRemote = remote != null
+ // Lyrics are lightweight text — fetch them immediately without delay.
+ // Wait until title and artist metadata have arrived to avoid fetching
+ // with empty strings and polluting the session cache with false nulls.
+ val currentTitle = if (isRemote) playback.title else localState.value.title.ifBlank { playback.title }
+ val currentArtist = if (isRemote) playback.artist else localState.value.artist.ifBlank { playback.artist }
+ val currentDuration = if (isRemote && playback.durationMs > 0) {
+ playback.durationMs
+ } else {
+ localState.value.durationMs.takeIf { it > 0 } ?: playback.durationMs
+ }
+
+ if (currentTitle.isBlank()) return@LaunchedEffect
+
+ if (lyricsFor != uri) {
+ lyrics = null
+ lyricsFor = null
+ }
+
+ if (playback.mediaId != uri && localState.value.mediaId != uri) return@LaunchedEffect
- // Read again here, rather than used as they were when this started.
- //
- // The id and the metadata do not arrive together: the player reports
- // the new item as soon as it has one, and the title and artist land a
- // moment later. Asking with what was in hand at launch meant asking for
- // the *previous* song's words and then filing them under this song's
- // id, which is why the panel kept showing the last track's lyrics until
- // it was opened again.
- //
- // The two providers this ends up in — the TTML archive keyed by id, and
- // LrcLib keyed by title and artist — disagree about which is authority,
- // so both halves have to describe the same song.
- val now = localState.value
- if (now.mediaId != uri) return@LaunchedEffect
lyrics = runCatching {
(context.applicationContext as dev.lelonio.square.SquareApplication)
.activeBackend
.lyrics(
uri = uri,
- title = now.title,
- artist = now.artist,
- durationMs = now.durationMs,
+ title = currentTitle,
+ artist = currentArtist,
+ durationMs = currentDuration,
)
}.getOrNull()
- // Only if this is still the song being played. A slow answer for a
- // track the listener has already skipped past would otherwise replace
- // the words of the one they are on now.
- if (localState.value.mediaId == uri) lyricsFor = uri else lyrics = null
+
+ // Only if this is still the song being played. Dismiss the spinner by assigning lyricsFor.
+ if (playback.mediaId == uri || localState.value.mediaId == uri) {
+ lyricsFor = uri
+ } else {
+ lyrics = null
+ }
}
// The language the app is read in. Changing it re-creates the activity,
@@ -1234,7 +1250,9 @@ fun SquareApp(
sharedTrack = viewModel.resolveTrack(uri)
} else {
viewModel.openLink(uri)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
}
}
@@ -1416,11 +1434,14 @@ fun SquareApp(
},
) {
composable(Routes.HOME) {
+ LaunchedEffect(Unit) {
+ viewModel.loadBrowse()
+ }
HomeScreen(
state = state,
contentPadding = listPadding,
onLogIn = viewModel::logIn,
- onRetry = { viewModel.refresh() },
+ onRetry = { viewModel.retryFailed() },
onLogOut = viewModel::logOut,
onOpenPlaylist = { navController.openPlaylist(viewModel, it) },
playlistOrder = playlistOrder,
@@ -1434,7 +1455,9 @@ fun SquareApp(
feed = feed,
onOpenItem = { item ->
viewModel.openContext(item.uri, item.title, item.artworkUrl)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
},
backdrop = artBackdrop,
youtubeMode =
@@ -1442,6 +1465,7 @@ fun SquareApp(
onRetryOnline = viewModel::retryOnline,
youtubeHome = youtubeHome,
shelves = homeShelves,
+ mixShelves = radioShelves,
onPlayTrending = { tracks, index ->
onPlay(tracks, index, null, false, trendingLabel, 0L)
},
@@ -1481,7 +1505,9 @@ fun SquareApp(
item.title,
item.artworkUrl,
)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
},
)
}
@@ -1496,7 +1522,9 @@ fun SquareApp(
contentPadding = listPadding,
onOpenMix = { mix ->
viewModel.openContext(mix.uri, mix.name, mix.artworkUrl)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
},
onOpen = { seed ->
scope.launch {
@@ -1523,7 +1551,9 @@ fun SquareApp(
artworkUrl = seed.artworkUrl,
tracks = tracks,
)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
onPlay(tracks, 0, station, true, name, 0L)
}.onFailure {
android.util.Log.w(
@@ -1568,7 +1598,9 @@ fun SquareApp(
// having back as much as a song is.
viewModel.recordSearchOpen(item)
viewModel.openContext(item.uri, item.title, item.artworkUrl)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
},
onLoadMore = viewModel::loadMoreSearch,
backdrop = artBackdrop,
@@ -1580,7 +1612,7 @@ fun SquareApp(
state = state,
contentPadding = listPadding,
onLogIn = viewModel::logIn,
- onRetry = { viewModel.refresh() },
+ onRetry = { viewModel.retryFailed() },
onLogOut = viewModel::logOut,
onOpenPlaylist = { navController.openPlaylist(viewModel, it) },
playlistOrder = playlistOrder,
@@ -1597,7 +1629,9 @@ fun SquareApp(
artist.title,
artist.artworkUrl,
)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
},
backdrop = artBackdrop,
)
@@ -1716,7 +1750,7 @@ fun SquareApp(
onPlay(
tracks,
index,
- playlist.uri,
+ page.uri,
asContext,
source,
0L,
@@ -1734,7 +1768,7 @@ fun SquareApp(
onPlay(
tracks,
0,
- playlist.uri,
+ page.uri,
false,
source,
0L,
@@ -1751,7 +1785,7 @@ fun SquareApp(
// Taking a track out goes through
// the Spotify Web API, so only a
// Spotify playlist can offer it.
- removable = playlist.kind ==
+ removable = page.kind ==
MainViewModel.DetailKind.PLAYLIST &&
backend ==
dev.lelonio.square.backend.BackendId.SPOTIFY,
@@ -1768,31 +1802,31 @@ fun SquareApp(
item.artworkUrl,
)
},
- downloadState = playlist.uri
+ downloadState = page.uri
?.let { downloadOwners[it] }
?: dev.lelonio.square.data.OwnerState.None,
- onToggleDownload = { viewModel.toggleDownload(playlist) },
+ onToggleDownload = { viewModel.toggleDownload(page) },
// The store belongs to the librespot engine,
// so only Spotify pages can be kept — and
// with no network the button would only ever
// queue work that cannot start.
canDownload = backend ==
dev.lelonio.square.backend.BackendId.SPOTIFY &&
- playlist.uri?.startsWith("spotify:") == true &&
+ page.uri?.startsWith("spotify:") == true &&
!offlineNow,
onToggleFollow = viewModel::toggleFollowArtist,
onToggleLatestSaved = viewModel::toggleLatestSaved,
onToggleSaved = viewModel::toggleSaved,
onMenu = {
- val uri = playlist.uri ?: return@PlaylistScreen
+ val uri = page.uri ?: return@PlaylistScreen
// What the menu is allowed to offer, from
// the page that knows: whose list this is,
// and whether it is in the library at all.
- playlistMenuMine = playlist.mine != false
- playlistMenuSaved = playlist.saved != false
+ playlistMenuMine = page.mine != false
+ playlistMenuSaved = page.saved != false
playlistMenu = CatalogPlaylist(
uri = uri,
- name = playlist.name,
+ name = page.name,
artworkUrl = playlist.artworkUrl,
)
},
@@ -2786,40 +2820,34 @@ fun SquareApp(
?.let { uri ->
{
scope.launch {
- val tracks = viewModel.radioFor(uri)
- if (tracks.isEmpty()) return@launch
- // The station as a page, not
- // just as a queue. A radio the
- // listener cannot look at is a
- // shuffle with a different
- // name: the point of it is
- // seeing what it built.
- val station =
- "spotify:station:track:" +
- uri.substringAfterLast(':')
- // Named after the song it grew
- // from: two stations are told
- // apart by nothing else, and
- // "Radio" alone says which
- // feature it is rather than
- // which station this is.
- val name = radioOf(playback.title)
- viewModel.showStation(
- uri = station,
- name = name,
- artworkUrl = playback.artworkUrl,
- tracks = tracks,
- )
- expand.animateTo(0f, expandSpec)
- navController.navigate(Routes.PLAYLIST)
- onPlay(
- tracks,
- 0,
- station,
- true,
- name,
- 0L,
- )
+ runCatching {
+ val tracks = viewModel.radioFor(uri)
+ if (tracks.isEmpty()) return@launch
+ val station =
+ "spotify:station:track:" +
+ uri.substringAfterLast(':')
+ val name = radioOf(playback.title)
+ viewModel.showStation(
+ uri = station,
+ name = name,
+ artworkUrl = playback.artworkUrl,
+ tracks = tracks,
+ )
+ expand.animateTo(0f, expandSpec)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
+ onPlay(
+ tracks,
+ 0,
+ station,
+ true,
+ name,
+ 0L,
+ )
+ }.onFailure {
+ android.util.Log.e("SquareApp", "Failed to start radio: ${it.message}")
+ }
}
Unit
}
@@ -2841,13 +2869,11 @@ fun SquareApp(
onSelectDevice = {
viewModel.transferPlayback(it, positionMs.value)
},
- // The artist line and the line naming what is
- // playing both open the page they name. The
- // player has already folded itself away by the
- // time this runs, so the page arrives in front.
onOpenUri = { uri, name ->
viewModel.openContext(uri, name)
- navController.navigate(Routes.PLAYLIST)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
},
onAddToPlaylist = {
viewModel.openAddToPlaylist(
@@ -2856,6 +2882,16 @@ fun SquareApp(
asSheet = false,
)
},
+ onToggleLike = playback.mediaId?.let { uri ->
+ {
+ viewModel.toggleLike(
+ uri,
+ playback.title,
+ playback.artist,
+ playback.artworkUrl,
+ )
+ }
+ },
addToPlaylist = addToPlaylist,
onPickPlaylist = viewModel::addToPlaylist,
playlistEditAvailable =
@@ -2872,6 +2908,19 @@ fun SquareApp(
videoOn = videoOn || spotifyVideoOn,
videoPlayer = player,
videoAttachKey = spotifyVideoGeneration,
+ onMore = playback.mediaId?.let { uri ->
+ {
+ trackMenu = TrackMenuRequest(
+ track = CatalogTrack(
+ uri = uri,
+ name = playback.title,
+ artist = playback.artist,
+ artworkUrl = playback.artworkUrl,
+ ),
+ removable = false,
+ )
+ }
+ },
)
}
},
@@ -2965,8 +3014,7 @@ fun SquareApp(
!offlineNow
if (keepable) {
val kept = downloadOwners[shownPlaylist.uri]
- val isKept = kept is dev.lelonio.square.data.OwnerState.Complete ||
- kept is dev.lelonio.square.data.OwnerState.Partial
+ val isKept = kept != null && kept !is dev.lelonio.square.data.OwnerState.None
TrackSheetAction(
stringResource(
if (isKept) R.string.remove_download else R.string.download,
@@ -3104,6 +3152,22 @@ fun SquareApp(
viewModel.openAddToPlaylist(menu.track.uri, menu.track.name)
}
}
+ TrackSheetAction(stringResource(R.string.go_to_artist), PhosphorIcons.Regular.User) {
+ val track = menu.track
+ trackMenu = null
+ scope.launch {
+ if (expand.value > 0f) {
+ expand.animateTo(0f, expandSpec)
+ }
+ val artist = viewModel.artistOf(track)
+ if (artist != null) {
+ viewModel.openContext(artist.uri, artist.title, artist.artworkUrl)
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
+ }
+ }
+ }
// Keeping one song, as opposed to keeping the list it
// came from. Spotify only: this is the engine's own
// store, and the other backend streams from elsewhere.
@@ -3133,10 +3197,36 @@ fun SquareApp(
viewModel.toggleTrackDownload(menu.track)
}
}
+ TrackSheetAction(stringResource(R.string.radio), PhosphorIcons.Regular.Broadcast) {
+ val track = menu.track
+ trackMenu = null
+ scope.launch {
+ runCatching {
+ val tracks = viewModel.radioFor(track.uri)
+ if (tracks.isEmpty()) return@launch
+ val station = "spotify:station:track:" + track.uri.substringAfterLast(':')
+ val name = radioOf(track.name)
+ viewModel.showStation(
+ uri = station,
+ name = name,
+ artworkUrl = track.artworkUrl,
+ tracks = tracks,
+ )
+ if (expand.value > 0f) {
+ expand.animateTo(0f, expandSpec)
+ }
+ if (navController.currentDestination?.route != Routes.PLAYLIST) {
+ navController.navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
+ onPlay(tracks, 0, station, true, name, 0L)
+ }
+ }
+ }
TrackSheetAction(stringResource(R.string.copy_link), PhosphorIcons.Regular.LinkSimple) {
trackMenu = null
clipboard.setText(AnnotatedString(menu.track.openLink()))
}
+
// YouTube only. A Spotify link handed to a downloader
// is a link it cannot do anything with, so offering the
// action there would be offering a failure.
@@ -3168,6 +3258,7 @@ fun SquareApp(
}
}
+
FriendsPanel(
visible = friendsOpen,
friends = friends,
@@ -3532,7 +3623,9 @@ private fun RowScope.BottomItem(
/** Loads the playlist and shows it, from whichever tab asked. */
private fun NavHostController.openPlaylist(viewModel: MainViewModel, playlist: CatalogPlaylist) {
viewModel.openPlaylist(playlist)
- navigate(Routes.PLAYLIST)
+ if (currentDestination?.route != Routes.PLAYLIST) {
+ navigate(Routes.PLAYLIST) { launchSingleTop = true }
+ }
}
/**
@@ -3692,7 +3785,7 @@ private const val UPDATE_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000L
private fun savedPlaybackSeed(context: android.content.Context): PlaybackState? {
val saved = dev.lelonio.square.data.PlaybackStore(context).load() ?: return null
val position = saved.shuffleOrder?.getOrNull(saved.index) ?: saved.index
- val track = saved.tracks.getOrNull(position) ?: return null
+ val track = saved.tracks.getOrNull(position)?.takeIf { it.name.isNotBlank() } ?: return null
return PlaybackState(
hasItem = true,
mediaId = track.uri,
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/AmbientArtworkBackground.kt b/app/src/main/java/dev/lelonio/square/ui/components/AmbientArtworkBackground.kt
index f1975c2..3808966 100644
--- a/app/src/main/java/dev/lelonio/square/ui/components/AmbientArtworkBackground.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/components/AmbientArtworkBackground.kt
@@ -1,5 +1,7 @@
package dev.lelonio.square.ui.components
+import android.content.Context
+import android.os.PowerManager
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
@@ -153,6 +155,11 @@ fun AmbientArtworkBackground(
columns: List<Color> = emptyList(),
) {
val context = LocalContext.current
+ val powerManager = remember(context) {
+ context.getSystemService(Context.POWER_SERVICE) as? PowerManager
+ }
+ val isPowerSave = powerManager?.isPowerSaveMode == true
+ val effectiveMotion = motion && !isPowerSave
// Which picture is showing, and which one is on its way out.
//
@@ -235,7 +242,7 @@ fun AmbientArtworkBackground(
// One clock for the drift, shared by both copies so they cannot beat
// against each other.
- val drift: State<Float> = if (motion && enabled) {
+ val drift: State<Float> = if (effectiveMotion && enabled) {
rememberInfiniteTransition(label = "ambientDrift").animateFloat(
initialValue = 0f,
targetValue = 1f,
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt b/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
index 4699ad4..353c13c 100644
--- a/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
@@ -88,51 +88,65 @@ fun Artwork(
DownloadsCover()
} else if (url == dev.lelonio.square.data.LocalLibrary.COVER) {
LocalFilesCover()
- } else if (url != null && (!offlineOnly() || isOnThisPhone(url))) {
- // Offline the url is not something that can be fetched, so what is
- // handed to the loader is the copy on the disk. Online the url
- // stays: covers are kept keyed on the picture rather than its size,
- // so the file behind a url may be a smaller print of it, and a page
- // that can fetch the large one should.
- val source = remember(url) { artSource(url) }
+ } else if (url != null) {
+ // Offline the url is not something that can be fetched over network,
+ // so network cache is disabled but disk and memory cache remain enabled,
+ // allowing already cached covers to be shown offline.
+ val densityVal = density
+ val source = remember(url, decodeSize) {
+ val base = artSource(url)
+ if (base is String && decodeSize > 0.dp) {
+ val targetPx = with(densityVal) { decodeSize.toPx() }.roundToInt()
+ spotifyResizedUrl(base, targetPx)
+ } else base
+ }
val request = remember(source, decodeSize, crossfadeMs) {
ImageRequest.Builder(context)
.data(source)
.scale(Scale.FILL)
+ .networkCachePolicy(
+ if (offlineOnly() && !isOnThisPhone(url)) coil.request.CachePolicy.DISABLED
+ else coil.request.CachePolicy.ENABLED,
+ )
+ .diskCachePolicy(coil.request.CachePolicy.ENABLED)
+ .memoryCachePolicy(coil.request.CachePolicy.ENABLED)
.apply {
if (decodeSize > 0.dp) {
val px = with(density) { decodeSize.toPx() }.roundToInt()
size(px, px)
}
}
- // The fade is done here rather than by the loader; see
- // below.
.crossfade(false)
.build()
}
- // Faded in by hand, and deliberately.
- //
- // The loader's own crossfade is skipped whenever the picture comes
- // out of memory — which, since the next song's cover is fetched
- // while the current one plays, is exactly the case that matters:
- // the artwork appeared with a cut while everything around it was
- // still animating, and arrived before the colour it is supposed to
- // bring with it. An animation of our own does not care where the
- // bytes came from.
var arrived by remember(source) { mutableStateOf(false) }
+ var failed by remember(source) { mutableStateOf(false) }
val appear by animateFloatAsState(
targetValue = if (arrived || crossfadeMs <= 0) 1f else 0f,
animationSpec = tween(crossfadeMs),
label = "artwork",
)
+ if (fallback && failed) {
+ GeneratedCover(title, corner)
+ }
+
AsyncImage(
model = request,
contentDescription = null,
contentScale = ContentScale.Crop,
onState = { state ->
- if (state is coil.compose.AsyncImagePainter.State.Success) arrived = true
+ when (state) {
+ is coil.compose.AsyncImagePainter.State.Success -> {
+ arrived = true
+ failed = false
+ }
+ is coil.compose.AsyncImagePainter.State.Error -> {
+ failed = true
+ }
+ else -> {}
+ }
},
modifier = Modifier
.fillMaxSize()
@@ -224,6 +238,72 @@ private fun isOnThisPhone(url: String): Boolean =
url.startsWith("content:") ||
dev.lelonio.square.download.DownloadExtras.fileOf(url, "art") != null
+/**
+ * Requests a smaller print of a Spotify CDN image when a small decode target
+ * is given, rather than fetching 640 px and throwing most of it away.
+ *
+ * Spotify image IDs are forty lowercase hex characters. The first sixteen
+ * encode the resolution; the last twenty-four identify the picture. Swapping
+ * the prefix is enough to request any print the CDN publishes.
+ *
+ * Known prefixes (from the Spotify web player / CDN):
+ * - Albums / tracks / covers (`ab67616d`):
+ * - `ab67616d0000b273` → 640 × 640 px
+ * - `ab67616d00001e02` → 300 × 300 px
+ * - `ab67616d00004851` → 64 × 64 px
+ * - Artist avatars (`ab676161`):
+ * - `ab6761610000e5eb` → 640 × 640 px
+ * - `ab67616100005174` → 320 × 320 px
+ * - `ab6761610000f178` → 160 × 160 px
+ *
+ * Only fires for URLs whose last path component looks like a Spotify image ID
+ * (40 hex chars). Everything else is returned unchanged.
+ */
+fun spotifyResizedUrl(url: String, targetPx: Int): String {
+ if (targetPx <= 0) return url
+ val id = url.substringAfterLast('/')
+ if (id.length != SPOTIFY_ID_LEN || !id.all { it.isDigit() || it in 'a'..'f' }) return url
+ val family = id.take(8)
+ val rendition = when (family) {
+ "ab67616d" -> when {
+ targetPx <= 64 -> "00004851"
+ targetPx <= 300 -> "00001e02"
+ else -> return url // 640 px — keep the original URL
+ }
+ "ab676161" -> when {
+ targetPx <= 160 -> "0000f178"
+ targetPx <= 320 -> "00005174"
+ else -> return url // 640 px — keep the original URL
+ }
+ else -> return url // Unrecognized Spotify image family: leave unmodified
+ }
+ val tail = id.drop(SPOTIFY_SIZE_PREFIX_LEN)
+ return url.dropLast(SPOTIFY_ID_LEN) + family + rendition + tail
+}
+
+/**
+ * Resolves a canonical cache key for an image URL.
+ *
+ * Spotify image IDs are 40 hex chars: 16 prefix chars encoding size/rendition,
+ * followed by 24 chars identifying the image. Keying on the last 24 characters
+ * ensures that any size variant (e.g. 64px row thumbnail, 300px list print,
+ * 640px cover) shares the exact same palette and tint in cache.
+ */
+fun canonicalArtworkKey(url: String): String {
+ val id = url.substringAfterLast('/')
+ return if (id.length == SPOTIFY_ID_LEN && id.all { it.isDigit() || it in 'a'..'f' }) {
+ id.takeLast(SPOTIFY_ID_LEN - SPOTIFY_SIZE_PREFIX_LEN)
+ } else {
+ url
+ }
+}
+
+/** Length of a Spotify image ID, in hex characters. */
+const val SPOTIFY_ID_LEN = 40
+
+/** How many of those characters encode the image size. */
+const val SPOTIFY_SIZE_PREFIX_LEN = 16
+
/** The shelf of songs downloaded on their own; see DownloadStore.SINGLES. */
const val DOWNLOADS_COVER = "square:downloads-cover"
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt b/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt
index a6ea4b9..6059187 100644
--- a/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/components/HeroBackdrop.kt
@@ -146,7 +146,7 @@ fun HeroBackdrop(
// between two versions of the same artwork is the most visible
// change this screen ever makes; a fade makes it a refinement.
crossfadeMs = SWAP_MS,
- fallback = !pending,
+ fallback = false,
)
// The moving cover over the still one, which stays underneath as what is
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt
index 752a2cc..b5dd5a8 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidButton.kt
@@ -10,8 +10,10 @@
package dev.lelonio.square.ui.glass
+import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
+import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
@@ -38,11 +40,13 @@ import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.tanh
+@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LiquidButton(
onClick: () -> Unit,
backdrop: Backdrop,
modifier: Modifier = Modifier,
+ onLongClick: (() -> Unit)? = null,
isInteractive: Boolean = true,
tint: Color = Color.Unspecified,
/**
@@ -190,11 +194,23 @@ fun LiquidButton(
null
},
)
- .clickable(
- interactionSource = null,
- indication = if (isInteractive) null else LocalIndication.current,
- role = Role.Button,
- onClick = onClick
+ .then(
+ if (onLongClick != null) {
+ Modifier.combinedClickable(
+ interactionSource = null,
+ indication = if (isInteractive) null else LocalIndication.current,
+ role = Role.Button,
+ onClick = onClick,
+ onLongClick = onLongClick,
+ )
+ } else {
+ Modifier.clickable(
+ interactionSource = null,
+ indication = if (isInteractive) null else LocalIndication.current,
+ role = Role.Button,
+ onClick = onClick,
+ )
+ }
)
.then(
if (isInteractive) {
diff --git a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
index fb3f049..7e35114 100644
--- a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
@@ -162,6 +162,7 @@ fun HomeScreen(
* cannot be reconstructed from the account's playlists.
*/
shelves: List<dev.lelonio.square.data.HomeShelf> = emptyList(),
+ mixShelves: List<dev.lelonio.square.data.HomeShelf> = emptyList(),
) {
if (youtubeMode) {
YouTubeHome(
@@ -329,13 +330,15 @@ fun HomeScreen(
.graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)
.drawWithContent {
drawContent()
- drawRect(
- brush = Brush.verticalGradient(
- 0f to Color.Transparent,
- FADE_FRACTION to Color.Black,
- ),
- blendMode = BlendMode.DstIn,
- )
+ if (collapse > 0.01f) {
+ drawRect(
+ brush = Brush.verticalGradient(
+ 0f to Color.Transparent,
+ (FADE_FRACTION * collapse) to Color.Black,
+ ),
+ blendMode = BlendMode.DstIn,
+ )
+ }
},
state = listState,
// The header already covers the status bar, so only the
@@ -370,7 +373,8 @@ fun HomeScreen(
// placeholder the page arrived in two halves and shifted under
// whatever was being read.
if (filter == Feed.ALL) {
- shelves.forEach { shelf ->
+ val allShelves = if (mixShelves.isEmpty()) shelves else (shelves + mixShelves).distinctBy { it.title }
+ allShelves.forEach { shelf ->
item(contentType = "shelf") { Heading(shelf.title) }
item(contentType = "shelf") {
Carousel(shelf.items, key = { it.uri }) { entry ->
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 f428c57..2a422aa 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
@@ -14,8 +14,11 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
@@ -44,6 +47,7 @@ import dev.lelonio.square.R
import dev.lelonio.square.data.CatalogPlaylist
import dev.lelonio.square.data.sortedByRecentlyOpened
import dev.lelonio.square.data.withLocalFilesFirst
+import dev.lelonio.square.data.withLikedSecond
import dev.lelonio.square.data.withPinnedFirst
import dev.lelonio.square.ui.MainViewModel
import dev.lelonio.square.ui.components.Artwork
@@ -64,6 +68,7 @@ import dev.lelonio.square.ui.components.GlassChoiceMenu
import dev.lelonio.square.ui.glass.backdrop.backdrops.layerBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberCombinedBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberLayerBackdrop
+import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberBackdropFreeze
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.PushPin
@@ -183,6 +188,9 @@ fun LibraryScreen(
// comes out looking like a hole. Safe to record — the menu is drawn
// outside the grid, so nothing in this layer samples it.
val listBackdrop = rememberLayerBackdrop()
+ val listBackdropFreeze = rememberBackdropFreeze()
+ val gridState = rememberLazyGridState()
+ val listState = rememberLazyListState()
var descending by remember { mutableStateOf(view.descending) }
val onOrderChosen: (Order) -> Unit = {
order = it
@@ -279,13 +287,18 @@ fun LibraryScreen(
when (layout) {
Layout.GRID -> LazyVerticalGrid(
+ state = gridState,
columns = GridCells.Fixed(2),
contentPadding = listPadding,
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalArrangement = Arrangement.spacedBy(18.dp),
modifier = Modifier
.fillMaxSize()
- .layerBackdrop(listBackdrop),
+ .nestedScroll(listBackdropFreeze.connection)
+ .layerBackdrop(
+ listBackdrop,
+ frozen = { listBackdropFreeze.frozen() || gridState.isScrollInProgress },
+ ),
) {
item(span = { GridItemSpan(maxLineSpan) }, key = "search") {
dev.lelonio.square.ui.components.ListSearchField(
@@ -324,11 +337,16 @@ fun LibraryScreen(
}
Layout.LIST -> LazyColumn(
+ state = listState,
contentPadding = listPadding,
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier
.fillMaxSize()
- .layerBackdrop(listBackdrop),
+ .nestedScroll(listBackdropFreeze.connection)
+ .layerBackdrop(
+ listBackdrop,
+ frozen = { listBackdropFreeze.frozen() || listState.isScrollInProgress },
+ ),
) {
item(key = "search") {
dev.lelonio.square.ui.components.ListSearchField(
@@ -695,6 +713,7 @@ private fun ArtistShelf(
color = Ink,
modifier = Modifier.padding(start = 4.dp, bottom = 10.dp),
)
+ val uniqueArtists = remember(artists) { artists.distinctBy { it.uri } }
LazyRow(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
items(uniqueArtists, key = { "artist_${it.uri}" }) { artist ->
Column(
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
index 3491db7..0404d71 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
@@ -36,7 +36,6 @@ import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -100,6 +99,7 @@ import dev.lelonio.square.ui.glass.backdrop.Backdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.layerBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberCombinedBackdrop
import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberLayerBackdrop
+import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberBackdropFreeze
import dev.lelonio.square.ui.components.Artwork
import dev.lelonio.square.ui.components.CHOICE_MENU_WIDTH
import dev.lelonio.square.ui.components.GlassChoiceItem
@@ -245,8 +245,8 @@ fun PlaylistScreen(
storedSortDescending: Boolean = false,
onSortDescendingChange: (Boolean) -> Unit = {},
) {
- var query by remember { mutableStateOf("") }
- var searching by remember { mutableStateOf(false) }
+ var query by remember(state.uri) { mutableStateOf("") }
+ var searching by remember(state.uri) { mutableStateOf(false) }
// Opening and closing the field, as one number.
//
// The field used to appear and disappear on the frame the button was
@@ -323,6 +323,7 @@ fun PlaylistScreen(
// the rest. Kept per artist: opening a second artist starts closed again.
var topSongsOpen by remember(state.uri) { mutableStateOf(false) }
+
// Derived, not stored: keeping a second list in state would leave the two
// able to disagree after a reload.
val visible = remember(state.tracks, query, sort, descending) {
@@ -354,7 +355,13 @@ fun PlaylistScreen(
// that changes, and the one the reference prints here.
val updated = remember(state.kind, state.tracks) {
if (state.kind == MainViewModel.DetailKind.PLAYLIST) {
- state.tracks.mapNotNull { it.addedAt }.maxOrNull()
+ state.tracks.mapNotNull { it.addedAt }
+ .filter { iso ->
+ runCatching {
+ java.time.Instant.parse(iso).epochSecond > 1262304000L
+ }.getOrDefault(false)
+ }
+ .maxOrNull()
} else {
null
}
@@ -443,6 +450,7 @@ fun PlaylistScreen(
/** The rows, for the one piece of glass that opens over them. */
val listBackdrop = rememberLayerBackdrop()
+ val listBackdropFreeze = rememberBackdropFreeze()
var sortAnchor by remember { mutableStateOf(IntOffset.Zero) }
@@ -462,7 +470,10 @@ fun PlaylistScreen(
// list, so a single gesture closes the cover and then carries on into the
// tracks.
val collapseRange = with(density) { (heroHeight - collapsedHeight).toPx() }
- var collapsed by remember { mutableFloatStateOf(0f) }
+ var collapsed by remember(state.uri) { mutableFloatStateOf(0f) }
+ LaunchedEffect(state.uri) {
+ listState.scrollToItem(0)
+ }
val collapseFraction = { (collapsed / collapseRange).coerceIn(0f, 1f) }
// How much of a drag the header itself uses up, closing on the way up and
@@ -603,6 +614,7 @@ fun PlaylistScreen(
collapsedPx = collapsedPx,
collapse = collapseFraction,
imageAspect = state.heroAspect,
+ pending = state.heroPending,
)
}
@@ -656,8 +668,7 @@ fun PlaylistScreen(
onToggleFollow = onToggleFollow,
download = downloadState,
onToggleDownload = {
- val kept = downloadState is dev.lelonio.square.data.OwnerState.Complete ||
- downloadState is dev.lelonio.square.data.OwnerState.Partial
+ val kept = downloadState !is dev.lelonio.square.data.OwnerState.None
if (kept) confirmingRemoval = true else onToggleDownload()
},
// Only where the reference puts one: a record or a list. An artist
@@ -694,8 +705,11 @@ fun PlaylistScreen(
// colour — over a flat fill, glass has nothing to bend and comes
// out as a grey card. Safe to record: the menu is drawn outside the
// list, so nothing in this layer samples it.
+ // Frozen during scroll so the layer is not re-recorded every frame,
+ // taking frame time down from 47ms to 1.9ms.
modifier = Modifier
- .layerBackdrop(listBackdrop)
+ .nestedScroll(listBackdropFreeze.connection)
+ .layerBackdrop(listBackdrop, frozen = { listBackdropFreeze.frozen() || listState.isScrollInProgress })
.nestedScroll(headerScroll),
contentPadding = PaddingValues(bottom = contentPadding.calculateBottomPadding()),
) {
@@ -774,7 +788,6 @@ fun PlaylistScreen(
onToggle = { topSongsOpen = !topSongsOpen },
)
}
-
}
when {
@@ -907,7 +920,7 @@ fun PlaylistScreen(
// past the artist to reach the artist. Albums, then singles, then
// the records that are somebody else's, then what Spotify built
// around them — the order is how much of the artist is in each.
- if (state.albums.isNotEmpty()) {
+ if (state.albums.isNotEmpty() && query.isBlank()) {
item(contentType = "albums") {
AlbumStrip(
albums = state.albums,
@@ -917,7 +930,7 @@ fun PlaylistScreen(
}
}
- if (state.singles.isNotEmpty()) {
+ if (state.singles.isNotEmpty() && query.isBlank()) {
item(contentType = "singles") {
AlbumStrip(
albums = state.singles,
@@ -927,7 +940,7 @@ fun PlaylistScreen(
}
}
- if (state.appearsOn.isNotEmpty()) {
+ if (state.appearsOn.isNotEmpty() && query.isBlank()) {
item(contentType = "appearsOn") {
AlbumStrip(
albums = state.appearsOn,
@@ -937,7 +950,7 @@ fun PlaylistScreen(
}
}
- if (state.artistPlaylists.isNotEmpty()) {
+ if (state.artistPlaylists.isNotEmpty() && query.isBlank()) {
item(contentType = "artistPlaylists") {
AlbumStrip(
albums = state.artistPlaylists,
@@ -1082,6 +1095,7 @@ fun PlaylistScreen(
}
}
+ if (!isArtist) {
GlassCapsule(
backdrop = pageBackdrop,
modifier = Modifier
@@ -1151,6 +1165,7 @@ fun PlaylistScreen(
)
}
}
+ }
// Floating rather than a top bar: the list scrolls under it, so the
// picture stays uninterrupted. It gives way to the collapsed bar, which
@@ -1332,9 +1347,26 @@ private fun DetailHeader(
)
}
+ val ago = updatedAt?.let { agoOf(it) }.orEmpty()
+ val isDaylist = kind == MainViewModel.DetailKind.PLAYLIST && (
+ name.contains("daylist", ignoreCase = true) ||
+ description.contains("daylist", ignoreCase = true)
+ )
+ val isDailyMix = kind == MainViewModel.DetailKind.PLAYLIST && (
+ name.contains(Regex("(?i)(daily\\s*mix|mix\\s*di[aá]rio|daily\\s*drive|ruta\\s*diaria)")) ||
+ description.contains(Regex("(?i)(daily\\s*mix|mix\\s*di[aá]rio)"))
+ )
+ val isWeekly = kind == MainViewModel.DetailKind.PLAYLIST && (
+ name.contains(Regex("(?i)(discover\\s*weekly|descubrimiento\\s*semanal|release\\s*radar|radar\\s*de\\s*novedades)")) ||
+ description.contains(Regex("(?i)(discover\\s*weekly|descubrimiento\\s*semanal|release\\s*radar|radar\\s*de\\s*novedades)"))
+ )
+
Text(
text = when {
- updatedAt != null -> stringResource(R.string.updated_ago, agoOf(updatedAt))
+ isDaylist -> stringResource(R.string.daylist_schedule)
+ isDailyMix -> stringResource(R.string.daily_mix_schedule)
+ isWeekly -> stringResource(R.string.weekly_schedule)
+ ago.isNotEmpty() -> stringResource(R.string.updated_ago, ago)
year.isNotEmpty() -> stringResource(kind.label) + " · " + year
else -> stringResource(kind.label)
},
@@ -1588,6 +1620,7 @@ private fun HeroArt(
collapse: () -> Float,
/** The picture's own proportions, where the catalogue gave them. */
imageAspect: Float? = null,
+ pending: Boolean = false,
) {
// The picture and its fade are the same everywhere the app shows a cover
// large — here and in the player; see HeroBackdrop. What belongs to this
@@ -1598,6 +1631,7 @@ private fun HeroArt(
pageColor = pageColor,
motionUrl = motionUrl,
imageAspect = imageAspect,
+ pending = pending,
// Measured against the reference rather than chosen.
//
// Ours was flat page colour by 38% of the way down the screen; theirs
@@ -2540,9 +2574,6 @@ private fun TrackRow(
// never needs to be a target.
DownloadMark(download)
Text(
- // Artist and length on one line, as the reference has it:
- // two stacked grey lines under every title turn the list
- // into a wall of secondary text.
text = subtitle
?: "${track.artist} · ${formatDuration(track.durationMs)}",
style = MaterialTheme.typography.bodySmall,
@@ -2661,15 +2692,23 @@ private fun EditorialNotes(notes: String) {
*/
@Composable
private fun agoOf(iso: String): String {
- val then = runCatching { java.time.Instant.parse(iso) }.getOrNull()
- ?: return ""
- val days = java.time.Duration.between(then, java.time.Instant.now()).toDays()
+ val then = runCatching { java.time.Instant.parse(iso) }
+ .recoverCatching { java.time.OffsetDateTime.parse(iso).toInstant() }
+ .getOrNull() ?: return ""
+ if (then.epochSecond < 1262304000L) return ""
+ val duration = java.time.Duration.between(then, java.time.Instant.now())
+ if (duration.isNegative) return stringResource(R.string.ago_just_now)
+ val minutes = duration.toMinutes()
+ val hours = duration.toHours()
+ val days = duration.toDays()
return when {
- days <= 0 -> stringResource(R.string.ago_today)
+ minutes < 1 -> stringResource(R.string.ago_just_now)
+ minutes < 60 -> stringResource(R.string.ago_minutes, minutes.toInt().coerceAtLeast(1))
+ hours < 24 -> stringResource(R.string.ago_hours, hours.toInt().coerceAtLeast(1))
days < 7 -> stringResource(R.string.ago_days, days)
- days < 31 -> stringResource(R.string.ago_weeks, days / 7)
- days < 365 -> stringResource(R.string.ago_months, days / 30)
- else -> stringResource(R.string.ago_years, days / 365)
+ days < 31 -> stringResource(R.string.ago_weeks, (days / 7).coerceAtLeast(1))
+ days < 365 -> stringResource(R.string.ago_months, (days / 30).coerceAtLeast(1))
+ else -> stringResource(R.string.ago_years, (days / 365).coerceAtLeast(1))
}
}
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.kt
index 246cad0..a4437d5 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
@@ -20,7 +20,10 @@ import androidx.compose.animation.core.spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.sp
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.clickable
@@ -111,7 +114,8 @@ import com.adamglin.phosphoricons.fill.SkipBack
import com.adamglin.phosphoricons.fill.SkipForward
import com.adamglin.phosphoricons.regular.CaretDown
import com.adamglin.phosphoricons.regular.Devices
-import com.adamglin.phosphoricons.regular.Check
+import com.adamglin.phosphoricons.regular.DotsThree
+import com.adamglin.phosphoricons.regular.Heart
import com.adamglin.phosphoricons.regular.Plus
import com.adamglin.phosphoricons.regular.Queue
import com.adamglin.phosphoricons.regular.Broadcast
@@ -119,6 +123,7 @@ import com.adamglin.phosphoricons.regular.YoutubeLogo
import com.adamglin.phosphoricons.regular.Repeat
import com.adamglin.phosphoricons.regular.RepeatOnce
import com.adamglin.phosphoricons.regular.Shuffle
+import com.adamglin.phosphoricons.regular.TextAlignLeft
import kotlin.math.abs
/**
@@ -308,6 +313,8 @@ fun PlayerScreen(
* mark: a heart, the way every Spotify client says it.
*/
inLikedSongs: Boolean = false,
+ /** Direct toggle for Liked Songs ("Tus me gusta"). */
+ onToggleLike: (() -> Unit)? = null,
/** Starts a station from the current track; null where there is none. */
onRadio: (() -> Unit)? = null,
/** The playlist picker's state, shown in the panel rather than as a sheet. */
@@ -344,6 +351,8 @@ fun PlayerScreen(
connectAvailable: Boolean = true,
/** Whether the sound is coming out of another of the account's devices. */
onAnotherDevice: Boolean = false,
+ /** Opens the contextual menu sheet for the current track ("…"). */
+ onMore: (() -> Unit)? = null,
) {
var panel by remember { mutableStateOf(PlayerPanel.NONE) }
@@ -761,6 +770,7 @@ fun PlayerScreen(
onAnotherDevice = onAnotherDevice,
onWatchVideo = onWatchVideo,
videoOn = videoOn,
+ onMore = onMore,
)
// Everything sits at the bottom, as in the reference: the
@@ -1170,6 +1180,18 @@ fun PlayerScreen(
backdrop = glassBackdrop,
size = 40.dp,
onClick = {
+ if (onToggleLike != null) {
+ onToggleLike()
+ } else {
+ panel = if (panel == PlayerPanel.ADD_TO_PLAYLIST) {
+ PlayerPanel.NONE
+ } else {
+ onAddToPlaylist()
+ PlayerPanel.ADD_TO_PLAYLIST
+ }
+ }
+ },
+ onLongClick = {
panel = if (panel == PlayerPanel.ADD_TO_PLAYLIST) {
PlayerPanel.NONE
} else {
@@ -1179,22 +1201,14 @@ fun PlayerScreen(
},
) {
Icon(
- when {
- inLikedSongs -> PhosphorIcons.Fill.Heart
- alreadySaved -> PhosphorIcons.Regular.Check
- else -> PhosphorIcons.Regular.Plus
- },
+ if (inLikedSongs) PhosphorIcons.Fill.Heart else PhosphorIcons.Regular.Heart,
contentDescription = stringResource(
- when {
- inLikedSongs -> R.string.liked_songs
- alreadySaved -> R.string.in_a_playlist
- else -> R.string.add_to_playlist
- },
+ if (inLikedSongs) R.string.remove_from_liked else R.string.liked_songs,
),
tint = when {
panel == PlayerPanel.ADD_TO_PLAYLIST ->
panelTint(true)
- inLikedSongs || alreadySaved -> SavedInk
+ inLikedSongs -> SavedInk
else -> panelTint(false)
},
modifier = Modifier.size(20.dp),
@@ -1229,6 +1243,7 @@ fun PlayerScreen(
Spacer(Modifier.height(14.dp))
+
PlayerPanelSection(
panel = panel,
onSelect = { panel = it },
@@ -1524,6 +1539,7 @@ private fun TopBar(
/** Null when the track has no video to watch. */
onWatchVideo: (() -> Unit)?,
videoOn: Boolean,
+ onMore: (() -> Unit)? = null,
) {
Row(
Modifier
@@ -1621,6 +1637,16 @@ private fun TopBar(
)
}
}
+ if (onMore != null) {
+ Spacer(Modifier.size(8.dp))
+ GlassButton(backdrop, onClick = onMore) {
+ Icon(
+ PhosphorIcons.Regular.DotsThree,
+ contentDescription = stringResource(R.string.more),
+ tint = GlassInk,
+ )
+ }
+ }
}
}
@@ -1991,10 +2017,12 @@ private fun RoundGlassButton(
modifier: Modifier = Modifier,
enabled: Boolean = true,
onClick: () -> Unit,
+ onLongClick: (() -> Unit)? = null,
content: @Composable () -> Unit,
) {
LiquidButton(
onClick = { if (enabled) onClick() },
+ onLongClick = if (enabled) onLongClick else null,
backdrop = backdrop,
modifier = modifier
.size(size)
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 7b2d85d..3716259 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
@@ -33,8 +33,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
-import androidx.compose.ui.focus.FocusRequester
-import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
@@ -55,8 +53,6 @@ import dev.lelonio.square.ui.theme.Ink
import dev.lelonio.square.ui.theme.InkDim
import androidx.compose.foundation.clickable
import com.adamglin.PhosphorIcons
-import com.adamglin.phosphoricons.Bold
-import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.bold.MagnifyingGlass
import com.adamglin.phosphoricons.bold.X
@@ -527,6 +523,8 @@ 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.
*
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index c4e0201..660c8f6 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -267,9 +267,14 @@ fun SettingsScreen(
QualitySection()
}
- // Also librespot's: the crossfade is mixed by the engine's own player.
- if (open == SettingsPage.Playback && showSpotify) item("crossfade") {
- CrossfadeSection()
+ // Crossfade: mixed by the engine on Spotify, volume-shaped on YouTube Music.
+ if (open == SettingsPage.Playback) item("crossfade") {
+ CrossfadeSection(backdrop)
+ }
+
+ // Autoplay: automatically append similar tracks when queue reaches the end.
+ if (open == SettingsPage.Playback) item("autoplay") {
+ AutoplaySection(backdrop)
}
// Spotify's own, served by its access point: on another source there is
@@ -640,6 +645,24 @@ private fun CanvasSection(backdrop: Backdrop) {
}
}
+@Composable
+private fun AutoplaySection(backdrop: Backdrop) {
+ val context = LocalContext.current
+ val store = remember(context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).preferences
+ }
+ val enabled by store.autoplayInfinite.collectAsStateWithLifecycle()
+
+ Section(stringResource(R.string.autoplay)) {
+ DownloadSwitch(
+ label = stringResource(R.string.autoplay_infinite_title),
+ checked = enabled,
+ backdrop = backdrop,
+ onChange = store::setAutoplayInfinite,
+ )
+ }
+}
+
@Composable
private fun EffectQualitySection() {
val context = LocalContext.current
@@ -660,12 +683,16 @@ private fun EffectQualitySection() {
}
@Composable
-private fun CrossfadeSection() {
+private fun CrossfadeSection(backdrop: Backdrop) {
val context = LocalContext.current
val store = remember(context) {
(context.applicationContext as dev.lelonio.square.SquareApplication).crossfade
}
+ val preferences = remember(context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).preferences
+ }
val chosen by store.seconds.collectAsStateWithLifecycle()
+ val trimSilence by preferences.trimSilence.collectAsStateWithLifecycle()
Section(stringResource(R.string.crossfade)) {
CrossfadeSteps.forEachIndexed { index, seconds ->
@@ -680,6 +707,13 @@ private fun CrossfadeSection() {
) { store.set(seconds) }
}
RowDivider()
+ DownloadSwitch(
+ label = stringResource(R.string.trim_silence),
+ checked = trimSilence,
+ backdrop = backdrop,
+ onChange = preferences::setTrimSilence,
+ )
+ RowDivider()
Text(
stringResource(R.string.quality_restarts),
style = MaterialTheme.typography.bodySmall,
@@ -864,6 +898,7 @@ private fun DownloadsSection(backdrop: Backdrop) {
val failures by store.failures.collectAsStateWithLifecycle()
val quality by settings.quality.collectAsStateWithLifecycle()
val wifiOnly by settings.wifiOnly.collectAsStateWithLifecycle()
+ val likedSongs by settings.downloadLikedSongs.collectAsStateWithLifecycle()
val offline by settings.offlineMode.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
@@ -916,6 +951,40 @@ private fun DownloadsSection(backdrop: Backdrop) {
onChange = settings::setWifiOnly,
)
+ RowDivider()
+ DownloadSwitch(
+ label = stringResource(R.string.download_liked_songs),
+ checked = likedSongs,
+ backdrop = backdrop,
+ onChange = { enable ->
+ settings.setDownloadLikedSongs(enable)
+ if (enable) {
+ scope.launch {
+ val tracks = app.likedStore.likedTracks.value
+ if (tracks.isNotEmpty()) {
+ val likedTracksList = tracks.map { uri ->
+ store.trackOf(uri) ?: dev.lelonio.square.data.CatalogTrack(
+ uri = uri,
+ name = "",
+ artist = "",
+ )
+ }
+ store.setOwner(dev.lelonio.square.data.DownloadStore.LIKED, likedTracksList, label = null)
+ dev.lelonio.square.download.DownloadService.start(app)
+ }
+ }
+ } else {
+ scope.launch {
+ store.removeOwner(dev.lelonio.square.data.DownloadStore.LIKED)
+ store.pruneOrphans().forEach { orphanUri ->
+ runCatching { dev.lelonio.square.nativecore.NativeBridge.removeDownload(orphanUri) }
+ dev.lelonio.square.download.DownloadExtras.forget(orphanUri)
+ }
+ }
+ }
+ },
+ )
+
RowDivider()
DownloadSwitch(
label = stringResource(R.string.offline_mode),
diff --git a/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt b/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt
index cd17950..41814f9 100644
--- a/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/theme/ArtworkColor.kt
@@ -18,6 +18,7 @@ import coil.request.ImageRequest
import coil.request.SuccessResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+import dev.lelonio.square.ui.components.canonicalArtworkKey
/**
* Where a page ends up once the artwork's colour has faded out of it.
@@ -171,11 +172,12 @@ fun rememberArtworkColor(artworkUrl: String?): State<Color?> {
state.value = null
return@LaunchedEffect
}
- cached[artworkUrl]?.let {
+ val key = canonicalArtworkKey(artworkUrl)
+ cached[key]?.let {
state.value = it
return@LaunchedEffect
}
- state.value = extractDominant(context, artworkUrl)?.also { cached[artworkUrl] = it }
+ state.value = extractDominant(context, artworkUrl)?.also { cached[key] = it }
}
return state
}
@@ -195,14 +197,15 @@ private val cached = object : LinkedHashMap<String, Color>(16, 0.75f, true) {
* will look for it, at the same time as the picture.
*/
suspend fun warmArtworkColor(context: Context, url: String) {
- if (!cached.containsKey(url)) {
- extractDominant(context, url)?.let { cached[url] = it }
+ val key = canonicalArtworkKey(url)
+ if (!cached.containsKey(key)) {
+ extractDominant(context, url)?.let { cached[key] = it }
}
// And the foot of it, for the same reason and off the same decode: the
// player's whole background is that colour, so arriving without it is the
// screen changing twice.
- if (!cachedFeet.containsKey(url)) {
- extractFoot(context, url)?.let { cachedFeet[url] = it }
+ if (!cachedFeet.containsKey(key)) {
+ extractFoot(context, url)?.let { cachedFeet[key] = it }
}
}
@@ -224,12 +227,13 @@ fun rememberArtworkPalette(artworkUrl: String?): State<List<Color>> {
state.value = emptyList()
return@LaunchedEffect
}
- cachedPalettes[artworkUrl]?.let {
+ val key = canonicalArtworkKey(artworkUrl)
+ cachedPalettes[key]?.let {
state.value = it
return@LaunchedEffect
}
val swatches = extractPalette(context, artworkUrl)
- if (swatches.isNotEmpty()) cachedPalettes[artworkUrl] = swatches
+ if (swatches.isNotEmpty()) cachedPalettes[key] = swatches
state.value = swatches
}
return state
@@ -328,11 +332,12 @@ fun rememberArtworkFootColor(artworkUrl: String?): State<Color?> {
state.value = null
return@LaunchedEffect
}
- cachedFeet[artworkUrl]?.let {
+ val key = canonicalArtworkKey(artworkUrl)
+ cachedFeet[key]?.let {
state.value = it
return@LaunchedEffect
}
- state.value = extractFoot(context, artworkUrl)?.also { cachedFeet[artworkUrl] = it }
+ state.value = extractFoot(context, artworkUrl)?.also { cachedFeet[key] = it }
}
return state
}
diff --git a/app/src/main/res/drawable/ic_heart_filled.xml b/app/src/main/res/drawable/ic_heart_filled.xml
new file mode 100644
index 0000000..dd7dbd6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_heart_filled.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36,2,12.28,2,8.5,2,5.42,4.42,3,7.5,3c1.74,0,3.41,0.81,4.5,2.09C13.09,3.81,14.76,3,16.5,3,19.58,3,22,5.42,22,8.5c0,3.78,-3.4,6.86,-8.55,11.54L12,21.35z" />
+</vector>
diff --git a/app/src/main/res/drawable/ic_heart_outline.xml b/app/src/main/res/drawable/ic_heart_outline.xml
new file mode 100644
index 0000000..3753ba2
--- /dev/null
+++ b/app/src/main/res/drawable/ic_heart_outline.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M16.5,3c-1.74,0,-3.41,0.81,-4.5,2.09C10.91,3.81,9.24,3,7.5,3,4.42,3,2,5.42,2,8.5c0,3.78,3.4,6.86,8.55,11.54L12,21.35l1.45,-1.32C18.6,15.36,22,12.28,22,8.5,22,5.42,19.58,3,16.5,3zm-4.4,15.55l-0.1,0.1,-0.1,-0.1C7.14,14.24,4,11.39,4,8.5,4,6.5,5.5,5,7.5,5c1.54,0,3.04,0.99,3.57,2.36h1.87C13.46,5.99,14.96,5,16.5,5,18.5,5,20,6.5,20,8.5c0,2.89,-3.14,5.74,-7.9,10.05z" />
+</vector>
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 01474b0..8ebc10b 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -30,6 +30,8 @@
<string name="title">Titel</string>
<string name="artist">Künstler</string>
<string name="album">Album</string>
+ <string name="single">Single</string>
+ <string name="compilation">Kompilation</string>
<string name="playlist">Playlist</string>
<string name="duration">Länge</string>
<string name="tracks">Titel</string>
@@ -105,6 +107,7 @@
<string name="add_to_queue">Zur Warteschlange</string>
<string name="add_to_playlist">Zu einer Playlist hinzufügen</string>
+ <string name="go_to_artist">Zum Künstler</string>
<string name="copy_link">Link kopieren</string>
<string name="remove_from_playlist">Aus der Playlist entfernen</string>
<string name="queued">In der Warteschlange</string>
@@ -387,14 +390,24 @@
<item quantity="one">%1$d Titel</item>
<item quantity="other">%1$d Titel</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s monatlicher Hörer</item>
+ <item quantity="other">%s monatliche Hörer</item>
+ </plurals>
<string name="songs_and_length">%1$d Titel, %2$s</string>
<string name="more_notes">MEHR</string>
<string name="updated_ago">Aktualisiert: %1$s</string>
+ <string name="ago_just_now">gerade eben</string>
+ <string name="ago_minutes">%1$d Min.</string>
+ <string name="ago_hours">%1$d Std.</string>
<string name="ago_today">heute</string>
<string name="ago_days">%1$d T</string>
<string name="ago_weeks">%1$d Wo</string>
<string name="ago_months">%1$d Mon</string>
<string name="ago_years">%1$d J</string>
+ <string name="daylist_schedule">Wird alle paar Stunden aktualisiert</string>
+ <string name="daily_mix_schedule">Wird täglich aktualisiert</string>
+ <string name="weekly_schedule">Wird wöchentlich aktualisiert</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Loop-Clips zeigen</string>
<string name="canvas_note">Das kurze Video, das manche Titel mitbringen. Aus wird es auch nicht geladen.</string>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 49a087b..6a8f3c2 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -30,6 +30,8 @@
<string name="title">Título</string>
<string name="artist">Artista</string>
<string name="album">Álbum</string>
+ <string name="single">Sencillo</string>
+ <string name="compilation">Recopilación</string>
<string name="playlist">Playlist</string>
<string name="duration">Duración</string>
<string name="tracks">Canciones</string>
@@ -105,6 +107,7 @@
<string name="add_to_queue">Añadir a la cola</string>
<string name="add_to_playlist">Añadir a una playlist</string>
+ <string name="go_to_artist">Ir al artista</string>
<string name="copy_link">Copiar enlace</string>
<string name="remove_from_playlist">Quitar de la playlist</string>
<string name="queued">En cola</string>
@@ -359,7 +362,7 @@
<string name="download_artist_confirm">¿Descargar %1$d canciones de %2$s? Son unos %3$s.</string>
<string name="download_failed_count">%1$d no se pudieron descargar</string>
<string name="download_retry_failed">Reintentar</string>
- <string name="downloaded_tracks">Canciones descargadas</string>
+ <string name="downloaded_tracks">Música descargada</string>
<string name="offline_mode">Modo sin conexión</string>
<string name="offline_mode_note">Reproduce solo lo descargado, sin pedirle nada a Spotify.</string>
<string name="offline_banner_manual">Sin conexión — lo activaste tú</string>
@@ -387,18 +390,34 @@
<item quantity="one">%1$d canción</item>
<item quantity="other">%1$d canciones</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s oyente mensual</item>
+ <item quantity="other">%s oyentes mensuales</item>
+ </plurals>
<string name="songs_and_length">%1$d canciones, %2$s</string>
<string name="more_notes">MÁS</string>
<string name="updated_ago">Actualizada: %1$s</string>
+ <string name="ago_just_now">hace un momento</string>
+ <string name="ago_minutes">%1$d min</string>
+ <string name="ago_hours">%1$d h</string>
<string name="ago_today">hoy</string>
<string name="ago_days">%1$d d</string>
<string name="ago_weeks">%1$d sem</string>
<string name="ago_months">%1$d meses</string>
<string name="ago_years">%1$d años</string>
+ <string name="daylist_schedule">Se actualiza cada pocas horas</string>
+ <string name="daily_mix_schedule">Se actualiza a diario</string>
+ <string name="weekly_schedule">Se actualiza cada semana</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Mostrar clips en bucle</string>
<string name="canvas_note">El vídeo corto que traen algunas canciones. Desactivado, tampoco se descarga.</string>
<string name="show_all">Mostrar todo</string>
<string name="show_less">Mostrar menos</string>
<string name="search_library">Buscar en tu biblioteca</string>
+ <string name="autoplay">Reproducción continua</string>
+ <string name="autoplay_infinite_title">Autoplay infinito</string>
+ <string name="autoplay_infinite_summary">Sigue reproduciendo música similar al terminar la cola</string>
+ <string name="trim_silence">Recortar silencio</string>
+ <string name="trim_silence_summary">Evita el silencio al final de las canciones durante el fundido</string>
+ <string name="mood_mixes">Mixes por estado de ánimo</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index d60757d..6d6ee0a 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -30,6 +30,8 @@
<string name="title">Titre</string>
<string name="artist">Artiste</string>
<string name="album">Album</string>
+ <string name="single">Single</string>
+ <string name="compilation">Compilation</string>
<string name="playlist">Playlist</string>
<string name="duration">Durée</string>
<string name="tracks">Titres</string>
@@ -105,6 +107,7 @@
<string name="add_to_queue">Ajouter à la file</string>
<string name="add_to_playlist">Ajouter à une playlist</string>
+ <string name="go_to_artist">Accéder à l\'artiste</string>
<string name="copy_link">Copier le lien</string>
<string name="remove_from_playlist">Retirer de la playlist</string>
<string name="queued">Dans la file</string>
@@ -387,14 +390,24 @@
<item quantity="one">%1$d titre</item>
<item quantity="other">%1$d titres</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s auditeur mensuel</item>
+ <item quantity="other">%s auditeurs mensuels</item>
+ </plurals>
<string name="songs_and_length">%1$d titres, %2$s</string>
<string name="more_notes">PLUS</string>
<string name="updated_ago">Mise à jour : %1$s</string>
+ <string name="ago_just_now">à l\'instant</string>
+ <string name="ago_minutes">%1$d min</string>
+ <string name="ago_hours">%1$d h</string>
<string name="ago_today">aujourd\'hui</string>
<string name="ago_days">%1$d j</string>
<string name="ago_weeks">%1$d sem</string>
<string name="ago_months">%1$d mois</string>
<string name="ago_years">%1$d ans</string>
+ <string name="daylist_schedule">Mise à jour toutes les quelques heures</string>
+ <string name="daily_mix_schedule">Mise à jour quotidienne</string>
+ <string name="weekly_schedule">Mise à jour hebdomadaire</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Afficher les clips en boucle</string>
<string name="canvas_note">La courte vidéo que portent certains titres. Désactivé, elle n\'est pas téléchargée non plus.</string>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index ba16d36..2884f76 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -35,6 +35,8 @@
<string name="title">शीर्षक</string>
<string name="artist">कलाकार</string>
<string name="album">एल्बम</string>
+ <string name="single">सिंगल</string>
+ <string name="compilation">संकलन</string>
<string name="playlist">प्लेलिस्ट</string>
<string name="duration">अवधि</string>
<string name="tracks">गाने</string>
@@ -114,6 +116,7 @@
<!-- Track menu -->
<string name="add_to_queue">कतार में जोड़ें</string>
<string name="add_to_playlist">प्लेलिस्ट में जोड़ें</string>
+ <string name="go_to_artist">कलाकार पर जाएँ</string>
<string name="copy_link">लिंक कॉपी करें</string>
<string name="remove_from_playlist">प्लेलिस्ट से हटाएँ</string>
<string name="queued">कतार में</string>
@@ -402,14 +405,24 @@
<item quantity="one">%1$d गाना</item>
<item quantity="other">%1$d गाने</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s मासिक श्रोता</item>
+ <item quantity="other">%s मासिक श्रोता</item>
+ </plurals>
<string name="songs_and_length">%1$d गाने, %2$s</string>
<string name="more_notes">और</string>
<string name="updated_ago">अपडेट: %1$s</string>
+ <string name="ago_just_now">अभी</string>
+ <string name="ago_minutes">%1$d मिनट</string>
+ <string name="ago_hours">%1$d घंटे</string>
<string name="ago_today">आज</string>
<string name="ago_days">%1$d दि</string>
<string name="ago_weeks">%1$d सप्ता</string>
<string name="ago_months">%1$d माह</string>
<string name="ago_years">%1$d वर्ष</string>
+ <string name="daylist_schedule">हर कुछ घंटों में अपडेट होता है</string>
+ <string name="daily_mix_schedule">रोजाना अपडेट होता है</string>
+ <string name="weekly_schedule">हर हफ्ते अपडेट होता है</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">लूप क्लिप दिखाएँ</string>
<string name="canvas_note">कुछ गानों के साथ आने वाला छोटा वीडियो. बंद होने पर डाउनलोड भी नहीं होता.</string>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 647966b..f9321a2 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -31,6 +31,8 @@
<string name="title">Titolo</string>
<string name="artist">Artista</string>
<string name="album">Album</string>
+ <string name="single">Singolo</string>
+ <string name="compilation">Raccolta</string>
<string name="playlist">Playlist</string>
<string name="duration">Durata</string>
<string name="tracks">Brani</string>
@@ -106,6 +108,7 @@
<string name="add_to_queue">Aggiungi alla coda</string>
<string name="add_to_playlist">Aggiungi a una playlist</string>
+ <string name="go_to_artist">Vai all\'artista</string>
<string name="copy_link">Copia link</string>
<string name="remove_from_playlist">Rimuovi dalla playlist</string>
<string name="queued">In coda</string>
@@ -388,14 +391,24 @@
<item quantity="one">%1$d brano</item>
<item quantity="other">%1$d brani</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s ascoltatore mensile</item>
+ <item quantity="other">%s ascoltatori mensili</item>
+ </plurals>
<string name="songs_and_length">%1$d brani, %2$s</string>
<string name="more_notes">ALTRO</string>
<string name="updated_ago">Aggiornata: %1$s</string>
+ <string name="ago_just_now">poco fa</string>
+ <string name="ago_minutes">%1$d min</string>
+ <string name="ago_hours">%1$d h</string>
<string name="ago_today">oggi</string>
<string name="ago_days">%1$d g</string>
<string name="ago_weeks">%1$d sett</string>
<string name="ago_months">%1$d mesi</string>
<string name="ago_years">%1$d anni</string>
+ <string name="daylist_schedule">Si aggiorna ogni poche ore</string>
+ <string name="daily_mix_schedule">Si aggiorna ogni giorno</string>
+ <string name="weekly_schedule">Si aggiorna ogni settimana</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Mostra i video in loop</string>
<string name="canvas_note">Il breve video che alcuni brani portano con sé. Disattivato, non viene nemmeno scaricato.</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 9ea1839..b08f124 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -30,6 +30,8 @@
<string name="title">Título</string>
<string name="artist">Artista</string>
<string name="album">Álbum</string>
+ <string name="single">Single</string>
+ <string name="compilation">Compilação</string>
<string name="playlist">Playlist</string>
<string name="duration">Duração</string>
<string name="tracks">Faixas</string>
@@ -105,6 +107,7 @@
<string name="add_to_queue">Adicionar à fila</string>
<string name="add_to_playlist">Adicionar a uma playlist</string>
+ <string name="go_to_artist">Ir para o artista</string>
<string name="copy_link">Copiar link</string>
<string name="remove_from_playlist">Remover da playlist</string>
<string name="queued">Na fila</string>
@@ -387,14 +390,24 @@
<item quantity="one">%1$d faixa</item>
<item quantity="other">%1$d faixas</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s ouvinte mensal</item>
+ <item quantity="other">%s ouvintes mensais</item>
+ </plurals>
<string name="songs_and_length">%1$d faixas, %2$s</string>
<string name="more_notes">MAIS</string>
<string name="updated_ago">Atualizada: %1$s</string>
+ <string name="ago_just_now">agora mesmo</string>
+ <string name="ago_minutes">%1$d min</string>
+ <string name="ago_hours">%1$d h</string>
<string name="ago_today">hoje</string>
<string name="ago_days">%1$d d</string>
<string name="ago_weeks">%1$d sem</string>
<string name="ago_months">%1$d meses</string>
<string name="ago_years">%1$d anos</string>
+ <string name="daylist_schedule">Atualiza a cada poucas horas</string>
+ <string name="daily_mix_schedule">Atualiza diariamente</string>
+ <string name="weekly_schedule">Atualiza semanalmente</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Mostrar clipes em loop</string>
<string name="canvas_note">O vídeo curto que algumas faixas trazem. Desligado, também não é baixado.</string>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 2b9746a..dd60d10 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -35,6 +35,8 @@
<string name="title">Başlık</string>
<string name="artist">Sanatçı</string>
<string name="album">Albüm</string>
+ <string name="single">Tekli</string>
+ <string name="compilation">Derleme</string>
<string name="playlist">Çalma listesi</string>
<string name="duration">Süre</string>
<string name="tracks">Şarkılar</string>
@@ -114,6 +116,7 @@
<!-- Track menu -->
<string name="add_to_queue">Sıraya ekle</string>
<string name="add_to_playlist">Çalma listesine ekle</string>
+ <string name="go_to_artist">Sanatçıya git</string>
<string name="copy_link">Bağlantıyı kopyala</string>
<string name="remove_from_playlist">Çalma listesinden çıkar</string>
<string name="queued">Sıraya eklendi</string>
@@ -401,14 +404,23 @@
<plurals name="song_count">
<item quantity="other">%1$d şarkı</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="other">%s aylık dinleyici</item>
+ </plurals>
<string name="songs_and_length">%1$d şarkı, %2$s</string>
<string name="more_notes">DAHA</string>
<string name="updated_ago">Güncellendi: %1$s</string>
+ <string name="ago_just_now">az önce</string>
+ <string name="ago_minutes">%1$d dk.</string>
+ <string name="ago_hours">%1$d sa.</string>
<string name="ago_today">bugün</string>
<string name="ago_days">%1$d g</string>
<string name="ago_weeks">%1$d hf</string>
<string name="ago_months">%1$d ay</string>
<string name="ago_years">%1$d yıl</string>
+ <string name="daylist_schedule">Birkaç saatte bir güncellenir</string>
+ <string name="daily_mix_schedule">Günlük güncellenir</string>
+ <string name="weekly_schedule">Haftalık güncellenir</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Döngü kliplerini göster</string>
<string name="canvas_note">Bazı şarkıların getirdiği kısa video. Kapalıyken indirilmez de.</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 6ecc31f..f028300 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -41,6 +41,8 @@
<string name="title">Title</string>
<string name="artist">Artist</string>
<string name="album">Album</string>
+ <string name="single">Single</string>
+ <string name="compilation">Compilation</string>
<string name="playlist">Playlist</string>
<string name="duration">Length</string>
<string name="tracks">Songs</string>
@@ -120,6 +122,7 @@
<!-- Track menu -->
<string name="add_to_queue">Add to queue</string>
<string name="add_to_playlist">Add to a playlist</string>
+ <string name="go_to_artist">Go to artist</string>
<string name="copy_link">Copy link</string>
<string name="remove_from_playlist">Remove from playlist</string>
<string name="queued">Queued</string>
@@ -408,18 +411,34 @@
<item quantity="one">%1$d song</item>
<item quantity="other">%1$d songs</item>
</plurals>
+ <plurals name="monthly_listeners">
+ <item quantity="one">%s monthly listener</item>
+ <item quantity="other">%s monthly listeners</item>
+ </plurals>
<string name="songs_and_length">%1$d songs, %2$s</string>
<string name="more_notes">MORE</string>
<string name="updated_ago">Updated: %1$s</string>
+ <string name="ago_just_now">just now</string>
+ <string name="ago_minutes">%1$d min</string>
+ <string name="ago_hours">%1$d h</string>
<string name="ago_today">today</string>
<string name="ago_days">%1$d d</string>
<string name="ago_weeks">%1$d w</string>
<string name="ago_months">%1$d mo</string>
<string name="ago_years">%1$d y</string>
+ <string name="daylist_schedule">Updates every few hours</string>
+ <string name="daily_mix_schedule">Updates daily</string>
+ <string name="weekly_schedule">Updates weekly</string>
<string name="canvas">Canvas</string>
<string name="canvas_show">Show looping clips</string>
<string name="canvas_note">The short video some tracks come with. Off, none is downloaded either.</string>
<string name="show_all">Show all</string>
<string name="show_less">Show less</string>
<string name="search_library">Search your library</string>
+ <string name="autoplay">Autoplay</string>
+ <string name="autoplay_infinite_title">Infinite Autoplay</string>
+ <string name="autoplay_infinite_summary">Keep playing similar tracks when queue ends</string>
+ <string name="trim_silence">Trim silence</string>
+ <string name="trim_silence_summary">Skip trailing silence at track ends during crossfade</string>
+ <string name="mood_mixes">Mood Mixes</string>
</resources>
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 10e24d8..46c1be8 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -136,6 +136,7 @@ fn tune_fetching() {
// a second of waiting on every track; half of one is still several
// blocks at this size.
read_ahead_before_playback: Duration::from_millis(500),
+ // Keep 5 seconds of audio decoded and cached ahead during playback.
read_ahead_during_playback: Duration::from_secs(5),
prefetch_threshold_factor: 4.0,
// A block that has not arrived in fifteen seconds is not going to.
@@ -985,6 +986,17 @@ pub fn set_bitrate(bitrate_kbps: i32) -> EngineResult<()> {
Ok(())
}
+/// Changes whether trailing silence near the end of a track triggers early crossfade.
+pub fn set_trim_silence(enabled: bool) -> EngineResult<()> {
+ let mut guard = ENGINE.lock().map_err(|_| "engine mutex poisoned")?;
+ let engine = guard.as_mut().ok_or("engine not started")?;
+ engine.recipe.player_config.trim_silence = enabled;
+ if let Some(bundle) = engine.bundle.as_ref() {
+ bundle.player.set_trim_silence(enabled);
+ }
+ Ok(())
+}
+
/// Throws away a bundle and builds another one, leaving the runtime and the
/// audio output alone.
///
@@ -1787,7 +1799,11 @@ fn transport(
// back as an error, so the app saw a pause that had been accepted and a
// player that went on regardless. The load path has taken this step
// since it was written; the transport path never did.
- let _ = engine.spirc().map(|spirc| spirc.activate());
+ let _ = engine.spirc().map(|spirc| {
+ if !spirc.is_active() {
+ let _ = spirc.activate();
+ }
+ });
via_spirc(engine)
} {
Ok(()) => Ok(()),
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index a0d63e8..2282ef1 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -525,6 +525,18 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSet
guard(&mut env, "SetBitrate", || engine::set_bitrate(bitrate_kbps));
}
+/// Changes whether silence trimming is enabled, with no rebuild.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetTrimSilence(
+ mut env: JNIEnv,
+ _class: JClass,
+ enabled: jboolean,
+) {
+ guard(&mut env, "SetTrimSilence", || {
+ engine::set_trim_silence(enabled != 0)
+ });
+}
+
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeReconnect(
mut env: JNIEnv,
diff --git a/native/vendor/librespot-core/src/dealer/protocol.rs b/native/vendor/librespot-core/src/dealer/protocol.rs
index 803fe30..a98d933 100644
--- a/native/vendor/librespot-core/src/dealer/protocol.rs
+++ b/native/vendor/librespot-core/src/dealer/protocol.rs
@@ -135,9 +135,15 @@ impl WebsocketMessage {
let payload = self.payloads.pop().ok_or(ProtocolError::Empty)?;
let bytes = match payload {
- MessagePayloadValue::String(string) => BASE64_STANDARD
- .decode(string)
- .map_err(ProtocolError::Base64)?,
+ MessagePayloadValue::String(string) => {
+ let trimmed = string.trim_start();
+ if trimmed.starts_with('{') || trimmed.starts_with('[') {
+ return Ok(PayloadValue::Json(string));
+ }
+ BASE64_STANDARD
+ .decode(string)
+ .map_err(ProtocolError::Base64)?
+ }
MessagePayloadValue::Bytes(bytes) => bytes,
MessagePayloadValue::Json(json) => return Ok(PayloadValue::Json(json.to_string())),
};
diff --git a/native/vendor/librespot-playback/src/config.rs b/native/vendor/librespot-playback/src/config.rs
index 8a9de90..e8d5a5d 100644
--- a/native/vendor/librespot-playback/src/config.rs
+++ b/native/vendor/librespot-playback/src/config.rs
@@ -193,6 +193,9 @@ pub struct PlayerConfig {
/// LOCAL PATCH: asked before falling back to the network; see [`DownloadsOnly`].
pub downloads_only: Option<DownloadsOnly>,
+
+ /// LOCAL PATCH: whether trailing silence near the end of a track triggers early crossfade.
+ pub trim_silence: bool,
}
impl Default for PlayerConfig {
@@ -215,6 +218,7 @@ impl Default for PlayerConfig {
crossfade_duration_ms: 0,
download_lookup: None,
downloads_only: None,
+ trim_silence: true,
}
}
}
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index 032a08f..fcc9008 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -73,6 +73,23 @@ const MAX_SHORT_END_RELOADS: u8 = 2;
/// Full scale is asymmetric: -32768 exists, +32768 does not, so a mix that
/// reaches 1.0 on the way up wraps around to the bottom and is heard as a click.
const MAX_SAMPLE: f64 = 32767.0 / 32768.0;
+
+/// LOCAL PATCH: smooth soft-knee saturation limiter to prevent digital clipping (0 dBFS overflow)
+/// while maintaining bit-perfect audio transparency below 0.85 (~ -1.4 dBFS).
+#[inline]
+fn soft_limit(x: f64) -> f64 {
+ const THRESHOLD: f64 = 0.85;
+ let abs_x = x.abs();
+ if abs_x <= THRESHOLD {
+ x
+ } else {
+ let sign = x.signum();
+ let excess = abs_x - THRESHOLD;
+ let margin = 1.0 - THRESHOLD;
+ let limited = THRESHOLD + margin * (excess / margin).tanh();
+ (sign * limited).clamp(-1.0, MAX_SAMPLE)
+ }
+}
pub const DB_VOLTAGE_RATIO: f64 = 20.0;
pub const PCM_AT_0DBFS: f64 = 1.0;
@@ -133,6 +150,8 @@ struct PlayerInternal {
/// LOCAL PATCH: the play request that has been heard playing before its own
/// fade window, and so may have its end announced early. See the use of it.
fade_armed: Option<u64>,
+ /// LOCAL PATCH: consecutive silent samples observed near end of track for silence trimming.
+ consecutive_silent_samples: usize,
/// LOCAL PATCH: how many times a play request has had its stream run out
/// before the end of the track, so a stream that never completes gives up
/// instead of putting the same song back on for ever.
@@ -193,6 +212,8 @@ enum PlayerCommand {
SetAutoNormaliseAsAlbum(bool),
/// LOCAL PATCH: the quality to ask for from the next load onwards.
SetBitrate(Bitrate),
+ /// LOCAL PATCH: whether trailing silence triggers early crossfade.
+ SetTrimSilence(bool),
EmitSessionDisconnectedEvent {
connection_id: String,
user_name: String,
@@ -577,6 +598,7 @@ impl Player {
fade_out: None,
early_end: None,
fade_armed: None,
+ consecutive_silent_samples: 0,
short_end: None,
ended: None,
load_attempt: 0,
@@ -699,6 +721,11 @@ impl Player {
self.command(PlayerCommand::SetBitrate(bitrate));
}
+ /// LOCAL PATCH: whether trailing silence triggers early crossfade.
+ pub fn set_trim_silence(&self, enabled: bool) {
+ self.command(PlayerCommand::SetTrimSilence(enabled));
+ }
+
pub fn emit_filter_explicit_content_changed_event(&self, filter: bool) {
self.command(PlayerCommand::EmitFilterExplicitContentChangedEvent(filter));
}
@@ -2103,7 +2130,12 @@ impl Future for PlayerInternal {
let position = stream_position_ms as i64;
let duration = duration_ms as i64;
if crossfade_ms > 0 && duration > crossfade_ms {
- if position < duration - crossfade_ms {
+ let silence_threshold_samples = (SAMPLE_RATE as usize * NUM_CHANNELS as usize * 350) / 1000;
+ let trailing_silence = self.config.trim_silence
+ && self.consecutive_silent_samples >= silence_threshold_samples
+ && position >= duration - crossfade_ms - 2000;
+
+ if position < duration - crossfade_ms && !trailing_silence {
// LOCAL PATCH: the track has been heard playing outside
// its own ending, so its ending means something.
//
@@ -2123,9 +2155,15 @@ impl Future for PlayerInternal {
&& self.fade_armed == Some(play_request_id)
&& self.state.is_playing()
{
- info!(
- "crossfade: {position} ms of {duration} ms played, announcing the end of <{track_id:?}>"
- );
+ if trailing_silence {
+ info!(
+ "silence trimming: {position} ms of {duration} ms played, trailing silence detected, triggering crossfade early for <{track_id:?}>"
+ );
+ } else {
+ info!(
+ "crossfade: {position} ms of {duration} ms played, announcing the end of <{track_id:?}>"
+ );
+ }
self.early_end = Some(play_request_id);
self.announce_end(track_id, play_request_id);
}
@@ -2281,21 +2319,26 @@ impl PlayerInternal {
}
let x = fade.done as f64 / fade.total as f64;
- let gain_in = (x * std::f64::consts::FRAC_PI_2).sin();
+ // If the outgoing track has finished draining early, bring the incoming track to full scale
+ let gain_in = if fade.drained && fade.spare.is_empty() {
+ 1.0
+ } else {
+ (x * std::f64::consts::FRAC_PI_2).sin()
+ };
let gain_out = (x * std::f64::consts::FRAC_PI_2).cos();
for sample in data.iter_mut().skip(offset).take(channels) {
let tail = fade.spare.pop_front().unwrap_or(0.0);
let mixed = *sample * gain_in
+ tail * gain_out * fade.normalisation_factor * volume;
- *sample = mixed.clamp(-1.0, MAX_SAMPLE);
+ *sample = soft_limit(mixed);
}
fade.done += channels;
offset += channels;
}
- if fade.done >= fade.total {
+ if fade.done >= fade.total || (fade.drained && fade.spare.is_empty()) {
// Dropping it closes the outgoing stream.
self.fade_out = None;
}
@@ -2334,7 +2377,7 @@ impl PlayerInternal {
* fade.normalisation_factor
* volume;
for sample in samples.iter_mut() {
- *sample = (*sample * gain).clamp(-1.0, MAX_SAMPLE);
+ *sample = soft_limit(*sample * gain);
}
// Counted here as well, or the curve would stand still through the
@@ -2596,6 +2639,19 @@ impl PlayerInternal {
if let AudioPacket::Samples(ref mut data) = packet {
self.apply_fade(data);
}
+ } else if let AudioPacket::Samples(ref data) = packet {
+ // LOCAL PATCH: track trailing silence near the end of a track for silence trimming
+ let crossfade_ms = self.config.crossfade_duration_ms as i64;
+ if self.config.trim_silence && crossfade_ms > 0 && self.fade_armed.is_some() && self.early_end.is_none() {
+ const SILENCE_THRESHOLD: f64 = 0.00316; // -50 dBFS
+ if data.iter().all(|s| s.abs() < SILENCE_THRESHOLD) {
+ self.consecutive_silent_samples += data.len();
+ } else {
+ self.consecutive_silent_samples = 0;
+ }
+ } else {
+ self.consecutive_silent_samples = 0;
+ }
}
if let Err(e) = self.sink.write(packet, &mut self.converter) {
@@ -2765,6 +2821,7 @@ impl PlayerInternal {
if let Some(previous) = self.state.play_request_id() {
if previous != play_request_id {
self.ended = Some(previous);
+ self.consecutive_silent_samples = 0;
}
}
@@ -3176,6 +3233,12 @@ impl PlayerInternal {
}
}
+ // LOCAL PATCH: see Player::set_trim_silence.
+ PlayerCommand::SetTrimSilence(enabled) => {
+ info!("trim_silence is now {enabled}");
+ self.config.trim_silence = enabled;
+ }
+
PlayerCommand::EmitFilterExplicitContentChangedEvent(filter) => {
self.send_event(PlayerEvent::FilterExplicitContentChanged { filter });
@@ -3258,7 +3321,6 @@ impl PlayerInternal {
let loader = self.load_track(track_id.clone(), position_ms);
let loader = Box::pin(
async move {
- tokio::time::sleep(LOAD_RETRY_BACKOFF).await;
loader.await
}
.fuse(),
@@ -3385,6 +3447,9 @@ impl fmt::Debug for PlayerCommand {
PlayerCommand::SetBitrate(bitrate) => {
f.debug_tuple("SetBitrate").field(bitrate).finish()
}
+ PlayerCommand::SetTrimSilence(enabled) => {
+ f.debug_tuple("SetTrimSilence").field(enabled).finish()
+ }
PlayerCommand::SetAutoNormaliseAsAlbum(setting) => f
.debug_tuple("SetAutoNormaliseAsAlbum")
.field(&setting)