Skip to content

Native Android client for Spotify, built with Jetpack Compose

Encrypted downloads, local queue for downloads, Wrapped retries, shorter debug logs

kota-zocaab28b66c60
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e31e501..e7acf7f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,11 @@ A new engine, written from scratch, and a cleaner app on top of it.
- **Downloads ask their quality** if you want ("Ask each time"): once for a whole playlist, kept for its new songs.
- **Liked Songs update at once** after a like or an unlike, without reloading the whole list.
- **No more "bop" between two songs** on the phone's speaker: the sound output stays awake across the change.
+- **Downloads are encrypted**: a downloaded song only plays in Myspoti, on the phone that downloaded it. Songs downloaded before are encrypted in the background.
+- **The queue of downloaded songs is the real one**: it shows what plays next, and moving, removing or skipping songs works offline.
+- **Offline listens reach your Wrapped**: listens kept while offline are sent within a minute once the network and Spotify are back, not only at the next app start.
+- **Downloads say when the SpotiFLAC verification is missing**, with a banner that opens it.
+- **Shorter debug logs**: the copied logs keep Myspoti's own lines and crashes only.
- **Updates install in the app**: "Update" downloads the new version with a progress bar and hands it to Android's installer; no trip to GitHub. The first time, Android asks to allow installs from Myspoti.
- **Haptics work again**: buttons, likes and the debug icon vibrate.
- **Solid bottom bar** as an option in Settings, Display.
diff --git a/base/app/src/androidTest/java/com/music/spotui/data/offline/OfflineCryptoTest.kt b/base/app/src/androidTest/java/com/music/spotui/data/offline/OfflineCryptoTest.kt
new file mode 100644
index 00000000..bf10a3bc
--- /dev/null
+++ b/base/app/src/androidTest/java/com/music/spotui/data/offline/OfflineCryptoTest.kt
@@ -0,0 +1,71 @@
+package com.music.spotui.data.offline
+
+import android.net.Uri
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.DataSpec
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import java.io.File
+import kotlin.random.Random
+
+@UnstableApi
+@RunWith(AndroidJUnit4::class)
+class OfflineCryptoTest {
+ @Test fun encryptsAndReadsBackFromAnyPosition() {
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val data = Random(7).nextBytes(1_000_003)
+ val file = File(context.cacheDir, "crypto-test.flac").apply { writeBytes(data) }
+ OfflineCrypto.encryptInPlace(context, file)
+ assertTrue(OfflineCrypto.isEncrypted(file))
+ assertFalse(file.readBytes().copyOfRange(OfflineCrypto.HEADER, OfflineCrypto.HEADER + 64)
+ .contentEquals(data.copyOfRange(0, 64)))
+
+ val source = OfflineCrypto.Factory(context).createDataSource()
+ for (pos in listOf(0L, 1L, 15L, 16L, 17L, 4095L, 500_000L, 999_990L)) {
+ val n = source.open(DataSpec.Builder().setUri(Uri.fromFile(file)).setPosition(pos).build()).toInt()
+ val out = ByteArray(n)
+ var read = 0
+ while (read < n) {
+ val r = source.read(out, read, minOf(8192, n - read))
+ if (r < 0) break
+ read += r
+ }
+ source.close()
+ assertArrayEquals("position $pos", data.copyOfRange(pos.toInt(), data.size), out)
+ }
+ file.delete()
+ }
+
+ /** An encrypted FLAC plays: the player finds the format and the length through the decrypting source. */
+ @Test fun playerReadsEncryptedFlac() {
+ val inst = InstrumentationRegistry.getInstrumentation()
+ val context = inst.targetContext
+ val file = File(context.cacheDir, "crypto-play.flac")
+ inst.context.assets.open("tone16.flac").use { i -> file.outputStream().use { i.copyTo(it) } }
+ OfflineCrypto.encryptInPlace(context, file)
+ val latch = java.util.concurrent.CountDownLatch(1)
+ var duration = 0L
+ var error: Throwable? = null
+ inst.runOnMainSync {
+ val p = androidx.media3.exoplayer.ExoPlayer.Builder(context)
+ .setMediaSourceFactory(androidx.media3.exoplayer.source.DefaultMediaSourceFactory(OfflineCrypto.Factory(context)))
+ .build()
+ p.addListener(object : androidx.media3.common.Player.Listener {
+ override fun onPlaybackStateChanged(state: Int) {
+ if (state == androidx.media3.common.Player.STATE_READY) { duration = p.duration; p.release(); latch.countDown() }
+ }
+ override fun onPlayerError(e: androidx.media3.common.PlaybackException) { error = e; p.release(); latch.countDown() }
+ })
+ p.setMediaItem(androidx.media3.common.MediaItem.fromUri(Uri.fromFile(file)))
+ p.prepare()
+ }
+ assertTrue("timed out", latch.await(20, java.util.concurrent.TimeUnit.SECONDS))
+ assertTrue("error: $error", error == null && duration > 0)
+ file.delete()
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/data/BetaLogs.kt b/base/app/src/main/java/com/music/spotui/data/BetaLogs.kt
index da29a604..605d9508 100644
--- a/base/app/src/main/java/com/music/spotui/data/BetaLogs.kt
+++ b/base/app/src/main/java/com/music/spotui/data/BetaLogs.kt
@@ -7,7 +7,9 @@ import java.util.Date
import java.util.Locale
/**
- * The app's own Logcat lines of the last minutes, for beta testers to paste in a bug report.
+ * The app's own Logcat lines of the last minutes, for beta testers to paste in a bug report:
+ * only Myspoti's own tags and crashes (not the system's codec, window and WebView chatter),
+ * without the lines that repeat with no news.
* An app can always read its own process's logs; nothing leaves the phone unless the user
* copies or shares the text. Tokens, e-mails and account ids are masked.
*/
@@ -19,13 +21,40 @@ object BetaLogs {
suspend fun recent(minutes: Int = MINUTES): String = withContext(Dispatchers.IO) {
val since = SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US).format(Date(System.currentTimeMillis() - minutes * 60_000L))
val text = runCatching {
- val process = ProcessBuilder("logcat", "-d", "-v", "threadtime", "--pid=${android.os.Process.myPid()}", "-T", since)
+ val process = ProcessBuilder(listOf("logcat", "-d", "-v", "threadtime", "--pid=${android.os.Process.myPid()}", "-T", since) +
+ TAGS.map { "$it:V" } + listOf("AndroidRuntime:E", "*:S"))
.redirectErrorStream(true).start()
process.inputStream.bufferedReader().use { it.readText() }.also { process.waitFor() }
}.getOrElse { "logcat unavailable: ${it.message}" }
val header = "Myspoti ${app.myspoti.engine.BuildConfig.VERSION_NAME} · Android ${android.os.Build.VERSION.RELEASE} (SDK ${android.os.Build.VERSION.SDK_INT}) · " +
"${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL} · last $minutes min\n\n"
- header + sanitize(text).takeLast(MAX_CHARS)
+ header + sanitize(useful(text)).takeLast(MAX_CHARS)
+ }
+
+ /** The app's log tags (Myspoti = the Web Player bridge). */
+ private val TAGS = listOf(
+ "Myspoti", "MspPlayer", "Api", "player", "Offline", "OfflineLists", "LosslessSource", "LosslessRegistry",
+ "DashFlacRemux", "Spotiflac", "Wrapped", "SpotifySync", "LyricsApi", "LyricTranslate", "MusicVideo",
+ "ScreenCache", "AppUpdater",
+ )
+
+ /** Lines that only repeat what the page or the player already said. */
+ private val noise = listOf(
+ Regex("console WARNING: The resource .* was preloaded"),
+ Regex("page net: .*\"status\":200"),
+ Regex("MusicVideo: decode "),
+ Regex("^-+ beginning of "),
+ )
+
+ /** Drops the [noise] and a status line identical to the one before it. */
+ internal fun useful(text: String): String {
+ var lastStatus = ""
+ return text.lineSequence().filter { line ->
+ if (noise.any { it.containsMatchIn(line) }) return@filter false
+ val status = line.substringAfter(" status ", "").takeIf { line.contains(" Myspoti : status ") }
+ if (status != null) { if (status == lastStatus) return@filter false; lastStatus = status }
+ true
+ }.joinToString("\n")
}
private val rules = listOf(
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.kt
new file mode 100644
index 00000000..ac44128a
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.kt
@@ -0,0 +1,181 @@
+package com.music.spotui.data.offline
+
+import android.content.Context
+import android.net.Uri
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import androidx.annotation.OptIn
+import androidx.media3.common.C
+import androidx.media3.common.util.UnstableApi
+import androidx.media3.datasource.BaseDataSource
+import androidx.media3.datasource.DataSource
+import androidx.media3.datasource.DataSpec
+import androidx.media3.datasource.DefaultDataSource
+import java.io.File
+import java.io.IOException
+import java.io.RandomAccessFile
+import java.math.BigInteger
+import java.security.KeyStore
+import java.security.SecureRandom
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+import javax.crypto.spec.IvParameterSpec
+import javax.crypto.spec.SecretKeySpec
+
+/**
+ * Downloaded songs are kept encrypted (AES-CTR), so they only play in Myspoti on this
+ * phone: copied out of the app, a file is noise.
+ *
+ * The file key is random, and stored wrapped by a key of the Android Keystore that
+ * never leaves the phone (nor its secure hardware). File layout: "MSE1", a 16-byte IV,
+ * then the encrypted audio. CTR mode lets the player seek anywhere.
+ */
+object OfflineCrypto {
+ private val MAGIC = "MSE1".toByteArray()
+ private const val IV_BYTES = 16
+ const val HEADER = 4 + IV_BYTES
+ private const val KEYSTORE_ALIAS = "myspoti_offline"
+ private const val PREFS = "offline_crypto"
+
+ @Volatile private var key: SecretKey? = null
+
+ /** The file key; made on first use. Null only when the Keystore lost its key. */
+ fun key(context: Context): SecretKey = key ?: synchronized(this) {
+ key ?: loadOrCreate(context).also { key = it }
+ }
+
+ private fun loadOrCreate(context: Context): SecretKey {
+ val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ val wrapped = prefs.getString("key", null)
+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ val master = (ks.getKey(KEYSTORE_ALIAS, null) as? SecretKey)
+ if (wrapped != null && master != null) {
+ runCatching {
+ val raw = android.util.Base64.decode(wrapped, android.util.Base64.NO_WRAP)
+ val c = Cipher.getInstance("AES/GCM/NoPadding")
+ c.init(Cipher.DECRYPT_MODE, master, GCMParameterSpec(128, raw.copyOfRange(0, 12)))
+ return SecretKeySpec(c.doFinal(raw, 12, raw.size - 12), "AES")
+ }
+ }
+ // No key yet (or the Keystore's is gone: older files can no longer be read).
+ val newMaster = master ?: KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
+ init(KeyGenParameterSpec.Builder(KEYSTORE_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256).build())
+ }.generateKey()
+ val fileKey = ByteArray(32).also { SecureRandom().nextBytes(it) }
+ val c = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, newMaster) }
+ val sealed = c.iv + c.doFinal(fileKey)
+ prefs.edit().putString("key", android.util.Base64.encodeToString(sealed, android.util.Base64.NO_WRAP)).commit()
+ return SecretKeySpec(fileKey, "AES")
+ }
+
+ fun isEncrypted(file: File): Boolean = runCatching {
+ file.length() >= HEADER && file.inputStream().use { s -> ByteArray(4).also { s.read(it) }.contentEquals(MAGIC) }
+ }.getOrDefault(false)
+
+ /** Writes [plain] encrypted to [out]. */
+ fun encrypt(context: Context, plain: File, out: File) {
+ val iv = ByteArray(IV_BYTES).also { SecureRandom().nextBytes(it) }
+ val c = cipher(key(context), iv, 0)
+ out.outputStream().buffered(256 * 1024).use { o ->
+ o.write(MAGIC); o.write(iv)
+ plain.inputStream().use { i ->
+ val buf = ByteArray(256 * 1024)
+ while (true) {
+ val n = i.read(buf)
+ if (n < 0) break
+ o.write(c.update(buf, 0, n))
+ }
+ }
+ c.doFinal().takeIf { it.isNotEmpty() }?.let(o::write)
+ }
+ }
+
+ /** Encrypts [file] in place (through a temporary file next to it). */
+ fun encryptInPlace(context: Context, file: File) {
+ if (isEncrypted(file)) return
+ val tmp = File(file.parentFile, file.name + ".enc")
+ try {
+ encrypt(context, file, tmp)
+ if (!tmp.renameTo(file)) throw IOException("could not replace ${file.name}")
+ } finally {
+ tmp.delete()
+ }
+ }
+
+ /** AES-CTR positioned at byte [offset] of the stream (the caller skips offset % 16). */
+ internal fun cipher(key: SecretKey, iv: ByteArray, offset: Long): Cipher {
+ val counter = BigInteger(1, iv).add(BigInteger.valueOf(offset / 16))
+ val bytes = counter.toByteArray().let { b ->
+ when {
+ b.size > 16 -> b.copyOfRange(b.size - 16, b.size) // wrapped around
+ b.size < 16 -> ByteArray(16 - b.size) + b
+ else -> b
+ }
+ }
+ return Cipher.getInstance("AES/CTR/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(bytes)) }
+ .also { c -> val skip = (offset % 16).toInt(); if (skip > 0) c.update(ByteArray(skip)) }
+ }
+
+ /** The player's data source: decrypts downloaded files, reads anything else as usual. */
+ @OptIn(UnstableApi::class)
+ class Factory(private val context: Context) : DataSource.Factory {
+ private val fallback = DefaultDataSource.Factory(context)
+ override fun createDataSource(): DataSource = Switching(context, fallback.createDataSource())
+ }
+
+ @OptIn(UnstableApi::class)
+ private class Switching(private val context: Context, private val other: DataSource) : BaseDataSource(false) {
+ private var raf: RandomAccessFile? = null
+ private var cipher: Cipher? = null
+ private var uri: Uri? = null
+ private var left = 0L
+ private var usingOther = false
+
+ override fun open(dataSpec: DataSpec): Long {
+ uri = dataSpec.uri
+ val file = dataSpec.uri.takeIf { it.scheme == "file" }?.path?.let(::File)
+ if (file == null || !isEncrypted(file)) {
+ usingOther = true
+ return other.open(dataSpec)
+ }
+ transferInitializing(dataSpec)
+ val r = RandomAccessFile(file, "r")
+ val iv = ByteArray(IV_BYTES)
+ r.seek(4); r.readFully(iv)
+ val total = file.length() - HEADER
+ if (dataSpec.position > total) { r.close(); throw IOException("position past the end") }
+ r.seek(HEADER + dataSpec.position)
+ cipher = cipher(key(context), iv, dataSpec.position)
+ raf = r
+ left = if (dataSpec.length != C.LENGTH_UNSET.toLong()) dataSpec.length else total - dataSpec.position
+ transferStarted(dataSpec)
+ return left
+ }
+
+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
+ if (usingOther) return other.read(buffer, offset, length)
+ if (length == 0) return 0
+ if (left == 0L) return C.RESULT_END_OF_INPUT
+ val r = raf ?: return C.RESULT_END_OF_INPUT
+ val n = r.read(buffer, offset, minOf(length.toLong(), left).toInt())
+ if (n < 0) return C.RESULT_END_OF_INPUT
+ cipher!!.update(buffer, offset, n, buffer, offset)
+ left -= n
+ bytesTransferred(n)
+ return n
+ }
+
+ override fun getUri(): Uri? = if (usingOther) other.uri else uri
+
+ override fun close() {
+ if (usingOther) { usingOther = false; other.close(); return }
+ raf?.close(); raf = null; cipher = null
+ if (uri != null) { uri = null; transferEnded() }
+ }
+ }
+}
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 856f5d6e..15bf772d 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
@@ -299,6 +299,8 @@ object OfflineDownloader {
out = File(OfflineStore.audioDir, "${r.trackId}.flac")
if (!audioTmp.renameTo(out)) throw IOException("could not move the file")
}
+ // Kept encrypted: the file only plays in Myspoti, on this phone.
+ runInterruptible(Dispatchers.IO) { OfflineCrypto.encryptInPlace(Graph.app, out) }
val cover = runCatching {
val c = File(OfflineStore.coverDir, "${r.trackId}.jpg")
httpGet(meta.coverUrl, c); c.name
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 b82c8303..547c2c53 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
@@ -85,6 +85,12 @@ object OfflineStore {
audioDir.listFiles()?.forEach { if (it.name !in names) it.delete() }
val covers = kept.map { it.cover }.toSet()
coverDir.listFiles()?.forEach { if (it.name !in covers) it.delete() }
+ // Songs downloaded before encryption existed: encrypted once, in the background.
+ val plain = kept.map { File(audioDir, it.file) }
+ if (plain.isNotEmpty()) Thread {
+ plain.forEach { f -> runCatching { OfflineCrypto.encryptInPlace(context.applicationContext, f) }
+ .onFailure { android.util.Log.w("Offline", "could not encrypt ${f.name}: ${it.message}") } }
+ }.apply { name = "offline-encrypt"; priority = Thread.MIN_PRIORITY }.start()
}
val audioDir: File get() = File(root, "audio")
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
index 20d52145..e92bb7a8 100644
--- 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
@@ -31,6 +31,7 @@ import java.util.concurrent.TimeUnit
*/
object WrappedSync {
private const val TAG = "Wrapped"
+ private const val RETRY_MS = 60_000L
/** Spotify's own countable threshold: reaching it makes the listen real. */
internal const val THRESHOLD_MS = 30_000L
@@ -107,7 +108,25 @@ object WrappedSync {
}
Log.i(TAG, "queued listens to sync: ${queue.size}")
}
- if (queue.isNotEmpty()) flush()
+ startRetries()
+ }
+
+ @Volatile private var retrying = false
+
+ /**
+ * Retries the kept listens every minute while some are left: at app start the Web Player
+ * has no session yet, and the network may come back with no local song played after it.
+ */
+ private fun startRetries() {
+ if (retrying) return
+ retrying = true
+ scope.launch {
+ while (true) {
+ if (queue.isNotEmpty() && OfflineStore.isOnline(Graph.app) && RelayCredentials.ready())
+ lock.withLock { flushLocked() }
+ kotlinx.coroutines.delay(RETRY_MS)
+ }
+ }
}
private suspend fun step(localId: Long, isPlaying: Boolean, pos: Long, dur: Long) {
@@ -195,8 +214,9 @@ object WrappedSync {
}
}
- private fun enqueue(listen: Listen) = synchronized(persistLock) {
- queue.add(listen); persistLocked()
+ private fun enqueue(listen: Listen) {
+ synchronized(persistLock) { queue.add(listen); persistLocked() }
+ startRetries()
}
/** A kept listen replays on the same context it started from, its facts, its own fresh playback id. */
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 a3c57fdd..0c3a5776 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
@@ -17,15 +17,22 @@ import com.music.spotui.data.local.LocalTrack
object LocalPlayer {
/** Local playback is the current source. */
val active = mutableStateOf(false)
- private var tracks: List<LocalTrack> = emptyList()
+ /** The play order, kept in step with the player's items (shuffle reorders it, see [setShuffle]). */
+ private val tracks = mutableListOf<LocalTrack>()
+ /** The order before shuffle, to go back to. */
+ private var unshuffled: List<LocalTrack>? = null
/** Where the queue comes from (Local Files, Downloaded…), shown in the player. */
var contextName: String = ""
private set
private var exo: ExoPlayer? = null
+ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
private fun player(): ExoPlayer = exo ?: ExoPlayer.Builder(Graph.app)
.setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(), true)
.setHandleAudioBecomingNoisy(true)
+ // Downloaded songs are encrypted files: the player reads them through the decrypting source.
+ .setMediaSourceFactory(androidx.media3.exoplayer.source.DefaultMediaSourceFactory(
+ com.music.spotui.data.offline.OfflineCrypto.Factory(Graph.app)))
.build().also { p ->
p.addListener(object : Player.Listener {
override fun onEvents(player: Player, events: Player.Events) = publish()
@@ -36,16 +43,14 @@ object LocalPlayer {
fun play(list: List<LocalTrack>, index: Int, shuffle: Boolean = false, context: String? = null) {
if (list.isEmpty()) return
SongPlayer.pauseEngineForLocal()
- tracks = list
+ tracks.clear(); tracks.addAll(list); unshuffled = null
contextName = context ?: Graph.app.getString(app.myspoti.engine.R.string.local_files_title)
active.value = true
val p = player()
- p.setMediaItems(list.map { t ->
- MediaItem.Builder().setUri(t.uri).setMediaId(t.id.toString())
- .setMediaMetadata(MediaMetadata.Builder().setTitle(t.title).setArtist(t.artist).build()).build()
- }, index.coerceIn(0, list.lastIndex), 0L)
- p.shuffleModeEnabled = shuffle
+ p.shuffleModeEnabled = false
+ p.setMediaItems(list.map(::item), index.coerceIn(0, list.lastIndex), 0L)
p.prepare()
+ if (shuffle) setShuffle(true)
p.play()
}
@@ -54,6 +59,8 @@ object LocalPlayer {
if (!active.value) return
active.value = false
exo?.let { it.stop(); it.clearMediaItems() }
+ tracks.clear(); unshuffled = null
+ SongPlayer.restoreEngineQueue()
// Whatever this run played gets closed honestly (Wrapped reporting).
com.music.spotui.data.offline.WrappedSync.finish()
}
@@ -63,7 +70,67 @@ object LocalPlayer {
fun next() { exo?.let { if (it.hasNextMediaItem()) it.seekToNextMediaItem() } }
fun previous() { exo?.let { if (it.currentPosition > 3000 || !it.hasPreviousMediaItem()) it.seekTo(0) else it.seekToPreviousMediaItem() } }
fun seekTo(ms: Long) { exo?.seekTo(ms) }
- fun setShuffle(on: Boolean) { exo?.shuffleModeEnabled = on }
+ /**
+ * Shuffle reorders the songs after the current one (and off puts the list's order back),
+ * so the queue shown is the order that really plays and can be edited like any list.
+ */
+ fun setShuffle(on: Boolean) {
+ val p = exo ?: return
+ if (on == (unshuffled != null) || tracks.isEmpty()) return
+ val cur = p.currentMediaItemIndex.coerceIn(0, tracks.lastIndex)
+ if (on) {
+ unshuffled = tracks.toList()
+ arrange(tracks.subList(0, cur + 1).toList() + tracks.subList(cur + 1, tracks.size).shuffled())
+ } else {
+ val before = unshuffled.orEmpty()
+ unshuffled = null
+ arrange(before.filter { b -> tracks.any { it === b } } + tracks.filter { t -> before.none { it === t } })
+ }
+ }
+
+ val shuffled get() = unshuffled != null
+
+ /** The songs after the current one, in play order, with their index in the list. */
+ fun upcoming(): List<Pair<Int, LocalTrack>> {
+ val i = exo?.currentMediaItemIndex ?: return emptyList()
+ return (i + 1 until tracks.size).map { it to tracks[it] }
+ }
+
+ fun skipTo(index: Int) { exo?.let { if (index in tracks.indices) { it.seekTo(index, 0L); it.play() } } }
+
+ /** Moves the song at [from] so it ends at [to] (indices of the list after the move). */
+ fun move(from: Int, to: Int) {
+ val p = exo ?: return
+ if (from !in tracks.indices || to !in tracks.indices || from == to) return
+ p.moveMediaItem(from, to)
+ tracks.add(to, tracks.removeAt(from))
+ publish()
+ }
+
+ /** Moves the song at [from] right after the current one. */
+ fun moveNext(from: Int) { exo?.let { val cur = it.currentMediaItemIndex; move(from, if (from > cur) cur + 1 else cur) } }
+
+ fun remove(index: Int) {
+ val p = exo ?: return
+ if (index !in tracks.indices || index == p.currentMediaItemIndex) return
+ p.removeMediaItem(index)
+ val t = tracks.removeAt(index)
+ unshuffled = unshuffled?.filterNot { it === t }
+ publish()
+ }
+
+ /** Puts the player's items in [target]'s order with moves only, so the current song keeps playing. */
+ private fun arrange(target: List<LocalTrack>) {
+ val p = exo ?: return
+ for (k in target.indices) {
+ val j = (k until tracks.size).firstOrNull { tracks[it] === target[k] } ?: continue
+ if (j != k) { p.moveMediaItem(j, k); tracks.add(k, tracks.removeAt(j)) }
+ }
+ publish()
+ }
+
+ private fun item(t: LocalTrack) = MediaItem.Builder().setUri(t.uri).setMediaId(t.id.toString())
+ .setMediaMetadata(MediaMetadata.Builder().setTitle(t.title).setArtist(t.artist).build()).build()
fun setRepeatMode(mode: Int) {
exo?.repeatMode = when (mode) { 1 -> Player.REPEAT_MODE_ALL; 2 -> Player.REPEAT_MODE_ONE; else -> Player.REPEAT_MODE_OFF }
}
@@ -76,5 +143,6 @@ object LocalPlayer {
if (!active.value) return
val t = current() ?: return
SongPlayer.onLocalState(t, exo?.playWhenReady == true, position(), duration())
+ SongPlayer.onLocalQueue(t, upcoming())
}
}
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 20ecb6e9..e92316a4 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
@@ -82,6 +82,9 @@ object SongPlayer {
@Volatile var currentSource: String = "Spotify"
@Volatile var currentQuality: String = ""
+ /** Queue items of the local player (downloads, Local Files). */
+ private const val LOCAL = "local"
+
/** Spotify's real queue. */
data class QueueItem(val song: SongsModel, val uri: String, val uid: String, val provider: String)
data class EngineQueue(
@@ -344,9 +347,13 @@ object SongPlayer {
}
}
+ /** Back from the local player: the Spotify queue again. */
+ fun restoreEngineQueue() = main.post { _queue.value = EngineQueue(); applyQueue(apiQueue) }
+
private fun applyQueue(q: app.myspoti.api.Queue?) {
apiQueue = q
- if (q == null) return
+ // While a downloaded or local file plays, the queue shown is the local player's.
+ if (q == null || LocalPlayer.active.value) return
fun items(list: List<app.myspoti.api.NowPlaying>) = list
.filter { it.uri.startsWith("spotify:track:") || it.uri.startsWith("spotify:episode:") }
.map { QueueItem(songOf(it), it.uri, it.uid.orEmpty(), "") }
@@ -733,6 +740,7 @@ object SongPlayer {
}
fun skipTo(item: QueueItem) {
+ if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::skipTo); return }
val id = trackIdOf(item.uri)
if (id.isNotBlank()) markPending(id)
boundState?.updateSongState(item.song.coverUri, item.song.title, item.song.singer, true, item.song.id, 0, item.song.album)
@@ -750,6 +758,12 @@ object SongPlayer {
/** Move [item] just before / after [target] (same section of the queue). */
fun reorder(item: QueueItem, target: QueueItem, after: Boolean) {
+ if (item.provider == LOCAL) {
+ val from = item.uid.toIntOrNull() ?: return
+ val t = target.uid.toIntOrNull() ?: return
+ LocalPlayer.move(from, if (after) (if (from < t) t else t + 1) else (if (from < t) t - 1 else t))
+ return
+ }
val a = apiItem(item) ?: return
val b = apiItem(target) ?: return
command { api.player.moveInQueue(a, b, after) }
@@ -757,6 +771,7 @@ object SongPlayer {
/** Move a "next up" track into the queue, right after the current one. */
fun moveToQueueFront(item: QueueItem) {
+ if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::moveNext); return }
val a = apiItem(item) ?: return
command {
api.player.addToQueue(listOf(a.uri))
@@ -765,6 +780,7 @@ object SongPlayer {
}
fun removeFromQueue(item: QueueItem) {
+ if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::remove); return }
_queue.value = _queue.value.let { q -> q.copy(queued = q.queued - item, nextUp = q.nextUp - item) }
val a = apiItem(item) ?: return
command { api.player.removeFromQueue(listOf(a)) }
@@ -795,8 +811,7 @@ object SongPlayer {
bufferingState.value = false
val uri = "local:${t.id}"
if (_nowPlaying.value.uri != uri) _nowPlaying.value = NowPlaying(uri = uri, contextName = LocalPlayer.contextName)
- val song = SongsModel(id = ("local:" + t.id).hashCode() and 0x7fffffff, title = t.title, album = t.album,
- singer = t.artist, coverUri = t.artUri.toString(), url = "local:${t.uri}", durationMs = dur.toInt())
+ val song = localSong(t, dur)
boundState?.let { st ->
st.likeState.value = false
st.updateSongState(song.coverUri, song.title, song.singer, isPlaying, song.id, 0, song.album)
@@ -811,6 +826,21 @@ object SongPlayer {
}
}
+ private fun localSong(t: com.music.spotui.data.local.LocalTrack, dur: Long = t.durationMs) =
+ SongsModel(id = ("local:" + t.id).hashCode() and 0x7fffffff, title = t.title, album = t.album,
+ singer = t.artist, coverUri = t.artUri.toString(), url = "local:${t.uri}", durationMs = dur.toInt())
+
+ /** The local player's queue: [upcoming] are the songs after [current], with their list index as uid. */
+ fun onLocalQueue(current: com.music.spotui.data.local.LocalTrack, upcoming: List<Pair<Int, com.music.spotui.data.local.LocalTrack>>) {
+ main.post {
+ if (!LocalPlayer.active.value) return@post
+ _queue.value = EngineQueue(
+ current = localSong(current),
+ nextUp = upcoming.map { (i, t) -> QueueItem(localSong(t), "local:${t.id}", i.toString(), LOCAL) },
+ )
+ }
+ }
+
fun isCrossfadeActive(): Boolean = false
fun release() {}
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 c807638f..bdf905b5 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
@@ -135,6 +135,17 @@ fun DownloadsScreen(navController: NavController) {
}
}
}
+ // No SpotiFLAC verification: the reliable source is off, say it where downloads fail.
+ if (!com.music.spotui.data.preferences.hasSpotiflacSession(context)) item(key = "verify") {
+ Text(
+ stringResource(R.string.downloads_verify_banner),
+ color = Color.White, fontSize = 14.sp, lineHeight = 19.sp,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp).fillMaxWidth()
+ .clip(RoundedCornerShape(8.dp)).background(Color(0xFF2A2A2A))
+ .pressable(0.98f) { navController.navigate(com.music.spotui.ui.navigation.Routes.Spotiflac.route) }
+ .padding(14.dp),
+ )
+ }
// Songs still on their way (or that could not be downloaded).
items(waiting, key = { "w:" + it.trackId }) { r ->
val status = OfflineStore.status[r.trackId]
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 913c0d02..1dcff3bf 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -255,4 +255,5 @@
<string name="update_allow">Autoriser</string>
<string name="update_failed">La mise à jour a échoué : %1$s</string>
<string name="update_retry">Réessayer</string>
+ <string name="downloads_verify_banner">Les téléchargements demandent la vérification SpotiFLAC une fois dans cette app. Touchez ici pour la faire.</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index 2c2e8089..9c77a35b 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -255,4 +255,5 @@
<string name="update_allow">Consenti</string>
<string name="update_failed">Aggiornamento non riuscito: %1$s</string>
<string name="update_retry">Riprova</string>
+ <string name="downloads_verify_banner">I download richiedono la verifica SpotiFLAC una volta in questa app. Tocca qui per farla.</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 20cd13cb..89fa9c0a 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -255,4 +255,5 @@
<string name="update_allow">Allow</string>
<string name="update_failed">The update failed: %1$s</string>
<string name="update_retry">Try again</string>
+ <string name="downloads_verify_banner">Downloads need the SpotiFLAC verification once on this app. Tap here to do it.</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/data/BetaLogsTest.kt b/base/app/src/test/java/com/music/spotui/data/BetaLogsTest.kt
new file mode 100644
index 00000000..00ac1755
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/BetaLogsTest.kt
@@ -0,0 +1,21 @@
+package com.music.spotui.data
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class BetaLogsTest {
+ @Test fun dropsRepeatsAndNoise() {
+ val text = listOf(
+ "10-16 23:28:16.561 1 1 D Myspoti : status ready=true track=A paused=false",
+ "10-16 23:28:18.625 1 1 D Myspoti : console WARNING: The resource https://x/a.woff2 was preloaded using link preload but not used",
+ "10-16 23:28:26.563 1 1 D Myspoti : status ready=true track=A paused=false",
+ "10-16 23:28:27.000 1 1 D Myspoti : page net: {\"type\":\"net\",\"status\":200,\"ms\":3}",
+ "10-16 23:28:36.564 1 1 D Myspoti : status ready=true track=B paused=false",
+ "10-16 23:28:37.000 1 1 W MspPlayer: command failed: Timed out",
+ ).joinToString("\n")
+ val kept = BetaLogs.useful(text).lines()
+ assertEquals(3, kept.size)
+ assertEquals(true, kept[1].endsWith("track=B paused=false"))
+ assertEquals(true, kept[2].contains("MspPlayer"))
+ }
+}