Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Downloads try the file that fits the chosen quality best first, from every download extension at once, and extensions get myspoti.util.sleep(ms) for backoffs
kota-zoacd3b5b79730
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.ktindex f3e0e6ac..be4f5345 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@@ -340,7 +340,10 @@ object OfflineDownloader {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.isrcMatched,+ file = out.name, cover = cover,+ source = if (quality == com.music.spotui.data.preferences.DownloadQuality.SMALL && file.lossy == null)+ "${providerWithoutQuality(file.providerName)} AAC ${AacTranscoder.BITRATE / 1000} kbit/s" else file.provider,+ verified = file.isrcMatched,bytes = out.length(), addedAt = System.currentTimeMillis(), providerId = file.extensionId,extensionQuality = com.music.spotui.extensions.Extensions.qualityLine(file.extensionId, app.myspoti.extensions.SettingSection.DOWNLOADS),)@@ -357,6 +360,8 @@ object OfflineDownloader {val extensionId: String,/** The extension of a lossy file kept as served (m4a, mp3); null for a FLAC. */val lossy: String? = null,+ /** Source name before the measured quality is appended (encoding may change it). */+ val providerName: String = provider,)/** This download's quality: the one chosen when it started, else Settings (CD when Settings says "ask"). */@@ -374,77 +379,114 @@ object OfflineDownloader {/*** Asks the download-source extensions for [meta]'s files and saves the first one that works- * into [out]. Unavailable when no extension has a file, or none of them could be used.+ * into [out]: all of them are asked at once, and their files are tried best fit to [quality]+ * first ([downloadFit]; ties: the exact recording, then the user's order, then the order the+ * extension gave). When none of a round's files can be used, the extensions that answered+ * meanwhile are tried. Unavailable when no extension has a file, or none of them could be used.*/private suspend fun resolveAndFetch(r: Request, meta: Meta, out: File, quality: com.music.spotui.data.preferences.DownloadQuality): Fetched {val track = com.music.spotui.extensions.Extensions.trackInfo(r.trackId, meta.title, meta.artist, meta.album, meta.durationMs, meta.coverUrl).copy(isrc = meta.isrc)- val (extensionId, extension, files) = com.music.spotui.extensions.Extensions.downloadFiles(track, queryQuality(quality))- ?: throw Unavailable("no download source has this song")+ val seen = mutableListOf<String>()+ var tried = 0// The last error of a file that could not be fetched (not refused or failed a check): the song is then// a download that failed and can be tried again, not a recording that was not found.var fetchError: Exception? = null- for (file in files) {- currentCoroutineContext().ensureActive()- setStatus(r.trackId, OfflineStatus.Downloading(-1f))- val label = listOfNotNull(file.provider ?: extension, file.bitDepth?.takeIf { file.lossless }?.let { "$it-bit" }).joinToString(" ")- val ok = try {- when {- file.format == "dash-flac" -> runInterruptible(Dispatchers.IO) {- DashFlacRemux.download("data:application/dash+xml;base64,${file.manifest}", out, file.headers)- }- else -> fetchWithProgress(r.trackId, file.url!!, out, file.headers)- } && out.length() >= 10_000 && runInterruptible(Dispatchers.IO) {- file.transform?.let { spec ->- val staged = File.createTempFile("download-transform-", ".partial", out.parentFile)- try {- out.inputStream().use { input -> staged.outputStream().use { output ->- app.myspoti.extensions.PatternedBlowfish.transform(input, output, spec)- } }- if (Thread.currentThread().isInterrupted) throw java.io.InterruptedIOException("transform cancelled")- java.nio.file.Files.move(staged.toPath(), out.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)- } finally { staged.delete() }- }- true- }- } catch (e: CancellationException) {- throw e- } catch (e: Exception) {- Log.w(TAG, "${meta.title}: $label ${file.format}: ${e.message}")- if (e !is app.myspoti.extensions.ExtensionMediaHttp.Refused && !app.myspoti.extensions.SafeNet.isRefusal(e)) fetchError = e- false+ val fetched = com.music.spotui.extensions.Extensions.download(+ track, queryQuality(quality),+ fit = { files -> files.maxOf { downloadFit(quality, it) } },+ bestFit = BEST_FIT,+ graceMs = { best -> if (best >= BEST_FIT) GRACE_BEST_MS else GRACE_MS },+ ) { offers ->+ seen += offers.map { it.name }+ val files = downloadOrder(quality, offers.map { it.files })+ Log.i(TAG, "${meta.title}: trying ${files.size} files from ${offers.joinToString { it.name }}")+ files.firstNotNullOfOrNull { (i, file) ->+ tried+++ fetchOne(r, meta, out, file, offers[i].extensionId, offers[i].name) { fetchError = it }}- if (!ok) continue- val refused = runCatching {- if (file.lossless) checkFlacHeader(out, meta, file.bitDepth) else checkAudio(out, meta)- }.exceptionOrNull()- if (refused != null) { Log.i(TAG, "${meta.title}: $label: ${refused.message}"); continue }- if (!file.lossless) {- Log.i(TAG, "${meta.title}: saved $label ${file.format}")- return Fetched(label, file.isrcMatched, extensionId, lossy = file.format)+ }+ if (fetched != null) {+ com.music.spotui.extensions.Extensions.downloaded(fetched.extensionId, meta.title)+ return fetched+ }+ if (seen.isEmpty()) throw Unavailable("no download source has this song")+ fetchError?.let { throw IOException("none of the $tried files from ${seen.joinToString()} could be fetched: ${it.message}", it) }+ throw Unavailable("none of the $tried files from ${seen.joinToString()} could be used")+ }++ /**+ * [file] saved into [out] and checked, or null when it could not be fetched or is not the song+ * ([onFetchError] hears of a failure that is not a refusal).+ */+ private suspend fun fetchOne(+ r: Request, meta: Meta, out: File, file: app.myspoti.extensions.DownloadFile, extensionId: String, extension: String,+ onFetchError: (Exception) -> Unit,+ ): Fetched? {+ currentCoroutineContext().ensureActive()+ setStatus(r.trackId, OfflineStatus.Downloading(-1f))+ val provider = file.provider ?: extension+ var label = provider+ val ok = try {+ when {+ file.format == "dash-flac" -> runInterruptible(Dispatchers.IO) {+ DashFlacRemux.download("data:application/dash+xml;base64,${file.manifest}", out, file.headers)+ }+ else -> fetchWithProgress(r.trackId, file.url!!, out, file.headers)+ } && out.length() >= 10_000 && runInterruptible(Dispatchers.IO) {+ file.transform?.let { spec ->+ val staged = File.createTempFile("download-transform-", ".partial", out.parentFile)+ try {+ out.inputStream().use { input -> staged.outputStream().use { output ->+ app.myspoti.extensions.PatternedBlowfish.transform(input, output, spec)+ } }+ if (Thread.currentThread().isInterrupted) throw java.io.InterruptedIOException("transform cancelled")+ java.nio.file.Files.move(staged.toPath(), out.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)+ } finally { staged.delete() }+ }+ true}- Log.i(TAG, "${meta.title}: saved FLAC from $label")- return Fetched(label, file.isrcMatched, extensionId)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.w(TAG, "${meta.title}: $label ${file.format}: ${e.message}")+ if (e !is app.myspoti.extensions.ExtensionMediaHttp.Refused && !app.myspoti.extensions.SafeNet.isRefusal(e)) onFetchError(e)+ false+ }+ if (!ok) return null+ val refused = runCatching {+ if (file.lossless) {+ val actual = checkFlacHeader(out, meta)+ label = downloadSourceLabel(provider, actual)+ if (file.bitDepth != null && file.bitDepth != actual.bitDepth)+ Log.i(TAG, "${meta.title}: source labelled ${file.bitDepth}-bit, file is ${actual.bitDepth}-bit")+ } else checkAudio(out, meta)+ }.exceptionOrNull()+ if (refused != null) { Log.i(TAG, "${meta.title}: $label: ${refused.message}"); return null }+ if (!file.lossless) {+ Log.i(TAG, "${meta.title}: saved $label ${file.format}")+ return Fetched(label, file.isrcMatched, extensionId, lossy = file.format)}- fetchError?.let { throw IOException("none of the ${files.size} files from $extension could be fetched: ${it.message}", it) }- throw Unavailable("none of the ${files.size} files from $extension could be used")+ Log.i(TAG, "${meta.title}: saved FLAC from $label")+ return Fetched(label, file.isrcMatched, extensionId, providerName = provider)}/*** A STREAMINFO read on the saved file: anything that is not a FLAC file (an encrypted or* AAC stream) is refused, a preview or another cut is caught (the header states the real- * length), and a misplaced 24-bit label shows up in the log.+ * length). Bit depth and sample rate come from the file, not the extension's label.*/- private fun checkFlacHeader(file: File, meta: Meta, bitDepth: Int?) {- val seconds = runCatching {+ private fun checkFlacHeader(file: File, meta: Meta): FlacStreamInfo {+ val actual = runCatching {file.inputStream().use { s ->val head = ByteArray(42); var off = 0while (off < head.size) { val n = s.read(head, off, head.size - off); if (n < 0) break; off += n }- flacDurationSec(head)+ flacStreamInfo(head.copyOf(off))}}.getOrNull() ?: throw Unavailable("the source did not send a FLAC file")- checkLength(seconds.toLong(), meta)- Log.d(TAG, "${meta.title}: FLAC ${seconds}s header check, labelled ${bitDepth ?: "-"}-bit")+ checkLength(actual.durationSeconds, meta)+ Log.d(TAG, "${meta.title}: FLAC ${actual.durationSeconds}s, ${actual.bitDepth}-bit, ${actual.sampleRate} Hz")+ return actual}/** An M4A / MP3 as served: the phone's own extractor must find an audio track of the song's length. */@@ -629,18 +671,73 @@ object OfflineDownloader {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"- /** 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+ internal data class FlacStreamInfo(val sampleRate: Int, val bitDepth: Int, val channels: Int, val totalSamples: Long) {+ val durationSeconds: Long get() = totalSamples / sampleRate+ }++ /** The first metadata block must be the complete, 34-byte FLAC STREAMINFO block. */+ internal fun flacStreamInfo(head: ByteArray): FlacStreamInfo? {+ if (head.size < 42 || String(head, 0, 4, Charsets.US_ASCII) != "fLaC") return null+ if ((head[4].toInt() and 0x7F) != 0 || head[5] != 0.toByte() || head[6] != 0.toByte() || head[7] != 34.toByte()) return null// Bytes 18..25: sample rate (20 bits), channels (3), bits/sample (5), total samples (36).var bits = 0Lfor (i in 18..25) bits = (bits shl 8) or (head[i].toLong() and 0xFF)val sampleRate = (bits ushr 44).toInt()+ val channels = ((bits ushr 41) and 7).toInt() + 1+ val bitDepth = ((bits ushr 36) and 31).toInt() + 1val totalSamples = bits and 0xFFFFFFFFFL- if (sampleRate <= 0 || totalSamples <= 0) return null- return (totalSamples / sampleRate).toInt()+ if (sampleRate !in 1..768_000 || bitDepth !in 4..32 || totalSamples <= 0) return null+ return FlacStreamInfo(sampleRate, bitDepth, channels, totalSamples)+ }++ /** Length from a checked FLAC STREAMINFO header. */+ internal fun flacDurationSec(head: ByteArray): Int? = flacStreamInfo(head)?.durationSeconds?.toInt()++ /** Strip descriptive quality suffixes before appending what the file actually contains. */+ internal fun providerWithoutQuality(provider: String): String = provider.trim()+ .replace(Regex("(?i)(?:\\s+(?:\\d{1,2}\\s*-?\\s*bit|hi[- ]?res))+$"), "").trim()++ internal fun downloadSourceLabel(provider: String, actual: FlacStreamInfo): String {+ val rate = if (actual.sampleRate % 1000 == 0) (actual.sampleRate / 1000).toString()+ else "%.1f".format(java.util.Locale.ROOT, actual.sampleRate / 1000.0)+ return "${providerWithoutQuality(provider)} ${actual.bitDepth}-bit · $rate kHz"+ }++ /** The best [downloadFit]. */+ internal const val BEST_FIT = 3+ /** How long the best fit waits for the extensions above it, once it is in. */+ private const val GRACE_BEST_MS = 2_000L+ /** How long a lesser fit waits for a better one from a slower extension. */+ private const val GRACE_MS = 8_000L++ /**+ * How well [file] fits [quality], up to [BEST_FIT]: hi-res wants more than 16-bit or 48 kHz,+ * CD a 16-bit FLAC (a bigger one next), small a file kept as served (a FLAC is encoded to AAC+ * on the phone). A lossy file for CD or hi-res comes last, but is still kept as served.+ */+ internal fun downloadFit(quality: com.music.spotui.data.preferences.DownloadQuality, file: app.myspoti.extensions.DownloadFile): Int = when (quality) {+ com.music.spotui.data.preferences.DownloadQuality.SMALL -> if (file.lossless) 2 else 3+ com.music.spotui.data.preferences.DownloadQuality.HI_RES -> when {+ !file.lossless -> 1+ (file.bitDepth ?: 0) > 16 || (file.sampleRate ?: 0) > 48_000 -> 3+ else -> 2+ }+ else -> when {+ !file.lossless -> 1+ (file.bitDepth ?: 16) > 16 -> 2+ else -> 3+ }}+ /**+ * The files of a round's [offers] (best first, as [Extensions.download] gave them) in the+ * order they are tried, each with its offer's index: best fit, then the exact recording+ * (found by ISRC), then the offers' order, then each extension's own order.+ */+ internal fun downloadOrder(quality: com.music.spotui.data.preferences.DownloadQuality, offers: List<List<app.myspoti.extensions.DownloadFile>>): List<Pair<Int, app.myspoti.extensions.DownloadFile>> =+ offers.flatMapIndexed { i, files -> files.map { i to it } }+ .sortedWith(compareByDescending<Pair<Int, app.myspoti.extensions.DownloadFile>> { downloadFit(quality, it.second) }.thenByDescending { it.second.isrcMatched })+/** Why a file of [seconds] is not the song of [durationMs], or null when it is (or the song's length is unknown). */internal fun lengthMismatch(seconds: Long, durationMs: Long): String? {val expected = durationMs / 1000diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.ktindex 1b761519..021697b3 100644--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt@@ -752,14 +752,27 @@ object Extensions {private fun startingDownloadSource(): Boolean =!started.isCompleted && _registry.value.extensions.any { it.enabled && Action.DOWNLOAD_SOURCE.key in it.granted }+ /** One extension's answer for a download: its files, best first as it gave them. */+ class DownloadOffer(val extensionId: String, val name: String, val files: List<DownloadFile>)+/**- * The files [track] can be downloaded from in [quality] (`hi-res`, `cd`, `small`), best first,- * from the first extension (priority order) that has any, with that extension's id and name.- * A source set aside for a while ([SourceCooldown]) is not asked. Null when every source asked said it- * does not have the song; [NotAnswering] when none had it and one could not answer (busy, a timeout,- * set aside) or was not asked (its `status` said inactive, still starting: [downloadNotAsked]).+ * The files [track] can be downloaded from in [quality] (`hi-res`, `cd`, `small`): every+ * download extension is asked at once, and [use] gets their answers in rounds+ * ([HookDispatch.inRounds]): the ones that fit [quality] best first ([fit], up to [bestFit]),+ * ties in the user's order, until it saves a file (non-null). A slow extension holds a round+ * back for [graceMs] at most once another has answered; its answer still comes in a later+ * round. A source set aside for a while ([SourceCooldown]) is not asked. Null when every source asked said it+ * does not have the song, or [use] took none of their files; [NotAnswering] when none had it and one could not+ * answer (busy, a timeout, set aside) or was not asked (its `status` said inactive, still starting: [downloadNotAsked]).*/- suspend fun downloadFiles(track: TrackInfo, quality: String): Triple<String, String, List<DownloadFile>>? {+ suspend fun <T : Any> download(+ track: TrackInfo,+ quality: String,+ fit: (List<DownloadFile>) -> Int,+ bestFit: Int,+ graceMs: (bestSoFar: Int) -> Long,+ use: suspend (List<DownloadOffer>) -> T?,+ ): T? {if (!isReady) throw NotAnswering("extensions not started yet")// Asked right after launch (downloads resumed from the last session): the extensions still// loading are waited for, rather than the song marked unavailable for want of a source.@@ -771,12 +784,20 @@ object Extensions {val input = DownloadQuery.toJson(track, quality)probeStale(Hook.DOWNLOAD_SOURCE)val answers = ConcurrentHashMap<String, Outcome>()- val found = HookDispatch.firstInOrder(available(Hook.DOWNLOAD_SOURCE)) { (id, rt) ->- val a = ask(id, rt, Hook.DOWNLOAD_SOURCE, input, DOWNLOAD_MS) { DownloadFile.parseList(it).takeIf { l -> l.isNotEmpty() } }- answers[id] = a.outcome- a.value+ var offered = false+ val taken = HookDispatch.inRounds(+ available(Hook.DOWNLOAD_SOURCE),+ ask = { (id, rt) ->+ val a = ask(id, rt, Hook.DOWNLOAD_SOURCE, input, DOWNLOAD_MS) { DownloadFile.parseList(it).takeIf { l -> l.isNotEmpty() } }+ answers[id] = a.outcome+ a.value?.also { files -> log(id, "download files for ${track.title} ($quality, ${a.ms} ms): ${files.joinToString { "${it.format}/${it.bitDepth ?: "-"}" }}") }+ },+ fit = fit, bestFit = bestFit, graceMs = graceMs,+ ) { round ->+ offered = true+ use(round.map { (c, files) -> DownloadOffer(c.first, c.second.manifest.name, files) })}- if (found == null) {+ if (taken == null && !offered) {// A source that could not answer (busy, a timeout, a rate limit, set aside) has not said the song is not// there, nor has one on that was not asked: told apart from "no source has it", so the song is retried// instead of marked unavailable.@@ -789,11 +810,12 @@ object Extensions {throw NotAnswering(why, silent.map { (id, _) -> manifest(id)?.name ?: id }.distinct())}}- return found?.let { (c, files) ->- log(c.first, "download files for ${track.title}: ${files.joinToString { "${it.format}/${it.bitDepth ?: "-"}" }}")- did(Area.AUDIO, c.first, "Download of ${track.title} from ${c.second.manifest.name}")- Triple(c.first, c.second.manifest.name, files)- }+ return taken+ }++ /** [extensionId]'s file of [title] was saved: shown in its activity. */+ fun downloaded(extensionId: String, title: String) {+ did(Area.AUDIO, extensionId, "Download of $title from ${manifest(extensionId)?.name ?: extensionId}")}/**diff --git a/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt b/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.ktindex 94169178..a976d926 100644--- a/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/HookDispatch.kt@@ -8,6 +8,8 @@ import com.music.spotui.data.entity.Lyricsimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.asyncimport kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.selects.select+import kotlinx.coroutines.withTimeoutOrNull/*** The order hooks are asked in, without Android: every extension providing the hook is asked@@ -42,6 +44,56 @@ object HookDispatch {best}+ /**+ * Every candidate asked at once, the answers handed to [use] in rounds until it takes one+ * (non-null). A round starts once an answer is in, then waits [graceMs] at most for better+ * ones: it starts sooner when the best answer so far fits [bestFit] and every candidate before+ * it has answered. A round holds the answers not tried yet, best [fit] first, ties in+ * [candidates]' order; the answers that come in during [use] make the next round. The+ * candidates still asking are cancelled once [use] takes one or none is left to ask.+ */+ suspend fun <C, R : Any, T : Any> inRounds(+ candidates: List<C>,+ ask: suspend (C) -> R?,+ fit: (R) -> Int,+ bestFit: Int,+ graceMs: (bestSoFar: Int) -> Long,+ use: suspend (List<Pair<C, R>>) -> T?,+ ): T? = coroutineScope {+ val asked = candidates.map { c -> async { answer { ask(c) } } }+ val done = BooleanArray(asked.size)+ val results = arrayOfNulls<Any>(asked.size)+ val tried = BooleanArray(asked.size)+ suspend fun awaitOne() = select<Unit> {+ asked.forEachIndexed { i, d -> if (!done[i]) d.onAwait { done[i] = true; results[i] = it } }+ }+ @Suppress("UNCHECKED_CAST")+ fun fresh() = results.indices.filter { !tried[it] && results[it] != null }+ .sortedWith(compareByDescending<Int> { fit(results[it] as R) }.thenBy { it })+ @Suppress("UNCHECKED_CAST")+ fun ready(): Boolean {+ val best = fresh().firstOrNull() ?: return false+ return fit(results[best] as R) >= bestFit && (0 until best).all { done[it] }+ }+ try {+ var taken: T? = null+ while (taken == null) {+ while (fresh().isEmpty() && done.any { !it }) awaitOne()+ val first = fresh().firstOrNull() ?: break+ @Suppress("UNCHECKED_CAST")+ withTimeoutOrNull(graceMs(fit(results[first] as R))) {+ while (done.any { !it } && !ready()) awaitOne()+ }+ val round = fresh().onEach { tried[it] = true }+ @Suppress("UNCHECKED_CAST")+ taken = use(round.map { candidates[it] to results[it] as R })+ }+ taken+ } finally {+ asked.forEach { it.cancel() }+ }+ }+private suspend fun <R> answer(block: suspend () -> R?): R? = try {block()} catch (e: CancellationException) {diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xmlindex d951c343..256e0f34 100644--- a/base/app/src/main/res/values-de/myspoti_strings.xml+++ b/base/app/src/main/res/values-de/myspoti_strings.xml@@ -244,7 +244,7 @@<string name="downloads_off_toast">Downloads sind aus. Schalte sie in den Einstellungen ein.</string><string name="quality_streaming_high_detail">160 kbit/s, der beste Klang</string><string name="quality_download_small">Kleinste</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, am leichtesten: etwa 3 MB pro Song</string>+ <string name="quality_download_small_detail">Kleine Quelldatei oder AAC mit 96 kbit/s bei Konvertierung; Größe variiert</string><string name="settings_solid_nav_title">Feste untere Leiste</string><string name="settings_solid_nav_detail">Schwarz hinter den Tabs, statt eines Verlaufs über der Liste</string><string name="quality_download_ask">Jedes Mal fragen</string>diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xmlindex 9e447954..0423c2aa 100644--- a/base/app/src/main/res/values-el/myspoti_strings.xml+++ b/base/app/src/main/res/values-el/myspoti_strings.xml@@ -244,7 +244,7 @@<string name="downloads_off_toast">Οι λήψεις είναι απενεργοποιημένες. Ενεργοποίησέ τες στις Ρυθμίσεις.</string><string name="quality_streaming_high_detail">160 kbit/s, ο καλύτερος ήχος</string><string name="quality_download_small">Μικρότερη</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, η ελαφρύτερη: περίπου 3 MB ανά τραγούδι</string>+ <string name="quality_download_small_detail">Μικρό αρχείο πηγής ή AAC 96 kbit/s μετά τη μετατροπή· το μέγεθος ποικίλλει</string><string name="settings_solid_nav_title">Συμπαγής κάτω μπάρα</string><string name="settings_solid_nav_detail">Μαύρο πίσω από τις καρτέλες, αντί για σβήσιμο πάνω από τη λίστα</string><string name="quality_download_ask">Ρώτα κάθε φορά</string>diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xmlindex 0b35dc2d..9570a195 100644--- a/base/app/src/main/res/values-es/myspoti_strings.xml+++ b/base/app/src/main/res/values-es/myspoti_strings.xml@@ -244,7 +244,7 @@<string name="downloads_off_toast">Las descargas están desactivadas. Actívalas en Ajustes.</string><string name="quality_streaming_high_detail">160 kbit/s, el mejor sonido</string><string name="quality_download_small">La más ligera</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, la más ligera: unos 3 MB por canción</string>+ <string name="quality_download_small_detail">Archivo pequeño de la fuente o AAC a 96 kbit/s al convertir; tamaño variable</string><string name="settings_solid_nav_title">Barra inferior sólida</string><string name="settings_solid_nav_detail">Negra detrás de las pestañas, en lugar de un desvanecido sobre la lista</string><string name="quality_download_ask">Preguntar cada vez</string>diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xmlindex a2df8c91..8a713432 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -292,7 +292,7 @@<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="quality_download_small">La plus légère</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, le minimum : environ 3 Mo par titre</string>+ <string name="quality_download_small_detail">Petit fichier de la source, ou AAC 96 kbit/s après conversion ; taille variable</string><string name="settings_solid_nav_title">Barre du bas opaque</string><string name="settings_solid_nav_detail">Noire derrière les onglets, au lieu d\'un fondu sur la liste</string><string name="quality_download_ask">Demander à chaque fois</string>diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xmlindex 992f8b21..73b116a9 100644--- a/base/app/src/main/res/values-it/myspoti_strings.xml+++ b/base/app/src/main/res/values-it/myspoti_strings.xml@@ -244,7 +244,7 @@<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="quality_download_small">La più leggera</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, la minima: circa 3 MB per brano</string>+ <string name="quality_download_small_detail">File piccolo dalla fonte o AAC a 96 kbit/s dopo conversione; dimensioni variabili</string><string name="settings_solid_nav_title">Barra in basso opaca</string><string name="settings_solid_nav_detail">Nera dietro le schede, invece di una sfumatura sull\'elenco</string><string name="quality_download_ask">Chiedi ogni volta</string>diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xmlindex b93f04eb..90881d8f 100644--- a/base/app/src/main/res/values-pl/myspoti_strings.xml+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml@@ -268,7 +268,7 @@<string name="downloads_off_toast">Pobieranie jest wyłączone. Włącz je w Ustawieniach.</string><string name="quality_streaming_high_detail">160 kbit/s, najlepszy dźwięk</string><string name="quality_download_small">Najmniejsza</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, najlżejsza: około 3 MB na utwór</string>+ <string name="quality_download_small_detail">Mały plik źródłowy lub AAC 96 kbit/s po konwersji; rozmiar może się różnić</string><string name="settings_solid_nav_title">Pełny dolny pasek</string><string name="settings_solid_nav_detail">Czerń pod kartami zamiast zanikania nad listą</string><string name="quality_download_ask">Pytaj za każdym razem</string>diff --git a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xmlindex 846bfb64..0ede7218 100644--- a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml@@ -288,7 +288,7 @@<string name="downloads_off_toast">Os downloads estão desativados. Ative-os em Configurações.</string><string name="quality_streaming_high_detail">160 kbit/s, o melhor som</string><string name="quality_download_small">Menor</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, o mais leve: cerca de 3 MB por música</string>+ <string name="quality_download_small_detail">Arquivo pequeno da fonte ou AAC a 96 kbit/s após conversão; tamanho variável</string><string name="settings_solid_nav_title">Barra inferior sólida</string><string name="settings_solid_nav_detail">Preto atrás das abas, em vez de um esmaecido sobre a lista</string><string name="quality_download_ask">Perguntar sempre</string>diff --git a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xmlindex dcd5814c..766a532a 100644--- a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml@@ -238,7 +238,7 @@<string name="downloads_off_toast">As transferências estão desativadas. Ativa-as nas Definições.</string><string name="quality_streaming_high_detail">160 kbit/s, o melhor som</string><string name="quality_download_small">Mais pequena</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, a mais leve: cerca de 3 MB por música</string>+ <string name="quality_download_small_detail">Ficheiro pequeno da fonte ou AAC a 96 kbit/s após conversão; tamanho variável</string><string name="settings_solid_nav_title">Barra inferior opaca</string><string name="settings_solid_nav_detail">Preta por trás dos separadores, em vez de um esbatido sobre a lista</string><string name="quality_download_ask">Perguntar sempre</string>diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xmlindex 9c92218c..148ec8db 100644--- a/base/app/src/main/res/values-pt/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml@@ -244,7 +244,7 @@<string name="downloads_off_toast">Os downloads estão desativados. Ative-os nas Configurações.</string><string name="quality_streaming_high_detail">160 kbit/s, o melhor som</string><string name="quality_download_small">Mais pequena</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, a mais leve: cerca de 3 MB por música</string>+ <string name="quality_download_small_detail">Arquivo pequeno da fonte ou AAC a 96 kbit/s após conversão; tamanho variável</string><string name="settings_solid_nav_title">Barra inferior opaca</string><string name="settings_solid_nav_detail">Preta por trás das abas, em vez de um desfoque sobre a lista</string><string name="quality_download_ask">Perguntar sempre</string>diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xmlindex 0af7044e..540a5b34 100644--- a/base/app/src/main/res/values-ru/myspoti_strings.xml+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml@@ -268,7 +268,7 @@<string name="downloads_off_toast">Загрузки отключены. Включите их в настройках.</string><string name="quality_streaming_high_detail">160 кбит/с, лучший звук</string><string name="quality_download_small">Наименьшее</string>- <string name="quality_download_small_detail">AAC 96 кбит/с, самое лёгкое: около 3 МБ на трек</string>+ <string name="quality_download_small_detail">Небольшой файл источника или AAC 96 кбит/с после конвертации; размер может отличаться</string><string name="settings_solid_nav_title">Сплошная нижняя панель</string><string name="settings_solid_nav_detail">Чёрный фон под вкладками вместо затухания поверх списка</string><string name="quality_download_ask">Спрашивать каждый раз</string>diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xmlindex 3717d189..bb477d2d 100644--- a/base/app/src/main/res/values-zh/myspoti_strings.xml+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml@@ -265,7 +265,7 @@<string name="downloads_off_toast">下载已关闭。请在“设置”中开启。</string><string name="quality_streaming_high_detail">160 kbit/s,最佳音质</string><string name="quality_download_small">最小</string>- <string name="quality_download_small_detail">AAC 96 kbit/s,最轻量:每首约 3 MB</string>+ <string name="quality_download_small_detail">保留来源的小文件,或转换为 AAC 96 kbit/s;大小因来源而异</string><string name="settings_solid_nav_title">纯色底部栏</string><string name="settings_solid_nav_detail">标签栏后面为黑色,而不是在列表上渐隐</string><string name="quality_download_ask">每次询问</string>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 487cacf5..5a9fc416 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -297,7 +297,7 @@<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="quality_download_small">Smallest</string>- <string name="quality_download_small_detail">AAC 96 kbit/s, the lightest: about 3 MB a song</string>+ <string name="quality_download_small_detail">Small source file, or AAC 96 kbit/s when converted; size varies</string><string name="settings_solid_nav_title">Solid bottom bar</string><string name="settings_solid_nav_detail">Black behind the tabs, instead of a fade over the list</string><string name="quality_download_ask">Ask each time</string>diff --git a/base/app/src/test/java/com/music/spotui/data/offline/FlacDurationTest.kt b/base/app/src/test/java/com/music/spotui/data/offline/FlacDurationTest.ktindex 944e7d05..ce83e0ea 100644--- a/base/app/src/test/java/com/music/spotui/data/offline/FlacDurationTest.kt+++ b/base/app/src/test/java/com/music/spotui/data/offline/FlacDurationTest.kt@@ -9,11 +9,13 @@ class FlacDurationTest {private fun fakeFlac(sampleRate: Int = 44_100, samples: Long = sampleRate * 200L): ByteArray {val head = ByteArray(42)"fLaC".toByteArray().copyInto(head)+ head[4] = 0x80.toByte() // last metadata block, STREAMINFO+ head[7] = 34// 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))+ (1L shl 41) or // stereo (channels - 1)+ (15L shl 36) or ((samples and 0xFFFFFFFFL))for (i in 0 until 8) head[18 + i] = (packed ushr (56 - 8 * i)).toByte()return head}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.ktindex 5fefcaa6..ac672f6e 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,11 +1,74 @@package com.music.spotui.data.offline+import com.music.spotui.data.preferences.DownloadQualityimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Testclass OfflineDownloaderTest {+ private fun flacHeader(rate: Int = 44_100, depth: Int = 16, channels: Int = 2, seconds: Int = 200): ByteArray {+ val head = ByteArray(42)+ "fLaC".toByteArray(Charsets.US_ASCII).copyInto(head)+ head[4] = 0x80.toByte() // Last metadata block, type STREAMINFO.+ head[7] = 34+ val packed = (rate.toLong() shl 44) or ((channels - 1).toLong() shl 41) or+ ((depth - 1).toLong() shl 36) or (rate.toLong() * seconds)+ for (i in 0..7) head[18 + i] = (packed ushr ((7 - i) * 8)).toByte()+ return head+ }++ @Test fun flacQualityComesFromStreamInfo() {+ val cd = OfflineDownloader.flacStreamInfo(flacHeader())!!+ assertEquals(44_100, cd.sampleRate)+ assertEquals(16, cd.bitDepth)+ assertEquals(2, cd.channels)+ assertEquals(200L, cd.durationSeconds)+ val hiRes = OfflineDownloader.flacStreamInfo(flacHeader(96_000, 24, 1, 163))!!+ assertEquals(96_000, hiRes.sampleRate)+ assertEquals(24, hiRes.bitDepth)+ assertEquals(1, hiRes.channels)+ assertEquals(163, OfflineDownloader.flacDurationSec(flacHeader(96_000, 24, 1, 163)))+ }++ @Test fun measuredQualityReplacesFalseAndDuplicateLabels() {+ val cd = OfflineDownloader.flacStreamInfo(flacHeader())!!+ assertEquals("Qobuz 16-bit · 44.1 kHz", OfflineDownloader.downloadSourceLabel("Qobuz 24-bit 24-bit", cd))+ assertEquals("Tidal 16-bit · 44.1 kHz", OfflineDownloader.downloadSourceLabel("Tidal hi-res", cd))+ assertEquals("Example provider 16-bit · 44.1 kHz", OfflineDownloader.downloadSourceLabel("Example provider", cd))+ val hiRes = OfflineDownloader.flacStreamInfo(flacHeader(96_000, 24))!!+ assertEquals("Qobuz 24-bit · 96 kHz", OfflineDownloader.downloadSourceLabel("Qobuz 24-bit", hiRes))+ assertEquals("Qobuz 16-bit · 44.1 kHz", OfflineDownloader.downloadSourceLabel(" Qobuz 24-bit ", cd))+ }++ @Test fun filesAreTriedByFitToTheQualityThenRecordingThenOrder() {+ fun f(format: String, bits: Int? = null, isrc: Boolean = false) = app.myspoti.extensions.DownloadFile(+ url = "https://example.com/x.$format", manifest = null, headers = emptyMap(), format = format, bitDepth = bits,+ sampleRate = null, sizeHint = null, provider = null, isrcMatched = isrc)+ val first = listOf(f("m4a"), f("flac", 24))+ val second = listOf(f("flac", 16), f("flac", 16, isrc = true))+ val order = { quality: DownloadQuality ->+ OfflineDownloader.downloadOrder(quality, listOf(first, second)).map { (i, file) -> "$i:${file.format}/${file.bitDepth}/${file.isrcMatched}" }+ }+ assertEquals(listOf("1:flac/16/true", "1:flac/16/false", "0:flac/24/false", "0:m4a/null/false"), order(DownloadQuality.CD))+ assertEquals(listOf("0:flac/24/false", "1:flac/16/true", "1:flac/16/false", "0:m4a/null/false"), order(DownloadQuality.HI_RES))+ assertEquals(listOf("0:m4a/null/false", "1:flac/16/true", "0:flac/24/false", "1:flac/16/false"), order(DownloadQuality.SMALL))+ assertEquals(OfflineDownloader.BEST_FIT, OfflineDownloader.downloadFit(DownloadQuality.CD, f("flac")))+ }++ @Test fun malformedAndTruncatedFlacHeadersAreRefused() {+ val valid = flacHeader()+ assertNull(OfflineDownloader.flacStreamInfo(valid.copyOf(26)))+ assertNull(OfflineDownloader.flacStreamInfo(valid.copyOf().also { it[0] = 0 }))+ assertNull(OfflineDownloader.flacStreamInfo(valid.copyOf().also { it[4] = 0x81.toByte() }))+ assertNull(OfflineDownloader.flacStreamInfo(valid.copyOf().also { it[7] = 33 }))+ assertNull(OfflineDownloader.flacStreamInfo(flacHeader(rate = 0)))+ assertNull(OfflineDownloader.flacStreamInfo(flacHeader(depth = 1)))+ assertNull(OfflineDownloader.flacStreamInfo(flacHeader(seconds = 0)))+ // STREAMINFO need not be the final metadata block.+ assertEquals(16, OfflineDownloader.flacStreamInfo(valid.copyOf().also { it[4] = 0 })!!.bitDepth)+ }+@Test fun contentRangeTotalReadsTheFullSize() {assertEquals(1234L, OfflineDownloader.contentRangeTotal("bytes 0-99/1234"))assertNull(OfflineDownloader.contentRangeTotal("bytes 0-99/*"))diff --git a/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt b/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.ktindex 69f149b6..c36e580c 100644--- a/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt+++ b/base/app/src/test/java/com/music/spotui/extensions/HookDispatchTest.kt@@ -31,6 +31,50 @@ class HookDispatchTest {assertNull(HookDispatch.firstInOrder(emptyList<String>()) { "x" })}+ @Test fun aRoundTheUseRefusesGivesTheTurnToTheOthers() = runBlocking {+ val rounds = mutableListOf<List<String>>()+ val r = HookDispatch.inRounds(listOf("a", "b", "c"), ask = { c -> when (c) { "a" -> "from a"; "b" -> { delay(200); "from b" }; else -> null } },+ fit = { 1 }, bestFit = 1, graceMs = { 1_000 }) { round ->+ rounds += round.map { it.first }+ round.firstOrNull { it.first == "b" }?.second+ }+ assertEquals("from b", r)+ assertEquals(listOf(listOf("a"), listOf("b")), rounds)+ }++ @Test fun theBestFitGoesFirstThenTheOrder() = runBlocking {+ val r = HookDispatch.inRounds(listOf("a", "b", "c"), ask = { c -> c }, fit = { if (it == "c") 3 else 1 },+ bestFit = 3, graceMs = { 1_000 }) { round -> round.map { it.first } }+ assertEquals(listOf("c", "a", "b"), r)+ }++ @Test fun aSlowCandidateIsWaitedForOnlyItsGraceThenComesNext() = runBlocking {+ val rounds = mutableListOf<List<String>>()+ val started = System.currentTimeMillis()+ val r = HookDispatch.inRounds(listOf("slow", "quick"), ask = { c -> if (c == "slow") { delay(1_500); "slow" } else "quick" },+ fit = { 1 }, bestFit = 2, graceMs = { 300 }) { round ->+ rounds += round.map { it.first }+ round.firstOrNull { it.first == "slow" }?.second+ }+ assertEquals("slow", r)+ assertEquals(listOf(listOf("quick"), listOf("slow")), rounds)+ assertTrue(System.currentTimeMillis() - started < 3_000)+ }++ @Test fun theBestFitStartsWithoutWaitingTheGraceOnceThoseAboveAnswered() = runBlocking {+ val started = System.currentTimeMillis()+ val r = HookDispatch.inRounds(listOf("a", "b", "late"), ask = { c -> if (c == "late") { delay(5_000); c } else c },+ fit = { if (it == "b") 3 else 1 }, bestFit = 3, graceMs = { 4_000 }) { round -> round.first().first }+ assertEquals("b", r)+ assertTrue(System.currentTimeMillis() - started < 2_000)+ }++ @Test fun noAnswerAtAllIsNullWithoutARound() = runBlocking {+ var used = false+ assertNull(HookDispatch.inRounds(listOf("a", "b"), ask = { null as String? }, fit = { 1 }, bestFit = 1, graceMs = { 100 }) { used = true; "x" })+ assertTrue(!used)+ }+@Test fun theOthersAreNotWaitedForOnceTheFirstAnswers() = runBlocking {val started = System.currentTimeMillis()val r = HookDispatch.firstInOrder(listOf("a", "b")) { c -> if (c == "a") "quick" else { delay(5_000); "slow" } }diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.ktindex 3a0417ca..43426350 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt@@ -644,6 +644,20 @@ class ExtensionRuntime(}private fun util(op: String, input: String): String = when (op) {+ "sleep" -> {+ val millis = input.toLongOrNull()?.takeIf { it >= 0 }?.coerceAtMost(MAX_SLEEP_MS)+ ?: throw error("util.sleep: a non-negative integer number of milliseconds")+ // A backoff is the script's time, unlike waiting for the user to confirm an action.+ if (millis >= leftMs()) throw TimeLimit()+ try {+ host.sleep(millis)+ } catch (e: InterruptedException) {+ Thread.currentThread().interrupt()+ throw TimeLimit() // Neither close nor timeout may be swallowed by JS try/catch.+ }+ leftMs() // Also enforce the deadline if scheduling delayed the wake-up.+ ""+ }"base64Encode" -> java.util.Base64.getEncoder().encodeToString(input.toByteArray())"base64Decode" -> runCatching { String(java.util.Base64.getDecoder().decode(input)) }.getOrElse { throw error("base64Decode: not base64") }"md5" -> hex(MessageDigest.getInstance("MD5").digest(input.toByteArray()))@@ -694,6 +708,8 @@ class ExtensionRuntime(const val MAX_NOTIFY_PER_HOUR = 5/** `http.all`: the most requests sent together. */const val MAX_PARALLEL = 4+ /** `util.sleep`: a bounded synchronous backoff; never a timer or a wait on the app's main thread. */+ const val MAX_SLEEP_MS = 2_000Lprivate val CONTROLS = setOf("play", "pause", "next", "previous", "seek")private val PRELUDE: String = ExtensionRuntime::class.java.getResource("prelude.js")!!.readText()diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.ktindex fa3ffe31..9fc95f87 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt@@ -18,6 +18,9 @@ interface Host {fun log(extensionId: String, message: String)+ /** Waits on the extension's own thread; the runtime bounds the duration and its deadline. */+ fun sleep(millis: Long) = Thread.sleep(millis)+/** The extension's own small store (key → JSON text). */fun storage(extensionId: String): Storagediff --git a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.jsindex 23ed4534..6de7ae24 100644--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js@@ -125,12 +125,12 @@/*** What this app understands beyond the first API, for an extension to adapt to: "audio.manifest",- * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "results" (source hooks may answer { outcome }), "settings.section" (manifest section, role, perNetwork), "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.+ * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "results" (source hooks may answer { outcome }), "settings.section" (manifest section, role, perNetwork), "util.sleep", "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.*/sources: Object.freeze({ race: function (hook, query, lanes) {return parse(host.sourceRace(String(hook),JSON.stringify(query),JSON.stringify(lanes)));} }),- features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'results', 'download.transform', 'audio.transform', 'sources.race', 'settings.section'].concat(parse(host.info()).mirror ? ['player.localMute'] : [], parse(host.info()).attest ? ['attest'] : [])),+ features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'results', 'download.transform', 'audio.transform', 'sources.race', 'settings.section', 'util.sleep'].concat(parse(host.info()).mirror ? ['player.localMute'] : [], parse(host.info()).attest ? ['attest'] : [])),/*** A sign-in page (webview.auth): open({ url, callback, hidden }) shows url in a web view of its@@ -181,6 +181,11 @@},util: Object.freeze({+ /** Synchronous backoff, counted in the hook's budget; at most two seconds. */+ sleep: function (ms) {+ if (typeof ms !== 'number' || !isFinite(ms) || ms < 0 || Math.floor(ms) !== ms) throw new TypeError('util.sleep: a non-negative integer number of milliseconds');+ host.util('sleep', String(Math.min(ms, 2000)));+ },base64Encode: function (text) { return host.util('base64Encode', String(text)); },base64Decode: function (text) { return host.util('base64Decode', String(text)); },md5: function (text) { return host.util('md5', String(text)); },diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/BasicHttpTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/BasicHttpTest.ktnew file mode 100644index 00000000..ee6acd42--- /dev/null+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/BasicHttpTest.kt@@ -0,0 +1,33 @@+package app.myspoti.extensions++import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBody+import org.junit.Assert.assertEquals+import org.junit.Test++class BasicHttpTest {+ @Test fun responsesAreDecodedAsUtf8AcrossReadBoundaries() {+ // The bridge reads in 16 KiB chunks: split a multibyte character across that boundary.+ val bodies = listOf("", """{"artist":"Björk — 東京 🎵"}""", "x".repeat(16 * 1024 - 1) + "é🎵")+ for (body in bodies) {+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .header("Content-Type", "application/json; charset=utf-8")+ .body(body.toByteArray(Charsets.UTF_8).toResponseBody())+ .build()+ }.build()++ // The interceptor answers in memory; no DNS or network access is used.+ val reply = BasicHttp.send(HttpRequest("https://example.com/bootstrap"), "test", client)+ assertEquals(200, reply.status)+ assertEquals("application/json; charset=utf-8", reply.headers["content-type"])+ assertEquals(body, reply.body)+ }+ }+}diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.ktindex c6165fb3..682f7f49 100644--- a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt@@ -11,13 +11,15 @@ import org.junit.Testclass SandboxTest {private val track = TrackInfo("abc", "spotify:track:abc", "Song", "Artist", listOf("Artist"), "Album", 180_000)- private class FakeHost : Host {+ private class FakeHost(val sleeper: ((Long) -> Unit)? = null) : Host {val requests = mutableListOf<HttpRequest>()val logs = mutableListOf<String>()+ val sleeps = mutableListOf<Long>()val store = MemoryStorage()var answer = HttpResponse(200, mapOf("content-type" to "application/json"), """{"ok":1}""")override fun http(extensionId: String, request: HttpRequest): HttpResponse { requests += request; return answer }override fun log(extensionId: String, message: String) { logs += message }+ override fun sleep(millis: Long) { sleeps += millis; sleeper?.invoke(millis) ?: super.sleep(millis) }override fun storage(extensionId: String): Storage = storeoverride fun setting(extensionId: String, key: String): String? = if (key == "lang") "\"fr\"" else nulloverride fun nowPlaying(): String = """{"title":"Now"}"""@@ -199,7 +201,60 @@ class SandboxTest {}@Test fun featuresNameWhatThisAppUnderstands() {- assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64,results,download.transform,audio.transform,sources.race,settings.section"}""", eval("return myspoti.features.join(',');"))+ assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64,results,download.transform,audio.transform,sources.race,settings.section,util.sleep"}""", eval("return myspoti.features.join(',');"))+ }++ @Test fun sleepCapsBackoffWithoutNeedingPermissions() {+ val host = FakeHost(sleeper = {})+ val out = eval("return [0, 1, 2000, 1000000000000].map(function (ms) { return typeof myspoti.util.sleep(ms); }).join(',');", host, granted = setOf("lyrics.provide"))+ assertEquals("""{"v":"undefined,undefined,undefined,undefined"}""", out)+ assertEquals(listOf(0L, 1L, 2000L, 2000L), host.sleeps)+ }++ @Test fun sleepRejectsInvalidDurationsBeforeCallingTheHost() {+ val host = FakeHost(sleeper = {})+ val out = eval("""+ return [-1, NaN, Infinity, 1.5, '5', null, undefined].every(function (ms) {+ try { myspoti.util.sleep(ms); return false; }+ catch (e) { return e instanceof TypeError && e.message.indexOf('util.sleep') >= 0; }+ });+ """, host)+ assertEquals("""{"v":true}""", out)+ assertTrue(host.sleeps.isEmpty())+ }++ @Test fun sleepCannotOverrunOrCatchTheHooksDeadline() {+ val host = FakeHost(sleeper = { fail("a wait beyond the deadline reached the host") })+ runtime("myspoti.provide('lyrics', function () { try { myspoti.util.sleep(2000); } catch (e) { return { plain: 'caught' }; } return { plain: 'done' }; });", host = host).use { rt ->+ try {+ rt.call(Hook.LYRICS, track.toJson(), 100)+ fail("a wait past the hook's deadline answered")+ } catch (e: ExtensionException) {+ assertTrue(e is ExtensionTimeout)+ }+ }+ assertTrue(host.sleeps.isEmpty())+ }++ @Test fun closeInterruptsSleepAndCannotBeSwallowedByTheScript() {+ val entered = java.util.concurrent.CountDownLatch(1)+ val host = FakeHost(sleeper = { millis -> entered.countDown(); Thread.sleep(millis) })+ val rt = runtime("myspoti.provide('lyrics', function () { try { myspoti.util.sleep(2000); } catch (e) { return { plain: 'caught' }; } return { plain: 'done' }; });", host = host)+ val result = java.util.concurrent.atomic.AtomicReference<Result<String?>>()+ val caller = Thread { result.set(runCatching { rt.call(Hook.LYRICS, track.toJson(), 5_000) }) }.apply { start() }+ try {+ assertTrue("sleep was never reached", entered.await(1, java.util.concurrent.TimeUnit.SECONDS))+ rt.close()+ caller.join(1_000)+ assertFalse("sleep ignored the runtime shutdown", caller.isAlive)+ val failure = result.get()?.exceptionOrNull()+ assertTrue(failure is ExtensionException)+ assertEquals("stopped", failure?.message)+ assertNull(rt.lastError)+ } finally {+ rt.close()+ caller.join(1_000)+ }}@Test fun localMuteFeatureIsListedOnlyWhenMirrorIsGranted() {diff --git a/docs/extensions/API.md b/docs/extensions/API.mdindex f8e9e66f..d81f9ae5 100644--- a/docs/extensions/API.md+++ b/docs/extensions/API.md@@ -255,7 +255,7 @@ player.buttons action in the manifest`):The lyrics, song details, Home, search, menu and player hooks are **additive**: every extension isasked, the answers merged in the area's order (lyrics: the best, ties to the higher one). Audio and-downloads are **ordered**: asked one after the other in the user's order until one answers (section 4.2). Registering twice replaces. Returning+downloads are **ordered**: asked one after the other in the user's order until one answers (section 4.2); for downloads the file that fits the quality best goes first (`download-source` below). Registering twice replaces. Returning`null`/`undefined` means "no answer": the app goes on without this extension. A throw is afailure (recorded as the extension's last error, shown on its page; 3 in a row turn it off). Atimeout, or an `http` error your script did not catch (DNS, connection, timeout), is a **network**@@ -418,13 +418,17 @@ described by one `SegmentTemplate` with `initialization`, `media` using `$Number`SegmentTimeline`; Myspoti fetches the segments with your `headers` and joins them into one FLACfile. Anything else a service needs (another manifest layout, decryption, an API call persegment, a token refresh) is yours to do: hand over a plain file `url`, or a manifest in that form.-Myspoti tries the files in your order and keeps the first that passes the checks: a FLAC must be+Myspoti keeps the first file that passes the checks: a FLAC must bea real FLAC file (its header is read), an `m4a` or `mp3` must hold an audio track the phone canread, and the length must be the song's (Spotify's duration): not shorter by more than 5 s(previews are refused) nor longer by more than 15 s (another version). `m4a` and `mp3` are kept as-served. A format outside the list, a private address or a missing `format` is an error. The-extensions are asked in the user's order for downloads (section 4.2); the first one that answers-wins. Time limit: 30 s (the desktop runner: the same).+served. A format outside the list, a private address or a missing `format` is an error. All+download extensions are asked at once; their files are tried best fit to `quality` first (hi-res:+more than 16-bit or 48 kHz; cd: a 16-bit FLAC; small: a file kept as served), then a file found by+ISRC, then the user's order for downloads (section 4.2), then your own order. When none of them can+be used, the files of the extensions that answered later are tried. Once one extension has+answered, a slower one is waited for 2 s (8 s when nothing fits the quality yet); its files still+come next if needed. Time limit: 30 s (the desktop runner: the same).### `status`@@ -794,7 +798,7 @@ A script that throws while loading fails to load, with `file:line` in the messag| `myspoti.apiVersion` | `1`. || `myspoti.locale` | The language Myspoti shows, as a BCP 47 tag: `"fr"`, `"pt-BR"`, `"zh-TW"`. Below. || `myspoti.extension` | `{ id, name, version }` from the manifest. |-| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `results` (section 3, "Outcomes"), `settings.section` (section 2: a setting's `section`, `role`, `perNetwork`), `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. |+| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `results` (section 3, "Outcomes"), `settings.section` (section 2: a setting's `section`, `role`, `perNetwork`), `util.sleep`, `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. || `myspoti.provide(hook, fn)` | Section 3. || `myspoti.on('track' \| 'playback', fn)` | Section 3. Needs `playback.events`. || `myspoti.on('auth', fn)` | Section 3, sign in. Needs `webview.auth`. |@@ -820,6 +824,7 @@ A script that throws while loading fails to load, with `file:line` in the messag| `myspoti.util.base64Encode(s)` / `base64Decode(s)` | UTF-8 text. Decode throws on bad input. || `myspoti.util.md5(s)`, `sha1(s)`, `sha256(s)` | Lower-case hex. || `myspoti.util.hmacSha256(key, text)` | Lower-case hex. |+| `myspoti.util.sleep(ms)` | Synchronous backoff on the extension thread, with no permission required. `ms` must be a finite, non-negative integer; values above 2000 are capped to 2000 ms. Returns `undefined`. Counts against the current hook/event time limit and stops on cancellation. An older host has no method: check `myspoti.util && typeof myspoti.util.sleep === 'function'` or the `util.sleep` feature before use. |`myspoti.locale` needs no action. It is the language picked in Myspoti's settings, or thephone's when the app follows the phone, so it is never empty. It is read again each time you@@ -1260,6 +1265,7 @@ is. `playlists.setCover` takes a JPEG as base64.| Script work | Checked every 5000 instructions against the call's time; a loop cannot hold the thread. A call that runs over is abandoned, and it cannot be caught by `try/catch`. The next call waits behind it on the extension's own thread, never on the app's. || Recursion | 800 interpreter frames || Time spent waiting for the user to confirm | Not counted |+| `myspoti.util.sleep(ms)` | At most 2000 ms per call, counted in the current hook/event budget; never extends its deadline || `myspoti.http` | 120 requests/min, 5 MB per response, 20 s per request, https only; `http.all`: 4 at once || `myspoti.spotify` | 60 calls/min, 256 KB of arguments, 1000 items per list, 2 MB per answer || `myspoti.attest` | `sign` 120/min and 64 KB of text; `enroll` 5/hour and a challenge of 128 bytes |