Skip to content

Native Android client for Spotify, built with Jetpack Compose

Downloads through SpotiFLAC's servers, Connect with headphones, likes at once

kota-zo9f34634b708c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02e82e01..d512862a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,8 +6,14 @@ Each release on GitHub shows its section below. The app shows it too when it off
A new engine, written from scratch, and a cleaner app on top of it.
-- **Lossless downloads**: the offline downloads are now FLAC. Myspoti finds the same recording on a lossless service (Tidal, Qobuz or Amazon) by the track's ISRC and takes it as it is served, never re-encoded — 16-bit CD quality, **24-bit hi-res when it exists**, or AAC re-encoded on the phone to keep them small (in Settings). The matching is done the way [SpotiFLAC](https://github.com/spotbye/SpotiFLAC) does it, with SpotiFLAC's own signed servers first. A one-off verification (a quick invisible check) turns it on after sign-in. A track with no lossless recording anywhere is marked unavailable.
+- **Lossless downloads**: the offline downloads are now FLAC. Myspoti finds the same recording on a lossless service (Tidal, Qobuz or Amazon) by the track's ISRC and takes it as it is served, never re-encoded — 16-bit CD quality, **24-bit hi-res when it exists**, or AAC re-encoded on the phone to keep them small (in Settings). Tidal and Qobuz come through the same signed servers as SpotiFLAC Mobile's extensions, three songs at a time; a one-off verification in Settings turns them on. A track with no lossless recording anywhere is marked unavailable.
- **Sound quality, chosen at the start**: a first step after sign-in picks the streaming quality (Automatic, Low 24 kbit/s, Normal 96, High 160) and the download quality (off, smallest AAC 96 kbit/s, FLAC CD, FLAC hi-res). Both stay in the new **Settings** page.
+- **Connect shows your headphones**: with Bluetooth or wired headphones, their name replaces "This phone", a "This phone" row sends the sound back to the speaker, and a Bluetooth button opens the pairing settings. The quality badge opens a small page with what plays now (codec and bitrate) and the setting.
+- **Downloads ask their quality** if you want ("Ask each time"): once for a whole playlist, kept for its new songs.
+- **Liked Songs update at once** after a like or an unlike, without reloading the whole list.
+- **No more "bop" between two songs** on the phone's speaker: the sound output stays awake across the change.
+- **Haptics work again**: buttons, likes and the debug icon vibrate.
+- **Solid bottom bar** as an option in Settings, Display.
- **Settings page**: sound quality, downloads, data and battery, display and language, in one place (profile menu or Library's account menu).
- **Italian**: Myspoti's own texts are translated too.
- **Headphones unplugged or Bluetooth gone**: the music pauses instead of moving to the phone's speaker.
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index bb466286..be4dd407 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -233,6 +233,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (bridge.ready.value) applyAudioQuality()
}
+ /** What the page plays now: bitrate (bit/s, 0 = unknown) and codec ("audio/mp4; codecs=…"). */
+ suspend fun audioInfo(): Pair<Int, String> = runCatching {
+ val o = bridge.call("player.audioInfo") as? JsonObject ?: return@runCatching 0 to ""
+ (o["bitrate"]?.jsonPrimitive?.content?.toDoubleOrNull()?.toInt() ?: 0) to (o["mime"]?.jsonPrimitive?.content.orEmpty())
+ }.getOrDefault(0 to "")
+
private suspend fun applyAudioQuality() {
runCatching { bridge.call("player.setAudioQuality", buildJsonObject { put("level", audioQuality) }) }
.onFailure { bridge.logger?.invoke("audio quality $audioQuality not set: ${it.message}") }
diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.js
index 3f82ac48..b25f5976 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -204,6 +204,18 @@
'player.setSpeed': a => need().player.setSpeed(a.speed),
// Streaming quality, as the desktop app's setting: "auto", "low", "normal", "high",
// "very_high". The page's own player (PlayerSDK.harmony) picks the files with it.
+ // What the page plays now: bitrate, codec and the chosen quality level.
+ 'player.audioInfo': async () => {
+ const sdk = need().resolve('PlayerSDK');
+ const streamer = sdk && sdk.harmony && sdk.harmony._streamer;
+ const player = streamer && streamer._playerPromise ? await streamer._playerPromise : null;
+ const content = player && player._currentContent;
+ return {
+ bitrate: content && content._bitrate || 0,
+ mime: content && content._mimeType || '',
+ level: player && player._preferredMediaPlaybackQuality && player._preferredMediaPlaybackQuality.audio || '',
+ };
+ },
'player.setAudioQuality': async a => {
const sdk = need().resolve('PlayerSDK');
const harmony = sdk && sdk.harmony;
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index 9ec3c5d3..eb9b9d61 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -65,6 +65,8 @@ class MainActivity : AppCompatActivity() {
connecting -> ConnectingScreen()
else -> WelcomeScreen(onLogin = { showLogin() })
}
+ // "Ask each time": the download quality question, above every screen.
+ com.music.spotui.ui.components.DownloadAskHost()
// Beta and dev builds only: hold the faint dot to copy the recent logs.
if (com.music.spotui.data.api.UpdateChecker.isBeta || app.myspoti.engine.BuildConfig.DEBUG)
com.music.spotui.ui.components.BetaLogButton(
@@ -75,6 +77,8 @@ class MainActivity : AppCompatActivity() {
}
root.addView(compose, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
setContentView(root)
+ // Haptics (buttons, likes, the debug icon) go through this window.
+ com.music.spotui.di.Haptics.attach(compose)
// Debug builds: `am start ... --ez showPlayer true` shows the Web Player page full screen.
val debuggable = applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
MyspotiRuntime.host.attach(root, visible = debuggable && intent.getBooleanExtra("showPlayer", false))
diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
index 2143bcd4..1c9f8509 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
@@ -77,7 +77,22 @@ class Api constructor(
}
}
- object LikedCache { @Volatile var tracks: List<SongsModel>? = null }
+ object LikedCache {
+ @Volatile var tracks: List<SongsModel>? = null
+
+ /**
+ * [head] (the newest liked songs, from Spotify) then the rest of [known] after them.
+ * A song unliked inside the head's span is gone from it, so it goes from the list too.
+ */
+ fun merge(head: List<SongsModel>, known: List<SongsModel>): List<SongsModel> {
+ val ids = head.mapTo(HashSet()) { it.spotifyTrackId }
+ val lastHead = head.lastOrNull()?.spotifyTrackId
+ // What came after the head's last song in the old list is older: kept as it was.
+ val tailStart = known.indexOfFirst { it.spotifyTrackId == lastHead }.let { if (it < 0) known.size else it + 1 }
+ val tail = if (head.size < 50) emptyList() else known.drop(tailStart).filterNot { it.spotifyTrackId in ids }
+ return head + tail
+ }
+ }
/** True once the Web Player is signed in and ready (waits up to 30 s at startup). */
private suspend fun ready(): Boolean =
@@ -470,6 +485,20 @@ class Api constructor(
emit(Response.Success(page(tracks, true)))
}
+ /**
+ * After a like / unlike: the newest Liked Songs (one page) put on top of what is
+ * known, so the list is right at once without loading every page again.
+ */
+ suspend fun mergeLikedHead(): List<SongsModel>? = runCatching {
+ if (!ready()) return null
+ val head = api.library.likedTracks(0, 50).items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }
+ val merged = LikedCache.merge(head, LikedCache.tracks.orEmpty())
+ LikedCache.tracks = merged
+ withContext(Dispatchers.IO) { ScreenCache.liked.write(merged) }
+ SongPlayer.registerLikedSongs(merged.map { it.url })
+ merged
+ }.getOrNull()
+
private suspend fun allLiked(onPage: suspend (List<SongsModel>) -> Unit): List<SongsModel> {
val out = ArrayList<SongsModel>()
var offset = 0
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt
index 6fc659d2..8c5adeef 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt
@@ -27,6 +27,8 @@ data class OfflineCollection(
val name: String,
val trackIds: Set<String>,
val syncedAt: Long,
+ /** The quality chosen when the list was first downloaded; its new songs follow it. */
+ val quality: String = "",
)
/**
@@ -61,11 +63,11 @@ object OfflineCollections {
collections.values.any { trackId in it.trackIds }
/** Download a song on its own. */
- fun downloadSong(song: SongsModel) {
+ fun downloadSong(song: SongsModel, quality: com.music.spotui.data.preferences.DownloadQuality? = null) {
if (song.spotifyTrackId.isBlank()) return
synchronized(lock) { singles += song.spotifyTrackId }
save()
- OfflineDownloader.enqueue(listOf(song))
+ OfflineDownloader.enqueue(listOf(song), quality)
}
/**
@@ -81,11 +83,11 @@ object OfflineCollections {
}
/** Download a list as a whole, and keep it in step from now on. */
- fun download(page: ContextPageModel) {
+ fun download(page: ContextPageModel, quality: com.music.spotui.data.preferences.DownloadQuality? = null) {
val ids = page.tracks.map { it.spotifyTrackId }.filter { it.isNotBlank() }.toSet()
- collections[page.uri] = OfflineCollection(page.uri, page.type, page.name, ids, System.currentTimeMillis())
+ collections[page.uri] = OfflineCollection(page.uri, page.type, page.name, ids, System.currentTimeMillis(), quality?.name.orEmpty())
save()
- OfflineDownloader.enqueue(page.tracks)
+ OfflineDownloader.enqueue(page.tracks, quality)
}
/** Stop keeping a list: its songs go, unless another reason keeps them. */
@@ -114,7 +116,7 @@ object OfflineCollections {
collections[page.uri] = c.copy(name = page.name, trackIds = ids, syncedAt = System.currentTimeMillis())
save()
val missing = songs.filter { !OfflineStore.isDownloaded(it.spotifyTrackId) && OfflineStore.status[it.spotifyTrackId] == null }
- if (missing.isNotEmpty()) OfflineDownloader.enqueue(missing)
+ if (missing.isNotEmpty()) OfflineDownloader.enqueue(missing, com.music.spotui.data.preferences.DownloadQuality.saved(c.quality))
gone.filterNot { isKept(it) }.forEach { OfflineDownloader.remove(it) }
if (missing.isNotEmpty() || gone.isNotEmpty()) Log.i(TAG, "${page.name}: +${missing.size} -${gone.size}")
}
@@ -149,7 +151,7 @@ object OfflineCollections {
val lists = JSONArray()
collections.values.forEach { c ->
lists.put(JSONObject().put("uri", c.uri).put("type", c.type).put("name", c.name)
- .put("synced", c.syncedAt).put("tracks", JSONArray(c.trackIds.toList())))
+ .put("synced", c.syncedAt).put("tracks", JSONArray(c.trackIds.toList())).put("quality", c.quality))
}
JSONObject().put("version", 1).put("lists", lists).put("singles", JSONArray(singles.toList())).toString()
}
@@ -169,7 +171,7 @@ object OfflineCollections {
val tracks = c.optJSONArray("tracks") ?: JSONArray()
collections[c.getString("uri")] = OfflineCollection(
c.getString("uri"), c.optString("type"), c.optString("name"),
- (0 until tracks.length()).map { tracks.getString(it) }.toSet(), c.optLong("synced"),
+ (0 until tracks.length()).map { tracks.getString(it) }.toSet(), c.optLong("synced"), c.optString("quality"),
)
}
val s = o.optJSONArray("singles") ?: JSONArray()
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
index 0c80fd02..39762fae 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
@@ -4,9 +4,7 @@ import android.util.Log
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.snapshots.SnapshotStateMap
import com.music.spotui.data.entity.SongsModel
-import com.music.spotui.data.preferences.isHiRes
import com.music.spotui.data.preferences.isLosslessEnabled
-import com.music.spotui.data.preferences.isSmallDownloads
import com.music.spotui.di.Graph
import com.music.spotui.lossless.DashFlacRemux
import com.music.spotui.lossless.LosslessSource
@@ -54,7 +52,7 @@ import java.util.concurrent.ConcurrentHashMap
*/
object OfflineDownloader {
private const val TAG = "Offline"
- private const val WORKERS = 2
+ private const val WORKERS = 3
private const val MIN_SCORE = 0.5
data class Request(
@@ -65,9 +63,12 @@ object OfflineDownloader {
val albumId: String,
val durationMs: Long,
val coverUrl: String,
+ /** The quality chosen for this download ([DownloadQuality.name]); empty = the setting. */
+ val quality: String = "",
) {
fun toJson(): JSONObject = JSONObject().put("id", trackId).put("title", title).put("artist", artist)
.put("album", album).put("albumId", albumId).put("duration", durationMs).put("cover", coverUrl)
+ .put("quality", quality)
companion object {
fun of(s: SongsModel) = Request(
@@ -76,7 +77,7 @@ object OfflineDownloader {
)
fun fromJson(o: JSONObject) = Request(
o.getString("id"), o.optString("title"), o.optString("artist"), o.optString("album"),
- o.optString("albumId"), o.optLong("duration"), o.optString("cover"),
+ o.optString("albumId"), o.optLong("duration"), o.optString("cover"), o.optString("quality"),
)
}
}
@@ -127,7 +128,11 @@ object OfflineDownloader {
if (saved.isNotEmpty()) enqueueAll(saved)
}
- fun enqueue(songs: List<SongsModel>) {
+ /**
+ * Downloads [songs] in [quality] (asked when the setting is "ask each time"), else in
+ * the quality chosen in Settings.
+ */
+ fun enqueue(songs: List<SongsModel>, quality: com.music.spotui.data.preferences.DownloadQuality? = null) {
// Downloads switched off in Settings: say so, instead of a list of failed songs.
if (!isLosslessEnabled(Graph.app)) {
scope.launch(Dispatchers.Main) {
@@ -135,7 +140,8 @@ object OfflineDownloader {
}
return
}
- enqueueAll(songs.filter { it.spotifyTrackId.isNotBlank() }.map(Request::of))
+ val q = quality?.let { com.music.spotui.data.preferences.DownloadQuality.saved(it.name) }?.name.orEmpty()
+ enqueueAll(songs.filter { it.spotifyTrackId.isNotBlank() }.map { Request.of(it).copy(quality = q) })
}
private fun enqueueAll(list: List<Request>) {
@@ -227,6 +233,7 @@ object OfflineDownloader {
private suspend fun download(r: Request): OfflineTrack {
if (!isLosslessEnabled(Graph.app)) throw Unavailable("lossless downloads are off")
+ val quality = qualityOf(r)
val tmp = OfflineStore.tmpDir
val audioTmp = File(tmp, "${r.trackId}.flacpart")
val previewTmp = File(tmp, "${r.trackId}.preview")
@@ -248,7 +255,8 @@ object OfflineDownloader {
Log.i(TAG, "${meta.title}: isrc=${meta.isrc ?: "-"} preview=${if (previewFeatures != null) "ok" else if (previewLink != null) "unusable" else "none"}")
// ── Lossless resolve: gated SpotiFLAC first, then the community backends.
- val file = resolveAndFetch(r, meta, audioTmp) ?: throw Unavailable("no lossless match")
+ val file = resolveAndFetch(r, meta, audioTmp, quality == com.music.spotui.data.preferences.DownloadQuality.HI_RES)
+ ?: throw Unavailable("no lossless match")
currentCoroutineContext().ensureActive()
// ── Verification before the file is kept.
@@ -267,7 +275,7 @@ object OfflineDownloader {
}
val out: File
- if (isSmallDownloads(Graph.app)) {
+ if (quality == com.music.spotui.data.preferences.DownloadQuality.SMALL) {
// "Smallest": the checked FLAC becomes AAC, encoded on the phone.
out = File(OfflineStore.audioDir, "${r.trackId}.m4a")
val aacTmp = File(OfflineStore.tmpDir, "${r.trackId}.m4apart")
@@ -301,11 +309,17 @@ object OfflineDownloader {
}
/** Runs the lossless resolver and saves the audio into [out]; null when nothing matched. */
- private suspend fun resolveAndFetch(r: Request, meta: Meta, out: File): Fetched? {
+ /** This download's quality: the one chosen when it started, else Settings (CD when Settings says "ask"). */
+ private fun qualityOf(r: Request): com.music.spotui.data.preferences.DownloadQuality =
+ com.music.spotui.data.preferences.DownloadQuality.saved(r.quality)
+ ?: com.music.spotui.data.preferences.DownloadQuality.saved(com.music.spotui.data.preferences.getDownloadQuality(Graph.app).name)
+ ?: com.music.spotui.data.preferences.DownloadQuality.CD
+
+ private suspend fun resolveAndFetch(r: Request, meta: Meta, out: File, hiRes: Boolean): Fetched? {
val resolved = LosslessSource.resolve(
Graph.app, r.trackId,
LosslessSource.TrackInfo(meta.title, meta.artist, (meta.durationMs / 1000).toInt(), meta.isrc.orEmpty()),
- preferHiRes = isHiRes(Graph.app),
+ preferHiRes = hiRes,
)
if (resolved !is LosslessSource.Success) return null
val track = resolved.track
@@ -420,7 +434,7 @@ object OfflineDownloader {
}
private fun rangedDownload(url: String, out: File, knownTotal: Long): Boolean {
- val chunk = 16L * 1024 * 1024 // 16 MB
+ val chunk = 4L * 1024 * 1024 // 4 MB: the stream gets its turn between two chunks
var total = knownTotal
java.io.RandomAccessFile(out, "rw").use { output ->
output.setLength(0)
@@ -429,6 +443,7 @@ object OfflineDownloader {
val end = if (total > 0) minOf(output.length() + chunk - 1, total - 1) else output.length() + chunk - 1
var done = false
var attempt = 0
+ yieldToPlayer()
while (true) {
attempt++
val position = output.length()
@@ -477,6 +492,22 @@ object OfflineDownloader {
return true
}
+ /**
+ * The song playing here is loading: downloads wait (up to 30 s) so they do not starve
+ * it, or the player's stall watchdog would take it for stuck and skip it.
+ */
+ private fun yieldToPlayer() {
+ var waited = 0
+ while (waited < 30_000 && playerStarving()) {
+ Thread.sleep(500); waited += 500
+ }
+ }
+
+ private fun playerStarving(): Boolean = runCatching {
+ com.music.spotui.di.SongPlayer.isPlaying() && com.music.spotui.di.SongPlayer.isBuffering &&
+ com.music.spotui.di.SongPlayer.activeDevice.value == null && !com.music.spotui.di.LocalPlayer.active.value
+ }.getOrDefault(false)
+
private fun contentLength(url: String): Long =
runCatching {
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/LosslessPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/LosslessPref.kt
index a2ea5a9b..13957614 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/LosslessPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/LosslessPref.kt
@@ -10,6 +10,7 @@ private const val PREF = "LosslessPref"
private const val KEY_HI_RES = "hires_24bit"
private const val KEY_ENABLED = "enabled"
private const val KEY_SMALL = "small_aac"
+private const val KEY_ASK = "ask_each_time"
/**
* Hi-res downloads (24-bit when the provider has it: bigger files, ~3× a CD-quality FLAC).
@@ -29,4 +30,9 @@ fun isSmallDownloads(context: Context): Boolean = prefs(context).getBoolean(KEY_
fun setSmallDownloads(context: Context, on: Boolean) = prefs(context).edit().putBoolean(KEY_SMALL, on).apply()
+/** The quality is asked at each download (once for a whole list). */
+fun isAskDownloadQuality(context: Context): Boolean = prefs(context).getBoolean(KEY_ASK, false)
+
+fun setAskDownloadQuality(context: Context, on: Boolean) = prefs(context).edit().putBoolean(KEY_ASK, on).apply()
+
private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
index 7c6737a1..a2b06387 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
@@ -27,7 +27,16 @@ enum class StreamingQuality(val level: String) {
* How a downloaded song is saved: not at all, small (AAC re-encoded from the checked FLAC),
* FLAC 16-bit (CD), or FLAC 24-bit when it exists.
*/
-enum class DownloadQuality { OFF, SMALL, CD, HI_RES }
+enum class DownloadQuality {
+ OFF, SMALL, CD, HI_RES,
+ /** Asked when a download starts (once for a whole playlist or album). */
+ ASK;
+
+ companion object {
+ /** A quality a file can be saved in ([ASK] and [OFF] are not); null when unknown. */
+ fun saved(name: String?): DownloadQuality? = entries.firstOrNull { it.name == name }?.takeIf { it != ASK && it != OFF }
+ }
+}
fun getStreamingQuality(c: Context): StreamingQuality =
StreamingQuality.of(prefs(c).getString(KEY_STREAMING, null))
@@ -47,6 +56,7 @@ fun applyStreamingQuality(q: StreamingQuality) {
fun getDownloadQuality(c: Context): DownloadQuality = when {
!isLosslessEnabled(c) -> DownloadQuality.OFF
+ isAskDownloadQuality(c) -> DownloadQuality.ASK
isSmallDownloads(c) -> DownloadQuality.SMALL
isHiRes(c) -> DownloadQuality.HI_RES
else -> DownloadQuality.CD
@@ -56,6 +66,7 @@ fun setDownloadQuality(c: Context, q: DownloadQuality) {
setLosslessEnabled(c, q != DownloadQuality.OFF)
setHiRes(c, q == DownloadQuality.HI_RES)
setSmallDownloads(c, q == DownloadQuality.SMALL)
+ setAskDownloadQuality(c, q == DownloadQuality.ASK)
}
/** The quality step of the onboarding was seen (new installs and updates alike). */
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
index 54215617..fdcc9a11 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
@@ -1,6 +1,8 @@
package com.music.spotui.data.preferences
import android.content.Context
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.setValue
// Trimmed from Spotui: stream quality, crossfade, YouTube and web-playback settings
// are gone (the Web Player engine streams Spotify's own audio).
@@ -16,6 +18,18 @@ fun setLyricsExtraSources(c: Context, v: Boolean) = prefs(c).edit().putBoolean(K
private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)
+/** The bottom bar: solid black, or fading into the list (the default). Read by the bar as state. */
+object SolidNavBar {
+ private const val KEY = "solid_nav_bar"
+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, false))
+ private set
+
+ fun set(c: Context, value: Boolean) {
+ on = value
+ prefs(c).edit().putBoolean(KEY, value).apply()
+ }
+}
+
/** Library layout: false = rows (default), true = Spotify-style 3-column grid. */
fun isLibraryGridView(c: Context): Boolean = prefs(c).getBoolean(KEY_LIBRARY_GRID, false)
fun setLibraryGridView(c: Context, v: Boolean) = prefs(c).edit().putBoolean(KEY_LIBRARY_GRID, v).apply()
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SpotiflacSessionPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SpotiflacSessionPref.kt
index 92a5817c..49268de7 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/SpotiflacSessionPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SpotiflacSessionPref.kt
@@ -1,32 +1,33 @@
package com.music.spotui.data.preferences
-/*
- * Ported from Spotui (https://github.com/Spotui/Spotui), GPL-3.0.
- */
-
import android.content.Context
/**
- * Stores the signed-session obtained from SpotiFLAC's gated backend: the
- * server-issued session_id + session_secret used to HMAC-sign the community
- * download requests. Captured by the verification screen after the user solves
- * the Turnstile themselves.
+ * The signed sessions of the SpotiFLAC download servers (Zarz), one per extension
+ * they are issued to (Tidal, Qobuz): the server-issued session_id + session_secret
+ * that sign the download requests, captured by the verification screen after the
+ * user solves the challenge themselves. The install id is shared.
*/
private const val PREF = "SpotiflacSession"
+private fun prefs(c: Context, appVersion: String) =
+ c.getSharedPreferences(PREF + "_" + appVersion.substringBefore('@'), Context.MODE_PRIVATE)
+
fun saveSpotiflacSession(
context: Context,
sessionId: String,
sessionSecret: String,
installId: String,
expiresAt: String,
+ appVersion: String,
) {
- context.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit()
+ prefs(context, appVersion).edit()
+ .putString("app_version", appVersion)
.putString("session_id", sessionId)
.putString("session_secret", sessionSecret)
- .putString("install_id", installId)
.putString("expires_at", expiresAt)
.apply()
+ context.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit().putString("install_id", installId).apply()
}
data class SpotiflacSession(
@@ -36,20 +37,28 @@ data class SpotiflacSession(
val expiresAt: String,
)
-fun getSpotiflacSession(context: Context): SpotiflacSession? {
- val p = context.getSharedPreferences(PREF, Context.MODE_PRIVATE)
+/** The install id the servers bind sessions to (kept across sessions). */
+fun spotiflacInstallId(context: Context): String =
+ context.getSharedPreferences(PREF, Context.MODE_PRIVATE).getString("install_id", "").orEmpty()
+
+fun getSpotiflacSession(context: Context, appVersion: String): SpotiflacSession? {
+ val p = prefs(context, appVersion)
+ // A session for another version of the extension does not sign this one's requests.
+ if (p.getString("app_version", "") != appVersion) return null
val id = p.getString("session_id", null)?.takeIf { it.isNotBlank() } ?: return null
val secret = p.getString("session_secret", null)?.takeIf { it.isNotBlank() } ?: return null
- return SpotiflacSession(
- sessionId = id,
- sessionSecret = secret,
- installId = p.getString("install_id", "").orEmpty(),
- expiresAt = p.getString("expires_at", "").orEmpty(),
- )
+ return SpotiflacSession(id, secret, spotiflacInstallId(context), p.getString("expires_at", "").orEmpty())
}
-fun hasSpotiflacSession(context: Context): Boolean = getSpotiflacSession(context) != null
+/** At least one download server is verified. */
+fun hasSpotiflacSession(context: Context): Boolean =
+ com.music.spotui.lossless.ZarzSession.Ext.entries.any { getSpotiflacSession(context, it.appVersion) != null }
+
+fun clearSpotiflacSession(context: Context, appVersion: String) {
+ prefs(context, appVersion).edit().clear().apply()
+}
-fun clearSpotiflacSession(context: Context) {
- context.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit().clear().apply()
+/** Forgets every session (Settings, "Forget"). */
+fun clearSpotiflacSessions(context: Context) {
+ com.music.spotui.lossless.ZarzSession.Ext.entries.forEach { clearSpotiflacSession(context, it.appVersion) }
}
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 8ba65ae5..20ecb6e9 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -277,6 +277,7 @@ object SongPlayer {
val predicted = getCurrentPosition()
bufferingState.value = s.isBuffering
playing = resolvePlaying(s.isPaused)
+ SpeakerKeepAlive.set(playing && _activeDevice.value == null)
durationMs = item?.durationMs ?: 0L
val reported = s.positionAt(System.currentTimeMillis())
// Keep the running clock when the player only nudges it (< 1 s).
@@ -589,6 +590,9 @@ object SongPlayer {
return saved
}
+ /** Bumped at every like / unlike of a track: the Liked Songs page refreshes its top. */
+ val likedChanges = kotlinx.coroutines.flow.MutableStateFlow(0)
+
/** Like / unlike a track by id. */
fun setTrackSaved(trackId: String, on: Boolean) {
if (trackId.isBlank()) return
@@ -602,12 +606,14 @@ object SongPlayer {
intentValue = on
intentUntil = SystemClock.elapsedRealtime() + 3000
onLibraryItem(uri, on)
+ val track = uri.startsWith(SPOTIFY_TRACK_PREFIX)
command {
if (uri.startsWith("spotify:playlist:")) {
if (on) api.playlists.follow(uri) else api.playlists.unfollow(uri)
} else {
if (on) api.library.add(listOf(uri)) else api.library.remove(listOf(uri))
}
+ if (track) likedChanges.value++
}
}
diff --git a/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt b/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt
new file mode 100644
index 00000000..acb3e056
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/SpeakerKeepAlive.kt
@@ -0,0 +1,71 @@
+package com.music.spotui.di
+
+import android.media.AudioAttributes
+import android.media.AudioFormat
+import android.media.AudioTrack
+import android.os.Handler
+import android.os.Looper
+
+/**
+ * The "bop" between two songs on the phone's speaker: the Web Player closes its audio
+ * stream at the end of a song and opens a new one for the next, and the phone powers
+ * its amplifier down and up again in between. A silent stream of our own, kept open
+ * while the music plays here (and a little after it stops), keeps the output awake
+ * across the change. It asks for no audio focus and plays nothing audible.
+ */
+object SpeakerKeepAlive {
+ private const val RATE = 48_000
+ /** Pauses and song changes shorter than this keep the stream (and the output) open. */
+ private const val LINGER_MS = 15_000L
+
+ private val main = Handler(Looper.getMainLooper())
+ @Volatile private var track: AudioTrack? = null
+ @Volatile private var feeder: Thread? = null
+ private val release = Runnable { stop() }
+
+ /** [playingHere]: music plays on this phone (not on a Connect device). */
+ fun set(playingHere: Boolean) = main.post {
+ if (playingHere) {
+ main.removeCallbacks(release)
+ start()
+ } else if (track != null) {
+ main.removeCallbacks(release)
+ main.postDelayed(release, LINGER_MS)
+ }
+ }
+
+ private fun start() {
+ if (track != null) return
+ val size = AudioTrack.getMinBufferSize(RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
+ val t = runCatching {
+ AudioTrack.Builder()
+ .setAudioAttributes(AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_MEDIA)
+ .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
+ .build())
+ .setAudioFormat(AudioFormat.Builder()
+ .setSampleRate(RATE)
+ .setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
+ .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
+ .build())
+ .setBufferSizeInBytes(size)
+ .setTransferMode(AudioTrack.MODE_STREAM)
+ .build()
+ }.getOrNull() ?: return
+ track = t
+ runCatching { t.play() }
+ feeder = Thread({
+ val zeros = ByteArray(size)
+ // Blocking writes pace themselves on the output: no busy loop.
+ while (track === t) if (t.write(zeros, 0, zeros.size) < 0) break
+ }, "speaker-keepalive").apply { isDaemon = true; start() }
+ }
+
+ private fun stop() {
+ val t = track ?: return
+ track = null
+ feeder = null
+ runCatching { t.pause(); t.flush(); t.stop() }
+ t.release()
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/lossless/LosslessRegistry.kt b/base/app/src/main/java/com/music/spotui/lossless/LosslessRegistry.kt
index 991d2e2d..dde3aef8 100644
--- a/base/app/src/main/java/com/music/spotui/lossless/LosslessRegistry.kt
+++ b/base/app/src/main/java/com/music/spotui/lossless/LosslessRegistry.kt
@@ -31,16 +31,6 @@ internal object LosslessRegistry {
// Community backend API key (shared/published constant in SpotiFLAC's sources).
const val API_KEY = "ak_8e3f1a7c2b5d9e4f0a6c3b8d1e5f2a9c7b4d0e6f"
- // Issues the signed sessions the community download servers accept. Sessions from
- // any other host fail there with 401 "Signed request validation failed". Network call: IO only.
- fun communityVerifyUrl(): String =
- registry()?.optJSONObject("community")?.optString("verify")?.takeIf { it.startsWith("https://") }
- ?.trimEnd('/') ?: "https://verify.spotbye.qzz.io"
-
- /** Community (gated) download endpoint for a provider, e.g. tidal → .../api/dl. */
- fun communityDlUrl(provider: String): String? =
- registry()?.optJSONObject(provider)?.optString("community")?.takeIf { it.isNotBlank() }
-
private const val GIST_URL =
"https://gist.githubusercontent.com/BartolomeoRusso9/ef9fdbbc894818aea89d25a8d99f8c77/raw"
diff --git a/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt b/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
index 8ba5a6ad..37fd4bb7 100644
--- a/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
+++ b/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
@@ -18,13 +18,13 @@ import java.net.URLEncoder
import java.security.MessageDigest
/**
- * Resolves a Spotify track to lossless FLAC via SpotiFLAC — its gated backend
- * first (the user's signed session), then the public community backends. Each
+ * Resolves a Spotify track to lossless FLAC — the SpotiFLAC download servers first
+ * (Qobuz, with the user's signed session), then the public community backends. Each
* provider fails gracefully: a down or throttled source just falls through.
*
* Priority (most reliable first):
- * 1. SpotiFLAC gated session — Qobuz (found by ISRC in its own catalogue), then
- * Tidal (16 or 24-bit).
+ * 1. Qobuz (found by ISRC in its own catalogue) through the SpotiFLAC (Zarz)
+ * servers and the user's signed session — 16 or 24-bit.
* 2. Tidal community backends — `/track/?id=`, single-file FLAC (16) or a
* DASH manifest to remux into one FLAC file (24).
* 3. Amazon self-resolve by Spotify id (often dormant).
@@ -67,68 +67,110 @@ object LosslessSource {
): Result = withContext(Dispatchers.IO) {
// Qobuz's own catalogue search finds the ISRC quickly and does not depend on the
// community backends; the Tidal id does (their search), and they are often down.
+ fun verified(ext: ZarzSession.Ext) = com.music.spotui.data.preferences.getSpotiflacSession(context, ext.appVersion) != null
+
+ // 1. Tidal through the SpotiFLAC download servers (Zarz), with the user's verified
+ // session, as SpotiFLAC Mobile's tidal-web extension does: the most reliable source.
+ // Tidal's own public API finds the exact ISRC.
+ if (verified(ZarzSession.Ext.TIDAL)) {
+ tidalIdForIsrc(info.isrc)?.let { id -> zarzTidal(context, id, info, preferHiRes)?.let { return@withContext it } }
+ }
+ // 2. Qobuz the same way (qobuz-web), found by ISRC in Qobuz's own catalogue.
val qobuz = qobuzIdForIsrc(info.isrc)
- val session = SpotiflacGated.hasSession(context)
+ if (qobuz != null && verified(ZarzSession.Ext.QOBUZ)) {
+ zarzQobuz(context, qobuz, info, preferHiRes)?.let { return@withContext it }
+ }
- // 1. SpotiFLAC's gated /api/dl (needs the user's verification session): Qobuz first
- // when the ISRC found it, so a dead Tidal backend costs no time.
- if (session && qobuz != null) gated(context, null, qobuz, info, preferHiRes)?.let { return@withContext it }
+ // 3. Tidal community backends (no account needed).
val tidal = tidalHit(info)
- if (session && tidal != null) gated(context, tidal, null, info, preferHiRes)?.let { return@withContext it }
-
- // 2. Tidal community backends (no account needed).
if (tidal != null) tidalDirect(tidal, info, preferHiRes)?.let { return@withContext it }
- // 3. Amazon (self-resolves from the Spotify id; usually dormant).
+ // 4. Amazon (self-resolves from the Spotify id; usually dormant).
amazon(spotifyId)?.let { return@withContext it }
NotFound
}
- /** Gated providers: Tidal first (its match is the strongest), then Qobuz by ISRC. */
- private suspend fun gated(
- context: Context,
- tidal: TidalHit?,
- qobuzId: String?,
- info: TrackInfo,
- preferHiRes: Boolean,
- ): Result? {
- if (tidal != null) {
- val qualities = if (preferHiRes) listOf("HI_RES_LOSSLESS", "LOSSLESS") else listOf("LOSSLESS")
- for (q in qualities) {
- val hit = runCatching { SpotiflacGated.flacUrl(context, "tidal", tidal.id, q) }
- .getOrElse { Log.w(TAG, "gated tidal $q: ${it.message}"); null } ?: continue
- val result = hitAsSuccess(hit, "SpotiFLAC tidal", info, isrcMatches(tidal.isrc, info.isrc))
- if (result is Success) return result
+ /**
+ * Qobuz by its track id, as the qobuz-web extension asks for it: a download ticket for
+ * the track's URL, then POST /dl/qbz with it. 24-bit max first when hi-res is wanted.
+ */
+ private fun zarzQobuz(context: Context, qobuzId: String, info: TrackInfo, preferHiRes: Boolean): Result? {
+ val trackUrl = "https://open.qobuz.com/track/$qobuzId"
+ val qualities = if (preferHiRes) listOf("hi-res-max", "cd") else listOf("cd")
+ for (q in qualities) {
+ try {
+ val ticket = ZarzSession.ticket(context, ZarzSession.Ext.QOBUZ, "qbz", "track", trackUrl)
+ val o = ZarzSession.signedJson(context, ZarzSession.Ext.QOBUZ, "POST", "/dl/qbz", JSONObject()
+ .put("quality", q).put("upload_to_r2", false).put("id", qobuzId)
+ .put("type", "track").put("url", trackUrl), mapOf("X-Zarz-Ticket" to ticket))
+ val data = o.optJSONObject("data") ?: JSONObject()
+ val url = listOf("download_url", "url", "link")
+ .firstNotNullOfOrNull { k -> o.optString(k).ifBlank { data.optString(k) }.takeIf { it.startsWith("http") } }
+ ?: continue
+ val bits = o.optInt("bit_depth", data.optInt("bit_depth", 0)).takeIf { it in 8..32 } ?: if (q == "cd") 16 else 24
+ if (!isFullTrack(url, info.durationSec)) continue
+ // The Qobuz id came from a search on the ISRC itself, checked against it.
+ return Success(LosslessFile(url, "", "Qobuz", bits), isrcMatched = true)
+ } catch (e: ZarzSession.VerifyRequired) {
+ // The servers want a new verification: forget the session, Settings asks again.
+ com.music.spotui.data.preferences.clearSpotiflacSession(context, ZarzSession.Ext.QOBUZ.appVersion)
+ Log.w(TAG, "zarz qobuz: verification required")
+ return null
+ } catch (e: Exception) {
+ Log.w(TAG, "zarz qobuz $q: ${e.message}")
}
}
- if (qobuzId != null) {
- val qualities = if (preferHiRes) listOf("HI_RES_LOSSLESS", "LOSSLESS") else listOf("LOSSLESS")
- for (q in qualities) {
- val hit = runCatching { SpotiflacGated.flacUrl(context, "qobuz", qobuzId, q) }
- .getOrElse { Log.w(TAG, "gated qobuz $q: ${it.message}"); null } ?: continue
- // Qobuz was looked up by the ISRC itself and its answer checked against it.
- val result = hitAsSuccess(hit, "SpotiFLAC qobuz", info, true)
- if (result is Success) return result
+ return null
+ }
+
+ /**
+ * Tidal by its track id, as the tidal-web extension asks for it: a ticket for the
+ * id, then POST /dl/tid. The answer carries Tidal's own manifest: one FLAC file
+ * (CD), or a DASH manifest remuxed into one FLAC (hi-res).
+ */
+ private fun zarzTidal(context: Context, tidalId: String, info: TrackInfo, preferHiRes: Boolean): Result? {
+ val qualities = if (preferHiRes) listOf("HI_RES_LOSSLESS", "LOSSLESS") else listOf("LOSSLESS")
+ for (q in qualities) {
+ try {
+ val ticket = ZarzSession.ticket(context, ZarzSession.Ext.TIDAL, "tid", "track", tidalId)
+ val o = ZarzSession.signedJson(context, ZarzSession.Ext.TIDAL, "POST", "/dl/tid",
+ JSONObject().put("id", tidalId).put("quality", q), mapOf("X-Zarz-Ticket" to ticket))
+ val data = o.optJSONObject("data") ?: continue
+ if (data.optString("assetPresentation").equals("PREVIEW", true)) continue
+ val file = parseTidalTrack(JSONObject().put("data", data).toString(), "https://tidal.zarz") ?: continue
+ val named = file.copy(provider = if (file.dashBase64.isNotBlank()) "Tidal hi-res" else "Tidal")
+ if (named.url.isNotBlank() && !isFullTrack(named.url, info.durationSec)) continue
+ return Success(named, isrcMatched = true)
+ } catch (e: ZarzSession.VerifyRequired) {
+ com.music.spotui.data.preferences.clearSpotiflacSession(context, ZarzSession.Ext.TIDAL.appVersion)
+ Log.w(TAG, "zarz tidal: verification required")
+ return null
+ } catch (e: Exception) {
+ Log.w(TAG, "zarz tidal $q: ${e.message}")
}
}
return null
}
- /** Turns a gated hit into a Success, rejecting what is not full-length audio. */
- private suspend fun hitAsSuccess(
- hit: SpotiflacGated.GatedHit,
- provider: String,
- info: TrackInfo,
- isrcMatched: Boolean,
- ): Result? {
- if (hit.dashBase64.isNotBlank()) return Success(LosslessFile("", hit.dashBase64, provider, 24), isrcMatched)
- if (hit.url.isBlank()) return null
- if (!isFullTrack(hit.url, info.durationSec)) return null
- val quality = if (hit.quality > 0) hit.quality else 16
- return Success(LosslessFile(hit.url, "", provider, quality), isrcMatched)
+ /** Tidal's public API: the track carrying this exact ISRC (the web player's own token). */
+ internal fun tidalIdForIsrc(isrc: String): String? {
+ if (isrc.isBlank()) return null
+ return runCatching {
+ val body = get("https://tidal.com/v1/tracks?isrc=${URLEncoder.encode(isrc.trim(), "UTF-8")}&countryCode=US",
+ mapOf("x-tidal-token" to TIDAL_PUBLIC_TOKEN))
+ val items = JSONObject(body).optJSONArray("items") ?: JSONArray()
+ (0 until items.length()).map { items.getJSONObject(it) }
+ // Several releases carry the ISRC: one that streams in full, lossless first.
+ .filter { isrcMatches(it.optString("isrc"), isrc.trim()) && it.optBoolean("streamReady", true) }
+ .sortedByDescending { if (it.optString("audioQuality") == "HI_RES_LOSSLESS") 2 else if (it.optString("audioQuality") == "LOSSLESS") 1 else 0 }
+ .firstOrNull()?.optString("id")?.takeIf(String::isNotBlank)
+ }.getOrElse { Log.w(TAG, "tidal isrc lookup: ${it.message}"); null }
}
+ /** The public token Tidal's web player sends (the tidal-web extension's default). */
+ private const val TIDAL_PUBLIC_TOKEN = "49YxDN9a2aFV6RTG"
+
/** The public Tidal community backends direct: search gave the id already. */
private fun tidalDirect(tidal: TidalHit, info: TrackInfo, preferHiRes: Boolean): Result? {
val qualities = if (preferHiRes) listOf("HI_RES", "LOSSLESS") else listOf("LOSSLESS")
diff --git a/base/app/src/main/java/com/music/spotui/lossless/SpotiflacGated.kt b/base/app/src/main/java/com/music/spotui/lossless/SpotiflacGated.kt
deleted file mode 100644
index 6bbebb41..00000000
--- a/base/app/src/main/java/com/music/spotui/lossless/SpotiflacGated.kt
+++ /dev/null
@@ -1,163 +0,0 @@
-package com.music.spotui.lossless
-
-/*
- * Ported and extended from Spotui (https://github.com/Spotui/Spotui), GPL-3.0.
- * Spotui gated Tidal only; Qobuz and Amazon use the same SPOTIFLAC-HMAC-V1
- * signing against their own community hosts.
- */
-
-import android.content.Context
-import android.util.Base64
-import android.util.Log
-import com.music.spotui.data.preferences.getSpotiflacSession
-import org.json.JSONObject
-import java.net.HttpURLConnection
-import java.net.URL
-import java.security.MessageDigest
-import java.text.SimpleDateFormat
-import java.util.Locale
-import java.util.TimeZone
-import javax.crypto.Mac
-import javax.crypto.spec.SecretKeySpec
-
-/**
- * SpotiFLAC's **gated** community download — SpotiFLAC's own, most reliable FLAC
- * source. Uses the signed session captured by the verification screen to HMAC-sign
- * a request to the community `/api/dl` endpoint.
- *
- * The `/api/dl` hosts are signature-gated (not Cloudflare-gated), so this runs
- * natively — no WebView. Signing scheme `SPOTIFLAC-HMAC-V1` is ported exactly
- * from SpotiFLAC's client.
- */
-internal object SpotiflacGated {
-
- private const val TAG = "SpotiflacGated"
- const val APP_VERSION = "4.8.5"
- const val PLATFORM = "android"
- private const val SCHEME = "SPOTIFLAC-HMAC-V1"
- private const val WINDOW_SECONDS = 300
- private const val USER_AGENT = "SpotiFLAC-Mobile/$APP_VERSION"
-
- /** Whether a session exists — cheap, no network. */
- fun hasSession(context: Context): Boolean = getSpotiflacSession(context) != null
-
- /**
- * Signed `/api/dl` for a provider track id → the audio payload reference.
- * Returns a [GatedHit]: a direct FLAC url, or a DASH `<MPD>` manifest base64
- * (single-file FLAC is returned as `url`; hi-res as `dashManifestBase64`).
- */
- data class GatedHit(val url: String, val dashBase64: String, val quality: Int)
-
- fun flacUrl(context: Context, provider: String, providerId: String, quality: String): GatedHit? {
- val session = getSpotiflacSession(context) ?: return null
- val community = LosslessRegistry.communityDlUrl(provider) ?: return null
- return runCatching {
- val payload = JSONObject().put("id", providerId).put("quality", quality).toString()
- val bodyBytes = payload.toByteArray(Charsets.UTF_8)
- val path = URL(community).path
- val headers = signHeaders(session.sessionId, session.sessionSecret, "POST", path, bodyBytes)
- val body = post(community, bodyBytes, headers)
- val root = JSONObject(body)
- val data = root.optJSONObject("data") ?: root
- // Either a plain url, or base64 manifest (BTS json single-file, or DASH MPD).
- val direct = data.optString("url").takeIf { it.startsWith("http") }
- val manifestB64 = data.optString("manifest").takeIf { m -> m.isNotBlank() }
- ?: data.optString("resource").takeIf { m -> m.startsWith("MANIFEST:") }
- ?.substringAfter("MANIFEST:")?.trim()
- when {
- direct != null && direct.contains(".flac", true) -> GatedHit(direct, "", 16)
- direct != null -> GatedHit(direct, "", 0)
- manifestB64 != null -> {
- val decoded = String(Base64.decode(manifestB64, Base64.DEFAULT), Charsets.UTF_8)
- val manifest = runCatching { JSONObject(decoded) }.getOrNull()
- val urls = manifest?.optJSONArray("urls")
- // Multi-segment BTS manifest without playable single file → not usable here;
- // a DASH <MPD> text is usable through DashFlacRemux.
- when {
- urls == null && decoded.contains("<MPD") -> GatedHit("", manifestB64, 24)
- urls != null && urls.length() == 1 &&
- (manifest.optString("mimeType").contains("flac", true) ||
- urls.optString(0).contains(".flac", true)) ->
- GatedHit(urls.optString(0), "", 16)
- // A multi-segment JSON manifest is not a DASH <MPD>: the remux cannot read it.
- else -> return@runCatching null
- }
- }
- else -> return@runCatching null
- }
- }.onFailure { Log.d(TAG, "gated miss: ${it.message}") }.getOrNull()
- }
-
- // ── SPOTIFLAC-HMAC-V1 signing (exact port) ────────────────────────────────
- private fun signHeaders(
- sessionId: String,
- sessionSecret: String,
- method: String,
- path: String,
- body: ByteArray,
- ): Map<String, String> {
- val ts = iso8601Millis()
- val nonce = randomHex(12)
- val bodyHash = sha256Hex(body)
- val window = (System.currentTimeMillis() / 1000L) / WINDOW_SECONDS
- // rolling key = HMAC(session_secret, "{window}:{session_id}") → base64url no-pad
- val rk = hmacSha256(sessionSecret.toByteArray(Charsets.UTF_8), "$window:$sessionId".toByteArray(Charsets.UTF_8))
- val rkString = b64UrlNoPad(rk)
- val signingInput =
- "$SCHEME\n$method\n$path\n\n$bodyHash\n$ts\n$nonce\n$sessionId\n$APP_VERSION\n$PLATFORM"
- val sig = b64UrlNoPad(hmacSha256(rkString.toByteArray(Charsets.UTF_8), signingInput.toByteArray(Charsets.UTF_8)))
- return mapOf(
- "X-Sig-Session" to sessionId,
- "X-Sig-Timestamp" to ts,
- "X-Sig-Nonce" to nonce,
- "X-Sig-Body-Sha256" to bodyHash,
- "X-Sig-Signature" to sig,
- "X-Sig-App-Version" to APP_VERSION,
- "X-Sig-Platform" to PLATFORM,
- )
- }
-
- private fun post(urlString: String, body: ByteArray, headers: Map<String, String>): String {
- val conn = (URL(urlString).openConnection() as HttpURLConnection).apply {
- requestMethod = "POST"
- connectTimeout = 12_000
- readTimeout = 12_000
- doOutput = true
- setRequestProperty("User-Agent", USER_AGENT)
- setRequestProperty("Accept", "application/json")
- setRequestProperty("Content-Type", "application/json")
- headers.forEach { (k, v) -> setRequestProperty(k, v) }
- }
- return try {
- conn.outputStream.use { it.write(body) }
- val code = conn.responseCode
- val stream = if (code in 200..299) conn.inputStream else conn.errorStream
- val text = stream?.bufferedReader()?.use { it.readText() }.orEmpty()
- if (code !in 200..299) throw java.io.IOException("HTTP $code: ${text.take(160)}")
- text
- } finally {
- conn.disconnect()
- }
- }
-
- private fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray =
- Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data)
-
- private fun sha256Hex(data: ByteArray): String =
- MessageDigest.getInstance("SHA-256").digest(data)
- .joinToString("") { "%02x".format(it.toInt() and 0xFF) }
-
- private fun b64UrlNoPad(bytes: ByteArray): String =
- Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
-
- private fun iso8601Millis(): String =
- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
- .apply { timeZone = TimeZone.getTimeZone("UTC") }
- .format(java.util.Date(System.currentTimeMillis()))
-
- private fun randomHex(nBytes: Int): String {
- val b = ByteArray(nBytes)
- java.security.SecureRandom().nextBytes(b)
- return b.joinToString("") { "%02x".format(it) }
- }
-}
diff --git a/base/app/src/main/java/com/music/spotui/lossless/ZarzSession.kt b/base/app/src/main/java/com/music/spotui/lossless/ZarzSession.kt
new file mode 100644
index 00000000..e0df4b75
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/lossless/ZarzSession.kt
@@ -0,0 +1,177 @@
+package com.music.spotui.lossless
+
+/*
+ * The signed session SpotiFLAC Mobile's download extensions use (qobuz-web,
+ * tidal-web…), written from its protocol: the extension manifest's `signedSession`
+ * block and the app's signed_session runtime (bootstrap → hosted challenge →
+ * grant → exchange; ZARZ-HMAC-V1 signatures; download tickets).
+ */
+
+import android.content.Context
+import com.music.spotui.data.preferences.getSpotiflacSession
+import com.music.spotui.data.preferences.saveSpotiflacSession
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+import java.net.URLEncoder
+import java.security.MessageDigest
+import java.security.SecureRandom
+import java.text.SimpleDateFormat
+import java.util.Locale
+import java.util.TimeZone
+import javax.crypto.Mac
+import javax.crypto.spec.SecretKeySpec
+
+internal object ZarzSession {
+ const val BASE = "https://api.zarz.moe/v2"
+ const val PLATFORM = "extension"
+
+ /** The extension a session is issued to; the server checks it in every signature. */
+ enum class Ext(val appVersion: String) {
+ TIDAL("[email protected]"),
+ QOBUZ("[email protected]"),
+ }
+ const val CALLBACK = "spotiflac://session-grant"
+ private const val SCHEME = "ZARZ-HMAC-V1"
+ private const val PREFIX = "X-Zarz-"
+ private const val WINDOW_SECONDS = 300L
+
+ /** A challenge page to open (the user solves it), or null when a session came back directly. */
+ class Bootstrap(val challengeUrl: String?, val state: String)
+
+ /** The gateway wants the user to verify again (HTTP 428 / VERIFY_REQUIRED). */
+ class VerifyRequired : Exception("VERIFY_REQUIRED")
+
+ fun installId(context: Context): String =
+ com.music.spotui.data.preferences.spotiflacInstallId(context).takeIf { it.isNotBlank() } ?: randomHex(16)
+
+ /** GET /bootstrap: a session right away, or the challenge to solve. */
+ fun bootstrap(context: Context, ext: Ext, installId: String): Bootstrap {
+ val o = JSONObject(request("GET", "$BASE/bootstrap?app_version=${enc(ext.appVersion)}&install_id=${enc(installId)}", null, emptyMap()).second)
+ if (store(context, ext, installId, o)) return Bootstrap(null, "")
+ val state = randomHex(16)
+ val given = o.optString("auth_url").ifBlank { o.optString("challenge_url") }
+ val callback = "$CALLBACK?cb_version=v2grant&state=$state"
+ val url = when {
+ given.startsWith("https://") -> if ("state=" in given) given else "$given${if ('?' in given) '&' else '?'}state=$state"
+ o.optString("challenge_id").isNotBlank() -> "$BASE/challenge?id=${enc(o.optString("challenge_id"))}&cb=${enc(callback)}"
+ else -> throw java.io.IOException("bootstrap gave neither a session nor a challenge")
+ }
+ return Bootstrap(url, state)
+ }
+
+ /** POST /session/exchange with the grant the challenge page handed back. */
+ fun exchange(context: Context, ext: Ext, installId: String, grant: String) {
+ val body = JSONObject().put("grant", grant).put("install_id", installId)
+ .put("app_version", ext.appVersion).put("platform", PLATFORM).toString()
+ val (code, text) = request("POST", "$BASE/session/exchange", body, mapOf("Content-Type" to "application/json"))
+ if (code !in 200..299 || !store(context, ext, installId, JSONObject(text))) throw java.io.IOException("session exchange failed: HTTP $code")
+ }
+
+ /**
+ * A signed JSON call ([path] under [BASE], e.g. "/tickets"); returns the body.
+ * Refreshes a session that expires within the hour first.
+ */
+ fun signedJson(context: Context, ext: Ext, method: String, path: String, body: JSONObject?, extra: Map<String, String> = emptyMap()): JSONObject {
+ refreshIfDue(context, ext)
+ val (code, text) = signed(context, ext, method, path, body?.toString(), extra)
+ val o = runCatching { JSONObject(text) }.getOrDefault(JSONObject())
+ if (code == 428 || o.optString("code").equals("VERIFY_REQUIRED", true) || o.optBoolean("needsVerification")) throw VerifyRequired()
+ if (code == 401 && o.optString("code").equals("SESSION_INVALID", true)) {
+ com.music.spotui.data.preferences.clearSpotiflacSession(context, ext.appVersion)
+ throw VerifyRequired()
+ }
+ if (code !in 200..299) throw java.io.IOException("HTTP $code: ${(o.optString("error").ifBlank { text }).take(160)}")
+ return o
+ }
+
+ /** A download ticket for one resource ("qbz", "track", the track's URL). */
+ fun ticket(context: Context, ext: Ext, provider: String, type: String, id: String): String {
+ val hash = sha256Hex("$provider:$type:${id.lowercase()}".toByteArray())
+ val o = signedJson(context, ext, "POST", "/tickets", JSONObject()
+ .put("capability", "download_ticket").put("provider", provider).put("resource_hash", hash))
+ return o.optString("ticket_id").ifBlank { o.optString("ticket") }.trim().ifBlank { throw java.io.IOException("no ticket_id") }
+ }
+
+ private fun refreshIfDue(context: Context, ext: Ext) {
+ val s = getSpotiflacSession(context, ext.appVersion) ?: throw VerifyRequired()
+ val expires = parseIso(s.expiresAt) ?: return
+ val left = expires - System.currentTimeMillis()
+ if (left <= 0) throw VerifyRequired()
+ if (left > 3_600_000) return
+ runCatching {
+ val (code, text) = signed(context, ext, "POST", "/session/refresh", JSONObject().put("install_id", s.installId).toString(), emptyMap())
+ if (code in 200..299) store(context, ext, s.installId, JSONObject(text), keepMissing = true)
+ }
+ }
+
+ private fun signed(context: Context, ext: Ext, method: String, path: String, body: String?, extra: Map<String, String>): Pair<Int, String> {
+ val s = getSpotiflacSession(context, ext.appVersion) ?: throw VerifyRequired()
+ val url = BASE + path
+ val bytes = (body ?: "").toByteArray(Charsets.UTF_8)
+ val headers = signHeaders(s.sessionId, s.sessionSecret, ext.appVersion, method, URL(url).path, bytes, System.currentTimeMillis(), randomHex(12)) +
+ extra + (if (body != null) mapOf("Content-Type" to "application/json") else emptyMap())
+ return request(method, url, body, headers)
+ }
+
+ /** ZARZ-HMAC-V1: a key rolled every 5 minutes from the secret, then the request signed with it. */
+ internal fun signHeaders(sessionId: String, secret: String, appVersion: String, method: String, path: String, body: ByteArray, nowMs: Long, nonce: String): Map<String, String> {
+ val ts = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(java.util.Date(nowMs))
+ val hash = sha256Hex(body)
+ val window = (nowMs / 1000) / WINDOW_SECONDS
+ val rolling = hmac(secret.toByteArray(), "$window:$sessionId".toByteArray())
+ val signing = listOf(SCHEME, method, path, "", hash, ts, nonce, sessionId, appVersion, PLATFORM).joinToString("\n")
+ val signature = hmac(rolling.toByteArray(), signing.toByteArray())
+ return linkedMapOf(
+ "Session" to sessionId, "Timestamp" to ts, "Nonce" to nonce, "Body-SHA256" to hash,
+ "Signature" to signature, "App-Version" to appVersion, "Platform" to PLATFORM,
+ ).mapKeys { PREFIX + it.key }
+ }
+
+ private fun store(context: Context, ext: Ext, installId: String, o: JSONObject, keepMissing: Boolean = false): Boolean {
+ val id = o.optString("session_id"); val secret = o.optString("session_secret"); val exp = o.optString("expires_at")
+ if (id.isBlank() || secret.isBlank()) {
+ if (!keepMissing || exp.isBlank()) return false
+ val old = getSpotiflacSession(context, ext.appVersion) ?: return false
+ saveSpotiflacSession(context, old.sessionId, old.sessionSecret, installId, exp, ext.appVersion)
+ return true
+ }
+ saveSpotiflacSession(context, id, secret, installId, exp, ext.appVersion)
+ return true
+ }
+
+ private fun request(method: String, url: String, body: String?, headers: Map<String, String>): Pair<Int, String> {
+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {
+ requestMethod = method
+ connectTimeout = 15_000
+ readTimeout = 30_000
+ setRequestProperty("Accept", "application/json")
+ setRequestProperty("User-Agent", "SpotiFLAC-Mobile")
+ headers.forEach { (k, v) -> setRequestProperty(k, v) }
+ if (body != null) doOutput = true
+ }
+ try {
+ if (body != null) conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
+ val code = conn.responseCode
+ val text = (if (code in 200..299) conn.inputStream else conn.errorStream)?.bufferedReader()?.use { it.readText() }.orEmpty()
+ return code to text
+ } finally {
+ conn.disconnect()
+ }
+ }
+
+ internal fun parseIso(value: String): Long? = runCatching {
+ java.time.OffsetDateTime.parse(value.trim()).toInstant().toEpochMilli()
+ }.getOrNull()
+
+ private fun hmac(key: ByteArray, data: ByteArray): String = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
+ Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data),
+ )
+
+ internal fun sha256Hex(data: ByteArray): String =
+ MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
+
+ private fun randomHex(n: Int): String = ByteArray(n).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
+
+ private fun enc(s: String) = URLEncoder.encode(s, "UTF-8")
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt b/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt
new file mode 100644
index 00000000..74ea0424
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt
@@ -0,0 +1,73 @@
+package com.music.spotui.ui.components
+
+import android.content.Context
+import android.media.AudioDeviceCallback
+import android.media.AudioDeviceInfo
+import android.media.AudioManager
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.platform.LocalContext
+
+/** Where this phone's sound goes: its speaker, a Bluetooth device or wired headphones. */
+data class AudioRoute(val kind: Kind, val name: String) {
+ enum class Kind { SPEAKER, BLUETOOTH, WIRED }
+
+ companion object {
+ /** The output media plays on now. Product names need no Bluetooth permission. */
+ fun current(context: Context): AudioRoute = runCatching {
+ val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ val outs = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
+ outs.firstOrNull { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP || it.type == AudioDeviceInfo.TYPE_BLE_HEADSET || it.type == AudioDeviceInfo.TYPE_BLE_SPEAKER }
+ ?.let { return@runCatching AudioRoute(Kind.BLUETOOTH, it.productName?.toString().orEmpty()) }
+ outs.firstOrNull { it.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || it.type == AudioDeviceInfo.TYPE_USB_HEADSET }
+ ?.let { return@runCatching AudioRoute(Kind.WIRED, it.productName?.toString().orEmpty()) }
+ AudioRoute(Kind.SPEAKER, "")
+ }.getOrDefault(AudioRoute(Kind.SPEAKER, ""))
+
+ /**
+ * The system's own output picker (speaker, headphones, Bluetooth), as the
+ * official app opens it; Bluetooth settings where the picker does not exist.
+ */
+ fun pickOutput(context: Context) {
+ val shown = runCatching {
+ if (android.os.Build.VERSION.SDK_INT >= 34)
+ android.media.MediaRouter2.getInstance(context).showSystemOutputSwitcher()
+ else {
+ context.sendBroadcast(android.content.Intent("com.android.systemui.action.LAUNCH_MEDIA_OUTPUT_DIALOG")
+ .setPackage("com.android.systemui")
+ .putExtra("com.android.systemui.extra.package_name", context.packageName))
+ true
+ }
+ }.getOrDefault(false)
+ if (!shown) openBluetooth(context)
+ }
+
+ fun openBluetooth(context: Context) {
+ runCatching {
+ context.startActivity(android.content.Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS)
+ .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+ }
+ }
+}
+
+/** [AudioRoute.current], kept up to date as headphones come and go. */
+@Composable
+fun rememberAudioRoute(): AudioRoute {
+ val context = LocalContext.current
+ var route by remember { mutableStateOf(AudioRoute.current(context)) }
+ DisposableEffect(Unit) {
+ val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ val cb = object : AudioDeviceCallback() {
+ override fun onAudioDevicesAdded(added: Array<out AudioDeviceInfo>?) { route = AudioRoute.current(context) }
+ override fun onAudioDevicesRemoved(removed: Array<out AudioDeviceInfo>?) { route = AudioRoute.current(context) }
+ }
+ am.registerAudioDeviceCallback(cb, null)
+ onDispose { am.unregisterAudioDeviceCallback(cb) }
+ }
+ return route
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index 4fed75f0..4b358962 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -33,6 +33,8 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Headphones
+import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.Computer
import androidx.compose.material.icons.filled.Equalizer
import androidx.compose.material.icons.filled.Pause
@@ -81,9 +83,20 @@ import com.music.spotui.ui.screens.ExplicitBadge
private val Green: Color get() = com.music.spotui.ui.theme.AppAccent
private val SheetColor = Color(0xFF282828)
-/** Name of the device playing now ("This phone" when it's this phone). */
+/**
+ * Name of the output playing now: the Connect device, else the headphones this phone
+ * plays into (their Bluetooth name), else "This phone".
+ */
@Composable
-fun activeDeviceLabel(): String = SongPlayer.activeDevice.value?.name ?: stringResource(R.string.connect_phone_is_self)
+fun activeDeviceLabel(): String {
+ SongPlayer.activeDevice.value?.let { return it.name }
+ val route = rememberAudioRoute()
+ return when (route.kind) {
+ AudioRoute.Kind.SPEAKER -> stringResource(R.string.connect_phone_is_self)
+ AudioRoute.Kind.BLUETOOTH -> route.name.ifBlank { stringResource(R.string.label_bluetooth) }
+ AudioRoute.Kind.WIRED -> stringResource(R.string.headphones)
+ }
+}
private fun deviceIcon(type: String): ImageVector = when (type.uppercase()) {
"SMARTPHONE", "TABLET" -> Icons.Default.Smartphone
@@ -92,65 +105,167 @@ private fun deviceIcon(type: String): ImageVector = when (type.uppercase()) {
else -> Icons.Default.Computer
}
-// ── Spotify Connect device picker ──
+// ── Connect: where the music plays ──
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DevicesSheet(onDismiss: () -> Unit) {
+ val context = androidx.compose.ui.platform.LocalContext.current
var devices by remember { mutableStateOf<List<SongPlayer.ConnectDevice>?>(null) }
+ var quality by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { devices = SongPlayer.devices() }
+ val remote = SongPlayer.activeDevice.value
+ val route = rememberAudioRoute()
+ val headphones = remote == null && route.kind != AudioRoute.Kind.SPEAKER
+ if (quality) QualitySheet(onDismiss = { quality = false })
ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {
Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {
Text(
stringResource(R.string.listen_on),
- color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold,
+ color = Color.White, fontSize = 22.sp, fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
)
+ // The output playing now, the song, and its quality (tap: what plays, and change it).
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp)
+ .clip(RoundedCornerShape(16.dp)).background(Color(0xFF333333)).padding(16.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(activeDeviceLabel(), color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold,
+ maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
+ if (remote == null) Text(
+ stringResource(streamingLabel(com.music.spotui.data.preferences.getStreamingQuality(context))),
+ color = Color(0xFFDDDDDD), fontSize = 12.sp, fontWeight = FontWeight.Medium,
+ modifier = Modifier.padding(start = 8.dp).clip(RoundedCornerShape(6.dp)).background(Color(0xFF4A4A4A))
+ .clickable { quality = true }.padding(horizontal = 6.dp, vertical = 2.dp),
+ )
+ }
+ val title = Graph.currentSongState.title.value
+ if (title.isNotBlank()) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) {
+ Icon(Icons.Default.Equalizer, null, tint = Green, modifier = Modifier.size(16.dp))
+ Text("$title — ${Graph.currentSongState.singer.value}", color = Green, fontSize = 14.sp, maxLines = 1,
+ overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 6.dp))
+ }
+ }
+ Icon(
+ when {
+ remote != null -> deviceIcon(remote.type)
+ headphones -> Icons.Default.Headphones
+ else -> Icons.Default.Smartphone
+ },
+ contentDescription = null, tint = Green, modifier = Modifier.padding(start = 12.dp).size(40.dp),
+ )
+ }
+ Spacer(Modifier.height(4.dp))
val list = devices
+ val self = list?.firstOrNull { it.isSelf }
+ // This phone's speaker: from headphones (the system's output picker), or back from a Connect device.
+ if (remote != null || headphones) DeviceRow(Icons.Default.Smartphone, stringResource(R.string.connect_phone_is_self), null) {
+ if (remote != null) self?.let { SongPlayer.transferTo(it) } else AudioRoute.pickOutput(context)
+ onDismiss()
+ }
+ // The headphones this phone plays into, while a Connect device has the music.
+ if (remote != null && route.kind != AudioRoute.Kind.SPEAKER || headphones) DeviceRow(
+ Icons.Default.Headphones,
+ if (route.kind == AudioRoute.Kind.BLUETOOTH) route.name.ifBlank { stringResource(R.string.label_bluetooth) } else stringResource(R.string.headphones),
+ if (route.kind == AudioRoute.Kind.BLUETOOTH) stringResource(R.string.label_bluetooth) else null,
+ current = headphones,
+ ) {
+ if (remote != null) self?.let { SongPlayer.transferTo(it) } else AudioRoute.pickOutput(context)
+ onDismiss()
+ }
if (list == null) {
Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) {
CircularProgressIndicator(color = Green, modifier = Modifier.size(28.dp))
}
- } else if (list.isEmpty()) {
- Text(stringResource(R.string.no_devices), color = Color.White.copy(alpha = 0.7f), modifier = Modifier.padding(20.dp))
} else {
- val anyActive = list.any { it.isActive }
- list.forEach { d ->
- // This phone counts as current when nothing else is playing.
- val current = d.isActive || (d.isSelf && !anyActive)
- Row(
- verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier
- .fillMaxWidth()
- .clickable {
- if (!current) SongPlayer.transferTo(d)
- onDismiss()
- }
- .padding(horizontal = 20.dp, vertical = 14.dp),
- ) {
- Icon(
- if (d.isSelf) Icons.Default.Smartphone else deviceIcon(d.type),
- contentDescription = null,
- tint = if (current) Green else Color.White,
- modifier = Modifier.size(28.dp),
- )
- Spacer(Modifier.width(16.dp))
- Column {
- Text(
- if (d.isSelf) stringResource(R.string.connect_phone_is_self) else d.name,
- color = if (current) Green else Color.White,
- fontSize = 16.sp, fontWeight = FontWeight.Medium,
- )
- if (current) Text(stringResource(R.string.default_notification_channel_name), color = Green.copy(alpha = 0.8f), fontSize = 12.sp)
- }
- }
+ list.filter { !it.isSelf && !it.isActive }.forEach { d ->
+ DeviceRow(deviceIcon(d.type), d.name, null) { SongPlayer.transferTo(d); onDismiss() }
}
+ if (list.none { !it.isSelf } && !headphones && remote == null)
+ Text(stringResource(R.string.no_devices), color = Color.White.copy(alpha = 0.7f), modifier = Modifier.padding(20.dp))
}
JamSection(onDismiss)
+ // Bluetooth: pair or pick headphones and speakers in the system settings.
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp)
+ .clip(RoundedCornerShape(12.dp)).background(Color(0xFF333333))
+ .clickable { AudioRoute.openBluetooth(context) }.padding(14.dp),
+ ) {
+ Icon(Icons.Default.Bluetooth, null, tint = Green, modifier = Modifier.size(26.dp))
+ Text(stringResource(R.string.label_bluetooth), color = Green, fontSize = 14.sp, modifier = Modifier.padding(top = 4.dp))
+ }
}
}
}
+@Composable
+private fun DeviceRow(icon: ImageVector, name: String, detail: String?, current: Boolean = false, onClick: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 20.dp, vertical = 14.dp),
+ ) {
+ Icon(icon, contentDescription = null, tint = if (current) Green else Color.White, modifier = Modifier.size(28.dp))
+ Spacer(Modifier.width(16.dp))
+ Column {
+ Text(name, color = if (current) Green else Color.White, fontSize = 16.sp, fontWeight = FontWeight.Medium)
+ if (detail != null) Text(detail, color = Color(0xFFB3B3B3), fontSize = 13.sp)
+ }
+ }
+}
+
+private fun streamingLabel(q: com.music.spotui.data.preferences.StreamingQuality): Int = when (q) {
+ com.music.spotui.data.preferences.StreamingQuality.AUTO -> R.string.quality_streaming_auto
+ com.music.spotui.data.preferences.StreamingQuality.LOW -> R.string.quality_streaming_low
+ com.music.spotui.data.preferences.StreamingQuality.NORMAL -> R.string.quality_streaming_normal
+ com.music.spotui.data.preferences.StreamingQuality.HIGH -> R.string.quality_streaming_high
+}
+
+/** The sound quality page: what plays now (codec and bitrate, or the downloaded file), and the setting. */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+private fun QualitySheet(onDismiss: () -> Unit) {
+ val local = com.music.spotui.di.LocalPlayer.active.value
+ val now by androidx.compose.runtime.produceState<String?>(null) {
+ value = if (local) {
+ val t = com.music.spotui.di.LocalPlayer.current()
+ val file = t?.let { com.music.spotui.data.offline.OfflineStore.byLocalId(it.id) }
+ file?.let { "${it.file.substringAfterLast('.').uppercase()} · ${it.source}" } ?: ""
+ } else {
+ val (bitrate, mime) = app.myspoti.host.android.MyspotiRuntime.spotify.player.audioInfo()
+ if (bitrate <= 0) "" else "${codecName(mime)} · ${bitrate / 1000} kbit/s"
+ }
+ }
+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {
+ Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {
+ Text(stringResource(R.string.quality_sheet_title), color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
+ val text = now
+ Text(
+ when {
+ text == null -> "…"
+ text.isBlank() -> stringResource(R.string.quality_now_unknown)
+ else -> stringResource(R.string.quality_now, text)
+ },
+ color = Green, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp),
+ )
+ if (!local) StreamingQualityPicker(Modifier.padding(top = 12.dp))
+ }
+ }
+}
+
+private fun codecName(mime: String): String = when {
+ "mp4a" in mime -> "AAC"
+ "flac" in mime -> "FLAC"
+ "opus" in mime -> "Opus"
+ "vorbis" in mime -> "Ogg Vorbis"
+ "mpeg" in mime -> "MP3"
+ else -> mime.substringBefore(';').substringAfter('/').uppercase()
+}
+
/** Spotify Jam: listen together. Free accounts can join (Spotify keeps starting one to Premium). */
@Composable
private fun JamSection(onDismiss: () -> Unit) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
index 5254d639..23dc9f88 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
@@ -65,6 +65,7 @@ fun DownloadQualityPicker(modifier: Modifier = Modifier) {
Option(DownloadQuality.SMALL, R.string.quality_download_small, R.string.quality_download_small_detail),
Option(DownloadQuality.CD, R.string.quality_download_cd, R.string.quality_download_cd_detail),
Option(DownloadQuality.HI_RES, R.string.quality_download_hires, R.string.quality_download_hires_detail),
+ Option(DownloadQuality.ASK, R.string.quality_download_ask, R.string.quality_download_ask_detail),
),
selected = current,
onSelect = { current = it; setDownloadQuality(ctx, it) },
@@ -102,3 +103,55 @@ private fun <T> QualityGroup(
}
}
}
+
+/**
+ * "Ask each time": a download asks its quality first, once for a whole list. The
+ * question is drawn by [DownloadAskHost], at the root, so it outlives the menu that
+ * started the download.
+ */
+object DownloadAsk {
+ internal var pending by mutableStateOf<((DownloadQuality) -> Unit)?>(null)
+
+ /** Runs [start] now with the Settings quality (null), or after the user picked one. */
+ fun start(context: android.content.Context, start: (DownloadQuality?) -> Unit) {
+ if (getDownloadQuality(context) == DownloadQuality.ASK) pending = { start(it) } else start(null)
+ }
+}
+
+@Composable
+fun DownloadAskHost() {
+ val action = DownloadAsk.pending ?: return
+ val choices = listOf(
+ Option(DownloadQuality.SMALL, R.string.quality_download_small, R.string.quality_download_small_detail),
+ Option(DownloadQuality.CD, R.string.quality_download_cd, R.string.quality_download_cd_detail),
+ Option(DownloadQuality.HI_RES, R.string.quality_download_hires, R.string.quality_download_hires_detail),
+ )
+ androidx.compose.material3.AlertDialog(
+ onDismissRequest = { DownloadAsk.pending = null },
+ containerColor = Color(0xFF282828),
+ title = { Text(stringResource(R.string.quality_download_title), color = Color.White) },
+ text = {
+ Column {
+ for (o in choices) {
+ Column(
+ Modifier.fillMaxWidth().heightIn(min = 52.dp)
+ .selectable(selected = false, role = Role.Button, onClick = {
+ DownloadAsk.pending = null
+ action(o.value)
+ })
+ .padding(vertical = 8.dp),
+ ) {
+ Text(stringResource(o.label), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(o.detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ }
+ }
+ },
+ confirmButton = {},
+ dismissButton = {
+ androidx.compose.material3.TextButton(onClick = { DownloadAsk.pending = null }) {
+ Text(stringResource(R.string.add_to_playlist_button_cancel), color = Color.White)
+ }
+ },
+ )
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
index 09522434..9040e727 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
@@ -186,9 +186,11 @@ fun SongOptionsSheet(
onDismiss()
}
else -> MenuRow(Icons.Outlined.ArrowCircleDown, stringResource(R.string.context_menu_download), enabled = hasId) {
- com.music.spotui.data.offline.OfflineCollections.downloadSong(song)
- com.music.spotui.di.Haptics.confirm()
- toast(context.getString(R.string.download_notification_downloading))
+ com.music.spotui.ui.components.DownloadAsk.start(context) { q ->
+ com.music.spotui.data.offline.OfflineCollections.downloadSong(song, q)
+ com.music.spotui.di.Haptics.confirm()
+ toast(context.getString(R.string.download_notification_downloading))
+ }
onDismiss()
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt
index f15c95ca..dbb9fa04 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt
@@ -76,14 +76,10 @@ fun MainBottomNavigation(navController: NavHostController, bottomBarState: Mutab
contentAlignment = Alignment.BottomCenter,
modifier = Modifier
.fillMaxWidth()
- .background(
- Brush.verticalGradient(
- colors = listOf(
- Color.Transparent,
- Color.Black
- ),
- startY = 0f
- )
+ // Settings, Display: a solid black bar, or the fade that lets the list show through.
+ .then(
+ if (com.music.spotui.data.preferences.SolidNavBar.on) Modifier.background(Color.Black)
+ else Modifier.background(Brush.verticalGradient(colors = listOf(Color.Transparent, Color.Black), startY = 0f))
)
) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index fe2076bb..afe9d449 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -77,6 +77,8 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.withContext
import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.filled.AutoAwesome
@@ -167,6 +169,20 @@ class ContextViewModel(
"liked" -> api.getLikedPage()
else -> api.getPlaylistPage(id)
}
+ // Liked Songs: a like or unlike anywhere puts the list right at once.
+ if (type == "liked") viewModelScope.launch(Dispatchers.IO) {
+ SongPlayer.likedChanges.drop(1).collectLatest {
+ kotlinx.coroutines.delay(1_500) // Spotify's library takes the change first
+ val songs = api.mergeLikedHead() ?: return@collectLatest
+ val current = (_page.value as? Response.Success)?.data ?: return@collectLatest
+ val updated = Response.Success(current.copy(
+ tracks = songs,
+ metaLine = Graph.app.resources.getQuantityString(R.plurals.liked_songs_header_metadata_text, songs.size, songs.size),
+ ))
+ _page.value = updated
+ recent[key!!] = updated
+ }
+ }
flow.collect { r ->
if (r is Response.Loading && _page.value is Response.Success) return@collect
_page.value = r
@@ -435,9 +451,11 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
com.music.spotui.ui.components.DownloadListButton(downloadedCount, ids.size, busy, kept = listKept) {
if (listKept) askRemoveDownloads = true
else {
- com.music.spotui.di.Haptics.confirm()
- com.music.spotui.data.offline.OfflineCollections.download(p)
- android.widget.Toast.makeText(context, context.getString(R.string.download_notification_downloading), android.widget.Toast.LENGTH_SHORT).show()
+ com.music.spotui.ui.components.DownloadAsk.start(context) { q ->
+ com.music.spotui.di.Haptics.confirm()
+ com.music.spotui.data.offline.OfflineCollections.download(p, q)
+ android.widget.Toast.makeText(context, context.getString(R.string.download_notification_downloading), android.widget.Toast.LENGTH_SHORT).show()
+ }
}
}
Spacer(Modifier.weight(1f))
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index 214afd9b..96efcc4a 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
@@ -962,29 +962,6 @@ fun PlayerFull(
}
}
-/** The current audio output route name for the Connect indicator (BT name if
- * connected, else Headphones / This device). Uses AudioDeviceInfo.productName
- * which needs no Bluetooth permission. */
-private fun currentAudioRoute(context: Context): String {
- return try {
- val am = context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager
- val outs = am.getDevices(android.media.AudioManager.GET_DEVICES_OUTPUTS)
- val bt = outs.firstOrNull {
- it.type == android.media.AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ||
- it.type == android.media.AudioDeviceInfo.TYPE_BLUETOOTH_SCO
- }
- if (bt != null) return bt.productName?.toString()?.takeIf { it.isNotBlank() } ?: context.getString(R.string.label_bluetooth)
- val wired = outs.firstOrNull {
- it.type == android.media.AudioDeviceInfo.TYPE_WIRED_HEADPHONES ||
- it.type == android.media.AudioDeviceInfo.TYPE_WIRED_HEADSET ||
- it.type == android.media.AudioDeviceInfo.TYPE_USB_HEADSET
- }
- if (wired != null) context.getString(R.string.headphones) else context.getString(R.string.connect_phone_is_self)
- } catch (e: Exception) {
- context.getString(R.string.connect_phone_is_self)
- }
-}
-
@Composable
fun PlayerConnectRow(
context: Context,
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
index 3d110aa3..22d45507 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -123,6 +123,12 @@ fun SettingsScreen(navController: NavController) {
enabled = !energy.policy.saverEnabled,
onChecked = app.myspoti.power.EnergySettings::setCanvasEnabled,
)
+ OptionRow(
+ label = stringResource(R.string.settings_solid_nav_title),
+ detail = stringResource(R.string.settings_solid_nav_detail),
+ checked = com.music.spotui.data.preferences.SolidNavBar.on,
+ onChecked = { com.music.spotui.data.preferences.SolidNavBar.set(ctx, it) },
+ )
LanguageRow()
Divider()
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
index 3bfc9f60..082eeeb0 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
@@ -45,19 +45,14 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import app.myspoti.engine.R
-import com.music.spotui.lossless.LosslessRegistry
import com.music.spotui.ui.theme.AppBackground
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
-import org.json.JSONObject
-import java.net.HttpURLConnection
-import java.net.URL
-import java.net.URLEncoder
/**
- * SpotiFLAC verification, the way the official client does it: bootstrap → the
+ * SpotiFLAC verification, the way SpotiFLAC Mobile's extensions do it: bootstrap → the
* service's own hosted challenge page (the user solves the Turnstile themselves)
* → redirect with a grant → exchange the grant for a signing session.
*
@@ -72,7 +67,11 @@ fun SpotiflacScreen(onClose: () -> Unit) {
val scope = rememberCoroutineScope()
var webView by remember { mutableStateOf<WebView?>(null) }
var attempt by remember { mutableStateOf(0) }
- var verified by remember { mutableStateOf(com.music.spotui.data.preferences.hasSpotiflacSession(context)) }
+ // One session per download server (Tidal, then Qobuz); verified once none is missing.
+ fun missing() = com.music.spotui.lossless.ZarzSession.Ext.entries
+ .firstOrNull { com.music.spotui.data.preferences.getSpotiflacSession(context, it.appVersion) == null }
+ var ext by remember { mutableStateOf(missing()) }
+ var verified by remember { mutableStateOf(ext == null) }
var message by remember { mutableStateOf("") }
var done by remember { mutableStateOf(false) }
val leave: () -> Unit = onClose
@@ -80,53 +79,51 @@ fun SpotiflacScreen(onClose: () -> Unit) {
fun res(id: Int): String = context.getString(id)
// Reused so a retry keeps the same install; the service binds the session to it.
- val installId = remember {
- com.music.spotui.data.preferences.getSpotiflacSession(context)?.installId?.takeIf { it.isNotBlank() }
- ?: java.security.SecureRandom().let { r -> (1..16).joinToString("") { "%02x".format(r.nextInt(256)) } }
- }
- val state = remember(attempt) {
- java.security.SecureRandom().let { r -> (1..16).joinToString("") { "%02x".format(r.nextInt(256)) } }
- }
+ val installId = remember { com.music.spotui.lossless.ZarzSession.installId(context) }
+ // The state the challenge page must send back with its grant.
+ var state by remember { mutableStateOf("") }
fun finish(grant: String) = scope.launch {
message = res(R.string.spotiflac_session_creating)
+ val current = ext ?: return@launch
val ok = withContext(Dispatchers.IO) {
- runCatching {
- val body = JSONObject()
- .put("grant", grant).put("install_id", installId)
- .put("app_version", APP_VERSION).put("platform", PLATFORM)
- val o = JSONObject(post("${LosslessRegistry.communityVerifyUrl()}/session/exchange", body.toString()))
- val id = o.optString("session_id")
- val secret = o.optString("session_secret")
- require(id.isNotBlank() && secret.isNotBlank())
- com.music.spotui.data.preferences.saveSpotiflacSession(context, id, secret, installId, o.optString("expires_at"))
- }.isSuccess
+ runCatching { com.music.spotui.lossless.ZarzSession.exchange(context, current, installId, grant) }
+ .onFailure { android.util.Log.w("Spotiflac", "exchange: ${it.message}") }.isSuccess
}
if (ok) {
- verified = true
- done = true
- android.widget.Toast.makeText(context, R.string.spotiflac_session_ok, android.widget.Toast.LENGTH_LONG).show()
+ // The next server, if one is still missing (often given at once to a verified install).
+ ext = missing()
+ if (ext == null) {
+ verified = true
+ done = true
+ android.widget.Toast.makeText(context, R.string.spotiflac_session_ok, android.widget.Toast.LENGTH_LONG).show()
+ }
} else {
message = res(R.string.spotiflac_session_failed)
}
}
- LaunchedEffect(attempt) {
- if (verified) return@LaunchedEffect
+ LaunchedEffect(attempt, ext) {
+ val current = ext
+ if (verified || current == null) return@LaunchedEffect
message = ""
- val challenge = withContext(Dispatchers.IO) {
- runCatching {
- val base = LosslessRegistry.communityVerifyUrl()
- val url = "$base/bootstrap?install_id=$installId&app_version=$APP_VERSION&platform=$PLATFORM"
- JSONObject(get(url)).optString("challenge_url").takeIf { it.startsWith("https://") }
- }.getOrNull()
+ val boot = withContext(Dispatchers.IO) {
+ runCatching { com.music.spotui.lossless.ZarzSession.bootstrap(context, current, installId) }
+ .onFailure { android.util.Log.w("Spotiflac", "bootstrap: ${it.message}") }.getOrNull()
}
- if (challenge == null) {
+ if (boot == null) {
message = res(R.string.spotiflac_verify_start_failed)
return@LaunchedEffect
}
+ if (boot.challengeUrl == null) {
+ // The servers gave a session straight away: nothing to solve for this one.
+ ext = missing()
+ if (ext == null) { verified = true; done = true }
+ return@LaunchedEffect
+ }
message = ""
- webView?.loadUrl("$challenge&cb=" + URLEncoder.encode("$CALLBACK?state=$state", "UTF-8"))
+ state = boot.state
+ webView?.loadUrl(boot.challengeUrl)
// Never leave the user on a page that silently stalled.
delay(180_000)
if (!done && !verified) message = res(R.string.spotiflac_verify_timeout)
@@ -211,14 +208,17 @@ private fun SpotiflacStatusScreen(onClose: () -> Unit) {
) {
Text(stringResource(R.string.spotiflac_status_title), color = Color.White, fontSize = 22.sp, fontWeight = FontWeight.Bold)
Text(stringResource(R.string.spotiflac_status_verified), color = Color(0xFFB3B3B3), fontSize = 14.sp)
- val session = com.music.spotui.data.preferences.getSpotiflacSession(context)
- Text(
- stringResource(R.string.spotiflac_session_expires, session?.expiresAt.orEmpty().take(19)),
- color = Color(0xFF00C7B7), fontSize = 13.sp,
- )
+ for (e in com.music.spotui.lossless.ZarzSession.Ext.entries) {
+ val session = com.music.spotui.data.preferences.getSpotiflacSession(context, e.appVersion) ?: continue
+ Text(
+ e.name.lowercase().replaceFirstChar { it.uppercase() } + " — " +
+ stringResource(R.string.spotiflac_session_expires, session.expiresAt.take(19).replace('T', ' ')),
+ color = Color(0xFF00C7B7), fontSize = 13.sp,
+ )
+ }
Button(
onClick = {
- com.music.spotui.data.preferences.clearSpotiflacSession(context)
+ com.music.spotui.data.preferences.clearSpotiflacSessions(context)
onClose()
},
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1E1E1E), contentColor = Color.White),
@@ -232,36 +232,4 @@ private fun SpotiflacStatusScreen(onClose: () -> Unit) {
}
}
-// Screen constants; APP_VERSION must stay in step with SpotiflacGated (same signing).
-private const val CALLBACK = "spotiflac://session-grant"
-private const val APP_VERSION = "4.8.5"
-private const val PLATFORM = "android"
-
-// ── HTTP helpers (same shape as Spotui's) ────────────────────────────────────
-
-private fun get(url: String): String = request(url, null)
-
-private fun post(url: String, json: String): String = request(url, json)
-
-private fun request(url: String, json: String?): String {
- val conn = (URL(url).openConnection() as HttpURLConnection).apply {
- connectTimeout = 20_000
- readTimeout = 20_000
- setRequestProperty("Accept", "application/json")
- if (json != null) {
- requestMethod = "POST"
- doOutput = true
- setRequestProperty("Content-Type", "application/json")
- }
- }
- try {
- if (json != null) conn.outputStream.use { it.write(json.toByteArray()) }
- val code = conn.responseCode
- val text = (if (code in 200..299) conn.inputStream else conn.errorStream)
- ?.bufferedReader()?.use { it.readText() }.orEmpty()
- if (code !in 200..299) throw java.io.IOException("HTTP $code")
- return text
- } finally {
- conn.disconnect()
- }
-}
+private const val CALLBACK = com.music.spotui.lossless.ZarzSession.CALLBACK
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 59a60fd7..43c7c0da 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -241,4 +241,11 @@
<string name="downloads_verify_hint">Aucune source sans perte n\'a répondu. Faites une fois la vérification SpotiFLAC dans Réglages, Téléchargements : ses serveurs sont les plus fiables.</string>
<string name="quality_download_small">La plus légère</string>
<string name="quality_download_small_detail">AAC 96 kbit/s, le minimum : environ 3 Mo par titre</string>
+ <string name="settings_solid_nav_title">Barre du bas opaque</string>
+ <string name="settings_solid_nav_detail">Noire derrière les onglets, au lieu d\'un fondu sur la liste</string>
+ <string name="quality_download_ask">Demander à chaque fois</string>
+ <string name="quality_download_ask_detail">Choisir au lancement d\'un téléchargement, une seule fois pour toute une playlist</string>
+ <string name="quality_sheet_title">Qualité du son</string>
+ <string name="quality_now">En cours : %1$s</string>
+ <string name="quality_now_unknown">Pas encore connue : lancez un titre</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index 4f841c85..1a1af856 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -241,4 +241,11 @@
<string name="downloads_verify_hint">Nessuna fonte senza perdita ha risposto. Verifica SpotiFLAC una volta in Impostazioni, Download: i suoi server sono i più affidabili.</string>
<string name="quality_download_small">La più leggera</string>
<string name="quality_download_small_detail">AAC 96 kbit/s, la minima: circa 3 MB per brano</string>
+ <string name="settings_solid_nav_title">Barra in basso opaca</string>
+ <string name="settings_solid_nav_detail">Nera dietro le schede, invece di una sfumatura sull\'elenco</string>
+ <string name="quality_download_ask">Chiedi ogni volta</string>
+ <string name="quality_download_ask_detail">Scegli all\'avvio di un download, una sola volta per tutta la playlist</string>
+ <string name="quality_sheet_title">Qualità audio</string>
+ <string name="quality_now">In riproduzione: %1$s</string>
+ <string name="quality_now_unknown">Non ancora nota: avvia un brano</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 79a376d8..9c472c7e 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -241,4 +241,11 @@
<string name="downloads_verify_hint">No lossless source answered. Verify SpotiFLAC once in Settings, Downloads: its servers are the reliable ones.</string>
<string name="quality_download_small">Smallest</string>
<string name="quality_download_small_detail">AAC 96 kbit/s, the lightest: about 3 MB a song</string>
+ <string name="settings_solid_nav_title">Solid bottom bar</string>
+ <string name="settings_solid_nav_detail">Black behind the tabs, instead of a fade over the list</string>
+ <string name="quality_download_ask">Ask each time</string>
+ <string name="quality_download_ask_detail">Choose when a download starts, once for a whole playlist</string>
+ <string name="quality_sheet_title">Sound quality</string>
+ <string name="quality_now">Playing now: %1$s</string>
+ <string name="quality_now_unknown">Not known yet: start a song</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.kt b/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.kt
new file mode 100644
index 00000000..bbf65b78
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/api/LikedMergeTest.kt
@@ -0,0 +1,29 @@
+package com.music.spotui.data.api
+
+import com.music.spotui.data.entity.SongsModel
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** A like or unlike puts Liked Songs right from its first page only. */
+class LikedMergeTest {
+ private fun song(id: String) = SongsModel(id = id.hashCode(), title = id, singer = "", album = "", coverUri = "", url = "spotify:track:$id").copy(spotifyTrackId = id)
+ private fun ids(list: List<SongsModel>) = list.map { it.spotifyTrackId }
+
+ @Test fun aNewLikeGoesOnTop() {
+ val known = listOf("b", "c").map(::song)
+ assertEquals(listOf("a", "b", "c"), ids(Api.LikedCache.merge(listOf("a", "b", "c").map(::song), known)))
+ }
+
+ @Test fun anUnlikedSongLeavesTheList() {
+ val known = listOf("a", "b", "c").map(::song)
+ assertEquals(listOf("a", "c"), ids(Api.LikedCache.merge(listOf("a", "c").map(::song), known)))
+ }
+
+ @Test fun olderSongsAfterAFullFirstPageStay() {
+ val head = (1..50).map { song("n$it") }
+ val known = (2..50).map { song("n$it") } + listOf(song("old1"), song("old2"))
+ val merged = Api.LikedCache.merge(head, known)
+ assertEquals(52, merged.size)
+ assertEquals(listOf("old1", "old2"), ids(merged).takeLast(2))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/lossless/ZarzSignatureTest.kt b/base/app/src/test/java/com/music/spotui/lossless/ZarzSignatureTest.kt
new file mode 100644
index 00000000..9659b820
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/lossless/ZarzSignatureTest.kt
@@ -0,0 +1,20 @@
+package com.music.spotui.lossless
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** ZARZ-HMAC-V1, checked against an independent implementation of the same protocol. */
+class ZarzSignatureTest {
+ @Test fun signsLikeTheExtensionRuntime() {
+ val h = ZarzSession.signHeaders(
+ sessionId = "sess_123", secret = "s3cr3t", appVersion = "[email protected]",
+ method = "POST", path = "/v2/dl/tid", body = """{"id":"1"}""".toByteArray(),
+ nowMs = 1_760_000_000_123, nonce = "abcdef012345",
+ )
+ assertEquals("2025-10-09T08:53:20.123Z", h["X-Zarz-Timestamp"])
+ assertEquals("5811967f540d300d249ab30ae681359a7815fdb5d3dc71a94be1d491006a6b27", h["X-Zarz-Body-SHA256"])
+ assertEquals("8EVagVFjx3zbtgAmLx-ZDgxj579Dc4nuoYlfYaOlJNw", h["X-Zarz-Signature"])
+ assertEquals("[email protected]", h["X-Zarz-App-Version"])
+ assertEquals("extension", h["X-Zarz-Platform"])
+ }
+}