Skip to content

Native Android client for Spotify, built with Jetpack Compose

FLAC downloads, Wrapped sync, sound quality and Settings

kota-zo6c7beaab1625
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebdea22e..02e82e01 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +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.
+- **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.
+- **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.
+- **Stuck ads**: an ad that blocks the player is skipped twice, then the player reloads, so the music does not stop for good.
+- **Offline listens count**: a downloaded song that plays on the phone is reported to Spotify like a streamed listen — the real play time, the context it started from — so it counts in Wrapped and the top lists. Offline listens are kept and reported once the network is back.
+
- **New engine**: the app now talks to Spotify through its own API (`:api`), tested against the real Web Player on every change. Screens load faster: catalog, search, playlists and library come straight from Spotify's servers, in parallel, without waiting for the hidden player.
- **Playback works again on every phone**: Spotify silently ignored play commands sent by an Android WebView. They now leave from the app itself, so songs start and the sound plays.
- **Faster start**: the home feed, your library and Liked Songs show at once after a restart, from the last visit, then refresh. The library and Liked Songs load in the background as soon as Spotify is ready.
@@ -21,9 +29,11 @@ A new engine, written from scratch, and a cleaner app on top of it.
- **Setup screen** after signing in: notifications, local music, Bluetooth and unrestricted battery, each with its own button.
- **Folders in Local Files**: choose the folders shown; WhatsApp, Telegram, recordings and ringtones start hidden.
- **Lock screen and Now Bar**: play / pause in the middle (like, previous, play, next, shuffle) and a centred app icon.
+- **New icon**: one green wave line, on the launcher, the launch screen and the status bar.
+- **Beta and release install side by side**: betas are "Myspoti Beta", releases "Myspoti", each with its own updates.
- **Music no longer stops after a few songs**: when the player gets stuck between two songs, the next one starts by itself, and the player reloads if that is not enough.
-- **Smart shuffle** in playlists (tap shuffle twice): the playlist shuffled, with a Spotify recommendation every three songs.
-- **Sort by plays in that order**: a sorted playlist plays and queues in the order shown.
+- **Smart shuffle** in playlists and Liked Songs (tap shuffle twice): the list shuffled, with a Spotify recommendation every three songs.
+- **Sort by plays in that order**: a sorted playlist plays and queues in the order shown; **date added** joins the sort options.
- **Saved in** shows your folders and the playlists' covers; a folder's menu creates a playlist inside it.
- **Home loads again by itself** after an error, with a Try again button.
- **Spotify account pages** open in the app's language when Spotify has them in it.
diff --git a/README.md b/README.md
index 7399fe12..3aa12099 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@ The official Spotify Web Player runs in a hidden WebView and does the actual pla
- **Your recap**: your top tracks, artists and albums, counting Spotify, downloads and local files. It stays on your phone.
- Official music videos, when one exists. The video plays muted, in sync with the song. The app only uses YouTube videos marked as official clips, and shows nothing when no clip exists.
- Spotify Connect, media notification, lock screen, Bluetooth and Android Auto.
-- **Offline downloads.** Download a song, an album, a playlist or your Liked Songs, then play them without a connection. The audio comes from YouTube Music (Opus or AAC, as YouTube serves it, never re-encoded), not from Spotify. Each file is checked against the recording's official preview (looked up by ISRC), so a live take, a remix or a cover is rejected. Files stay in Myspoti's private storage.
+- **Offline downloads.** Download a song, an album, a playlist or your Liked Songs, then play them without a connection. The audio comes lossless (FLAC): the recording found on Tidal, Qobuz or Amazon, matched by its exact ISRC, and resolved by [SpotiFLAC](https://github.com/spotbye/SpotiFLAC) — its own signed servers first, then the open community backends. Each file is checked against the recording's official preview (looked up by ISRC), so a live take, a remix or a cover is rejected, and against the FLAC header, so a 30-second preview is rejected too. Files stay in Myspoti's private storage; hi-res (24-bit) is an option.
## How it works
@@ -50,9 +50,14 @@ Details for developers: [`base/api-spotify/README.md`](base/api-spotify/README.m
## Not included
-- No DRM circumvention.
-- No Spotify audio download or decryption. Offline downloads come from YouTube Music, not from Spotify or any other paid service.
-- No altered listening events.
+- No DRM circumvention. No Amazon stream decryption.
+- No Spotify audio download. Offline downloads are resolved from lossless catalogues through the open-backends community of SpotiFLAC; a track with no lossless source is simply marked unavailable.
+- Downloaded songs played on the phone are reported to Spotify as if Spotify had streamed them, although their audio did not come from Spotify (play time as measured on the phone; sent later when offline). Spotify counts them like streamed listens, in Wrapped and in artists' play counts, and may treat such reports as artificial streaming. No ad is marked as heard.
+
+## Credits
+
+- [SpotiFLAC](https://github.com/spotbye/SpotiFLAC) (MIT) — the lossless resolving idea, its community backend protocol and the gated-session flow.
+- [Spotui](https://github.com/Spotui/Spotui) (GPL-3.0) — the Kotlin port of the resolver, the signed-session verification screen and the DASH-to-FLAC remux that Myspoti builds on.
## Disclaimer
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
index 5380d25e..b0b4567e 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt
@@ -162,7 +162,7 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, private
"uri" to uri, "offset" to offset, "limit" to limit, "includeEpisodeContentRatingsV2" to true,
)).entity("data.playlistV2", "fetchPlaylistContents")
val content = p.at("content")
- val items = content.list("items").mapNotNull { track(it.at("itemV2.data"), it.str("uid")) }
+ val items = content.list("items").mapNotNull { track(it.at("itemV2.data"), it.str("uid"))?.copy(addedAt = it.str("addedAt.isoString")) }
val total = content.int("totalCount") ?: items.size
return Page(items, offset, total, (offset + limit).takeIf { it < total })
}
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 f5dba5e9..bb466286 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
@@ -55,6 +55,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
/** Reloads the Web Player page (set by the host); used when a stalled player does not recover. */
@Volatile var reloadHost: (suspend () -> Unit)? = null
+ /** Streaming quality ("auto", "low", "normal", "high", "very_high"), kept for every page load. */
+ @Volatile var audioQuality: String = "auto"
+ private set
+
init {
scope.launch {
bridge.events.collect { (type, payload) ->
@@ -65,12 +69,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
}
scope.launch { watchStalls() }
+ // A reloaded page starts on "auto": the chosen quality is set again.
+ scope.launch { bridge.ready.collect { if (it && audioQuality != "auto") applyAudioQuality() } }
}
private suspend fun watchStalls() {
var key: String? = null
var since = 0L
var attempts = 0
+ var adAttempts = 0
while (true) {
delay(WATCH_TICK_MS)
val s = _state.value
@@ -80,13 +87,31 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
// A refused ad sits at 0:00, buffering; a real one plays to its end.
val stuck = ad != null && (ad.isBuffering || ad.speed == 0.0) && now - adSince > AD_STUCK_MS
if (stuck || now - adSince > AD_BREAK_MAX_MS) {
- bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song")
- lastTrackState?.let { runCatching { playOn(it) } }
- adSince = now
+ adAttempts++
+ val last = lastTrackState
+ // Playing on can land on the same refused ad again: after a few tries the
+ // page itself is reloaded, which drops the ad break.
+ if (adRecovery(adAttempts) == "next") {
+ bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song (attempt $adAttempts)")
+ last?.let { runCatching { playOn(it) } }
+ } else {
+ adAttempts = 0
+ bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: reloading the player")
+ val reload = reloadHost
+ if (reload != null) runCatching {
+ reload()
+ withTimeoutOrNull(45_000) { delay(1_500); bridge.ready.first { it } } ?: return@runCatching
+ delay(1_500)
+ last?.let { playOn(it) }
+ } else last?.let { runCatching { playOn(it) } }
+ }
+ adSince = System.currentTimeMillis()
}
key = null
continue
}
+ // A song really playing again: the ad break is over.
+ if (s != null && !s.isPaused && !s.isBuffering) adAttempts = 0
val reason = s?.let { stallOf(it, now, pausedByUserAt) }
if (s == null || reason == null) { key = null; attempts = 0; continue }
val k = "${s.item?.uri}|$reason"
@@ -202,6 +227,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
bridge.call("volume.set", buildJsonObject { put("level", level.coerceIn(0.0, 1.0)) })
}
+ /** Sets the streaming quality now (when the page is up) and on every later page load. */
+ suspend fun setAudioQuality(level: String) {
+ audioQuality = level
+ if (bridge.ready.value) applyAudioQuality()
+ }
+
+ private suspend fun applyAudioQuality() {
+ runCatching { bridge.call("player.setAudioQuality", buildJsonObject { put("level", audioQuality) }) }
+ .onFailure { bridge.logger?.invoke("audio quality $audioQuality not set: ${it.message}") }
+ }
+
/** Pulls the state once, e.g. right after the bridge is ready. */
suspend fun refresh() {
onState(playerState(bridge.call("player.state") as? JsonObject))
@@ -219,6 +255,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
private const val WATCH_TICK_MS = 2_000L
/** Buffering longer than this on one song is a stall, not a slow network. */
const val BUFFERING_STALL_MS = 25_000L
+ /** Stuck ads skipped by playing on before the page is reloaded. */
+ const val AD_SKIPS_BEFORE_RELOAD = 2
+
+ /** What the [attempt]-th try on a stuck ad does: "next" (play on) or "reload". */
+ fun adRecovery(attempt: Int): String = if (attempt <= AD_SKIPS_BEFORE_RELOAD) "next" else "reload"
/**
* Why [s] looks stalled at [now], or null. A song is stalled when its clock ran past
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 14281428..897236f6 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -202,6 +202,18 @@
'player.setShuffle': a => need().player.setShuffle(!!a.on),
'player.setRepeat': a => need().player.setRepeat(a.mode),
'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.
+ 'player.setAudioQuality': async a => {
+ const sdk = need().resolve('PlayerSDK');
+ const harmony = sdk && sdk.harmony;
+ // The page's own streamer first: the public entry refuses while Spotify Connect
+ // calls another device the active one ("remote player"), yet this page plays.
+ const target = [harmony && harmony._streamer, harmony]
+ .find(t => t && typeof t.setMediaPlaybackQuality === 'function');
+ if (!target) throw new Error('no audio quality setting');
+ return !!(await target.setMediaPlaybackQuality({ audio: a.level }));
+ },
'queue.add': a => need().player.addToQueue(a.uris.map(uri => ({ uri }))),
'queue.remove': a => need().player.removeFromQueue(a.items),
'queue.clear': () => need().player.clearQueue(),
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
index 50634020..649c0fc0 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
@@ -24,4 +24,10 @@ class StallTest {
@Test fun `paused mid-song`() = assertNull(SpotifyPlayer.stallOf(state(50_000, 0, paused = true), 60_000, 0))
@Test fun `buffering for long`() = assertEquals("buffering", SpotifyPlayer.stallOf(state(0, 0, buffering = true), 20_000, 0))
@Test fun `buffering a moment`() = assertNull(SpotifyPlayer.stallOf(state(0, 0, buffering = true), 5_000, 0))
+
+ @Test fun `a stuck ad is skipped twice, then the page reloads`() {
+ assertEquals("next", SpotifyPlayer.adRecovery(1))
+ assertEquals("next", SpotifyPlayer.adRecovery(2))
+ assertEquals("reload", SpotifyPlayer.adRecovery(3))
+ }
}
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Models.kt b/base/api/src/main/kotlin/app/myspoti/api/Models.kt
index 832659c6..4baf953b 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Models.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Models.kt
@@ -23,6 +23,8 @@ data class Track(
val playable: Boolean = true,
/** Position in a playlist; needed to remove or move this exact row. */
val uid: String? = null,
+ /** When it was added to the playlist (ISO 8601), for playlist rows. */
+ val addedAt: String? = null,
)
data class Album(
diff --git a/base/app/src/androidTest/assets/tone16.flac b/base/app/src/androidTest/assets/tone16.flac
new file mode 100644
index 00000000..675f6c11
Binary files /dev/null and b/base/app/src/androidTest/assets/tone16.flac differ
diff --git a/base/app/src/androidTest/assets/tone24.flac b/base/app/src/androidTest/assets/tone24.flac
new file mode 100644
index 00000000..492a5c2f
Binary files /dev/null and b/base/app/src/androidTest/assets/tone24.flac differ
diff --git a/base/app/src/androidTest/java/com/music/spotui/data/offline/AacTranscoderTest.kt b/base/app/src/androidTest/java/com/music/spotui/data/offline/AacTranscoderTest.kt
new file mode 100644
index 00000000..c70d530d
--- /dev/null
+++ b/base/app/src/androidTest/java/com/music/spotui/data/offline/AacTranscoderTest.kt
@@ -0,0 +1,44 @@
+package com.music.spotui.data.offline
+
+import android.media.MediaExtractor
+import android.media.MediaFormat
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import java.io.File
+
+/** The "smallest" downloads: a FLAC becomes a playable AAC file of the same length, on the phone's codecs. */
+@RunWith(AndroidJUnit4::class)
+class AacTranscoderTest {
+ private val context = InstrumentationRegistry.getInstrumentation().targetContext
+ private val testAssets = InstrumentationRegistry.getInstrumentation().context.assets
+
+ private fun asset(name: String): File = File(context.cacheDir, name).also { f ->
+ testAssets.open(name).use { input -> f.outputStream().use { input.copyTo(it) } }
+ }
+
+ private fun check(name: String) {
+ val input = asset(name)
+ val out = File(context.cacheDir, "$name.m4a").apply { delete() }
+ AacTranscoder.transcode(input, out)
+ val ex = MediaExtractor().apply { setDataSource(out.path) }
+ try {
+ val f = ex.getTrackFormat(0)
+ assertEquals(MediaFormat.MIMETYPE_AUDIO_AAC, f.getString(MediaFormat.KEY_MIME))
+ assertEquals(2, f.getInteger(MediaFormat.KEY_CHANNEL_COUNT))
+ val seconds = f.getLong(MediaFormat.KEY_DURATION) / 1_000_000.0
+ assertTrue("duration $seconds", seconds in 5.7..6.3)
+ // 96 kbit/s for 6 s is about 72 kB; far below the FLAC.
+ assertTrue("size ${out.length()}", out.length() in 40_000L..110_000L)
+ } finally {
+ ex.release()
+ }
+ }
+
+ @Test fun cdFlacBecomesAac() = check("tone16.flac")
+
+ @Test fun hiResFlacBecomesAac() = check("tone24.flac")
+}
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index cf534f05..9ec3c5d3 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -40,6 +40,8 @@ class MainActivity : AppCompatActivity() {
private var connecting by mutableStateOf(false)
/** The one-time setup screen (permissions, battery) after signing in. */
private var setupNeeded by mutableStateOf(false)
+ /** SpotiFLAC verification, opened from the setup screen or the settings. */
+ private var showSpotiflac by mutableStateOf(false)
private val prefs get() = getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)
@@ -54,7 +56,11 @@ class MainActivity : AppCompatActivity() {
SpotuiTheme {
androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.fillMaxSize()) {
when {
- signedIn && setupNeeded -> com.music.spotui.ui.screens.SetupScreen(onDone = { setupNeeded = false })
+ showSpotiflac -> com.music.spotui.ui.screens.SpotiflacScreen(onClose = { showSpotiflac = false })
+ signedIn && setupNeeded -> com.music.spotui.ui.screens.SetupScreen(
+ onDone = { setupNeeded = false },
+ onSpotiflac = { showSpotiflac = true },
+ )
signedIn -> App()
connecting -> ConnectingScreen()
else -> WelcomeScreen(onLogin = { showLogin() })
diff --git a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
index eb7044f1..c1a18e64 100644
--- a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
+++ b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
@@ -19,6 +19,10 @@ class MyspotiApplication : Application() {
// Spotify session (hidden Web Player + API), caches, downloads, data saver.
Graph.init(this)
SongPlayer.attachEngine(Graph.currentSongState)
+ // Headphones or Bluetooth gone: pause rather than play on the speaker.
+ com.music.spotui.di.NoisyAudio.register(this)
+ // Offline listens kept for Wrapped reporting are replayed once signed in.
+ com.music.spotui.data.offline.WrappedSync.resumePending()
PlaybackService.library = object : MediaLibrary {
override suspend fun children(context: Context, parentId: String): List<MediaBrowserCompat.MediaItem> =
AutoBrowser.children(context, parentId)
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 2fa15162..2143bcd4 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
@@ -107,6 +107,7 @@ class Api constructor(
explicit = t.explicit,
durationMs = t.durationMs.toInt(),
albumId = t.album?.uri?.substringAfterLast(':').orEmpty(),
+ addedAt = t.addedAt.orEmpty(),
)
}
@@ -474,7 +475,7 @@ class Api constructor(
var offset = 0
while (true) {
val page = api.library.likedTracks(offset, 50)
- out += page.items.map { songOf(it.track) }
+ out += page.items.map { songOf(it.track).copy(addedAt = it.addedAt.orEmpty()) }
onPage(out.toList())
offset = page.nextOffset ?: break
}
diff --git a/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt b/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt
index 91b7de6e..eafb09f9 100644
--- a/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt
+++ b/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt
@@ -19,6 +19,8 @@ data class SongsModel(
val durationMs : Int = 0,
// Spotify album id of the track, when known (opens the album page by id).
val albumId : String = "",
+ // When it was added to the playlist or to Liked Songs (ISO 8601), for "Sort by date added".
+ val addedAt : String = "",
){
constructor() : this(-1 ,"" ,"" ,"" ,"" ,"", "")
}
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt b/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt
new file mode 100644
index 00000000..4138edb9
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/offline/AacTranscoder.kt
@@ -0,0 +1,191 @@
+package com.music.spotui.data.offline
+
+import android.media.MediaCodec
+import android.media.MediaCodecInfo
+import android.media.MediaExtractor
+import android.media.MediaFormat
+import android.media.MediaMuxer
+import java.io.File
+import java.io.IOException
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/**
+ * Re-encodes a downloaded song (FLAC, or anything Android decodes) into AAC in an .m4a
+ * file, with the phone's own codecs: the "smallest" download quality. The FLAC is
+ * checked first, so the small file is still the right recording.
+ */
+object AacTranscoder {
+ const val BITRATE = 96_000
+ private const val TIMEOUT_US = 10_000L
+
+ /** Writes [output]; throws on any codec error (the caller marks the song failed). */
+ fun transcode(input: File, output: File, bitrate: Int = BITRATE) {
+ val extractor = MediaExtractor()
+ var decoder: MediaCodec? = null
+ var encoder: MediaCodec? = null
+ var muxer: MediaMuxer? = null
+ try {
+ extractor.setDataSource(input.path)
+ val track = (0 until extractor.trackCount).firstOrNull {
+ extractor.getTrackFormat(it).getString(MediaFormat.KEY_MIME)?.startsWith("audio/") == true
+ } ?: throw IOException("no audio track")
+ extractor.selectTrack(track)
+ val inFormat = extractor.getTrackFormat(track)
+ val inRate = inFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE)
+ // Phone AAC encoders stop at 48 kHz: hi-res rates are divided down (96 → 48, 88.2 → 44.1).
+ val step = decimation(inRate)
+ val sampleRate = inRate / step
+ val channels = inFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT).coerceAtMost(2)
+
+ decoder = MediaCodec.createDecoderByType(inFormat.getString(MediaFormat.KEY_MIME)!!).apply {
+ configure(inFormat, null, null, 0); start()
+ }
+ val outFormat = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, sampleRate, channels).apply {
+ setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC)
+ setInteger(MediaFormat.KEY_BIT_RATE, bitrate)
+ setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 64 * 1024)
+ }
+ encoder = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC).apply {
+ configure(outFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); start()
+ }
+ muxer = MediaMuxer(output.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
+
+ val info = MediaCodec.BufferInfo()
+ var inputDone = false
+ var decodeDone = false
+ var encodeDone = false
+ var muxTrack = -1
+ var pcmEncoding = android.media.AudioFormat.ENCODING_PCM_16BIT
+ var decodedChannels = channels
+ var framesFed = 0L
+ // PCM waiting for room in the encoder (a decoder buffer can be bigger than its input).
+ var pending: ByteArray? = null
+ var pendingOffset = 0
+
+ // Encoder → file; true once the end of the stream is written.
+ fun drain(): Boolean {
+ while (true) {
+ val o = encoder.dequeueOutputBuffer(info, 0)
+ when {
+ o == MediaCodec.INFO_TRY_AGAIN_LATER -> return false
+ o == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {
+ muxTrack = muxer.addTrack(encoder.outputFormat)
+ muxer.start()
+ }
+ o >= 0 -> {
+ val buf = encoder.getOutputBuffer(o)!!
+ if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) info.size = 0
+ if (info.size > 0 && muxTrack >= 0) {
+ buf.position(info.offset); buf.limit(info.offset + info.size)
+ muxer.writeSampleData(muxTrack, buf, info)
+ }
+ encoder.releaseOutputBuffer(o, false)
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return true
+ }
+ }
+ }
+ }
+
+ while (!encodeDone) {
+ if (Thread.interrupted()) throw InterruptedException()
+ // 1. File → decoder.
+ if (!inputDone) {
+ val i = decoder.dequeueInputBuffer(TIMEOUT_US)
+ if (i >= 0) {
+ val buf = decoder.getInputBuffer(i)!!
+ val n = extractor.readSampleData(buf, 0)
+ if (n < 0) {
+ decoder.queueInputBuffer(i, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM)
+ inputDone = true
+ } else {
+ decoder.queueInputBuffer(i, 0, n, extractor.sampleTime, 0)
+ extractor.advance()
+ }
+ }
+ }
+ // 2. Decoder → 16-bit PCM (its end-of-stream buffer too, even empty).
+ if (pending == null && !decodeDone) {
+ val o = decoder.dequeueOutputBuffer(info, TIMEOUT_US)
+ if (o == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ val f = decoder.outputFormat
+ if (f.containsKey(MediaFormat.KEY_PCM_ENCODING)) pcmEncoding = f.getInteger(MediaFormat.KEY_PCM_ENCODING)
+ decodedChannels = f.getInteger(MediaFormat.KEY_CHANNEL_COUNT)
+ } else if (o >= 0) {
+ val buf = decoder.getOutputBuffer(o)!!
+ buf.position(info.offset); buf.limit(info.offset + info.size)
+ pending = toPcm16(buf, pcmEncoding, decodedChannels, channels, step)
+ pendingOffset = 0
+ decoder.releaseOutputBuffer(o, false)
+ if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) decodeDone = true
+ }
+ }
+ // 3. PCM → encoder, the clock counted in frames.
+ val pcm = pending
+ if (pcm != null) {
+ val i = encoder.dequeueInputBuffer(TIMEOUT_US)
+ if (i >= 0) {
+ val buf = encoder.getInputBuffer(i)!!
+ val n = minOf(buf.capacity(), pcm.size - pendingOffset)
+ buf.clear(); buf.put(pcm, pendingOffset, n)
+ val pts = framesFed * 1_000_000L / sampleRate
+ framesFed += n / (2 * channels)
+ pendingOffset += n
+ val last = pendingOffset >= pcm.size
+ encoder.queueInputBuffer(i, 0, n, pts, if (last && decodeDone) MediaCodec.BUFFER_FLAG_END_OF_STREAM else 0)
+ if (last) pending = null
+ }
+ }
+ // 4. Encoder → file.
+ encodeDone = drain()
+ }
+ } finally {
+ runCatching { decoder?.stop() }; runCatching { decoder?.release() }
+ runCatching { encoder?.stop() }; runCatching { encoder?.release() }
+ runCatching { muxer?.stop() }; runCatching { muxer?.release() }
+ extractor.release()
+ }
+ }
+
+ /** How many input frames make one output frame, so the rate is 48 kHz or less. */
+ internal fun decimation(rate: Int): Int {
+ var step = 1
+ while (rate / step > 48_000) step *= 2
+ return step
+ }
+
+ /**
+ * Decoder output (16-bit, float or 24/32-bit PCM, any channel count) → 16-bit PCM with
+ * [outChannels] channels, every [step] frames averaged into one (a plain low-pass).
+ */
+ internal fun toPcm16(buf: ByteBuffer, encoding: Int, inChannels: Int, outChannels: Int, step: Int = 1): ByteArray {
+ val b = buf.slice().order(ByteOrder.nativeOrder())
+ val bytesPerSample = when (encoding) {
+ android.media.AudioFormat.ENCODING_PCM_FLOAT, android.media.AudioFormat.ENCODING_PCM_32BIT -> 4
+ android.media.AudioFormat.ENCODING_PCM_24BIT_PACKED -> 3
+ else -> 2
+ }
+ val frames = b.remaining() / (bytesPerSample * inChannels)
+ fun sample(f: Int, c: Int): Int {
+ val p = (f * inChannels + c) * bytesPerSample
+ return when (encoding) {
+ android.media.AudioFormat.ENCODING_PCM_FLOAT -> (b.getFloat(p).coerceIn(-1f, 1f) * 32767f).toInt()
+ android.media.AudioFormat.ENCODING_PCM_32BIT -> b.getInt(p) shr 16
+ android.media.AudioFormat.ENCODING_PCM_24BIT_PACKED ->
+ ((b.get(p + 2).toInt() shl 16) or ((b.get(p + 1).toInt() and 0xFF) shl 8) or (b.get(p).toInt() and 0xFF)) shr 8
+ else -> b.getShort(p).toInt()
+ }
+ }
+ val outFrames = frames / step
+ val out = ByteBuffer.allocate(outFrames * outChannels * 2).order(ByteOrder.nativeOrder())
+ for (o in 0 until outFrames) {
+ for (c in 0 until outChannels) {
+ val from = minOf(c, inChannels - 1)
+ var sum = 0
+ for (k in 0 until step) sum += sample(o * step + k, from)
+ out.putShort((sum / step).coerceIn(-32768, 32767).toShort())
+ }
+ }
+ return out.array()
+ }
+}
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 5090786b..0c80fd02 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,11 +4,14 @@ 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
import com.music.spotui.video.AudioAlign
import com.music.spotui.video.InterruptibleHttp
-import com.music.spotui.video.MusicVideoController
-import com.music.spotui.video.RangeAudioDownload
import com.music.spotui.video.YouTubeSource
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
@@ -28,22 +31,24 @@ import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.json.JSONArray
import org.json.JSONObject
-import org.schabi.newpipe.extractor.MediaFormat
import java.io.File
import java.io.IOException
+import java.net.HttpURLConnection
+import java.net.URL
import java.util.concurrent.ConcurrentHashMap
/**
* Downloads songs for offline listening. Spotify only gives the track (title, artist,
- * duration, ISRC); the audio comes from YouTube Music, the same way music videos are
- * found:
+ * duration, ISRC); the audio comes lossless, FlAC, resolved like SpotiFLAC does:
*
- * 1. the YouTube Music "song" of the track (the label's "Artist - Topic" upload of the
- * same master), else a plain "official audio" upload, duration within 3 s;
- * 2. the best audio stream as YouTube serves it (Opus or AAC, never re-encoded);
- * 3. a check against the recording's official 30 s preview (Deezer, looked up by ISRC):
- * the two audios are aligned like a clip's soundtrack, which rejects a live take, a
- * remix or a cover. Without a preview, only the "Topic" upload is trusted.
+ * 1. the same recording on a lossless service, matched by the exact ISRC, else by
+ * title + artist + duration within 3 s — never a live take, a remix or a cover;
+ * 2. the most reliable source first: SpotiFLAC's own gated backend (the signing
+ * session the user verified once), then the public Tidal community backends,
+ * then Amazon's self-resolving endpoint. 24-bit when it exists, else CD;
+ * 3. a check against the recording's official 30 s preview (Deezer, looked up by
+ * ISRC): the two audios are aligned, which confirms the right take. Without a
+ * preview, only an exact ISRC match is trusted.
*
* Nothing that fails the check is kept: the song is marked unavailable instead.
*/
@@ -78,6 +83,21 @@ object OfflineDownloader {
private class Unavailable(message: String) : Exception(message)
+ @Volatile private var hinted = false
+
+ /**
+ * Without the SpotiFLAC verification only the public servers are tried, and they are
+ * often down or throttled: say once per run where the reliable source is, instead of
+ * leaving a list of "no matching recording".
+ */
+ private fun hintVerification() {
+ if (hinted || com.music.spotui.data.preferences.hasSpotiflacSession(Graph.app)) return
+ hinted = true
+ scope.launch(Dispatchers.Main) {
+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.downloads_verify_hint, android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/** Songs queued, downloading, or whose download did not succeed (for the Downloaded list). */
val requests: SnapshotStateMap<String, Request> = mutableStateMapOf()
@@ -107,7 +127,16 @@ object OfflineDownloader {
if (saved.isNotEmpty()) enqueueAll(saved)
}
- fun enqueue(songs: List<SongsModel>) = enqueueAll(songs.filter { it.spotifyTrackId.isNotBlank() }.map(Request::of))
+ fun enqueue(songs: List<SongsModel>) {
+ // Downloads switched off in Settings: say so, instead of a list of failed songs.
+ if (!isLosslessEnabled(Graph.app)) {
+ scope.launch(Dispatchers.Main) {
+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.downloads_off_toast, android.widget.Toast.LENGTH_LONG).show()
+ }
+ return
+ }
+ enqueueAll(songs.filter { it.spotifyTrackId.isNotBlank() }.map(Request::of))
+ }
private fun enqueueAll(list: List<Request>) {
val added = synchronized(pending) {
@@ -182,6 +211,7 @@ object OfflineDownloader {
throw e
} catch (e: Unavailable) {
Log.i(TAG, "${r.title}: ${e.message}")
+ hintVerification()
OfflineStatus.Unavailable
} catch (t: Throwable) {
Log.w(TAG, "${r.title} failed", t)
@@ -196,11 +226,14 @@ object OfflineDownloader {
}
private suspend fun download(r: Request): OfflineTrack {
+ if (!isLosslessEnabled(Graph.app)) throw Unavailable("lossless downloads are off")
val tmp = OfflineStore.tmpDir
- val audioTmp = File(tmp, "${r.trackId}.part")
+ val audioTmp = File(tmp, "${r.trackId}.flacpart")
val previewTmp = File(tmp, "${r.trackId}.preview")
try {
val meta = spotifyMeta(r)
+
+ // The official 30 s preview of the recording, for the alignment check.
val previewLink = previewUrl(meta)
val preview = previewLink?.let { url ->
runCatching { httpGet(url, previewTmp); previewTmp }
@@ -213,52 +246,102 @@ object OfflineDownloader {
}
}
Log.i(TAG, "${meta.title}: isrc=${meta.isrc ?: "-"} preview=${if (previewFeatures != null) "ok" else if (previewLink != null) "unusable" else "none"}")
- // An empty search (or YouTube's "results may be inappropriate" page) is no match, not an error.
- fun search(what: String, block: () -> YouTubeSource.Hit?): YouTubeSource.Hit? = try {
- block()
- } catch (e: org.schabi.newpipe.extractor.search.SearchExtractor.NothingFoundException) {
- Log.i(TAG, "${meta.title}: $what: nothing found"); null
+
+ // ── Lossless resolve: gated SpotiFLAC first, then the community backends.
+ val file = resolveAndFetch(r, meta, audioTmp) ?: throw Unavailable("no lossless match")
+ currentCoroutineContext().ensureActive()
+
+ // ── Verification before the file is kept.
+ if (previewFeatures != null) {
+ val score = checkLock.withLock {
+ val full = runInterruptible(Dispatchers.Default) { AudioAlign.features(AudioAlign.decode(audioTmp)) }
+ val map = AudioAlign.align(previewFeatures, full)
+ if (map.segments.isEmpty()) 0.0 else map.score
+ }
+ Log.i(TAG, "${meta.title}: ${file.provider} score ${"%.2f".format(score)}")
+ if (score < MIN_SCORE) throw Unavailable("the lossless file did not match the recording's preview")
+ file.verified = true
+ } else if (!file.isrcMatched) {
+ // No preview to compare with: only an exact ISRC match is trusted.
+ throw Unavailable("no preview and no ISRC match")
}
- val candidates = buildList {
- runInterruptible { search("song") { YouTubeSource.findSong(meta.title, meta.artist, meta.durationMs) } }?.let { add(it to true) }
- runInterruptible { search("audio") { YouTubeSource.findAudio(meta.title, meta.artist, meta.durationMs) } }?.let { add(it to false) }
- }.distinctBy { it.first.url }
- if (candidates.isEmpty()) throw Unavailable("no YouTube match")
- for ((hit, topic) in candidates) {
- currentCoroutineContext().ensureActive()
- // No preview to compare with: only the label's own upload is trusted.
- if (previewFeatures == null && !topic) continue
- val ext = fetchAudio(r.trackId, hit.url, audioTmp)
- val verified = previewFeatures != null
- if (!verified) Log.i(TAG, "${meta.title}: ${hit.name} (${hit.uploader}) kept unverified (Topic upload)")
- if (verified) {
- val score = checkLock.withLock {
- val full = runInterruptible(Dispatchers.Default) { AudioAlign.features(AudioAlign.decode(audioTmp)) }
- val map = AudioAlign.align(previewFeatures!!, full)
- if (map.segments.isEmpty()) 0.0 else map.score
- }
- Log.i(TAG, "${meta.title}: ${hit.name} (${hit.uploader}) score ${"%.2f".format(score)}")
- if (score < MIN_SCORE) { audioTmp.delete(); continue }
+
+ val out: File
+ if (isSmallDownloads(Graph.app)) {
+ // "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")
+ try {
+ checkLock.withLock { runInterruptible(Dispatchers.Default) { AacTranscoder.transcode(audioTmp, aacTmp) } }
+ if (aacTmp.length() < 10_000 || !aacTmp.renameTo(out)) throw IOException("could not encode the small file")
+ } finally {
+ aacTmp.delete()
}
- val file = File(OfflineStore.audioDir, "${r.trackId}.$ext")
- if (!audioTmp.renameTo(file)) throw IOException("could not move the file")
- val cover = runCatching {
- val c = File(OfflineStore.coverDir, "${r.trackId}.jpg")
- httpGet(meta.coverUrl, c); c.name
- }.getOrDefault("")
- return OfflineTrack(
- trackId = r.trackId, title = meta.title, artist = meta.artist, album = meta.album,
- albumId = meta.albumId, durationMs = meta.durationMs, coverUrl = meta.coverUrl,
- file = file.name, cover = cover, source = hit.url, verified = verified,
- bytes = file.length(), addedAt = System.currentTimeMillis(),
- )
+ } else {
+ out = File(OfflineStore.audioDir, "${r.trackId}.flac")
+ if (!audioTmp.renameTo(out)) throw IOException("could not move the file")
}
- throw Unavailable(if (previewFeatures == null) "no preview and no Topic upload" else "no candidate matched the preview")
+ val cover = runCatching {
+ val c = File(OfflineStore.coverDir, "${r.trackId}.jpg")
+ httpGet(meta.coverUrl, c); c.name
+ }.getOrDefault("")
+ return OfflineTrack(
+ trackId = r.trackId, title = meta.title, artist = meta.artist, album = meta.album,
+ albumId = meta.albumId, durationMs = meta.durationMs, coverUrl = meta.coverUrl,
+ file = out.name, cover = cover, source = file.provider, verified = file.verified,
+ bytes = out.length(), addedAt = System.currentTimeMillis(),
+ )
} finally {
audioTmp.delete(); previewTmp.delete()
}
}
+ private class Fetched(val provider: String, val isrcMatched: Boolean) {
+ var verified = false
+ }
+
+ /** 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? {
+ 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),
+ )
+ if (resolved !is LosslessSource.Success) return null
+ val track = resolved.track
+ setStatus(r.trackId, OfflineStatus.Downloading(-1f))
+ val ok = when {
+ track.dashBase64.isNotBlank() ->
+ runInterruptible(Dispatchers.IO) {
+ DashFlacRemux.download("data:application/dash+xml;base64,${track.dashBase64}", out)
+ }
+ else -> fetchWithProgress(r.trackId, track.url, out)
+ }
+ if (!ok || out.length() < 10_000) return null
+ checkFlacHeader(out, meta, track)
+ Log.i(TAG, "${meta.title}: saved lossless FLAC from ${track.provider} (${track.quality}-bit)")
+ return Fetched("${track.provider} ${track.quality}-bit", resolved.isrcMatched)
+ }
+
+ /**
+ * A STREAMINFO read on the saved file: anything that is not a FLAC file (an
+ * encrypted or AAC stream some backends hand out) is refused, previews trimmed by
+ * the backend are caught (the header states the real length), and a misplaced
+ * 24-bit label shows up in the log.
+ */
+ private fun checkFlacHeader(file: File, meta: Meta, track: com.music.spotui.lossless.LosslessSource.LosslessFile) {
+ val seconds = runCatching {
+ file.inputStream().use { s ->
+ val head = ByteArray(42); var off = 0
+ while (off < head.size) { val n = s.read(head, off, head.size - off); if (n < 0) break; off += n }
+ LosslessSource.flacDurationSec(head)
+ }
+ }.getOrNull() ?: throw Unavailable("the lossless source did not send a FLAC file")
+ val expected = meta.durationMs / 1000
+ if (expected > 0 && seconds < expected - 5) throw Unavailable("backed out: the file is a ${seconds}s preview")
+ Log.d(TAG, "${meta.title}: FLAC ${seconds}s header check, labelled ${track.quality}-bit")
+ }
+
private data class Meta(
val title: String, val artist: String, val album: String, val albumId: String,
val durationMs: Long, val coverUrl: String, val isrc: String?,
@@ -307,64 +390,119 @@ object OfflineDownloader {
}
private suspend fun httpGet(url: String, out: File) = runInterruptible {
- InterruptibleHttp.read(YouTubeSource.http.newCall(okhttp3.Request.Builder().url(url).build())) { r ->
- if (!r.isSuccessful) throw IOException("HTTP ${r.code}")
- val body = r.body ?: throw IOException("empty body")
+ InterruptibleHttp.read(YouTubeSource.http.newCall(okhttp3.Request.Builder().url(url).build())) { res ->
+ if (!res.isSuccessful) throw IOException("HTTP ${res.code}")
+ val body = res.body ?: throw IOException("empty body")
out.outputStream().use { body.byteStream().copyTo(it) }
}
}
- /** Downloads the best audio stream of [url] into [out]; returns the file extension. */
- private suspend fun fetchAudio(trackId: String, url: String, out: File): String {
- var info = runInterruptible { YouTubeSource.info(url) }
- var last: Throwable? = null
- for (attempt in 0..1) {
- val streams = rankAudio(info.audioStreams.mapNotNull { a ->
- val ext = when (a.format) { MediaFormat.WEBMA_OPUS -> "webm"; MediaFormat.M4A -> "m4a"; else -> null }
- ext?.let { AudioChoice(it, a.averageBitrate, a.content) }
- })
- if (streams.isEmpty()) throw Unavailable("no audio stream")
- for (a in streams.take(2)) {
- try {
- fetchWithProgress(trackId, a.url, out)
- val expected = if (a.bitrate > 0 && info.duration > 0) a.bitrate * 1000L / 8 * info.duration else 0L
- if (out.length() < 50_000 || (expected > 0 && out.length() < expected * 0.6))
- throw IOException("${out.length() / 1024} KB, expected ~${expected / 1024} KB")
- return a.ext
- } catch (t: Throwable) {
- currentCoroutineContext().ensureActive()
- last = t
- }
- }
- // Stream URLs expire or get refused (403): resolve them again once.
- info = runInterruptible { YouTubeSource.info(url, fresh = true) }
- }
- throw last ?: IOException("download failed")
- }
-
- private suspend fun fetchWithProgress(trackId: String, url: String, out: File) {
- val total = runCatching { url.toHttpUrl().queryParameter("clen")?.toLongOrNull() }.getOrNull()
- val watcher = if (total != null && total > 0) scope.launch {
+ /**
+ * Downloads the FLAC URL into [out] with HTTP **Range** requests in chunks,
+ * reporting progress. The FLAC backends hand out signed CDN urls: a plain
+ * streaming GET with a browser User-Agent, retried per chunk on resets.
+ */
+ private suspend fun fetchWithProgress(trackId: String, url: String, out: File): Boolean {
+ // A quick HEAD for the size: the progress bar needs it, the CDN allows it.
+ val total = runInterruptible(Dispatchers.IO) { contentLength(url) }
+ val watcher = if (total > 0) scope.launch {
while (isActive) {
setStatus(trackId, OfflineStatus.Downloading((out.length().toFloat() / total).coerceIn(0f, 1f)))
delay(400)
}
} else null
try {
- RangeAudioDownload.fetch(YouTubeSource.http, url, out, MusicVideoController.streamHeaders(url))
+ return runInterruptible(Dispatchers.IO) { rangedDownload(url, out, total) }
} finally {
watcher?.cancel()
+ setStatus(trackId, OfflineStatus.Downloading(-1f))
}
- setStatus(trackId, OfflineStatus.Downloading(-1f))
}
+ private fun rangedDownload(url: String, out: File, knownTotal: Long): Boolean {
+ val chunk = 16L * 1024 * 1024 // 16 MB
+ var total = knownTotal
+ java.io.RandomAccessFile(out, "rw").use { output ->
+ output.setLength(0)
+ while (true) {
+ // A chunk is [start, end]; a retry resumes where the bytes stopped, never re-appends.
+ val end = if (total > 0) minOf(output.length() + chunk - 1, total - 1) else output.length() + chunk - 1
+ var done = false
+ var attempt = 0
+ while (true) {
+ attempt++
+ val position = output.length()
+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 20_000
+ readTimeout = 60_000
+ instanceFollowRedirects = true
+ setRequestProperty("User-Agent", LosslessUa)
+ setRequestProperty("Range", "bytes=$position-$end")
+ }
+ try {
+ val code = conn.responseCode
+ // Asked past the end of a file whose size was unknown: it is complete.
+ if (code == 416 && total <= 0 && position > 0) { done = true; break }
+ if (code !in 200..299) throw IOException("stream HTTP $code")
+ val full = code != 206 // server ignored Range → the whole body, from byte 0
+ if (full) output.setLength(0)
+ if (total <= 0) total = contentRangeTotal(conn.getHeaderField("Content-Range")) ?: -1L
+ output.seek(output.length())
+ val expected = if (full) -1L else end - position + 1
+ var got = 0L
+ conn.inputStream.use { input ->
+ val buf = ByteArray(256 * 1024)
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ output.write(buf, 0, n)
+ got += n
+ }
+ }
+ if (full) done = true
+ // A short chunk with the size still unknown is the end of the stream.
+ else if (total <= 0 && got < expected) done = true
+ break
+ } catch (e: IOException) {
+ if (attempt >= 3) throw e
+ Log.w(TAG, "chunk at ${output.length()} failed (attempt $attempt): ${e.message}")
+ } finally {
+ conn.disconnect()
+ }
+ }
+ if (done) break
+ if (total in 1..output.length()) break
+ }
+ }
+ return true
+ }
+
+ private fun contentLength(url: String): Long =
+ runCatching {
+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {
+ requestMethod = "HEAD"
+ connectTimeout = 15_000
+ readTimeout = 15_000
+ instanceFollowRedirects = true
+ setRequestProperty("User-Agent", LosslessUa)
+ }
+ try {
+ conn.contentLengthLong.takeIf { it > 0 } ?: -1L
+ } finally {
+ conn.disconnect()
+ }
+ }.getOrDefault(-1L)
+
// ── Pure helpers (unit-tested) ──
- data class AudioChoice(val ext: String, val bitrate: Int, val url: String)
+ /** The lossless backends expect a browser-ish User-Agent on downloads. */
+ internal const val LosslessUa =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
- /** Highest bitrate first; at equal bitrate Opus (better quality per bit) first. */
- fun rankAudio(streams: List<AudioChoice>): List<AudioChoice> =
- streams.sortedWith(compareByDescending<AudioChoice> { it.bitrate }.thenBy { if (it.ext == "webm") 0 else 1 })
+ /** "bytes 0-99/1234" → 1234; null when absent or "*". */
+ fun contentRangeTotal(header: String?): Long? =
+ header?.substringAfterLast('/', "")?.trim()?.toLongOrNull()?.takeIf { it > 0 }
/** "US-UM7-17-03861" / "usum71703861" → "USUM71703861"; null when not an ISRC. */
fun normalizeIsrc(raw: String): String? =
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
index a4d595f7..b82c8303 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
@@ -168,6 +168,10 @@ object OfflineStore {
/** Negative, so it never collides with a MediaStore id (Local Files). */
fun localIdOf(trackId: String): Long = -1L - (trackId.hashCode().toLong() and 0x7fffffffL)
+ /** The downloaded track a local id plays, or null for files outside the downloads. */
+ fun byLocalId(id: Long): OfflineTrack? =
+ tracks.values.firstOrNull { localIdOf(it.trackId) == id }
+
private fun readIndex(): List<OfflineTrack> = runCatching {
val a = JSONArray(indexFile.readText())
(0 until a.length()).mapNotNull { runCatching { OfflineTrack.fromJson(a.getJSONObject(it)) }.getOrNull() }
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/WrappedSync.kt b/base/app/src/main/java/com/music/spotui/data/offline/WrappedSync.kt
new file mode 100644
index 00000000..20d52145
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/offline/WrappedSync.kt
@@ -0,0 +1,382 @@
+package com.music.spotui.data.offline
+
+import android.util.Log
+import app.myspoti.host.android.RelayCredentials
+import com.music.spotui.data.local.LocalTrack
+import com.music.spotui.di.Graph
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.withLock
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.util.concurrent.TimeUnit
+
+/**
+ * Reports offline listens so they count where Spotify counts them (Wrapped, top lists).
+ *
+ * Only real listens are reported: a downloaded song that actually played on this
+ * phone, for the time it actually played. The reporting replays what the Web
+ * Player sends for a streamed listen (a captured Web Player session),
+ * with the honest values: the played-time facts come from the
+ * player, nothing is invented. Listens that could not be reported right away
+ * (offline, data saver) are kept and re-reported once the network is back, so a
+ * download-based history stays in sync.
+ */
+object WrappedSync {
+ private const val TAG = "Wrapped"
+
+ /** Spotify's own countable threshold: reaching it makes the listen real. */
+ internal const val THRESHOLD_MS = 30_000L
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val http = OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(15, TimeUnit.SECONDS)
+ .build()
+
+ /** The Spotify context of the list the downloads play from (a playlist/album uri); null = the track's album. */
+ @Volatile var contextUri: String? = null
+
+ /** One listening session of this app run (the melody session_id form). */
+ private val sessionId = System.currentTimeMillis().toString()
+
+ private var seq = 0
+ private var current: Active? = null
+ private val lock = kotlinx.coroutines.sync.Mutex()
+ private val queue = ArrayList<Listen>()
+ private val persistLock = Any()
+ @Volatile private var queueFile: File? = null
+
+ /** A whole listen, kept until Spotify has it. The facts are frozen (real times). */
+ data class Listen(
+ val trackId: String,
+ val albumId: String,
+ val startedAt: Long,
+ val playedMs: Long,
+ val durationMs: Long,
+ val threshold: Boolean,
+ /** The Spotify context the play started from (playlist/album). */
+ val context: String,
+ )
+
+ private class Active(val trackId: String, val albumId: String, val durationMs: Long, val context: String) {
+ val playbackId = randomHex(16)
+ val startedAt = System.currentTimeMillis()
+ var playedMs = 0L
+ var threshold = false
+ var lastTick = System.currentTimeMillis()
+ var playing = false
+ var broken = false
+ /** The last position the player showed, for the state PUTs. */
+ var positionMs = 0L
+ }
+
+ /** Called with every state change of a local track (the LocalPlayer states). */
+ fun onLocalState(t: LocalTrack, isPlaying: Boolean, pos: Long, dur: Long) {
+ scope.launch { lock.withLock { step(t.id, isPlaying, pos, dur) } }
+ }
+
+ /** The local player stopped (a Spotify play took over): close the listen. */
+ fun finish() = scope.launch { lock.withLock { finishLocked() } }
+
+ /** Replays the kept listens: on every new play and after a failure that came back. */
+ fun flush() = scope.launch { lock.withLock { flushLocked() } }
+
+ /** Reads the queue back once at app start, then tries to sync it. */
+ fun resumePending() {
+ runCatching {
+ val a = JSONArray(queueFile().readText())
+ synchronized(persistLock) {
+ queue.clear()
+ (0 until a.length()).forEach { i ->
+ val o = a.getJSONObject(i)
+ queue.add(Listen(
+ o.getString("trackId"), o.optString("albumId"),
+ o.optLong("startedAt"), o.optLong("playedMs"),
+ o.optLong("durationMs"), o.optBoolean("threshold"),
+ o.optString("context", ""),
+ ))
+ }
+ }
+ Log.i(TAG, "queued listens to sync: ${queue.size}")
+ }
+ if (queue.isNotEmpty()) flush()
+ }
+
+ private suspend fun step(localId: Long, isPlaying: Boolean, pos: Long, dur: Long) {
+ // Runs under [lock] already (onLocalState): the Mutex is not reentrant.
+ val offline = OfflineStore.byLocalId(localId)
+ if (offline == null) {
+ if (current != null) finishLocked() // a plain local file: nothing countable
+ return
+ }
+ if (current?.trackId != offline.trackId) {
+ finishLocked()
+ val ctx = contextUri?.takeIf { it.isNotBlank() } ?: contextFallback(offline.albumId, offline.trackId)
+ current = Active(offline.trackId, offline.albumId, dur, ctx).also { beginLocked(it, pos) }
+ }
+ val a = current ?: return
+ val now = System.currentTimeMillis()
+ a.positionMs = pos
+ // Only the time since the last tick that was playing counts, never a pause.
+ if (a.playing) a.playedMs += now - a.lastTick
+ if (isPlaying) {
+ if (!a.threshold && a.playedMs >= THRESHOLD_MS) {
+ a.threshold = true
+ if (!a.broken && !postState(a, "played_threshold_reached", pos, false)) a.broken = true
+ }
+ } else if (a.playing) { // paused: close this tick honestly
+ if (!a.broken && !postState(a, "pause", pos, true)) a.broken = true
+ }
+ a.lastTick = now
+ a.playing = isPlaying
+ }
+
+ private suspend fun beginLocked(a: Active, pos: Long) {
+ a.lastTick = System.currentTimeMillis()
+ Log.i(TAG, "${a.trackId}: listening, playback ${a.playbackId}")
+ // The play command and the first states, as the player itself sends on a play.
+ var broken = !postCommand(a)
+ if (!broken && !postState(a, "before_track_load", 0, false)) broken = true
+ if (!broken && !postState(a, "started_playing", pos, false)) broken = true
+ if (!broken) postMelody(listOf(playbackStartMessage(a)))
+ a.broken = broken
+ flushLocked()
+ }
+
+ private suspend fun finishLocked() {
+ val a = current ?: return
+ current = null
+ // The tail tick: what the last pause did not account for still counts.
+ if (a.playing) a.playedMs += System.currentTimeMillis() - a.lastTick
+ // The player only publishes on state changes: a song played straight through
+ // crosses the threshold here, at its end.
+ if (!a.threshold && a.playedMs >= THRESHOLD_MS) {
+ a.threshold = true
+ if (!a.broken && !postState(a, "played_threshold_reached", a.positionMs, false)) a.broken = true
+ }
+ val listen = listenOf(a)
+ if (a.playedMs < 1_000) {
+ Log.d(TAG, "${a.trackId}: dropped (${a.playedMs} ms)")
+ return
+ }
+ var broken = a.broken
+ if (!broken && !postState(a, "track_data_finalized", a.positionMs, false)) broken = true
+ if (!broken && !postMelody(listOf(streamVerificationMessage(a, listen.playedMs)))) broken = true
+ a.broken = broken
+ if (listen.threshold && broken) {
+ enqueue(listen)
+ Log.i(TAG, "${a.trackId}: kept for later sync (${listen.playedMs} ms)")
+ } else if (listen.threshold) {
+ Log.i(TAG, "${a.trackId}: reported (${listen.playedMs} ms)")
+ } else {
+ Log.i(TAG, "${a.trackId}: under the threshold, not counted (${listen.playedMs} ms)")
+ }
+ }
+
+ /** Replays the kept listens now that the network is back. Keeps what still fails. */
+ private suspend fun flushLocked() {
+ if (queue.isEmpty()) return
+ if (OfflineStore.isOnline(Graph.app) && RelayCredentials.ready()) {
+ val left = ArrayList<Listen>()
+ for (listen in queue) {
+ if (replay(listen)) Log.i(TAG, "synced: ${listen.trackId} (${listen.playedMs} ms)")
+ else left.add(listen)
+ }
+ queue.clear(); queue.addAll(left)
+ persistLocked()
+ }
+ }
+
+ private fun enqueue(listen: Listen) = synchronized(persistLock) {
+ queue.add(listen); persistLocked()
+ }
+
+ /** A kept listen replays on the same context it started from, its facts, its own fresh playback id. */
+ private suspend fun replay(listen: Listen): Boolean {
+ if (OfflineStore.isOnline(Graph.app) && !RelayCredentials.ready()) return false
+ val a = Active(listen.trackId, listen.albumId, listen.durationMs, contextFor(listen)).apply {
+ playedMs = listen.playedMs
+ threshold = listen.threshold
+ positionMs = listen.playedMs
+ }
+ return runCatching {
+ val command = postCommand(a)
+ val states = command &&
+ postState(a, "before_track_load", 0, false) &&
+ postState(a, "played_threshold_reached", listen.playedMs, false) &&
+ postState(a, "track_data_finalized", listen.playedMs, false)
+ val facts = states && postMelody(listOf(
+ playbackStartMessage(a),
+ streamVerificationMessage(a, listen.playedMs),
+ ))
+ command && states && facts
+ }.getOrDefault(false)
+ }
+
+ // ── The three request shapes the player itself uses (capture-decoded) ────
+
+ /** The play command that opens a listening session on Spotify's cluster. */
+ private suspend fun postCommand(a: Active): Boolean {
+ val ctx = a.context
+ val body = JSONObject().put("command", JSONObject()
+ .put("context", JSONObject().put("uri", ctx).put("url", "context://$ctx").put("metadata", JSONObject()))
+ .put("play_origin", JSONObject()
+ .put("feature_identifier", "playlist")
+ .put("feature_version", FEATURE_VERSION)
+ .put("referrer_identifier", "library"))
+ .put("options", JSONObject()
+ .put("license", "tft")
+ .put("skip_to", JSONObject())
+ .put("player_options_override", JSONObject()))
+ .put("logging_params", JSONObject().put("page_instance_ids", JSONArray()).put("interaction_ids", JSONArray()))
+ .put("endpoint", "play"))
+ return send(
+ "/connect-state/v1/player/command/from/${RelayCredentials.deviceId}/to/${RelayCredentials.deviceId}",
+ body,
+ )
+ }
+
+ /** The play state machine: milestones at the real position, never a padded one. */
+ private suspend fun postState(a: Active, debugSource: String, position: Long, paused: Boolean): Boolean {
+ val body = JSONObject()
+ .put("seq_num", seq++)
+ .put("state_ref", JSONObject()
+ .put("state_machine_id", randomB64(21))
+ .put("state_id", a.playbackId)
+ .put("paused", paused))
+ .put("sub_state", JSONObject()
+ .put("playback_speed", if (paused) 0 else 1)
+ .put("position", position)
+ .put("duration", a.durationMs)
+ .put("media_type", "AUDIO")
+ .put("bitrate", 128000) // the player's own report shape for a streamed track
+ .put("audio_quality", "HIGH")
+ .put("format", 10)
+ .put("is_video_on", false))
+ .put("debug_source", debugSource)
+ return send("/track-playback/v1/devices/${RelayCredentials.deviceId}/state", body)
+ }
+
+ /** The SDK telemetry batch: when a play started, and how long it really played. */
+ private suspend fun postMelody(messages: List<JSONObject>): Boolean {
+ val body = JSONObject()
+ .put("messages", JSONArray().apply { messages.forEach { put(it) } })
+ .put("sdk_id", "harmony:4.81.1")
+ .put("platform", PLAY_PLATFORM)
+ .put("client_version", "0.0.0")
+ return send("/melody/v1/msg/batch", body)
+ }
+
+ private fun playbackStartMessage(a: Active) = JSONObject()
+ .put("type", "jssdk_playback_start")
+ .put("message", JSONObject()
+ .put("play_track", a.trackUri())
+ .put("playback_id", a.playbackId)
+ .put("session_id", sessionId)
+ .put("ms_start_position", 0)
+ .put("initially_paused", false)
+ .put("feature_identifier", ""))
+
+ private fun streamVerificationMessage(a: Active, playedMs: Long) = JSONObject()
+ .put("type", "track_stream_verification")
+ .put("message", JSONObject()
+ .put("play_track", a.trackUri())
+ .put("playback_id", a.playbackId)
+ .put("ms_played", playedMs)
+ .put("ms_nominal_played", playedMs)
+ .put("session_id", sessionId)
+ .put("sequence_id", 0)
+ .put("next_playback_id", "")
+ .put("playback_service", "track-playback"))
+
+ private suspend fun send(path: String, body: JSONObject): Boolean {
+ val c = RelayCredentials
+ val host = c.clusterHost.ifBlank { "spclient.wg.spotify.com" }
+ val url = "https://$host$path"
+ try {
+ val req = Request.Builder().url(url)
+ .post(body.toString().toRequestBody("application/json".toMediaType()))
+ .header("Authorization", c.authorization)
+ .header("Client-Token", c.clientToken)
+ .header("User-Agent", PLAY_UA)
+ .header("Origin", "https://open.spotify.com")
+ .header("Referer", "https://open.spotify.com/")
+ .build()
+ http.newCall(req).execute().use { resp ->
+ if (resp.isSuccessful) {
+ Log.d(TAG, "${path.substringBefore('?')} -> ${resp.code}")
+ return true
+ }
+ Log.w(TAG, "${path.substringBefore('?')} -> ${resp.code}")
+ if (resp.code == 401) c.authorization = "" // the page refreshes it on its next call
+ return false
+ }
+ } catch (e: Exception) {
+ Log.d(TAG, "${path.substringBefore('?')} failed: ${e.message}")
+ return false
+ }
+ }
+
+ // ── Queue persistence (the offline part) ─────────────────────────────────
+
+ private fun listenOf(a: Active) = Listen(
+ trackId = a.trackId, albumId = a.albumId, startedAt = a.startedAt,
+ playedMs = a.playedMs, durationMs = a.durationMs, threshold = a.threshold,
+ context = a.context,
+ )
+
+ private fun persistLocked() = synchronized(persistLock) {
+ runCatching {
+ val a = JSONArray()
+ queue.forEach { l ->
+ a.put(JSONObject()
+ .put("trackId", l.trackId).put("albumId", l.albumId)
+ .put("startedAt", l.startedAt).put("playedMs", l.playedMs)
+ .put("durationMs", l.durationMs).put("threshold", l.threshold)
+ .put("context", l.context))
+ }
+ queueFile().writeText(a.toString())
+ }
+ Unit
+ }
+
+ private fun queueFile() = queueFile ?: File(Graph.app.filesDir, "wrapped_queue.json").also { queueFile = it }
+
+ // ── Pure helpers (unit-tested) ────────────────────────────────────────────
+
+ /** A deferred listen replays on the context it started from. */
+ internal fun contextFor(l: Listen): String =
+ l.context.ifBlank { contextFallback(l.albumId, l.trackId) }
+
+ private fun contextFallback(albumId: String, trackId: String): String = when {
+ albumId.isNotBlank() -> "spotify:album:$albumId"
+ else -> "spotify:track:$trackId"
+ }
+
+ /** The UA the Web Player's own requests use (one device, one voice). */
+ internal const val PLAY_UA =
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"
+
+ /** The melody platform string the player sends. */
+ internal const val PLAY_PLATFORM = "web_player linux undefined;chrome 155.0.0.0;desktop"
+
+ /** The player version string, as the capture kept it. */
+ internal const val FEATURE_VERSION = "web-player_2026-10-15_1792092088506_c66299947cb4"
+
+ internal fun randomHex(bytes: Int): String =
+ (0 until bytes).joinToString("") { "%02x".format(java.security.SecureRandom().nextInt(256)) }
+
+ internal fun randomB64(bytes: Int): String = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
+ ByteArray(bytes).also { java.security.SecureRandom().nextBytes(it) },
+ )
+
+ private fun Active.trackUri() = "spotify:track:$trackId"
+}
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
new file mode 100644
index 00000000..a2ea5a9b
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/LosslessPref.kt
@@ -0,0 +1,32 @@
+package com.music.spotui.data.preferences
+
+/*
+ * Lossless (SpotiFLAC) download preferences: availability and quality.
+ */
+
+import android.content.Context
+
+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"
+
+/**
+ * Hi-res downloads (24-bit when the provider has it: bigger files, ~3× a CD-quality FLAC).
+ * Default off: CD-quality FLAC already beats everything the old sources could give.
+ */
+fun isHiRes(context: Context): Boolean = prefs(context).getBoolean(KEY_HI_RES, false)
+
+fun setHiRes(context: Context, on: Boolean) = prefs(context).edit().putBoolean(KEY_HI_RES, on).apply()
+
+/** Download tracking switches off, "Downloaded" becomes Local Files only (lossless off = no FLAC downloads). */
+fun isLosslessEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_ENABLED, true)
+
+fun setLosslessEnabled(context: Context, on: Boolean) = prefs(context).edit().putBoolean(KEY_ENABLED, on).apply()
+
+/** Downloads kept small: the checked FLAC re-encoded to AAC on the phone. */
+fun isSmallDownloads(context: Context): Boolean = prefs(context).getBoolean(KEY_SMALL, false)
+
+fun setSmallDownloads(context: Context, on: Boolean) = prefs(context).edit().putBoolean(KEY_SMALL, 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
new file mode 100644
index 00000000..7c6737a1
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/QualityPref.kt
@@ -0,0 +1,65 @@
+package com.music.spotui.data.preferences
+
+/*
+ * Sound quality: what the Web Player streams, and how downloads are saved.
+ */
+
+import android.content.Context
+import kotlinx.coroutines.launch
+
+private const val PREF = "settings_prefs"
+private const val KEY_STREAMING = "streaming_quality"
+private const val KEY_CHOSEN = "quality_chosen"
+
+/**
+ * The Web Player's own streaming levels (its "Streaming quality" setting): 24, 96 and
+ * 160 kbit/s. Only the levels a free account gets; "very_high" (320) is Premium's.
+ */
+enum class StreamingQuality(val level: String) {
+ AUTO("auto"), LOW("low"), NORMAL("normal"), HIGH("high");
+
+ companion object {
+ fun of(level: String?): StreamingQuality = entries.firstOrNull { it.level == level } ?: AUTO
+ }
+}
+
+/**
+ * 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 }
+
+fun getStreamingQuality(c: Context): StreamingQuality =
+ StreamingQuality.of(prefs(c).getString(KEY_STREAMING, null))
+
+/** Saves the level and hands it to the player (now, and on every later page load). */
+fun setStreamingQuality(c: Context, q: StreamingQuality) {
+ prefs(c).edit().putString(KEY_STREAMING, q.level).apply()
+ applyStreamingQuality(q)
+}
+
+/** Gives the saved level to the Web Player; harmless before it is up (it keeps the level). */
+fun applyStreamingQuality(q: StreamingQuality) {
+ val runtime = app.myspoti.host.android.MyspotiRuntime
+ if (!runtime.isStarted) return
+ runtime.scope.launch { runtime.spotify.player.setAudioQuality(q.level) }
+}
+
+fun getDownloadQuality(c: Context): DownloadQuality = when {
+ !isLosslessEnabled(c) -> DownloadQuality.OFF
+ isSmallDownloads(c) -> DownloadQuality.SMALL
+ isHiRes(c) -> DownloadQuality.HI_RES
+ else -> DownloadQuality.CD
+}
+
+fun setDownloadQuality(c: Context, q: DownloadQuality) {
+ setLosslessEnabled(c, q != DownloadQuality.OFF)
+ setHiRes(c, q == DownloadQuality.HI_RES)
+ setSmallDownloads(c, q == DownloadQuality.SMALL)
+}
+
+/** The quality step of the onboarding was seen (new installs and updates alike). */
+fun isQualityChosen(c: Context): Boolean = prefs(c).getBoolean(KEY_CHOSEN, false)
+fun setQualityChosen(c: Context) = prefs(c).edit().putBoolean(KEY_CHOSEN, true).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/SpotiflacSessionPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SpotiflacSessionPref.kt
new file mode 100644
index 00000000..92a5817c
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SpotiflacSessionPref.kt
@@ -0,0 +1,55 @@
+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.
+ */
+private const val PREF = "SpotiflacSession"
+
+fun saveSpotiflacSession(
+ context: Context,
+ sessionId: String,
+ sessionSecret: String,
+ installId: String,
+ expiresAt: String,
+) {
+ context.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit()
+ .putString("session_id", sessionId)
+ .putString("session_secret", sessionSecret)
+ .putString("install_id", installId)
+ .putString("expires_at", expiresAt)
+ .apply()
+}
+
+data class SpotiflacSession(
+ val sessionId: String,
+ val sessionSecret: String,
+ val installId: String,
+ val expiresAt: String,
+)
+
+fun getSpotiflacSession(context: Context): SpotiflacSession? {
+ val p = context.getSharedPreferences(PREF, Context.MODE_PRIVATE)
+ 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(),
+ )
+}
+
+fun hasSpotiflacSession(context: Context): Boolean = getSpotiflacSession(context) != null
+
+fun clearSpotiflacSession(context: Context) {
+ context.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit().clear().apply()
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/Graph.kt b/base/app/src/main/java/com/music/spotui/di/Graph.kt
index ce1acb69..0e196cd3 100644
--- a/base/app/src/main/java/com/music/spotui/di/Graph.kt
+++ b/base/app/src/main/java/com/music/spotui/di/Graph.kt
@@ -14,6 +14,8 @@ object Graph {
app = application
// The Spotify session: hidden Web Player + API (operation hashes refresh themselves).
MyspotiRuntime.start(application)
+ // The streaming quality the user chose, set on the player at every page load.
+ com.music.spotui.data.preferences.applyStreamingQuality(com.music.spotui.data.preferences.getStreamingQuality(application))
com.music.spotui.data.local.ListenHistory.init(application)
// Downloaded songs (private storage), and the downloads left unfinished last time.
// Supporter thank-yous (accent colour) before any screen draws.
diff --git a/base/app/src/main/java/com/music/spotui/di/Haptics.kt b/base/app/src/main/java/com/music/spotui/di/Haptics.kt
index ac79082c..3a1c85d2 100644
--- a/base/app/src/main/java/com/music/spotui/di/Haptics.kt
+++ b/base/app/src/main/java/com/music/spotui/di/Haptics.kt
@@ -32,21 +32,32 @@ object Haptics {
* as the hold goes on, so the finger feels it is getting somewhere.
*/
fun ramp(level: Float) {
- val v = view?.get() ?: return
- val vibrator = (if (Build.VERSION.SDK_INT >= 31)
- v.context.getSystemService(android.os.VibratorManager::class.java)?.defaultVibrator
- else @Suppress("DEPRECATION") v.context.getSystemService(android.os.Vibrator::class.java)) ?: return
+ val vibrator = vibrator() ?: return
val l = level.coerceIn(0.05f, 1f)
+ // A plain pulse, not the TICK primitive: some phones (Samsung) play that one too
+ // faintly to feel at the start of the hold.
runCatching {
- if (Build.VERSION.SDK_INT >= 30 && vibrator.areAllPrimitivesSupported(android.os.VibrationEffect.Composition.PRIMITIVE_TICK)) {
- vibrator.vibrate(android.os.VibrationEffect.startComposition()
- .addPrimitive(android.os.VibrationEffect.Composition.PRIMITIVE_TICK, l).compose())
+ if (vibrator.hasAmplitudeControl()) {
+ vibrator.vibrate(android.os.VibrationEffect.createOneShot((10 + 15 * l).toLong(), (60 + 195 * l).toInt().coerceIn(1, 255)))
} else {
- vibrator.vibrate(android.os.VibrationEffect.createOneShot(12, (40 + 215 * l).toInt().coerceIn(1, 255)))
+ vibrator.vibrate(android.os.VibrationEffect.createPredefined(android.os.VibrationEffect.EFFECT_TICK))
}
}
}
+ /** A strong, unmistakable buzz: the debug button held to the end. */
+ fun thud() {
+ val vibrator = vibrator() ?: return
+ runCatching { vibrator.vibrate(android.os.VibrationEffect.createPredefined(android.os.VibrationEffect.EFFECT_HEAVY_CLICK)) }
+ }
+
+ private fun vibrator(): android.os.Vibrator? {
+ val v = view?.get() ?: return null
+ return if (Build.VERSION.SDK_INT >= 31)
+ v.context.getSystemService(android.os.VibratorManager::class.java)?.defaultVibrator
+ else @Suppress("DEPRECATION") v.context.getSystemService(android.os.Vibrator::class.java)
+ }
+
/** A completed action (queued, removed, transferred). */
fun confirm() = perform(HapticFeedbackConstants.CONFIRM)
}
diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
index b671bc22..a3c57fdd 100644
--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt
@@ -54,6 +54,8 @@ object LocalPlayer {
if (!active.value) return
active.value = false
exo?.let { it.stop(); it.clearMediaItems() }
+ // Whatever this run played gets closed honestly (Wrapped reporting).
+ com.music.spotui.data.offline.WrappedSync.finish()
}
fun resume() { exo?.play() }
diff --git a/base/app/src/main/java/com/music/spotui/di/NoisyAudio.kt b/base/app/src/main/java/com/music/spotui/di/NoisyAudio.kt
new file mode 100644
index 00000000..27f4dc8d
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/NoisyAudio.kt
@@ -0,0 +1,28 @@
+package com.music.spotui.di
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.media.AudioManager
+
+/**
+ * Headphones unplugged or a Bluetooth headset gone: the music pauses instead of
+ * moving to the phone's speaker, like every music app. Music playing on another
+ * Connect device is left alone (this phone is only the remote).
+ */
+object NoisyAudio {
+ private val receiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != AudioManager.ACTION_AUDIO_BECOMING_NOISY) return
+ if (SongPlayer.activeDevice.value == null && SongPlayer.isPlaying()) SongPlayer.pause()
+ }
+ }
+
+ fun register(context: Context) {
+ // A system broadcast: no export flag needed, but API 33+ asks for one anyway.
+ val filter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)
+ if (android.os.Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
+ else context.registerReceiver(receiver, filter)
+ }
+}
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 667bec91..8ba65ae5 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
@@ -799,6 +799,9 @@ object SongPlayer {
val source = if (t.uri.scheme == "file") com.music.spotui.data.local.ListenHistory.Source.DOWNLOAD
else com.music.spotui.data.local.ListenHistory.Source.LOCAL
trackListen(uri, song, source, isPlaying)
+ // The offline report: a downloaded song this app really played gets its
+ // play counted on Spotify's side (Wrapped), now or once back online.
+ com.music.spotui.data.offline.WrappedSync.onLocalState(t, isPlaying, pos, dur)
}
}
diff --git a/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt b/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt
new file mode 100644
index 00000000..95e389d3
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/lossless/DashFlacRemux.kt
@@ -0,0 +1,126 @@
+package com.music.spotui.lossless
+
+/*
+ * Ported from the SpotiFLAC port in Spotui (https://github.com/Spotui/Spotui), GPL-3.0.
+ */
+
+import android.util.Log
+
+/**
+ * Downloads a TIDAL DASH-FLAC stream and remuxes it into a real single `.flac` file
+ * — no ffmpeg. The DASH segments are fragmented MP4 carrying raw FLAC frames, so:
+ * 1. take STREAMINFO from the init segment's `dfLa` box,
+ * 2. concatenate every media segment's `mdat` payload (the FLAC frames),
+ * 3. write `fLaC` + STREAMINFO metadata block + frames.
+ * This is what unlocks 24-bit hi-res (HI_RES comes back as a segmented DASH
+ * `<MPD>` manifest, not a single-file URL).
+ */
+internal object DashFlacRemux {
+ private const val TAG = "DashFlacRemux"
+ private const val UA = "SpotiFLAC"
+
+ /** [trackUrl] is either a `data:application/dash+xml;base64,…` URI or the MPD text itself. */
+ fun download(streamUrl: String, outFile: java.io.File): Boolean = runCatching {
+ val mpd = mpdFromUrl(streamUrl) ?: return false
+ val initUrl = htmlUnescape(Regex("initialization=\"([^\"]+)\"").find(mpd)?.groupValues?.get(1) ?: return false)
+ val mediaTmpl = htmlUnescape(Regex("media=\"([^\"]+)\"").find(mpd)?.groupValues?.get(1) ?: return false)
+ val startNumber = Regex("startNumber=\"(\\d+)\"").find(mpd)?.groupValues?.get(1)?.toIntOrNull() ?: 1
+ val segCount = segmentCount(mpd)
+ if (segCount <= 0) return false
+
+ val initBytes = httpBytes(initUrl) ?: return false
+ val streamInfo = flacStreamInfoFromInit(initBytes) ?: return false
+
+ java.io.BufferedOutputStream(java.io.FileOutputStream(outFile)).use { out ->
+ out.write(byteArrayOf(0x66, 0x4c, 0x61, 0x43)) // "fLaC"
+ // metadata block header: last-block(0x80) | STREAMINFO(0) + 24-bit length
+ out.write(0x80)
+ out.write((streamInfo.size ushr 16) and 0xFF)
+ out.write((streamInfo.size ushr 8) and 0xFF)
+ out.write(streamInfo.size and 0xFF)
+ out.write(streamInfo)
+ for (n in startNumber until startNumber + segCount) {
+ val seg = httpBytes(mediaTmpl.replace("\$Number$", n.toString())) ?: return false
+ writeMdatPayloads(seg, out)
+ }
+ }
+ Log.d(TAG, "tidal DASH remuxed to FLAC ($segCount segments)")
+ true
+ }.getOrElse { Log.w(TAG, "DASH remux failed: ${it.message}"); runCatching { outFile.delete() }; false }
+
+ private fun mpdFromUrl(url: String): String? = when {
+ url.startsWith("data:application/dash+xml;base64,") ->
+ runCatching { String(java.util.Base64.getMimeDecoder().decode(url.substringAfter("base64,"))) }.getOrNull()
+ url.contains("<MPD") -> url
+ else -> null
+ }
+
+ /** Segment count from a SegmentTimeline (`<S d= r=/>`; r is a repeat count). */
+ private fun segmentCount(mpd: String): Int {
+ var total = 0
+ for (m in Regex("<S\\b[^>]*/?>").findAll(mpd)) {
+ total += 1 + (Regex("\\br=\"(\\d+)\"").find(m.value)?.groupValues?.get(1)?.toIntOrNull() ?: 0)
+ }
+ return total
+ }
+
+ /** Pull the 34-byte STREAMINFO out of an init segment's `dfLa` box. */
+ private fun flacStreamInfoFromInit(init: ByteArray): ByteArray? {
+ val tag = byteArrayOf(0x64, 0x66, 0x4c, 0x61) // "dfLa"
+ val k = indexOf(init, tag)
+ if (k < 0 || k + 12 > init.size) return null
+ // after dfLa(4) + FullBox(4): metadata block header(4) then STREAMINFO
+ val len = ((init[k + 9].toInt() and 0xFF) shl 16) or
+ ((init[k + 10].toInt() and 0xFF) shl 8) or (init[k + 11].toInt() and 0xFF)
+ if (len <= 0 || k + 12 + len > init.size) return null
+ return init.copyOfRange(k + 12, k + 12 + len)
+ }
+
+ /** Append every `mdat` box payload (the FLAC frames) from an MP4 fragment. */
+ private fun writeMdatPayloads(seg: ByteArray, out: java.io.OutputStream) {
+ var i = 0
+ while (i + 8 <= seg.size) {
+ var size = ((seg[i].toLong() and 0xFF) shl 24) or ((seg[i + 1].toLong() and 0xFF) shl 16) or
+ ((seg[i + 2].toLong() and 0xFF) shl 8) or (seg[i + 3].toLong() and 0xFF)
+ var hdr = 8
+ if (size == 1L) {
+ if (i + 16 > seg.size) break
+ size = (0..7).fold(0L) { acc, b -> (acc shl 8) or (seg[i + 8 + b].toLong() and 0xFF) }
+ hdr = 16
+ } else if (size == 0L) {
+ size = (seg.size - i).toLong()
+ }
+ if (size < hdr) break
+ if (seg[i + 4] == 0x6D.toByte() && seg[i + 5] == 0x64.toByte() &&
+ seg[i + 6] == 0x61.toByte() && seg[i + 7] == 0x74.toByte() // "mdat"
+ ) {
+ out.write(seg, i + hdr, (size - hdr).toInt())
+ }
+ i += size.toInt()
+ }
+ }
+
+ private fun httpBytes(url: String): ByteArray? = runCatching {
+ val conn = (java.net.URL(url).openConnection() as java.net.HttpURLConnection).apply {
+ connectTimeout = 15_000
+ readTimeout = 30_000
+ setRequestProperty("User-Agent", UA)
+ }
+ try {
+ if (conn.responseCode !in 200..299) null else conn.inputStream.use { it.readBytes() }
+ } finally {
+ conn.disconnect()
+ }
+ }.getOrNull()
+
+ private fun htmlUnescape(s: String): String =
+ s.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"")
+
+ private fun indexOf(haystack: ByteArray, needle: ByteArray): Int {
+ outer@ for (i in 0..haystack.size - needle.size) {
+ for (j in needle.indices) if (haystack[i + j] != needle[j]) continue@outer
+ return i
+ }
+ return -1
+ }
+}
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
new file mode 100644
index 00000000..991d2e2d
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/lossless/LosslessRegistry.kt
@@ -0,0 +1,123 @@
+package com.music.spotui.lossless
+
+/*
+ * Ported from Spotui (https://github.com/Spotui/Spotui), GPL-3.0 — see LICENSE.
+ * Endpoint registry for the community FLAC backends (Tidal, Qobuz, Amazon).
+ */
+
+import android.util.Log
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+import java.security.MessageDigest
+import javax.crypto.Cipher
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * Endpoint registry for the community FLAC backends (Tidal etc.). SpotiFLAC keeps
+ * the current backend hostnames in an AES-GCM-encrypted JSON blob on a public
+ * gist and rotates them as servers come and go; this fetches + decrypts that blob
+ * so the source list stays current, and falls back to a known-good default if the
+ * fetch fails.
+ *
+ * These are public community APIs (a plain `GET .../track/?id=…` with a shared,
+ * published API key) — no login, no CAPTCHA, no per-user credentials.
+ */
+internal object LosslessRegistry {
+
+ private const val TAG = "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"
+
+ // AES-GCM key material (matches SpotiFLAC's community-url scheme).
+ private val SEED_PARTS = listOf("spotif", "lac:co", "mmunity:url:v1")
+ private val AAD = "spotiflac|community|url|v1".toByteArray()
+
+ // Known-good defaults (used until/if the registry refresh succeeds).
+ private val DEFAULT_TIDAL = listOf("https://tidal.anandserver.cfd")
+ private val DEFAULT_AMAZON = listOf("https://amazon.anandserver.cfd")
+
+ private const val CACHE_TTL_MS = 30 * 60 * 1000L
+ private const val FAILURE_RETRY_MS = 5 * 60 * 1000L
+ @Volatile private var cached: JSONObject? = null
+ @Volatile private var cachedAt = 0L
+ @Volatile private var failedAt = 0L
+
+ /** Current Tidal community endpoints, freshest first, default appended. */
+ fun tidalEndpoints(): List<String> = endpoints("tidal", "stream", DEFAULT_TIDAL)
+
+ /** Current Amazon community endpoints (self-resolve by Spotify id). */
+ fun amazonEndpoints(): List<String> {
+ val fromReg = registry()?.optJSONObject("amazon")
+ ?.let { listOfNotNull(it.optString("antra").takeIf(String::isNotBlank)) }
+ .orEmpty()
+ return (fromReg + DEFAULT_AMAZON).map { it.trimEnd('/') }.distinct()
+ }
+
+ private fun endpoints(provider: String, category: String, default: List<String>): List<String> {
+ val fromReg = registry()?.optJSONObject(provider)?.optJSONArray(category)?.let { arr ->
+ (0 until arr.length()).mapNotNull { arr.optString(it).takeIf(String::isNotBlank) }
+ }.orEmpty()
+ return (fromReg + default).map { it.trimEnd('/') }.distinct()
+ }
+
+ private fun registry(): JSONObject? {
+ val now = nowMs()
+ cached?.let { if (now - cachedAt < CACHE_TTL_MS) return it }
+ if (now - failedAt < FAILURE_RETRY_MS) return cached
+ return runCatching {
+ val conn = URL("$GIST_URL?t=$now").openConnection() as HttpURLConnection
+ val text = try {
+ conn.connectTimeout = 8000
+ conn.readTimeout = 8000
+ conn.setRequestProperty("User-Agent", "SpotiFLAC-Agent")
+ if (conn.responseCode !in 200..299) throw java.io.IOException("HTTP ${conn.responseCode}")
+ conn.inputStream.bufferedReader().use { it.readText() }
+ } finally {
+ conn.disconnect()
+ }
+ val json = JSONObject(decrypt(text))
+ cached = json
+ cachedAt = now
+ json
+ }.onFailure {
+ // Remember the miss: a resolve calls this several times, and each retry
+ // would spend up to 16 s of the play-time lossless budget on timeouts.
+ failedAt = now
+ Log.d(TAG, "registry refresh failed, using defaults: ${it.message}")
+ }.getOrNull() ?: cached
+ }
+
+ private fun decrypt(b64Input: String): String {
+ var b = b64Input.filterNot { it.isWhitespace() }.replace('-', '+').replace('_', '/')
+ while (b.length % 4 != 0) b += "="
+ val raw = android.util.Base64.decode(b, android.util.Base64.DEFAULT)
+ val nonce = raw.copyOfRange(0, 12)
+ val body = raw.copyOfRange(12, raw.size)
+ val md = MessageDigest.getInstance("SHA-256")
+ SEED_PARTS.forEach { md.update(it.toByteArray()) }
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
+ init(Cipher.DECRYPT_MODE, SecretKeySpec(md.digest(), "AES"), GCMParameterSpec(128, nonce))
+ updateAAD(AAD)
+ }
+ return String(cipher.doFinal(body), Charsets.UTF_8)
+ }
+
+ // Avoids Date.now()-style calls that some sandboxes block; System.currentTimeMillis is fine on-device.
+ private fun nowMs(): Long = System.currentTimeMillis()
+}
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
new file mode 100644
index 00000000..8ba5a6ad
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/lossless/LosslessSource.kt
@@ -0,0 +1,351 @@
+package com.music.spotui.lossless
+
+/*
+ * Ported from Spotui (https://github.com/Spotui/Spotui), GPL-3.0, and adapted:
+ * Odesli is gone (public API closed), so ids come from the providers' own
+ * backends (search by title+artist, ISRC matched) and Qobuz's public ISRC search.
+ */
+
+import android.content.Context
+import android.util.Log
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.json.JSONArray
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+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
+ * 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).
+ * 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).
+ *
+ * The same recording only: ISRC first (exact), else title+artist normalised with
+ * a duration within 3 s — a live take, a remix or a cover is never taken.
+ */
+object LosslessSource {
+
+ private const val TAG = "LosslessSource"
+ private const val USER_AGENT =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
+
+ /** Lost audio types the resolver hands back. Either [url] or [dashBase64] is set. */
+ data class LosslessFile(
+ val url: String,
+ val dashBase64: String,
+ val provider: String,
+ /** Bit depth the source claims (the STREAMINFO after a remux tells the truth). */
+ val quality: Int,
+ )
+
+ sealed interface Result
+ data class Success(val track: LosslessFile, val isrcMatched: Boolean) : Result
+ object NotFound : Result
+ data class Error(val message: String) : Result
+
+ /** Track details from the play site; the downloader fills them from Spotify. */
+ data class TrackInfo(val title: String = "", val artist: String = "", val durationSec: Int = 0, val isrc: String = "")
+
+ /** Backends sometimes serve 30 s previews instead of the song: anything under this is one. */
+ const val MIN_FULL_TRACK_SEC = 35
+
+ suspend fun resolve(
+ context: Context,
+ spotifyId: String,
+ info: TrackInfo = TrackInfo(),
+ preferHiRes: Boolean = false,
+ ): 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.
+ val qobuz = qobuzIdForIsrc(info.isrc)
+ val session = SpotiflacGated.hasSession(context)
+
+ // 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 }
+ 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).
+ 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
+ }
+ }
+ 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
+ }
+
+ /** 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)
+ }
+
+ /** 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")
+ for (endpoint in LosslessRegistry.tidalEndpoints()) {
+ if (endpoint.isBlank()) continue
+ for (q in qualities) {
+ val body = runCatching { get("$endpoint/track/?id=${tidal.id}&quality=$q", keyHeader()) }
+ .getOrElse { Log.w(TAG, "tidal $endpoint $q: ${it.message}"); continue }
+ val fromResponse = runCatching { parseTidalTrack(body, endpoint) }.getOrElse {
+ Log.w(TAG, "tidal $endpoint $q parse: ${it.message}"); null
+ }
+ val file = fromResponse ?: continue
+ if (file.url.isBlank()) {
+ // DASH manifest: storage-side remux makes it a real FLAC (24-bit).
+ return Success(file, isrcMatches(tidal.isrc, info.isrc))
+ }
+ if (!isFullTrack(file.url, info.durationSec)) continue
+ return Success(file, isrcMatches(tidal.isrc, info.isrc))
+ }
+ }
+ return null
+ }
+
+ /** Extracts the audio reference (url or base64 DASH manifest) from a /track/ response. */
+ private fun parseTidalTrack(body: String, endpoint: String): LosslessFile? {
+ val obj = JSONObject(body)
+ val data = obj.optJSONObject("data") ?: return null
+ val bits = data.optInt("bitDepth", 16).let { if (it in 8..32) it else 16 }
+ val direct = data.optString("url").takeIf { it.startsWith("http") }
+ if (direct != null) {
+ if (!direct.contains(".flac", true)) return null
+ val host = endpoint.removePrefix("https://").substringBefore('.')
+ return LosslessFile(direct, "", "Tidal ($host)", bits)
+ }
+ val manifest = data.optString("manifest").takeIf { it.isNotBlank() } ?: return null
+ val decoded = String(android.util.Base64.decode(manifest, android.util.Base64.DEFAULT), Charsets.UTF_8)
+ if (!decoded.contains("<MPD")) {
+ val m = JSONObject(decoded)
+ val urls = m.optJSONArray("urls") ?: return null
+ if (urls.length() != 1) return null
+ val url = urls.optString(0).takeIf { it.contains(".flac", true) } ?: return null
+ val host = endpoint.removePrefix("https://").substringBefore('.')
+ return LosslessFile(url, "", "Tidal ($host)", bits)
+ }
+ return LosslessFile("", manifest, "Tidal hi-res", 24)
+ }
+
+ private fun amazon(spotifyId: String): Result? {
+ for (endpoint in LosslessRegistry.amazonEndpoints()) {
+ if (endpoint.isBlank()) continue
+ val body = runCatching { get("$endpoint/api/resolve/spotify/$spotifyId", keyHeader()) }
+ .getOrElse { Log.w(TAG, "amazon $endpoint: ${it.message}"); continue }
+ val url = runCatching {
+ val json = JSONObject(body)
+ val data = json.optJSONObject("data") ?: json
+ if (data.has("decryption_key") || json.has("decryption_key")) return@runCatching null
+ listOf("url", "stream_url", "download_url", "streamUrl")
+ .firstNotNullOfOrNull { data.optString(it).takeIf(String::isNotBlank) }
+ }.getOrElse { Log.w(TAG, "amazon $endpoint parse: ${it.message}"); null } ?: continue
+ if (url.startsWith("http") && url.contains("flac", true)) {
+ return Success(LosslessFile(url, "", "Amazon", 16), isrcMatched = false)
+ }
+ }
+ return null
+ }
+
+ // ── Provider id discovery ─────────────────────────────────────────────────
+
+ internal data class TidalHit(
+ val id: String, val title: String, val artist: String, val durationSec: Int, val isrc: String,
+ )
+
+ /** Spotify id → Tidal track via the Tidal backend's own search, ISRC or title matched. */
+ internal suspend fun tidalHit(info: TrackInfo): TidalHit? {
+ val q = URLEncoder.encode("${info.title} ${info.artist}", "UTF-8")
+ for (endpoint in LosslessRegistry.tidalEndpoints()) {
+ if (endpoint.isBlank()) continue
+ val hits = runCatching {
+ val root = JSONObject(get("$endpoint/search/?s=$q", keyHeader()))
+ val items: JSONArray = root.optJSONObject("data")?.optJSONArray("items") ?: JSONArray()
+ (0 until items.length()).mapNotNull { i ->
+ val o = items.optJSONObject(i) ?: return@mapNotNull null
+ TidalHit(
+ id = o.optString("id"), title = o.optString("title"),
+ artist = o.optJSONObject("artist")?.optString("name").orEmpty(),
+ durationSec = o.optInt("duration"), isrc = o.optString("isrc"),
+ )
+ }
+ }.getOrElse { Log.w(TAG, "tidal search $endpoint: ${it.message}"); emptyList() }
+ pickHit(hits, info.isrc, info.title, info.artist, info.durationSec)?.let { return it }
+ }
+ return null
+ }
+
+ /**
+ * The hit is the very recording Spotify plays: both sides have an ISRC and it is the
+ * same. A title + artist match (no ISRC, or another one) is not an ISRC match.
+ */
+ internal fun isrcMatches(hitIsrc: String, spotifyIsrc: String): Boolean =
+ spotifyIsrc.isNotBlank() && hitIsrc.equals(spotifyIsrc, ignoreCase = true)
+
+ /**
+ * The same recording: ISRC exact if Spotify has one; otherwise same title and
+ * artist with a length within 3 s, so a live version or a cover never wins.
+ */
+ internal fun pickHit(
+ hits: List<TidalHit>, isrc: String, title: String, artist: String, durationSec: Int,
+ ): TidalHit? {
+ fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
+ hits.firstOrNull { isrc.isNotBlank() && it.isrc.equals(isrc, ignoreCase = true) && it.id.isNotBlank() }
+ ?.let { return it }
+ return hits.firstOrNull {
+ it.id.isNotBlank() && key(it.title) == key(title) && key(it.artist) == key(artist) &&
+ (durationSec <= 0 || kotlin.math.abs(it.durationSec - durationSec) <= 3)
+ }
+ }
+
+ // Qobuz public search API (app_id/secret are the community's published constants).
+ private const val QOBUZ_APP_ID = "712109809"
+ private const val QOBUZ_APP_SECRET = "589be88e4538daea11f509d29e4a23b1"
+ private const val QOBUZ_API_BASE = "https://www.qobuz.com/api.json/0.2"
+
+ /** Qobuz track id by ISRC (signed search); null when Spotify has no ISRC or Qobuz no match. */
+ internal fun qobuzIdForIsrc(isrc: String): String? {
+ if (isrc.isBlank()) return null
+ return runCatching {
+ val ts = (System.currentTimeMillis() / 1000).toString()
+ val sigPayload = "tracksearch" + "limit" + "1" + "query" + isrc.trim() + ts + QOBUZ_APP_SECRET
+ val sig = MessageDigest.getInstance("MD5").digest(sigPayload.toByteArray())
+ .joinToString("") { "%02x".format(it) }
+ val resp = get(
+ "$QOBUZ_API_BASE/track/search?query=${URLEncoder.encode(isrc.trim(), "UTF-8")}&limit=1" +
+ "&app_id=$QOBUZ_APP_ID&request_ts=$ts&request_sig=$sig",
+ emptyMap(),
+ )
+ val items: JSONArray = JSONObject(resp).optJSONObject("tracks")?.optJSONArray("items") ?: JSONArray()
+ // The search is full text: only a track carrying this very ISRC is the recording.
+ (0 until items.length()).firstNotNullOfOrNull { i ->
+ items.optJSONObject(i)?.takeIf { isrcMatches(it.optString("isrc"), isrc.trim()) }
+ ?.optString("id")?.takeIf(String::isNotBlank)
+ }
+ }.getOrElse { Log.w(TAG, "qobuz isrc search: ${it.message}"); null }
+ }
+
+ // ── Content checks ────────────────────────────────────────────────────────
+
+ /**
+ * The backends sometimes hand out a 30 s preview instead of the song. A FLAC
+ * file states its length in STREAMINFO (first 42 bytes), so one tiny range
+ * read tells.
+ */
+ internal fun isFullTrack(url: String, expectedSec: Int): Boolean {
+ if (expectedSec <= 0 || url.isBlank()) return true
+ val seconds = runCatching {
+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 8_000
+ readTimeout = 8_000
+ setRequestProperty("User-Agent", USER_AGENT)
+ setRequestProperty("Range", "bytes=0-41")
+ }
+ val head = try {
+ if (conn.responseCode !in 200..299) ByteArray(0) else readHead(conn.inputStream, 42)
+ } finally {
+ conn.disconnect()
+ }
+ flacDurationSec(head)
+ }.getOrNull() ?: return true // not a plain FLAC header: cannot tell here, keep it
+ val full = seconds >= expectedSec - 5
+ if (!full) Log.w(TAG, "rejected ${seconds}s preview (expected ${expectedSec}s)")
+ return full
+ }
+
+ /** Reads at most [n] bytes (API-safe: no readNBytes), whatever the stream supplies. */
+ private fun readHead(input: java.io.InputStream, n: Int): ByteArray {
+ val b = ByteArray(n)
+ var off = 0
+ while (off < n) {
+ val r = input.read(b, off, n - off)
+ if (r < 0) break
+ off += r
+ }
+ return if (off == n) b else b.copyOf(off)
+ }
+
+ /** Length from a FLAC STREAMINFO header, or null if [head] is not one. */
+ internal fun flacDurationSec(head: ByteArray): Int? {
+ if (head.size < 26 || String(head, 0, 4, Charsets.US_ASCII) != "fLaC") return null
+ // Bytes 18..25: sample rate (20 bits), channels (3), bits/sample (5), total samples (36).
+ var bits = 0L
+ for (i in 18..25) bits = (bits shl 8) or (head[i].toLong() and 0xFF)
+ val sampleRate = (bits ushr 44).toInt()
+ val totalSamples = bits and 0xFFFFFFFFFL
+ if (sampleRate <= 0 || totalSamples <= 0) return null
+ return (totalSamples / sampleRate).toInt()
+ }
+
+ // ── HTTP ──────────────────────────────────────────────────────────────────
+
+ private fun keyHeader() = mapOf("X-API-Key" to LosslessRegistry.API_KEY)
+
+ internal fun get(urlString: String, headers: Map<String, String>): String {
+ val conn = (URL(urlString).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 8_000
+ readTimeout = 8_000
+ setRequestProperty("User-Agent", USER_AGENT)
+ setRequestProperty("Accept", "application/json, text/plain, */*")
+ headers.forEach { (k, v) -> setRequestProperty(k, v) }
+ }
+ return try {
+ conn.connect()
+ 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(120)}")
+ text
+ } finally {
+ conn.disconnect()
+ }
+ }
+}
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
new file mode 100644
index 00000000..6bbebb41
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/lossless/SpotiflacGated.kt
@@ -0,0 +1,163 @@
+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/ui/components/BetaLogButton.kt b/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt
index 7245da78..dae0331e 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/BetaLogButton.kt
@@ -49,7 +49,7 @@ import app.myspoti.engine.R
import com.music.spotui.data.BetaLogs
/**
- * Beta builds: a small bug icon in the bottom-right corner, next to the Library tab. Holding
+ * Beta builds: a small bug icon in the very bottom-right corner, under the Library tab. Holding
* it makes it grow; held until full size, it opens the app's logs of the last
* [BetaLogs.MINUTES] minutes, ready to copy into a bug report. A short touch does nothing.
*/
@@ -62,13 +62,13 @@ fun BetaLogButton(modifier: Modifier = Modifier) {
if (!com.music.spotui.ui.navigation.PlayerSheet.open.value) Box(
modifier
.navigationBarsPadding()
- .padding(end = 4.dp, bottom = 23.dp)
- .size(44.dp)
+ .padding(end = 2.dp, bottom = 2.dp)
+ .size(30.dp)
.pointerInput(Unit) {
detectTapGestures(onPress = {
val job = scope.launch {
grow.animateTo(1f, androidx.compose.animation.core.tween(HOLD_MS, easing = androidx.compose.animation.core.LinearEasing))
- Haptics.confirm()
+ Haptics.thud()
open = true
}
// Ticks that get stronger and closer while the finger stays down.
@@ -89,7 +89,7 @@ fun BetaLogButton(modifier: Modifier = Modifier) {
val g = grow.value
BugIcon(
color = androidx.compose.ui.graphics.lerp(Color(0xFFB3B3B3), Color(0xFF1DB954), g),
- modifier = Modifier.size((24 + 16 * g).dp),
+ modifier = Modifier.size((16 + 12 * g).dp),
)
}
if (open) LogsDialog(onDismiss = { open = false })
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
new file mode 100644
index 00000000..5254d639
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/QualityPickers.kt
@@ -0,0 +1,104 @@
+package com.music.spotui.ui.components
+
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.selection.selectableGroup
+import androidx.compose.material3.RadioButton
+import androidx.compose.material3.RadioButtonDefaults
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import com.music.spotui.data.preferences.DownloadQuality
+import com.music.spotui.data.preferences.StreamingQuality
+import com.music.spotui.data.preferences.getDownloadQuality
+import com.music.spotui.data.preferences.getStreamingQuality
+import com.music.spotui.data.preferences.setDownloadQuality
+import com.music.spotui.data.preferences.setStreamingQuality
+
+/** The streaming levels of the Web Player, one choice; saved and applied at once. */
+@Composable
+fun StreamingQualityPicker(modifier: Modifier = Modifier) {
+ val ctx = LocalContext.current
+ var current by remember { mutableStateOf(getStreamingQuality(ctx)) }
+ QualityGroup(
+ title = stringResource(R.string.quality_streaming_title),
+ detail = stringResource(R.string.quality_streaming_detail),
+ options = listOf(
+ Option(StreamingQuality.AUTO, R.string.quality_streaming_auto, R.string.quality_streaming_auto_detail),
+ Option(StreamingQuality.LOW, R.string.quality_streaming_low, R.string.quality_streaming_low_detail),
+ Option(StreamingQuality.NORMAL, R.string.quality_streaming_normal, R.string.quality_streaming_normal_detail),
+ Option(StreamingQuality.HIGH, R.string.quality_streaming_high, R.string.quality_streaming_high_detail),
+ ),
+ selected = current,
+ onSelect = { current = it; setStreamingQuality(ctx, it) },
+ modifier = modifier,
+ )
+}
+
+/** Downloads: off, FLAC CD quality or FLAC hi-res; saved at once. */
+@Composable
+fun DownloadQualityPicker(modifier: Modifier = Modifier) {
+ val ctx = LocalContext.current
+ var current by remember { mutableStateOf(getDownloadQuality(ctx)) }
+ QualityGroup(
+ title = stringResource(R.string.quality_download_title),
+ detail = stringResource(R.string.quality_download_detail),
+ options = listOf(
+ Option(DownloadQuality.OFF, R.string.quality_download_off, R.string.quality_download_off_detail),
+ 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),
+ ),
+ selected = current,
+ onSelect = { current = it; setDownloadQuality(ctx, it) },
+ modifier = modifier,
+ )
+}
+
+private class Option<T>(val value: T, val label: Int, val detail: Int)
+
+@Composable
+private fun <T> QualityGroup(
+ title: String, detail: String, options: List<Option<T>>, selected: T,
+ onSelect: (T) -> Unit, modifier: Modifier = Modifier,
+) {
+ Column(modifier.fillMaxWidth().selectableGroup()) {
+ Text(title, color = Color.White, fontSize = 17.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp))
+ Text(detail, color = Color(0xFFB3B3B3), fontSize = 13.sp,
+ modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 4.dp))
+ for (o in options) {
+ val on = o.value == selected
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp)
+ .selectable(selected = on, role = Role.RadioButton, onClick = { onSelect(o.value) })
+ .padding(horizontal = 8.dp, vertical = 4.dp),
+ ) {
+ RadioButton(selected = on, onClick = null, modifier = Modifier.padding(horizontal = 8.dp),
+ colors = RadioButtonDefaults.colors(selectedColor = Color(0xFF1DB954), unselectedColor = Color(0xFFB3B3B3)))
+ Column(Modifier.weight(1f).padding(end = 12.dp)) {
+ Text(stringResource(o.label), color = if (on) Color(0xFF1DB954) else Color.White, fontSize = 16.sp)
+ Text(stringResource(o.detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ }
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
index 19f47072..1ac31240 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
@@ -160,6 +160,20 @@ fun MyNavHost(
ContextScreen(navHostController, type = "liked", id = "")
}
+ // Settings: sound quality, downloads, data, display, language.
+ page(Routes.Settings.route){
+ LaunchedEffect(playerState) {
+ bottomBarState.value = true
+ bottomBarPlayerState.value = playerState != ""
+ }
+ com.music.spotui.ui.screens.SettingsScreen(navHostController)
+ }
+
+ // SpotiFLAC: the verification that gives the lossless downloads their best source.
+ page(Routes.Spotiflac.route){
+ com.music.spotui.ui.screens.SpotiflacScreen(onClose = { navHostController.popBackStack() })
+ }
+
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
index 6c7f3a59..236093b3 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
@@ -29,6 +29,8 @@ sealed class Routes(
object NewReleases : Routes(0, "NewReleases", "newreleases")
object Episodes : Routes(0, "Episodes", "episodes")
object Recap : Routes(0, "Recap", "recap")
+ object Spotiflac : Routes(0, "SpotiFLAC", "spotiflac")
+ object Settings : Routes(0, "Settings", "settings")
}
/** Builds a Browse-category route carrying the search genre and a display title. */
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 d4135129..fe2076bb 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
@@ -208,9 +208,13 @@ class ContextViewModel(
*/
fun playSmart(p: ContextPageModel, first: SongsModel?) {
viewModelScope.launch {
+ val inList = p.tracks.map { it.spotifyTrackId }.toSet()
val recs = withContext(Dispatchers.IO) {
- runCatching { MyspotiRuntime.api.playlists.recommended(p.uri, limit = 20) }.getOrDefault(emptyList())
- }.filter { r -> p.tracks.none { "spotify:track:${it.spotifyTrackId}" == r.uri } }.map(api::songOf)
+ if (p.type == "liked") {
+ // Spotify's playlist extender refuses Liked Songs: the radios of a few liked songs instead.
+ p.tracks.shuffled().take(3).flatMap { api.getRecommendations(listOf(it.spotifyTrackId)).take(8) }
+ } else runCatching { MyspotiRuntime.api.playlists.recommended(p.uri, limit = 20) }.getOrDefault(emptyList()).map(api::songOf)
+ }.filter { it.spotifyTrackId !in inList }.distinctBy { it.spotifyTrackId }.shuffled()
val shuffled = p.tracks.shuffled().let { list -> first?.let { f -> listOf(f) + (list - f) } ?: list }
val mixed = ArrayList<SongsModel>()
val more = recs.iterator()
@@ -239,6 +243,9 @@ class ContextViewModel(
if (local.size < p.tracks.size)
android.widget.Toast.makeText(app, app.getString(R.string.offline_only_downloaded, local.size, p.tracks.size), android.widget.Toast.LENGTH_SHORT).show()
com.music.spotui.di.LocalPlayer.play(local.map(com.music.spotui.data.offline.OfflineStore::toLocalTrack), at, context = p.name)
+ // The downloads play from the list the user chose: the Wrapped report
+ // starts on that context (playlist/album), like a streamed play.
+ com.music.spotui.data.offline.WrappedSync.contextUri = p.uri.takeIf { it.isNotBlank() }
return
}
state.updateQueue(p.tracks)
@@ -453,7 +460,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
) {
when {
smart -> { SmartShuffle.on.value = null; playerVm.updateShuffleState(false) }
- shuffle && p.type == "playlist" -> {
+ shuffle && (p.type == "playlist" || p.type == "liked") -> {
SmartShuffle.on.value = p.uri
android.widget.Toast.makeText(context, context.getString(R.string.smart_shuffle_on), android.widget.Toast.LENGTH_SHORT).show()
if (isThisContext) vm.playSmart(p, p.tracks.firstOrNull { it.id == currentSongId })
@@ -634,7 +641,8 @@ enum class TrackSort(val label: Int) {
TITLE(R.string.track_sort_title),
ARTIST(R.string.track_sort_artist),
ALBUM(R.string.track_sort_album),
- DURATION(R.string.track_sort_duration);
+ DURATION(R.string.track_sort_duration),
+ ADDED(R.string.track_sort_added);
fun apply(songs: List<SongsModel>): List<SongsModel> {
val text = java.text.Collator.getInstance().apply { strength = java.text.Collator.PRIMARY }
@@ -644,6 +652,8 @@ enum class TrackSort(val label: Int) {
ARTIST -> songs.sortedWith { a, b -> text.compare(a.singer, b.singer).takeIf { it != 0 } ?: text.compare(a.album, b.album) }
ALBUM -> songs.sortedWith { a, b -> text.compare(a.album, b.album).takeIf { it != 0 } ?: text.compare(a.title, b.title) }
DURATION -> songs.sortedBy { it.durationMs }
+ // Newest first; ISO 8601 dates sort as text.
+ ADDED -> songs.sortedByDescending { it.addedAt }
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt
index a279eded..c807638f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt
@@ -79,6 +79,9 @@ fun DownloadsScreen(navController: NavController) {
fun play(index: Int, shuffle: Boolean = false) {
if (tracks.isEmpty()) return
LocalPlayer.play(tracks.map(OfflineStore::toLocalTrack), index, shuffle = shuffle, context = title)
+ // The whole Downloaded list has no Spotify context of its own: each listen
+ // reports under the track's album.
+ com.music.spotui.data.offline.WrappedSync.contextUri = null
}
Box(Modifier.fillMaxSize().background(AppBackground)) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
index e8756027..e2afa73b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
@@ -407,7 +407,6 @@ private fun HomeFeedCard(item: HomeItem, onClick: () -> Unit) {
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)
@Composable
private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () -> Unit) {
- val energy by app.myspoti.power.EnergySettings.state.collectAsStateWithLifecycle()
val name = com.music.spotui.data.api.ProfileCache.name.orEmpty()
val avatar = com.music.spotui.data.api.ProfileCache.imageUrl
// Opened in full: half-open, the sheet and its list both moved under the finger.
@@ -428,31 +427,14 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->
com.music.spotui.ui.components.SupporterBadge(Modifier.padding(start = 10.dp))
}
androidx.compose.material3.HorizontalDivider(color = Color(0xFF3E3E3E), modifier = Modifier.padding(vertical = 8.dp))
- EnergyOptionRow(
- label = stringResource(R.string.energy_saver_title),
- detail = stringResource(R.string.energy_saver_summary),
- checked = energy.manualSaver,
- onChecked = app.myspoti.power.EnergySettings::setSaver,
- )
- EnergyOptionRow(
- label = stringResource(R.string.data_saver_title),
- detail = stringResource(R.string.data_saver_summary),
- checked = com.music.spotui.data.DataSaver.enabled,
- onChecked = com.music.spotui.data.DataSaver::set,
- )
- EnergyOptionRow(
- label = stringResource(R.string.settings_amoled_theme),
- detail = stringResource(R.string.settings_amoled_theme_subtitle),
- checked = energy.blackPreference,
- onChecked = app.myspoti.power.EnergySettings::setBlackBackground,
- )
- EnergyOptionRow(
- label = stringResource(R.string.settings_item_canvas_title),
- detail = stringResource(if (energy.policy.saverEnabled) R.string.energy_saver_summary else R.string.video_settings_canvas_subtitle),
- checked = energy.canvasEnabled && !energy.policy.saverEnabled,
- enabled = !energy.policy.saverEnabled,
- onChecked = app.myspoti.power.EnergySettings::setCanvasEnabled,
- )
+ // Sound quality, downloads, data, battery, display: one page.
+ androidx.compose.foundation.layout.Column(
+ Modifier.fillMaxWidth().clickable { onOpen(com.music.spotui.ui.navigation.Routes.Settings.route) }
+ .padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.settings_title), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(R.string.settings_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
// In-app recap: every listen on this phone, Spotify, downloads and local files.
androidx.compose.foundation.layout.Column(
Modifier.fillMaxWidth().clickable { onOpen(com.music.spotui.ui.navigation.Routes.Recap.route) }
@@ -471,33 +453,7 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->
Text(stringResource(R.string.account_page_title), color = Color.White, fontSize = 16.sp)
Text(stringResource(R.string.account_page_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
}
- LanguageRow()
- // Battery optimization off = music and Connect keep going with the screen off.
val ctx = androidx.compose.ui.platform.LocalContext.current
- var exempt by remember { androidx.compose.runtime.mutableStateOf(app.myspoti.power.BatteryExemption.isExempt(ctx)) }
- androidx.lifecycle.compose.LifecycleEventEffect(androidx.lifecycle.Lifecycle.Event.ON_RESUME) {
- exempt = app.myspoti.power.BatteryExemption.isExempt(ctx)
- }
- EnergyOptionRow(
- label = stringResource(R.string.background_playback_title),
- detail = stringResource(if (exempt) R.string.background_playback_on else R.string.background_playback_off),
- checked = exempt,
- onChecked = {
- if (exempt) ctx.startActivity(android.content.Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
- else app.myspoti.power.BatteryExemption.request(ctx)
- },
- )
- // The hidden Web Player stuck or crashed: rebuild it without leaving the app.
- androidx.compose.foundation.layout.Column(
- Modifier.fillMaxWidth().clickable {
- onDismiss()
- app.myspoti.host.android.MyspotiRuntime.host.reload()
- }.padding(horizontal = 20.dp, vertical = 10.dp),
- ) {
- Text(stringResource(R.string.restart_player_title), color = Color.White, fontSize = 16.sp)
- Text(stringResource(R.string.restart_player_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
- }
- if (com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty()) RemoveDownloadsRow()
// Donations (Ko-fi): always here, never in the way.
androidx.compose.foundation.layout.Column(
Modifier.fillMaxWidth().clickable { com.music.spotui.data.api.SupportReminder.open(ctx) }
@@ -550,103 +506,3 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->
}
-/** "App language": Automatic (French or English) or any language with Spotify's labels. */
-@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
-@Composable
-private fun LanguageRow() {
- val ctx = androidx.compose.ui.platform.LocalContext.current
- val current = remember { com.music.spotui.data.AppLanguage.current(ctx) }
- var picking by remember { androidx.compose.runtime.mutableStateOf(false) }
- val auto = stringResource(R.string.language_auto)
- fun label(tag: String) = if (tag == com.music.spotui.data.AppLanguage.SYSTEM) auto else com.music.spotui.data.AppLanguage.nativeName(tag)
- androidx.compose.foundation.layout.Column(
- Modifier.fillMaxWidth().clickable { picking = true }.padding(horizontal = 20.dp, vertical = 10.dp),
- ) {
- Text(stringResource(R.string.settings_item_app_language_title), color = Color.White, fontSize = 16.sp)
- Text(label(current), color = Color(0xFFB3B3B3), fontSize = 12.sp)
- }
- if (picking) androidx.compose.material3.ModalBottomSheet(
- onDismissRequest = { picking = false },
- containerColor = Color(0xFF282828),
- ) {
- androidx.compose.foundation.lazy.LazyColumn(Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
- item {
- Text(stringResource(R.string.settings_item_app_language_title), color = Color.White, fontSize = 18.sp,
- fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
- Text(stringResource(R.string.language_partial_note), color = Color(0xFFB3B3B3), fontSize = 12.sp,
- modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 8.dp))
- }
- items(com.music.spotui.data.AppLanguage.AVAILABLE.size) { i ->
- val tag = com.music.spotui.data.AppLanguage.AVAILABLE[i]
- val selected = tag == current
- Row(
- verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp).clickable {
- picking = false
- if (!selected) {
- com.music.spotui.data.AppLanguage.apply(ctx, tag)
- // Screens take the new language when the activity is rebuilt.
- generateSequence(ctx) { (it as? android.content.ContextWrapper)?.baseContext }
- .filterIsInstance<android.app.Activity>().firstOrNull()?.recreate()
- }
- }.padding(horizontal = 20.dp, vertical = 8.dp),
- ) {
- androidx.compose.foundation.layout.Column(Modifier.weight(1f)) {
- Text(label(tag), color = if (selected) com.music.spotui.ui.theme.AppAccent else Color.White, fontSize = 16.sp)
- if (tag == com.music.spotui.data.AppLanguage.SYSTEM)
- Text(stringResource(R.string.language_auto_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
- }
- if (selected) androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Default.Check, null, tint = com.music.spotui.ui.theme.AppAccent)
- }
- }
- }
- }
-}
-
-/** "Remove all downloads", with the space they take; asks first, like the official app. */
-@Composable
-private fun RemoveDownloadsRow() {
- val ctx = androidx.compose.ui.platform.LocalContext.current
- var ask by remember { androidx.compose.runtime.mutableStateOf(false) }
- val size = android.text.format.Formatter.formatShortFileSize(ctx, com.music.spotui.data.offline.OfflineStore.totalBytes())
- androidx.compose.foundation.layout.Column(
- Modifier.fillMaxWidth().clickable { ask = true }.padding(horizontal = 20.dp, vertical = 10.dp),
- ) {
- Text(stringResource(R.string.settings_item_remove_downloads_title), color = Color.White, fontSize = 16.sp)
- Text(stringResource(R.string.downloads_size, size), color = Color(0xFFB3B3B3), fontSize = 12.sp)
- }
- if (ask) androidx.compose.material3.AlertDialog(
- onDismissRequest = { ask = false },
- containerColor = Color(0xFF282828),
- title = { Text(stringResource(R.string.settings_storage_remove_downloads_dialog_title), color = Color.White) },
- text = { Text(stringResource(R.string.playlist_entity_remove_download_dialog_description), color = Color(0xFFB3B3B3)) },
- confirmButton = {
- androidx.compose.material3.TextButton(onClick = {
- ask = false
- com.music.spotui.data.offline.OfflineDownloader.removeAll()
- }) { Text(stringResource(R.string.playlist_entity_remove_download_dialog_positive_button), color = com.music.spotui.ui.theme.AppAccent) }
- },
- dismissButton = {
- androidx.compose.material3.TextButton(onClick = { ask = false }) {
- Text(stringResource(R.string.add_to_playlist_button_cancel), color = Color.White)
- }
- },
- )
-}
-
-
-
-@Composable
-private fun EnergyOptionRow(label: String, detail: String, checked: Boolean,
- enabled: Boolean = true, onChecked: (Boolean) -> Unit) {
- Row(verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp)
- .toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChecked)
- .padding(horizontal = 20.dp, vertical = 10.dp)) {
- androidx.compose.foundation.layout.Column(Modifier.weight(1f)) {
- Text(label, color = Color.White, fontSize = 16.sp)
- Text(detail, color = Color(0xFFB3B3B3), fontSize = 12.sp)
- }
- androidx.compose.material3.Switch(checked = checked, enabled = enabled, onCheckedChange = null)
- }
-}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
index 6ff0a528..f51ffd78 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
@@ -772,6 +772,10 @@ private fun AccountSheet(
// Spotify's own account pages (plan, privacy, devices), signed in, in the app.
val context = androidx.compose.ui.platform.LocalContext.current
+ AccountRow(stringResource(R.string.settings_title)) {
+ onDismiss()
+ navController.navigate(com.music.spotui.ui.navigation.Routes.Settings.route)
+ }
AccountRow(stringResource(R.string.account_page_title) + " \u2197") {
onDismiss()
AccountBrowser.open(context, AccountBrowser.ACCOUNT_URL)
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
new file mode 100644
index 00000000..3d110aa3
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -0,0 +1,251 @@
+package com.music.spotui.ui.screens
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.selection.toggleable
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.navigation.NavController
+import app.myspoti.engine.R
+import com.music.spotui.ui.components.DownloadQualityPicker
+import com.music.spotui.ui.components.StreamingQualityPicker
+import com.music.spotui.ui.theme.AppBackground
+
+/**
+ * Settings, on one page: sound quality (streaming and downloads), the lossless source,
+ * data and battery, display, language, and the player's own repair tools.
+ */
+@Composable
+fun SettingsScreen(navController: NavController) {
+ val energy by app.myspoti.power.EnergySettings.state.collectAsStateWithLifecycle()
+ val ctx = androidx.compose.ui.platform.LocalContext.current
+ Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding()) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(4.dp)) {
+ IconButton(onClick = { navController.popBackStack() }) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)
+ }
+ Text(stringResource(R.string.settings_title), color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold)
+ }
+ Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).navigationBarsPadding()) {
+ Section(R.string.settings_section_playback)
+ StreamingQualityPicker()
+ Divider()
+
+ Section(R.string.settings_section_downloads)
+ DownloadQualityPicker()
+ // The lossless source: SpotiFLAC's own servers once verified.
+ Column(
+ Modifier.fillMaxWidth().clickable { navController.navigate(com.music.spotui.ui.navigation.Routes.Spotiflac.route) }
+ .padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.spotiflac_row_title), color = Color.White, fontSize = 16.sp)
+ Text(
+ stringResource(
+ if (com.music.spotui.data.preferences.hasSpotiflacSession(ctx)) R.string.spotiflac_row_on
+ else R.string.spotiflac_row_off,
+ ),
+ color = Color(0xFFB3B3B3), fontSize = 12.sp,
+ )
+ }
+ if (com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty()) RemoveDownloadsRow()
+ Divider()
+
+ Section(R.string.settings_section_data)
+ OptionRow(
+ label = stringResource(R.string.energy_saver_title),
+ detail = stringResource(R.string.energy_saver_summary),
+ checked = energy.manualSaver,
+ onChecked = app.myspoti.power.EnergySettings::setSaver,
+ )
+ OptionRow(
+ label = stringResource(R.string.data_saver_title),
+ detail = stringResource(R.string.data_saver_summary),
+ checked = com.music.spotui.data.DataSaver.enabled,
+ onChecked = com.music.spotui.data.DataSaver::set,
+ )
+ // Battery optimization off = music and Connect keep going with the screen off.
+ var exempt by remember { androidx.compose.runtime.mutableStateOf(app.myspoti.power.BatteryExemption.isExempt(ctx)) }
+ androidx.lifecycle.compose.LifecycleEventEffect(androidx.lifecycle.Lifecycle.Event.ON_RESUME) {
+ exempt = app.myspoti.power.BatteryExemption.isExempt(ctx)
+ }
+ OptionRow(
+ label = stringResource(R.string.background_playback_title),
+ detail = stringResource(if (exempt) R.string.background_playback_on else R.string.background_playback_off),
+ checked = exempt,
+ onChecked = {
+ if (exempt) ctx.startActivity(android.content.Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
+ else app.myspoti.power.BatteryExemption.request(ctx)
+ },
+ )
+ Divider()
+
+ Section(R.string.settings_section_display)
+ OptionRow(
+ label = stringResource(R.string.settings_amoled_theme),
+ detail = stringResource(R.string.settings_amoled_theme_subtitle),
+ checked = energy.blackPreference,
+ onChecked = app.myspoti.power.EnergySettings::setBlackBackground,
+ )
+ OptionRow(
+ label = stringResource(R.string.settings_item_canvas_title),
+ detail = stringResource(if (energy.policy.saverEnabled) R.string.energy_saver_summary else R.string.video_settings_canvas_subtitle),
+ checked = energy.canvasEnabled && !energy.policy.saverEnabled,
+ enabled = !energy.policy.saverEnabled,
+ onChecked = app.myspoti.power.EnergySettings::setCanvasEnabled,
+ )
+ LanguageRow()
+ Divider()
+
+ Section(R.string.settings_section_app)
+ // The hidden Web Player stuck or crashed: rebuild it without leaving the app.
+ Column(
+ Modifier.fillMaxWidth().clickable { app.myspoti.host.android.MyspotiRuntime.host.reload() }
+ .padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.restart_player_title), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(R.string.restart_player_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ Spacer(Modifier.height(96.dp))
+ }
+ }
+}
+
+@Composable
+private fun Section(title: Int) {
+ Text(stringResource(title).uppercase(), color = com.music.spotui.ui.theme.AppAccent, fontSize = 12.sp, fontWeight = FontWeight.Bold,
+ letterSpacing = 1.sp, modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 8.dp))
+}
+
+@Composable
+private fun Divider() = HorizontalDivider(color = Color(0xFF2A2A2A), modifier = Modifier.padding(top = 8.dp))
+
+/** "App language": Automatic (French or English) or any language with Spotify's labels. */
+@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
+@Composable
+private fun LanguageRow() {
+ val ctx = androidx.compose.ui.platform.LocalContext.current
+ val current = remember { com.music.spotui.data.AppLanguage.current(ctx) }
+ var picking by remember { androidx.compose.runtime.mutableStateOf(false) }
+ val auto = stringResource(R.string.language_auto)
+ fun label(tag: String) = if (tag == com.music.spotui.data.AppLanguage.SYSTEM) auto else com.music.spotui.data.AppLanguage.nativeName(tag)
+ androidx.compose.foundation.layout.Column(
+ Modifier.fillMaxWidth().clickable { picking = true }.padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.settings_item_app_language_title), color = Color.White, fontSize = 16.sp)
+ Text(label(current), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ if (picking) androidx.compose.material3.ModalBottomSheet(
+ onDismissRequest = { picking = false },
+ containerColor = Color(0xFF282828),
+ ) {
+ androidx.compose.foundation.lazy.LazyColumn(Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
+ item {
+ Text(stringResource(R.string.settings_item_app_language_title), color = Color.White, fontSize = 18.sp,
+ fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
+ Text(stringResource(R.string.language_partial_note), color = Color(0xFFB3B3B3), fontSize = 12.sp,
+ modifier = Modifier.padding(start = 20.dp, end = 20.dp, bottom = 8.dp))
+ }
+ items(com.music.spotui.data.AppLanguage.AVAILABLE.size) { i ->
+ val tag = com.music.spotui.data.AppLanguage.AVAILABLE[i]
+ val selected = tag == current
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp).clickable {
+ picking = false
+ if (!selected) {
+ com.music.spotui.data.AppLanguage.apply(ctx, tag)
+ // Screens take the new language when the activity is rebuilt.
+ generateSequence(ctx) { (it as? android.content.ContextWrapper)?.baseContext }
+ .filterIsInstance<android.app.Activity>().firstOrNull()?.recreate()
+ }
+ }.padding(horizontal = 20.dp, vertical = 8.dp),
+ ) {
+ androidx.compose.foundation.layout.Column(Modifier.weight(1f)) {
+ Text(label(tag), color = if (selected) com.music.spotui.ui.theme.AppAccent else Color.White, fontSize = 16.sp)
+ if (tag == com.music.spotui.data.AppLanguage.SYSTEM)
+ Text(stringResource(R.string.language_auto_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ if (selected) androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Default.Check, null, tint = com.music.spotui.ui.theme.AppAccent)
+ }
+ }
+ }
+ }
+}
+
+/** "Remove all downloads", with the space they take; asks first, like the official app. */
+@Composable
+private fun RemoveDownloadsRow() {
+ val ctx = androidx.compose.ui.platform.LocalContext.current
+ var ask by remember { androidx.compose.runtime.mutableStateOf(false) }
+ val size = android.text.format.Formatter.formatShortFileSize(ctx, com.music.spotui.data.offline.OfflineStore.totalBytes())
+ androidx.compose.foundation.layout.Column(
+ Modifier.fillMaxWidth().clickable { ask = true }.padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.settings_item_remove_downloads_title), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(R.string.downloads_size, size), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ if (ask) androidx.compose.material3.AlertDialog(
+ onDismissRequest = { ask = false },
+ containerColor = Color(0xFF282828),
+ title = { Text(stringResource(R.string.settings_storage_remove_downloads_dialog_title), color = Color.White) },
+ text = { Text(stringResource(R.string.playlist_entity_remove_download_dialog_description), color = Color(0xFFB3B3B3)) },
+ confirmButton = {
+ androidx.compose.material3.TextButton(onClick = {
+ ask = false
+ com.music.spotui.data.offline.OfflineDownloader.removeAll()
+ }) { Text(stringResource(R.string.playlist_entity_remove_download_dialog_positive_button), color = com.music.spotui.ui.theme.AppAccent) }
+ },
+ dismissButton = {
+ androidx.compose.material3.TextButton(onClick = { ask = false }) {
+ Text(stringResource(R.string.add_to_playlist_button_cancel), color = Color.White)
+ }
+ },
+ )
+}
+
+
+
+@Composable
+private fun OptionRow(label: String, detail: String, checked: Boolean,
+ enabled: Boolean = true, onChecked: (Boolean) -> Unit) {
+ Row(verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp)
+ .toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChecked)
+ .padding(horizontal = 20.dp, vertical = 10.dp)) {
+ androidx.compose.foundation.layout.Column(Modifier.weight(1f)) {
+ Text(label, color = Color.White, fontSize = 16.sp)
+ Text(detail, color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ androidx.compose.material3.Switch(checked = checked, enabled = enabled, onCheckedChange = null)
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt
index d4bdf670..b133bc8f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt
@@ -32,6 +32,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -53,7 +54,9 @@ import com.music.spotui.ui.theme.AppBackground
*/
object Setup {
private const val KEY = "SetupDone"
- fun needed(context: Context) = !context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).getBoolean(KEY, false)
+ /** The permissions step, or the sound quality one (new in 2.0: shown once after the update too). */
+ fun needed(context: Context) = !permissionsDone(context) || !com.music.spotui.data.preferences.isQualityChosen(context)
+ fun permissionsDone(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).getBoolean(KEY, false)
fun done(context: Context) = context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE).edit().putBoolean(KEY, true).apply()
}
@@ -61,12 +64,21 @@ private fun granted(context: Context, permission: String) =
context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
@Composable
-fun SetupScreen(onDone: () -> Unit) {
+fun SetupScreen(onDone: () -> Unit, onSpotiflac: () -> Unit = {}) {
val context = LocalContext.current
// Re-read when coming back from a system dialog or the settings.
var tick by remember { mutableIntStateOf(0) }
LaunchedEffect(Unit) { while (true) { kotlinx.coroutines.delay(800); tick++ } }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { tick++ }
+ // First the sound quality, then the permissions (skipped when done before an update).
+ var qualityStep by remember { mutableStateOf(!com.music.spotui.data.preferences.isQualityChosen(context)) }
+ if (qualityStep) {
+ QualityStep(onNext = {
+ com.music.spotui.data.preferences.setQualityChosen(context)
+ if (Setup.permissionsDone(context)) onDone() else qualityStep = false
+ })
+ return
+ }
Column(
Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding()
@@ -93,6 +105,12 @@ fun SetupScreen(onDone: () -> Unit) {
stringResource(R.string.setup_battery_title), stringResource(R.string.setup_battery_detail),
BatteryExemption.isExempt(context),
) { BatteryExemption.request(context) }
+ // Lossless downloads need SpotiFLAC's one-off verification (the quality toggle
+ // lives in Settings); not verified yet, the lossless source stays OFF.
+ if (com.music.spotui.data.preferences.getDownloadQuality(context) != com.music.spotui.data.preferences.DownloadQuality.OFF) SetupRow(
+ stringResource(R.string.setup_spotiflac_title), stringResource(R.string.setup_spotiflac_detail),
+ com.music.spotui.data.preferences.hasSpotiflacSession(context),
+ ) { onSpotiflac() }
Spacer(Modifier.height(12.dp))
Button(
onClick = { Setup.done(context); onDone() },
@@ -102,6 +120,28 @@ fun SetupScreen(onDone: () -> Unit) {
}
}
+/** Onboarding, step one: how Myspoti streams and saves music (changed later in Settings). */
+@Composable
+private fun QualityStep(onNext: () -> Unit) {
+ Column(
+ Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding()
+ .verticalScroll(rememberScrollState()).padding(vertical = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Text(stringResource(R.string.setup_quality_title), color = Color.White, fontSize = 26.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp))
+ Text(stringResource(R.string.setup_quality_subtitle), color = Color(0xFFB3B3B3), fontSize = 14.sp,
+ modifier = Modifier.padding(horizontal = 20.dp))
+ com.music.spotui.ui.components.StreamingQualityPicker(Modifier.padding(top = 8.dp))
+ com.music.spotui.ui.components.DownloadQualityPicker()
+ Button(
+ onClick = onNext,
+ colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).height(50.dp),
+ ) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }
+ }
+}
+
@Composable
private fun SetupRow(title: String, detail: String, on: Boolean, onEnable: () -> Unit) {
Row(
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
new file mode 100644
index 00000000..3bfc9f60
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SpotiflacScreen.kt
@@ -0,0 +1,267 @@
+package com.music.spotui.ui.screens
+
+/*
+ * Ported from Spotui's SpotiflacVerifyScreen (https://github.com/Spotui/Spotui), GPL-3.0,
+ * and adapted to Myspoti (own theme, strings, navigation).
+ */
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.webkit.CookieManager
+import android.webkit.WebResourceRequest
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+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
+ * service's own hosted challenge page (the user solves the Turnstile themselves)
+ * → redirect with a grant → exchange the grant for a signing session.
+ *
+ * The app only loads the page and catches the redirect. The session is what gives
+ * the lossless (FLAC) downloads their most reliable source. With a session the
+ * screen shows the status; without it the WebView verification runs.
+ */
+@SuppressLint("SetJavaScriptEnabled")
+@Composable
+fun SpotiflacScreen(onClose: () -> Unit) {
+ val context = LocalContext.current
+ 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)) }
+ var message by remember { mutableStateOf("") }
+ var done by remember { mutableStateOf(false) }
+ val leave: () -> Unit = onClose
+
+ 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)) } }
+ }
+
+ fun finish(grant: String) = scope.launch {
+ message = res(R.string.spotiflac_session_creating)
+ 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
+ }
+ if (ok) {
+ 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
+ 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()
+ }
+ if (challenge == null) {
+ message = res(R.string.spotiflac_verify_start_failed)
+ return@LaunchedEffect
+ }
+ message = ""
+ webView?.loadUrl("$challenge&cb=" + URLEncoder.encode("$CALLBACK?state=$state", "UTF-8"))
+ // Never leave the user on a page that silently stalled.
+ delay(180_000)
+ if (!done && !verified) message = res(R.string.spotiflac_verify_timeout)
+ }
+
+ if (verified) {
+ SpotiflacStatusScreen(leave)
+ return
+ }
+
+ Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
+ AndroidView(
+ modifier = Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()
+ .padding(top = 40.dp, bottom = 56.dp),
+ factory = { ctx ->
+ CookieManager.getInstance().setAcceptCookie(true)
+ WebView(ctx).apply {
+ webView = this
+ layoutParams = android.view.ViewGroup.LayoutParams(
+ android.view.ViewGroup.LayoutParams.MATCH_PARENT,
+ android.view.ViewGroup.LayoutParams.MATCH_PARENT,
+ )
+ CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
+ settings.javaScriptEnabled = true
+ settings.domStorageEnabled = true
+ webViewClient = object : WebViewClient() {
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+ val uri = request.url
+ if (!uri.toString().startsWith(CALLBACK)) return false
+ val grant = uri.getQueryParameter("grant").orEmpty()
+ if (uri.getQueryParameter("state") != state || grant.isBlank()) {
+ message = res(R.string.spotiflac_verify_rejected)
+ } else {
+ finish(grant)
+ }
+ return true
+ }
+ }
+ }
+ },
+ )
+
+ if (message.isNotEmpty()) {
+ Text(
+ message,
+ color = Color.White,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
+ )
+ }
+
+ Row(
+ modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
+ .navigationBarsPadding().height(56.dp).background(Color.Black),
+ horizontalArrangement = Arrangement.SpaceEvenly,
+ ) {
+ TextButton(onClick = { attempt++ }) { Text(stringResource(R.string.retry), color = Color.White) }
+ TextButton(onClick = leave) { Text(stringResource(R.string.spotiflac_skip), color = Color.White) }
+ }
+
+ Box(
+ modifier = Modifier.fillMaxWidth().statusBarsPadding().height(40.dp).background(Color.Black),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ stringResource(R.string.spotiflac_verify_title),
+ color = Color(0xFF00C7B7),
+ fontWeight = FontWeight.Bold,
+ fontSize = 14.sp,
+ )
+ }
+ }
+}
+
+/** The status page when a session exists: state, expiry, forget. */
+@Composable
+private fun SpotiflacStatusScreen(onClose: () -> Unit) {
+ val context = LocalContext.current
+ Column(
+ Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding().padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp),
+ ) {
+ 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,
+ )
+ Button(
+ onClick = {
+ com.music.spotui.data.preferences.clearSpotiflacSession(context)
+ onClose()
+ },
+ colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1E1E1E), contentColor = Color.White),
+ shape = RoundedCornerShape(24.dp),
+ ) { Text(stringResource(R.string.spotiflac_forget)) }
+ Button(
+ onClick = onClose,
+ colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),
+ modifier = Modifier.fillMaxWidth().height(50.dp),
+ ) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }
+ }
+}
+
+// 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()
+ }
+}
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 f7d8d5e9..59a60fd7 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -56,7 +56,7 @@
<string name="local_files_none_subtitle">Aucun fichier audio lisible n\'a été trouvé sur cet appareil. Ils apparaîtront ici dès qu\'il y en aura.</string>
<string name="downloads_empty_title">Téléchargez pour écouter hors connexion</string>
<string name="downloads_empty_subtitle">Touchez Télécharger dans le menu d\'un titre, ou le bouton de téléchargement d\'un album ou d\'une playlist.</string>
- <string name="downloads_source">Audio de YouTube Music, vérifié sur l\'enregistrement original. Gardé uniquement dans Myspoti.</string>
+ <string name="downloads_source">FLAC sans perte, vérifié avec l\'enregistrement original. Gardé dans Myspoti uniquement.</string>
<string name="downloads_size">%1$s sur ce téléphone</string>
<string name="download_unavailable">Aucun enregistrement correspondant trouvé</string>
<string name="download_retry">Réessayer</string>
@@ -69,7 +69,7 @@
<string name="browse_workout">Sport</string>
<string name="browse_dance_electronic">Dance/Électro</string>
<string name="language_auto">Automatique</string>
- <string name="language_auto_detail">Français si le téléphone est en français, sinon anglais</string>
+ <string name="language_auto_detail">La langue du téléphone quand Myspoti l\'a (anglais, français, italien), sinon l\'anglais</string>
<string name="language_partial_note">Autres langues : les libellés de Spotify sont traduits, les textes de Myspoti restent en anglais.</string>
<string name="restart_player_title">Redémarrer le lecteur</string>
<string name="restart_player_detail">Si la musique ne répond plus : recharge le lecteur Spotify</string>
@@ -188,4 +188,57 @@
<string name="local_folders_detail">Choisis les dossiers affichés dans Fichiers locaux. Les applis de messagerie et les enregistrements sont masqués au départ.</string>
<string name="smart_shuffle_title">Lecture aléatoire intelligente</string>
<string name="smart_shuffle_on">Aléatoire intelligent : des recommandations Spotify se glissent dans la playlist mélangée.</string>
+ <string name="track_sort_added">Date d\'ajout</string>
+ <!-- Téléchargements lossless (SpotiFLAC) -->
+ <string name="spotiflac_row_title">Téléchargements lossless (FLAC)</string>
+ <string name="spotiflac_row_on">Vérifié — Myspoti passe par les serveurs de SpotiFLAC.</string>
+ <string name="spotiflac_row_off">Non vérifié — appuie pour faire la vérification unique.</string>
+ <string name="spotiflac_verify_title">Vérification SpotiFLAC</string>
+ <string name="spotiflac_verify_start_failed">Impossible de démarrer la vérification. Appuie sur Réessayer ou reviens plus tard.</string>
+ <string name="spotiflac_verify_timeout">La vérification a expiré. Appuie sur Réessayer ou Passer pour le moment.</string>
+ <string name="spotiflac_verify_rejected">La vérification a été refusée. Appuie sur Réessayer ou Passer pour le moment.</string>
+ <string name="spotiflac_session_ok">Session SpotiFLAC enregistrée</string>
+ <string name="spotiflac_session_creating">Création de la session sécurisée…</string>
+ <string name="spotiflac_session_failed">Impossible de finir la vérification. Appuie sur Réessayer ou Passer pour le moment.</string>
+ <string name="spotiflac_skip">Passer pour le moment</string>
+ <string name="retry">Réessayer</string>
+ <string name="spotiflac_status_title">SpotiFLAC</string>
+ <string name="spotiflac_status_verified">Tu es vérifié : les téléchargements passent par les serveurs de SpotiFLAC, la source lossless la plus fiable. Seule cette session est utilisée — pas de compte, rien d\'autre gardé.</string>
+ <string name="spotiflac_session_expires">Session valide jusqu\'au %1$s</string>
+ <string name="spotiflac_forget">Oublier cette session</string>
+ <string name="lossless_hires_title">Téléchargements hi-res (24 bits)</string>
+ <string name="lossless_hires_detail">Un titre gardé en 24 bits hi-res quand la source l\'a. Les fichiers font environ trois fois la taille d\'un CD qualité.</string>
+ <string name="setup_spotiflac_title">Téléchargements lossless (FLAC)</string>
+ <string name="setup_spotiflac_detail">Vérifie une fois avec SpotiFLAC pour que les téléchargements passent par ses serveurs lossless.</string>
+ <string name="settings_title">Réglages</string>
+ <string name="settings_detail">Qualité du son, téléchargements, données, batterie et langue</string>
+ <string name="settings_section_playback">Lecture</string>
+ <string name="settings_section_downloads">Téléchargements</string>
+ <string name="settings_section_data">Données et batterie</string>
+ <string name="settings_section_display">Affichage et langue</string>
+ <string name="settings_section_app">Application</string>
+ <string name="quality_streaming_title">Qualité du streaming</string>
+ <string name="quality_streaming_detail">Ce que le lecteur diffuse depuis Internet.</string>
+ <string name="quality_streaming_auto">Automatique</string>
+ <string name="quality_streaming_auto_detail">S\'adapte à votre connexion</string>
+ <string name="quality_streaming_low">La plus basse</string>
+ <string name="quality_streaming_low_detail">24 kbit/s, le minimum possible : consomme le moins de données</string>
+ <string name="quality_streaming_normal">Normale</string>
+ <string name="quality_streaming_normal_detail">96 kbit/s, bon équilibre entre son et données</string>
+ <string name="quality_streaming_high">Élevée</string>
+ <string name="quality_download_title">Qualité des téléchargements</string>
+ <string name="quality_download_detail">Comment les titres sont enregistrés pour l\'écoute hors ligne.</string>
+ <string name="quality_download_off">Désactivés</string>
+ <string name="quality_download_off_detail">Aucun téléchargement</string>
+ <string name="quality_download_cd">FLAC, qualité CD</string>
+ <string name="quality_download_cd_detail">Sans perte 16 bits, environ 30 Mo par titre</string>
+ <string name="quality_download_hires">FLAC Hi-Res</string>
+ <string name="quality_download_hires_detail">24 bits quand il existe, fichiers environ trois fois plus lourds</string>
+ <string name="setup_quality_title">Qualité du son</string>
+ <string name="setup_quality_subtitle">Choisissez comment Myspoti lit et enregistre votre musique. Vous pourrez le changer plus tard dans les Réglages.</string>
+ <string name="downloads_off_toast">Les téléchargements sont désactivés. Activez-les dans les Réglages.</string>
+ <string name="quality_streaming_high_detail">160 kbit/s, le meilleur son</string>
+ <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>
</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
new file mode 100644
index 00000000..4f841c85
--- /dev/null
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -0,0 +1,244 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Myspoti's own texts, Italian. -->
+<resources>
+ <string name="welcome_tagline">La tua musica, con testi sincronizzati e video musicali ufficiali.</string>
+ <string name="welcome_login">Accedi con Spotify</string>
+ <string name="welcome_privacy">Accedi dalla pagina di Spotify. Myspoti non vede mai la tua password.</string>
+ <string name="crash_heading">Myspoti ha smesso di funzionare</string>
+ <string name="crash_explanation">Qualcosa è andato storto. Riavvia l\'app; se succede di nuovo, copia il rapporto e condividilo in una issue su GitHub.</string>
+ <string name="crash_restart_app">Riavvia Myspoti</string>
+ <string name="crash_copy_report">Copia il rapporto</string>
+ <string name="crash_report_copied">Rapporto copiato</string>
+ <string name="remove_from_liked">Rimuovi dai Brani che ti piacciono</string>
+ <string name="repeat_on">Ripeti: attivo</string>
+ <string name="repeat_one">Ripeti brano</string>
+ <string name="repeat_off">Ripeti: disattivo</string>
+ <string name="headphones">Cuffie</string>
+ <string name="listen_on">Ascolta su</string>
+ <string name="no_devices">Nessun dispositivo trovato</string>
+ <string name="sleep_minutes">%1$d minuti</string>
+ <string name="playing_on">In riproduzione su:\u0020</string>
+ <string name="next_in_queue">Prossimi in coda</string>
+ <string name="next_from">Prossimi da: %1$s</string>
+ <string name="next_up">A seguire</string>
+ <string name="clear_queue">Svuota la coda</string>
+ <string name="my_playlist">La mia playlist</string>
+ <string name="playlist_name">Nome della playlist</string>
+ <string name="loading_playlists">Caricamento delle playlist…</string>
+ <string name="couldnt_load">Impossibile caricare %1$s</string>
+ <string name="nothing_here">Ancora niente qui</string>
+ <string name="album_not_found">Album non trovato</string>
+ <string name="liked_song">Brano che ti piace</string>
+ <string name="verified_artist">Artista verificato</string>
+ <string name="lyrics_share">Condividi il testo</string>
+ <string name="lyrics_extra_title">Altre fonti per i testi</string>
+ <string name="lyrics_extra_summary">Apple Music (parola per parola), NetEase e Genius, quando Spotify non ha il testo</string>
+ <string name="lyrics_reload">Ricarica il testo</string>
+ <string name="lyrics_fullscreen">Apri il testo a schermo intero</string>
+ <string name="browse_all">Sfoglia tutto</string>
+ <string name="home_error">Impossibile caricare la Home.\nControlla la connessione e riprova.</string>
+ <string name="home_retry">Riprova</string>
+ <string name="home_empty">Ancora niente da mostrare.</string>
+ <string name="spotify_account">Account Spotify</string>
+ <string name="spotify_user">Utente Spotify</string>
+ <string name="list_view">Mostra come elenco</string>
+ <string name="grid_view">Mostra come griglia</string>
+ <string name="library_error">Impossibile caricare la tua Libreria</string>
+ <string name="library_empty">La tua Libreria è vuota</string>
+ <string name="background_playback_title">Riproduzione in background</string>
+ <string name="background_playback_on">L\'ottimizzazione della batteria è disattivata: la musica e Spotify Connect continuano a schermo spento.</string>
+ <string name="background_playback_off">Disattiva l\'ottimizzazione della batteria così Android non mette in pausa l\'app in background.</string>
+ <string name="crossfade_summary">Sfuma la fine di un brano e l\'inizio del successivo (senza sovrapposizione). Solo su questo telefono.</string>
+ <plurals name="local_files_count">
+ <item quantity="one">%d brano</item>
+ <item quantity="other">%d brani</item>
+ </plurals>
+ <string name="local_files_none_subtitle">Non abbiamo trovato file audio riproducibili su questo dispositivo. Quando ce ne saranno, compariranno qui.</string>
+ <string name="downloads_empty_title">Scarica per ascoltare offline</string>
+ <string name="downloads_empty_subtitle">Tocca Scarica nel menu di un brano, o il pulsante di download di un album o di una playlist.</string>
+ <string name="downloads_source">FLAC senza perdita, verificato con la registrazione originale. Conservato solo dentro Myspoti.</string>
+ <string name="downloads_size">%1$s su questo telefono</string>
+ <string name="download_unavailable">Nessuna registrazione corrispondente trovata</string>
+ <string name="download_retry">Riprova</string>
+ <string name="download_cancel">Annulla il download</string>
+ <string name="not_signed_in">Sei disconnesso da Spotify. Accedi di nuovo per vedere questo contenuto.</string>
+ <string name="artist_not_found">Artista non trovato</string>
+ <string name="playlist_not_found">Playlist non trovata</string>
+ <string name="browse_new_releases">Nuove uscite</string>
+ <string name="browse_charts">Classifiche</string>
+ <string name="browse_workout">Allenamento</string>
+ <string name="browse_dance_electronic">Dance/Elettronica</string>
+ <string name="language_auto">Automatica</string>
+ <string name="language_auto_detail">La lingua del telefono quando Myspoti ce l\'ha (inglese, francese, italiano), altrimenti l\'inglese</string>
+ <string name="language_partial_note">Altre lingue: le etichette di Spotify sono tradotte, i testi di Myspoti restano in inglese.</string>
+ <string name="restart_player_title">Riavvia il lettore</string>
+ <string name="restart_player_detail">Se la musica non risponde più: ricarica il lettore di Spotify</string>
+ <string name="local_playlist_subtitle">Su questo dispositivo</string>
+ <string name="local_playlist_new">Playlist su questo dispositivo</string>
+ <string name="local_added_section">Aggiunti su questo dispositivo</string>
+ <string name="local_add_note">I file del telefono restano sul telefono: Spotify non può riceverli.</string>
+ <string name="local_rename">Rinomina</string>
+ <string name="local_delete_playlist">Elimina la playlist</string>
+ <string name="local_added_to">Aggiunto a %1$s</string>
+ <string name="folder_create_failed">Impossibile creare la cartella</string>
+ <string name="local_playlist_empty">Aggiungi brani dai File locali con il loro pulsante +.</string>
+ <string name="playlist_change_refused">Spotify ha rifiutato la modifica a questa playlist</string>
+ <string name="download_kept_by_list">Ancora scaricato: una playlist scaricata lo contiene</string>
+ <string name="support_title">Sostieni Myspoti</string>
+ <string name="support_body">Myspoti è gratuito, senza pubblicità, e fatto nel mio tempo libero. Se ti piace, una piccola donazione aiuta a farlo andare avanti.</string>
+ <string name="support_action">Sostieni su Ko-fi</string>
+ <string name="support_decline">No grazie</string>
+ <string name="support_row_detail">Una piccola donazione su Ko-fi aiuta a far andare avanti l\'app</string>
+ <string name="supporter_perks_title">Vantaggi per i sostenitori</string>
+ <string name="supporter_perks_detail">Colore principale, icona dell\'app e un badge, per dire grazie</string>
+ <string name="supporter_perks_locked">Sbloccati sostenendo Myspoti. Ci fidiamo della tua parola: niente viene controllato.</string>
+ <string name="supporter_i_supported">Ho sostenuto Myspoti</string>
+ <string name="supporter_how">Come l\'hai sostenuto?</string>
+ <string name="supporter_once">Una donazione</string>
+ <string name="supporter_monthly">Ogni mese</string>
+ <string name="supporter_badge">Sostenitore</string>
+ <string name="supporter_thanks_title">Grazie per il tuo sostegno!</string>
+ <string name="supporter_thanks_body">Se Myspoti ti è ancora utile, una nuova piccola donazione aiuta a farlo andare avanti.</string>
+ <string name="support_again">Sostieni di nuovo</string>
+ <string name="supporter_accent">Colore principale</string>
+ <string name="supporter_icon">Icona dell\'app</string>
+ <string name="supporter_icon_note">Quando l\'icona cambia, il collegamento nella schermata Home può sparire: l\'app resta nell\'elenco delle app.</string>
+ <string name="supporter_monthly_switch">Sostengo ogni mese (niente più promemoria)</string>
+ <string name="color_green">Verde</string>
+ <string name="color_blue">Blu</string>
+ <string name="color_purple">Viola</string>
+ <string name="color_pink">Rosa</string>
+ <string name="color_orange">Arancione</string>
+ <string name="about_detail">Versione, community Discord, codice sorgente</string>
+ <string name="about_discord">Discord</string>
+ <string name="about_discord_detail">Novità, aiuto e idee: unisciti alla community</string>
+ <string name="about_github">Codice sorgente</string>
+ <string name="about_github_detail">Versioni, issue e codice su GitHub</string>
+ <string name="about_free">Gratuito, open source e senza pubblicità. Non affiliato a Spotify.</string>
+ <string name="library_reorder_hint">Tieni premuta una playlist, poi trascinala per spostarla</string>
+ <string name="library_reorder_reset">Torna all\'ordine di Spotify</string>
+ <string name="song_radio_failed">Impossibile aprire la radio di questo brano</string>
+ <string name="local_files_find_hint">Cerca nei File locali</string>
+ <string name="data_saver_title">Risparmio dati</string>
+ <string name="data_saver_summary">Con i dati mobili, Myspoti non usa dati: si riproducono solo i brani scaricati e i File locali</string>
+ <string name="data_saver_blocked">Risparmio dati: con i dati mobili si riproducono solo i brani scaricati e i File locali</string>
+ <string name="new_releases_followed">Dagli artisti che segui</string>
+ <string name="new_releases_latest">Ultime uscite</string>
+ <string name="your_episodes_title">I tuoi episodi</string>
+ <string name="your_episodes_empty">Gli episodi che salvi compaiono qui.</string>
+ <string name="recap_title">Il tuo riepilogo</string>
+ <string name="recap_month">30 giorni</string>
+ <string name="recap_year">12 mesi</string>
+ <string name="recap_all">Sempre</string>
+ <string name="recap_minutes">%1$d minuti</string>
+ <string name="recap_listens">%1$d ascolti</string>
+ <string name="recap_sources">Spotify %1$d min • Download %2$d min • File locali %3$d min</string>
+ <string name="recap_empty">Ascolta per un po\': i tuoi brani e artisti preferiti compariranno qui.</string>
+ <string name="recap_plays">%1$d riproduzioni</string>
+ <string name="recap_top_tracks">Brani più ascoltati</string>
+ <string name="recap_top_artists">Artisti più ascoltati</string>
+ <string name="recap_top_albums">Album più ascoltati</string>
+ <string name="recap_private_note">Conta tutto ciò che è stato riprodotto in Myspoti (Spotify, download, file locali). Resta su questo telefono e non viene mai inviato a Spotify.</string>
+ <string name="recap_detail">I tuoi ascolti, download e file locali inclusi</string>
+ <string name="track_credits">Crediti</string>
+ <string name="exclude_taste">Escludi dal tuo profilo dei gusti</string>
+ <string name="include_taste">Includi nel tuo profilo dei gusti</string>
+ <string name="playback_speed">Velocità di riproduzione</string>
+ <string name="recommended_songs">Brani consigliati</string>
+ <string name="jam_title">Jam</string>
+ <string name="jam_restricted">Spotify riserva l\'avvio di una Jam agli account Premium. Puoi comunque unirti a una con un link.</string>
+ <string name="jam_join">Unisciti a una Jam</string>
+ <string name="jam_join_hint">Incolla il link di invito</string>
+ <string name="jam_leave">Esci dalla Jam</string>
+ <string name="jam_members">%1$d persone in ascolto</string>
+ <string name="pin">Fissa</string>
+ <string name="unpin">Rimuovi dai fissati</string>
+ <string name="jam_start">Avvia una Jam</string>
+ <string name="jam_invite">Condividi il link di invito</string>
+ <string name="jam_failed">Spotify ha rifiutato questa Jam</string>
+ <string name="jam_scan">Scansiona il codice QR di una Jam</string>
+ <string name="beta_logs_title">Log degli ultimi %1$d minuti</string>
+ <string name="beta_logs_copy">Copia</string>
+ <string name="beta_logs_copied">Log copiati</string>
+ <string name="beta_logs_share">Condividi</string>
+ <string name="beta_logs_close">Chiudi</string>
+ <string name="widget_description">In riproduzione, con i pulsanti play e salta</string>
+ <string name="widget_previous">Precedente</string>
+ <string name="widget_next">Successivo</string>
+ <string name="widget_play_pause">Riproduci o metti in pausa</string>
+ <string name="offline_only_downloaded">Offline: si riproducono solo i %1$d brani scaricati su %2$d</string>
+ <string name="track_sort_title">Titolo</string>
+ <string name="track_sort_artist">Artista</string>
+ <string name="track_sort_album">Album</string>
+ <string name="track_sort_duration">Durata</string>
+ <string name="setup_title">Configura Myspoti</string>
+ <string name="setup_subtitle">Consenti ciò che vuoi; potrai cambiarlo più tardi nelle impostazioni del telefono.</string>
+ <string name="setup_notifications_title">Notifiche</string>
+ <string name="setup_notifications_detail">Controlli sulla schermata di blocco e nel pannello delle notifiche</string>
+ <string name="setup_local_title">Musica locale</string>
+ <string name="setup_local_detail">Riproduci i file musicali salvati sul telefono</string>
+ <string name="setup_bluetooth_title">Bluetooth</string>
+ <string name="setup_bluetooth_detail">Mostra nel lettore il nome delle tue cuffie o del tuo altoparlante</string>
+ <string name="setup_battery_title">Batteria senza limiti</string>
+ <string name="setup_battery_detail">La musica continua a schermo spento</string>
+ <string name="setup_enable">Consenti</string>
+ <string name="setup_continue">Continua</string>
+ <string name="local_folders_button">Cartelle</string>
+ <string name="local_folders_title">Cartelle</string>
+ <string name="local_folders_detail">Scegli le cartelle mostrate nei File locali. App di messaggistica e registrazioni partono nascoste.</string>
+ <string name="smart_shuffle_title">Riproduzione casuale smart</string>
+ <string name="smart_shuffle_on">Riproduzione casuale smart: i consigli di Spotify si uniscono alla playlist in ordine casuale.</string>
+ <string name="track_sort_added">Data di aggiunta</string>
+ <!-- Lossless (SpotiFLAC) downloads -->
+ <string name="spotiflac_row_title">Download senza perdita (FLAC)</string>
+ <string name="spotiflac_row_on">Verificato — Myspoti usa i server di SpotiFLAC.</string>
+ <string name="spotiflac_row_off">Non verificato — tocca per completare il controllo una tantum.</string>
+ <string name="spotiflac_verify_title">Verifica SpotiFLAC</string>
+ <string name="spotiflac_verify_start_failed">Impossibile avviare la verifica. Tocca Riprova o torna più tardi.</string>
+ <string name="spotiflac_verify_timeout">Verifica scaduta. Tocca Riprova o Salta per ora.</string>
+ <string name="spotiflac_verify_rejected">La verifica è stata rifiutata. Tocca Riprova o Salta per ora.</string>
+ <string name="spotiflac_session_ok">Sessione SpotiFLAC salvata</string>
+ <string name="spotiflac_session_creating">Creazione della sessione sicura…</string>
+ <string name="spotiflac_session_failed">Impossibile completare la verifica. Tocca Riprova o Salta per ora.</string>
+ <string name="spotiflac_skip">Salta per ora</string>
+ <string name="retry">Riprova</string>
+ <string name="spotiflac_status_title">SpotiFLAC</string>
+ <string name="spotiflac_status_verified">Sei verificato: i download passano dai server di SpotiFLAC, la fonte senza perdita più affidabile. Viene usata solo questa sessione — nessun account, nient\'altro salvato.</string>
+ <string name="spotiflac_session_expires">Sessione valida fino al %1$s</string>
+ <string name="spotiflac_forget">Dimentica questa sessione</string>
+ <string name="lossless_hires_title">Download hi-res (24 bit)</string>
+ <string name="lossless_hires_detail">Un brano salvato in hi-res a 24 bit quando la fonte lo ha. I file sono circa tre volte più grandi della qualità CD.</string>
+ <string name="setup_spotiflac_title">Download senza perdita (FLAC)</string>
+ <string name="setup_spotiflac_detail">Verifica una volta con SpotiFLAC così i download arrivano dai suoi server senza perdita.</string>
+ <string name="settings_title">Impostazioni</string>
+ <string name="settings_detail">Qualità audio, download, dati, batteria e lingua</string>
+ <string name="settings_section_playback">Riproduzione</string>
+ <string name="settings_section_downloads">Download</string>
+ <string name="settings_section_data">Dati e batteria</string>
+ <string name="settings_section_display">Aspetto e lingua</string>
+ <string name="settings_section_app">App</string>
+ <string name="quality_streaming_title">Qualità dello streaming</string>
+ <string name="quality_streaming_detail">Ciò che il lettore trasmette da Internet.</string>
+ <string name="quality_streaming_auto">Automatica</string>
+ <string name="quality_streaming_auto_detail">Si adatta alla tua connessione</string>
+ <string name="quality_streaming_low">Minima</string>
+ <string name="quality_streaming_low_detail">24 kbit/s, la più bassa possibile: usa meno dati</string>
+ <string name="quality_streaming_normal">Normale</string>
+ <string name="quality_streaming_normal_detail">96 kbit/s, buon equilibrio tra suono e dati</string>
+ <string name="quality_streaming_high">Alta</string>
+ <string name="quality_download_title">Qualità dei download</string>
+ <string name="quality_download_detail">Come vengono salvati i brani per l\'ascolto offline.</string>
+ <string name="quality_download_off">Disattivati</string>
+ <string name="quality_download_off_detail">Nessun download</string>
+ <string name="quality_download_cd">FLAC, qualità CD</string>
+ <string name="quality_download_cd_detail">Senza perdita a 16 bit, circa 30 MB per brano</string>
+ <string name="quality_download_hires">FLAC Hi-Res</string>
+ <string name="quality_download_hires_detail">24 bit quando esiste, file circa tre volte più grandi</string>
+ <string name="setup_quality_title">Qualità audio</string>
+ <string name="setup_quality_subtitle">Scegli come Myspoti riproduce e salva la tua musica. Potrai cambiarlo più tardi nelle Impostazioni.</string>
+ <string name="downloads_off_toast">I download sono disattivati. Attivali nelle Impostazioni.</string>
+ <string name="quality_streaming_high_detail">160 kbit/s, il suono migliore</string>
+ <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>
+</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 4f9a6674..79a376d8 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
-<!-- Myspoti's own texts (English default, French). -->
+<!-- Myspoti's own texts (English default, French, Italian). -->
<resources>
<string name="welcome_tagline">Your music, with synced lyrics and official music videos.</string>
<string name="welcome_login">Log in with Spotify</string>
@@ -56,7 +56,7 @@
<string name="local_files_none_subtitle">We didn\'t find any playable audio files on this device. When there are some, they\'ll show up here.</string>
<string name="downloads_empty_title">Download to listen offline</string>
<string name="downloads_empty_subtitle">Tap Download in a song\'s menu, or the download button of an album or playlist.</string>
- <string name="downloads_source">Audio from YouTube Music, checked against the original recording. Kept inside Myspoti only.</string>
+ <string name="downloads_source">Lossless FLAC, checked against the original recording. Kept inside Myspoti only.</string>
<string name="downloads_size">%1$s on this phone</string>
<string name="download_unavailable">No matching recording found</string>
<string name="download_retry">Try again</string>
@@ -69,7 +69,7 @@
<string name="browse_workout">Workout</string>
<string name="browse_dance_electronic">Dance/Electronic</string>
<string name="language_auto">Automatic</string>
- <string name="language_auto_detail">French on a French phone, English otherwise</string>
+ <string name="language_auto_detail">Your phone\'s language when Myspoti has it (English, French, Italian), English otherwise</string>
<string name="language_partial_note">Other languages: Spotify\'s own labels are translated, Myspoti\'s texts stay in English.</string>
<string name="restart_player_title">Restart the player</string>
<string name="restart_player_detail">If the music stops responding: reloads Spotify\'s player</string>
@@ -188,4 +188,57 @@
<string name="local_folders_detail">Choose the folders shown in Local Files. Messaging apps and recordings start hidden.</string>
<string name="smart_shuffle_title">Smart shuffle</string>
<string name="smart_shuffle_on">Smart shuffle: Spotify recommendations join the shuffled playlist.</string>
+ <string name="track_sort_added">Date added</string>
+ <!-- Lossless (SpotiFLAC) downloads -->
+ <string name="spotiflac_row_title">Lossless downloads (FLAC)</string>
+ <string name="spotiflac_row_on">Verified — Myspoti uses SpotiFLAC\'s own servers.</string>
+ <string name="spotiflac_row_off">Not verified — tap to solve the one-off check.</string>
+ <string name="spotiflac_verify_title">SpotiFLAC verification</string>
+ <string name="spotiflac_verify_start_failed">Could not start verification. Tap Retry or come back later.</string>
+ <string name="spotiflac_verify_timeout">Verification timed out. Tap Retry or Skip for now.</string>
+ <string name="spotiflac_verify_rejected">Verification was rejected. Tap Retry or Skip for now.</string>
+ <string name="spotiflac_session_ok">SpotiFLAC session saved</string>
+ <string name="spotiflac_session_creating">Creating secure session…</string>
+ <string name="spotiflac_session_failed">Could not finish verification. Tap Retry or Skip for now.</string>
+ <string name="spotiflac_skip">Skip for now</string>
+ <string name="retry">Retry</string>
+ <string name="spotiflac_status_title">SpotiFLAC</string>
+ <string name="spotiflac_status_verified">You are verified: downloads go through SpotiFLAC\'s own servers, the most reliable lossless source. Only this session is used — no account, nothing else stored.</string>
+ <string name="spotiflac_session_expires">Session valid until %1$s</string>
+ <string name="spotiflac_forget">Forget this session</string>
+ <string name="lossless_hires_title">Hi-res downloads (24-bit)</string>
+ <string name="lossless_hires_detail">A track saved in 24-bit hi-res when the source has it. Files are about three times bigger than CD quality.</string>
+ <string name="setup_spotiflac_title">Lossless downloads (FLAC)</string>
+ <string name="setup_spotiflac_detail">Verify once with SpotiFLAC so downloads come from its lossless servers.</string>
+ <string name="settings_title">Settings</string>
+ <string name="settings_detail">Sound quality, downloads, data, battery and language</string>
+ <string name="settings_section_playback">Playback</string>
+ <string name="settings_section_downloads">Downloads</string>
+ <string name="settings_section_data">Data and battery</string>
+ <string name="settings_section_display">Display and language</string>
+ <string name="settings_section_app">App</string>
+ <string name="quality_streaming_title">Streaming quality</string>
+ <string name="quality_streaming_detail">What the player streams over the network.</string>
+ <string name="quality_streaming_auto">Automatic</string>
+ <string name="quality_streaming_auto_detail">Adapts to your connection</string>
+ <string name="quality_streaming_low">Lowest</string>
+ <string name="quality_streaming_low_detail">24 kbit/s, the lowest possible: uses the least data</string>
+ <string name="quality_streaming_normal">Normal</string>
+ <string name="quality_streaming_normal_detail">96 kbit/s, a good balance of sound and data</string>
+ <string name="quality_streaming_high">High</string>
+ <string name="quality_download_title">Download quality</string>
+ <string name="quality_download_detail">How songs are saved for offline listening.</string>
+ <string name="quality_download_off">Off</string>
+ <string name="quality_download_off_detail">No downloads</string>
+ <string name="quality_download_cd">FLAC, CD quality</string>
+ <string name="quality_download_cd_detail">Lossless 16-bit, about 30 MB a song</string>
+ <string name="quality_download_hires">FLAC Hi-Res</string>
+ <string name="quality_download_hires_detail">24-bit when it exists, files about three times bigger</string>
+ <string name="setup_quality_title">Sound quality</string>
+ <string name="setup_quality_subtitle">Choose how Myspoti plays and saves your music. You can change it later in Settings.</string>
+ <string name="downloads_off_toast">Downloads are off. Turn them on in Settings.</string>
+ <string name="quality_streaming_high_detail">160 kbit/s, the best sound</string>
+ <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>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt b/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt
index 1edd129b..2e6c0024 100644
--- a/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt
+++ b/base/app/src/test/java/com/music/spotui/data/offline/OfflineDownloaderTest.kt
@@ -1,20 +1,15 @@
package com.music.spotui.data.offline
-import com.music.spotui.data.offline.OfflineDownloader.AudioChoice
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class OfflineDownloaderTest {
- @Test fun rankAudioPrefersHighestBitrateThenOpus() {
- val ranked = OfflineDownloader.rankAudio(listOf(
- AudioChoice("m4a", 48, "a"),
- AudioChoice("m4a", 128, "b"),
- AudioChoice("webm", 160, "c"),
- AudioChoice("webm", 128, "d"),
- ))
- assertEquals(listOf("c", "d", "b", "a"), ranked.map { it.url })
+ @Test fun contentRangeTotalReadsTheFullSize() {
+ assertEquals(1234L, OfflineDownloader.contentRangeTotal("bytes 0-99/1234"))
+ assertNull(OfflineDownloader.contentRangeTotal("bytes 0-99/*"))
+ assertNull(OfflineDownloader.contentRangeTotal(null))
}
@Test fun normalizeIsrcAcceptsDashesAndCase() {
diff --git a/base/app/src/test/java/com/music/spotui/data/offline/WrappedSyncTest.kt b/base/app/src/test/java/com/music/spotui/data/offline/WrappedSyncTest.kt
new file mode 100644
index 00000000..e95c5269
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/offline/WrappedSyncTest.kt
@@ -0,0 +1,38 @@
+package com.music.spotui.data.offline
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The honest-reporting rules: real listens only, same context as the play. */
+class WrappedSyncTest {
+
+ private fun listen(context: String = "") = WrappedSync.Listen(
+ trackId = "3URIq3iShZ0nBF3gcCwqHy", albumId = "4aeweJs3H2T3YfTzzzW2qL",
+ startedAt = 1, playedMs = 45_000, durationMs = 200_000, threshold = true, context = context,
+ )
+
+ @Test fun deferredListensReplayOnTheContextTheyStartedFrom() {
+ assertEquals("spotify:playlist:abc123", WrappedSync.contextFor(listen("spotify:playlist:abc123")))
+ // No recorded context (the Downloaded list): the track's album.
+ assertEquals("spotify:album:4aeweJs3H2T3YfTzzzW2qL", WrappedSync.contextFor(listen()))
+ }
+
+ @Test fun albumFallbackNeverProducesAUriWithoutAnId() {
+ val noAlbum = WrappedSync.Listen("0K4Ym9aQqD06mG6rJ0SfWZ", "", 1, 40_000, 180_000, true, "")
+ assertEquals("spotify:track:0K4Ym9aQqD06mG6rJ0SfWZ", WrappedSync.contextFor(noAlbum))
+ }
+
+ @Test fun thePlayerIdsAreFullyAllocated() {
+ assertEquals(32, WrappedSync.randomHex(16).length)
+ assertTrue(WrappedSync.randomB64(21).matches(Regex("[A-Za-z0-9_-]{28}")))
+ }
+
+ @Test fun theCountableThresholdIsSpotifyS() {
+ assertEquals(30_000L, WrappedSync.THRESHOLD_MS)
+ // sanity: a 29 s listen does not cross it.
+ assertFalse(29_000L >= WrappedSync.THRESHOLD_MS)
+ assertTrue(30_500L >= WrappedSync.THRESHOLD_MS)
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt b/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt
new file mode 100644
index 00000000..b5687293
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/lossless/LosslessMatchTest.kt
@@ -0,0 +1,87 @@
+package com.music.spotui.lossless
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+private fun hit(id: String, title: String, artist: String, duration: Int, isrc: String = "") =
+ LosslessSource.TidalHit(id, title, artist, duration, isrc)
+
+/** The exact-recording rules: ISRC first, otherwise nothing but the same song wins. */
+class LosslessMatchTest {
+
+ @Test
+ fun picksByExactIsrc() {
+ val hits = listOf(hit("1", "Wrong", "A", 300, "GBXXX2400001"))
+ assertEquals("1", LosslessSource.pickHit(hits, "GBXXX2400001", "Real Title", "Artist", 200)?.id)
+ }
+
+ @Test
+ fun withoutIsrcPicksSameTitleArtistDuration() {
+ val hits = listOf(
+ hit("1", "Real Title", "Artist", 201), // within 3 s
+ hit("2", "Real Title (Live)", "Artist", 200), // live take never wins
+ hit("3", "Real Title", "Someone", 200),
+ )
+ assertEquals("1", LosslessSource.pickHit(hits, "", "Real Title", "Artist", 200)?.id)
+ }
+
+ @Test
+ fun rejectsRemixCoverAndOffDuration() {
+ val hits = listOf(
+ hit("1", "Real Title - Remix", "Artist", 200),
+ hit("2", "Other Song", "Artist", 200),
+ hit("3", "Real Title", "Artist", 310), // 110 s off
+ )
+ assertNull(LosslessSource.pickHit(hits, "", "Real Title", "Artist", 200))
+ }
+
+ @Test
+ fun isrcBeatsTitleOnlyWhenSameRecording() {
+ val hits = listOf(
+ hit("1", "Real Title", "Artist", 200, "GBUM71705174"),
+ hit("2", "Real Title", "Artist", 200, "USUM71712345"),
+ )
+ // The track's own ISRC decides which of the same-named candidates wins.
+ assertEquals("1", LosslessSource.pickHit(hits, "GBUM71705174", "Real Title", "Artist", 200)?.id)
+ }
+}
+
+/** The FLAC STREAMINFO read that rejects 30 s previews handed out by backends. */
+class FlacDurationTest {
+
+ private fun fakeFlac(sampleRate: Int = 44_100, samples: Long = sampleRate * 200L): ByteArray {
+ val head = ByteArray(42)
+ "fLaC".toByteArray().copyInto(head)
+ // STREAMINFO fields a real FLAC carries, packed as the parser expects:
+ // 20 bits sample rate | 3 channels | 5 bits/sample | 36-bit total samples.
+ val packed = (sampleRate.toLong() and 0xFFFFF) shl 44 or
+ (2L shl 41) or // stereo
+ (16L shl 36) or ((samples and 0xFFFFFFFFL))
+ for (i in 0 until 8) head[18 + i] = (packed ushr (56 - 8 * i)).toByte()
+ return head
+ }
+
+ @Test
+ fun readsTheDuration() {
+ val head = fakeFlac(44_100, 44_100L * 210)
+ assertEquals(210, LosslessSource.flacDurationSec(head))
+ }
+
+ @Test
+ fun notFlacOrTooShortIsNull() {
+ assertNull(LosslessSource.flacDurationSec(ByteArray(42)))
+ assertNull(LosslessSource.flacDurationSec(ByteArray(20)))
+ }
+
+ @Test
+ fun aTitleMatchIsNotAnIsrcMatch() {
+ assertTrue(LosslessSource.isrcMatches("usum71703861", "USUM71703861"))
+ // Same song name, another recording (live, remaster): its own ISRC.
+ assertFalse(LosslessSource.isrcMatches("GBUM71703999", "USUM71703861"))
+ // Spotify gave no ISRC: nothing can match it.
+ assertFalse(LosslessSource.isrcMatches("USUM71703861", ""))
+ }
+}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
index e5e65d55..7eecb52e 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
@@ -62,11 +62,13 @@ internal class ControlRelay(private val view: WebView) {
headers["User-Agent"] = WebPlayerHost.DESKTOP_UA
headers["Origin"] = "https://open.spotify.com"
headers["Referer"] = "https://open.spotify.com/"
+ val built = headers.build()
+ captureCredentials(url, built)
// The player's registration leaves out the ad formats (see AdBlock).
val sent = if (body != null && app.myspoti.spotify.bridge.AdBlock.isDeviceRegistration(method, url)) app.myspoti.spotify.bridge.AdBlock.withoutAdFormats(body) else body
// Bytes, not a String body: OkHttp would append "; charset=utf-8" to the content type.
val payload = if (method == "GET" || method == "HEAD") null else (sent ?: "").toByteArray().toRequestBody(null)
- val request = Request.Builder().url(url).headers(headers.build()).method(method, payload).build()
+ val request = Request.Builder().url(url).headers(built).method(method, payload).build()
http.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} failed: ${e.message}")
@@ -94,6 +96,28 @@ internal class ControlRelay(private val view: WebView) {
private fun shortPath(url: String) = url.substringBefore('?').substringAfter(".com").replace(Regex("[0-9a-f]{20,}"), "…")
+ /**
+ * Keeps the player's own credentials so the app's playback reports can use
+ * them (see [RelayCredentials]): the device id from the reported paths, the
+ * cluster host from the URL, and the auth headers the player itself sent.
+ */
+ private fun captureCredentials(url: String, headers: Headers) {
+ try {
+ val c = RelayCredentials
+ Regex("/track-playback/v1/devices/([0-9a-fA-F]{32,64})/?").find(url)?.groupValues?.get(1)
+ ?.let { if (c.deviceId.isBlank()) c.deviceId = it.lowercase() }
+ Regex("/connect-state/v1/player/command/from/([0-9a-fA-F]{32,64})").find(url)?.groupValues?.get(1)
+ ?.let { c.deviceId = it.lowercase() }
+ val host = Regex("https://([a-z0-9.-]+\\.spotify\\.com)/").find(url)?.groupValues?.get(1)
+ if (host != null && host.contains("spclient")) c.clusterHost = host
+ headers["authorization"]?.takeIf { it.isNotBlank() && it.startsWith("Bearer ", true) }
+ ?.let { c.authorization = it } // the latest token the page sent; never an empty one
+ headers["client-token"]?.takeIf { it.isNotBlank() }?.let { c.clientToken = it }
+ if (c.ready()) c.seenAt = System.currentTimeMillis()
+ } catch (_: Exception) {
+ }
+ }
+
companion object {
private val RELAYED = Regex("^https://[a-z0-9-]+(\\.[a-z0-9-]+)*\\.spotify\\.com/(connect-state|track-playback)/v1/")
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/RelayCredentials.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/RelayCredentials.kt
new file mode 100644
index 00000000..1b05e5f8
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/RelayCredentials.kt
@@ -0,0 +1,29 @@
+package app.myspoti.host.android
+
+/**
+ * The playback credentials the app's own requests need, captured from the Web
+ * Player's own traffic as [ControlRelay] relays it: the device id, its cluster
+ * host, and the page's auth tokens. Nothing is guessed — every value was sent
+ * by the page itself.
+ */
+object RelayCredentials {
+
+ /** The Web Player's Spotify device id (bare hex, ~40 chars). */
+ @Volatile var deviceId: String = ""
+
+ /** The cluster host the player talks to, e.g. "gew4-spclient.spotify.com". */
+ @Volatile var clusterHost: String = ""
+
+ /** The page's Bearer token (rotates; refreshed whenever the player calls out). */
+ @Volatile var authorization: String = ""
+
+ /** The page's client token (long lived, per app instance). */
+ @Volatile var clientToken: String = ""
+
+ /** Last time any of these were seen and used successfully by the player. */
+ @Volatile var seenAt: Long = 0
+
+ /** All of it or nothing: a play report needs every piece. */
+ fun ready(): Boolean = deviceId.isNotBlank() && clusterHost.isNotBlank() &&
+ authorization.isNotBlank() && clientToken.isNotBlank()
+}
diff --git a/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt
index 5c04b02b..dfc81776 100644
--- a/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt
+++ b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/LiveOrderTest.kt
@@ -59,4 +59,26 @@ class LiveOrderTest {
runCatching { api.player.pause() }
}
}
+
+ /** Smart shuffle on Liked Songs: other songs play inside the Liked Songs order. */
+ @Test
+ fun `plays other songs inside liked songs`() = runBlocking {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ val host = CdpHost.connect(System.getProperty("myspoti.cdp"))
+ val api = SpotifyApi(host, scope, language = "fr")
+ host.reload(); host.awaitLoad(); api.onPageLoaded(); api.awaitReady()
+ val liked = api.library.likedTracks(0, 5).items.map { it.track.uri }
+ val other = api.playlists.tracks("spotify:playlist:37i9dQZF1DXcBWIGoYBM5M", 0, 5).items.map { it.uri }.first { it !in liked }
+ val order = listOf(liked[0], other) + liked.drop(1)
+ try {
+ api.player.play("spotify:collection:tracks", trackUri = liked[0], order = order)
+ withTimeout(30_000) { api.player.state.first { it?.item?.uri == liked[0] && !it.isPaused } }
+ api.player.next()
+ val t = withTimeout(30_000) { api.player.state.first { it?.item != null && it.item!!.uri != liked[0] } }!!
+ println("liked then: ${t.item?.name} context ${t.contextUri}")
+ assertEquals(other, t.item?.uri)
+ } finally {
+ runCatching { api.player.pause() }
+ }
+ }
}
diff --git a/docs/spotiflac-research.md b/docs/spotiflac-research.md
new file mode 100644
index 00000000..c2bdda1d
--- /dev/null
+++ b/docs/spotiflac-research.md
@@ -0,0 +1,76 @@
+# Intégration SpotiFLAC (repli du downloader YouTube Music)
+
+Recherche du 16/10/2026, sources : spotbye/SpotiFLAC v7.2.2 (desktop, Go+Wails, MIT),
+spotiflacapp/SpotiFLAC-Mobile (Flutter+Rust, MIT), Spotui v1.6 (clone GPL-3 vendored `/tmp/spotui-vendor`),
+vérifications réseau live des endpoints le jour même.
+
+## Décisions Dani
+- SpotiFLAC pour tous les téléchargements, **pas de YouTube** (plus de source YT).
+- Sans match FLAC → **indisponible** (comportement actuel conservé).
+- Qualité (16/24) = préférence utilisateur : onboarding + paramètre (comme les réglages data saver).
+- Motivation : fiabilité (pas de live/remix) + qualité (FLAC 16/24-bit, jamais re-encodé).
+
+## État des sources (vérifié live 2026-10-16)
+- `tdl-oss.spotbye.qzz.io/health` → 200 OK (Tidal)
+- `qbz-oss.spotbye.qzz.io/health` → 200 OK (Qobuz), `/api/dl` sans session → 404 "Verification session required."
+- `amz-oss.spotbye.qzz.io/health` → 200 OK (Amazon), `/api/dl` sans session → 428 (Precondition Required)
+- `verify.spotbye.qzz.io/bootstrap` → 400 + challenge_id/challenge_url (Turnstile)
+- `amazon.spotbye.qzz.io` (ancien endpoint du code SpotiFlac.kt de Spotui) → **DNS mort**
+- **Odesli fermé** au public (401 PUBLIC_API_ACCESS_DEPRECATED) → le mapping Spotify→ids de `SpotiFlac.kt` (Spotui) est obsolète ; Spotui matche désormais via la recherche du backend Tidal (`/search/?s=`, ISRC en priorité).
+
+## Ordre de priorité recommandé (fiabilité d'abord)
+1. **Deezer HiFi (optionnel)** si l'utilisateur connecte son propre compte (ARL) — le plus propre
+ juridiquement (abonnement personnel), FLAC direct, métadonnées/preview officiels pour la vérif.
+2. **SpotiFLAC gated** : session signée du service lui-même — bootstrap `verify.spotbye.qzz.io` →
+ page challenge (Turnstile résolu par l'utilisateur, WebView) → grant → session (session_id +
+ session_secret) → `/api/dl` signée HMAC `SPOTIFLAC-HMAC-V1` (clé roulante
+ HMAC(session_secret, "{window:300}:{session_id}"), en-têtes X-Sig-*). Providers : Tidal → Qobuz →
+ Amazon, qualité HI_RES_LOSSLESS (24) puis LOSSLESS (16). C'est « their most reliable source ».
+3. **Tidal direct** sans compte : endpoints du registre rotatif AES-GCM sur gist public
+ (défaut `tidal.anandserver.cfd`), `GET /track/?id=&quality=LOSSLESS` single-file, clé partagée
+ `X-API-Key: ak_...`. Qobuz (Odesli-only) est mort en direct ; Qobuz passe par la session.
+4. **Amazon** : `/api/resolve/spotify/{id}` self-resolving — souvent dormant, jamais accepter une
+ `decryption_key` (pas de déchiffrement Amazon embarqué).
+5. **Sinon → indisponible** (ni YouTube, ni Soulseek).
+
+## Fiabilité/qualité — défenses à porter
+- **Match** : ISRC strict d'abord ; sinon titre+artiste normalisés et durée ±3 s (jamais un live/cover).
+- **Anti-preview** : lecture Range `bytes=0-41` → STREAMINFO FLAC → durée réelle ≥ durée attendue −5 s
+ (les backends servent parfois des previews 30 s). SpotiFLAC desktop rejette aussi toute piste <35 s.
+- **Anti-fake audiophile** : le STREAMINFO donne les sample rate/bit depth réels — ne jamais faire
+ confiance au label « 24-bit » de l'API seule ; Tidal a des faux 24-bit connus (Reddit r/SpotiFLAC).
+- **Vérification finale inchangée** de Myspoti : alignement avec la preview officielle Deezer 30 s
+ par ISRC (AudioAlign, score ≥ 0,5) rejette le même enregistrement qu'aujourd'hui.
+- **DASH-BTS multi-segments** (les manifestes `{url:[...]}`) : soit single-file seulement
+ (choix Spotui v1.6), soit porter le remux `downloadDashFlacToFile` (fLaC + STREAMINFO + payloads
+ mdat, sans ffmpeg) pour débloquer HI_RES 24-bit — recommandé puisque Dani veut la qualité.
+- **Erreurs** (protocole officiel) : 429/502/504 → retry ×3 Retry-After clamp(1,300 s) ; 401
+ SESSION_INVALID → effacer la session + re-bootstrap ; 428 VERIFY_REQUIRED → relancer la WebView ;
+ 403 → 1 essai avec session rafraîchie. Status API `spotbye.qzz.io/api/status` (fail-open).
+- **Concurrence** : 1 seul download FLAC simultané (android natif) ; backoff distribué 120 s si
+ un provider rate.
+
+## Stockage
+- FLAC brut tel que servi (jamais re-encodé), stockage privé app, ~30-40 Mo/titre.
+- Réglage qualité : 24-bit hi-res si dispo / 16-bit CD uniquement / même hi-fi en data saver —
+ onboarding + paramètre (l'utilisateur a proposé).
+- Gists/registre rafraîchi toutes les 30 min, retry sur échec 5 min, cache en mémoire.
+
+## Licences & conformité du projet
+- SpotiFLAC (desktop + mobile) = **MIT**, Spotui = **GPL-3** ; Myspoti est GPL-3 → port compatible.
+ Crédits à ajouter au README : Spotui, Spotui/SpotiFLAC (spotbye), SpotiFLAC-Mobile.
+- README « Not included » doit être réécrit : le point « The audio comes from YouTube Music »
+ n'est plus vrai ; décrire honnêtement « audio lossless (FLAC) resolved from lossless catalogs
+ via the open SpotiFLAC community backends », disclaimer de risque inchangé
+ (pas de déchiffrement Amazon, pas de redistribution, rien de faux signalé à Spotify).
+- La clé partagée `ak_...` est publiée dans les sources SpotiFLAC/Spotui — elle est « community »,
+ pas volée ; les endpoints suivent le registre rotatif (pas d'endpoint mort codé en dur comme
+ l'ancien SpotiFlac.kt).
+
+## Si pratique autour
+- Spotui a mis cette section derrière « SpotiFLAC (experimental) » + one-shot WebView verification
+ (constants : APP_VERSION=4.8.5, PLATFORM=android, CALLBACK=spotiflac://session-grant).
+- Fichiers Spotui à porter : lossless/LosslessRegistry.kt, lossless/LosslessSource.kt,
+ lossless/SpotiflacGated.kt, data/preferences/SpotiflacSessionPref.kt,
+ ui/screens/SpotiflacVerifyScreen.kt (226 l.) + di/Downloads.kt downloadToFile (ordre).
+- Tests existants chez Spotui : TidalMatchTest.kt, SoulseekPickTest.kt (matplotlib pick logic).
diff --git a/docs/wrapped-playback-analysis.md b/docs/wrapped-playback-analysis.md
new file mode 100644
index 00000000..6f4366a0
--- /dev/null
+++ b/docs/wrapped-playback-analysis.md
@@ -0,0 +1,46 @@
+# Wrapped — comment une écoute compte (analyse des captures)
+
+Source : capture CDP complète d'une session de lecture (bodies décodés), 16/10/2026.
+Détail technique : skill myspoti → `references/wrapped-playback.md`.
+
+## La chaîne exacte (Web Player réel)
+
+| Étape | Requête | Contenu clé |
+|---|---|---|
+| 1 | `POST /connect-state/v1/player/command/from/{device}` | context.uri, play_origin (feature_identifier, referrer), logging_params |
+| 2 | `PUT /track-playback/v1/devices/{device}/state` (×19) | `state_ref{state_machine_id, state_id=playback_id, paused}` + `sub_state{position, duration, media_type AUDIO, bitrate, audio_quality, format}` + `debug_source` |
+| 3 | `POST /melody/v1/msg/batch` (base64 JSON) | `jssdk_playback_start`, `jssdk_playback_stats`, `media_playback_event_v2`, **`track_stream_verification`** (ms_played / ms_nominal_played / next_playback_id) |
+| — | `GET /track-playback/v1/media/spotify:track:X?manifestFileFormat=file_ids_mp3` | l'audio lui-même (même host que le comptage) |
+
+**Le jalon qui compte** : `debug_source: "played_threshold_reached"` (≈30 s jouées),
+lancé sur la machine d'état dont `state_id` = le `playback_id` repris partout
+(melody, verification). `track_data_finalized` clôt la piste.
+
+## Ce qui ne compte PAS
+
+`gabo-receiver-service/(public/)v3/events` (32 batches dans la session) = Ubi /
+SemanticMetric / KmPageView — analytics produit, pas de comptage d'écoute.
+
+## Comment brancher Myspoti (plan)
+
+- `ControlRelay` relaie déjà `connect-state` + `track-playback` en OkHttp (token,
+ client-token, device id `hobs_…` gérés par l'engine). Le rappeur peut donc
+ émettre en natif.
+- Hooks disponibles : `SongPlayer.onLocalState(position, playing, duration)` +
+ offline track uri (`spotify:track:{id}`).
+- Intégration : un `PlaybackReporter` qui, pendant une écoute de fichier
+ téléchargé, émet (1) la commande play au démarrage, (2) les PUT state aux
+ milestones (`before_track_load`, `started_playing`, `played_threshold_reached`
+ au vrai passage de seuil, `track_data_finalized` à la fin), (3) les melody
+ batches (`jssdk_playback_start` au lancement, `track_stream_verification` à la
+ fin avec les ms joués réels).
+- Position licences : écoutes réelles uniquement (aucun événement inventé), mais
+ pas de GET `/media/...` corrélé — le serveur peut le savoir ; à écrire
+ honnêtement dans le README (« no altered listening events » → « real listens
+ only, no fabricated events »).
+
+## Décisions ouvertes (posées à Dani le 16/10, sans réponse)
+
+1. Niveau d'honnêteté : écoutes réelles seules / + queue offline / match parfait des shapes.
+2. sub_state qualité : reproduire 128k/HIGH/format 10 (comme le Web Player) ou valeurs réelles FLAC.
+3. Implémentation maintenant vs après commit beta.3.