Skip to content

Native Android client for Spotify, built with Jetpack Compose

Extensions phase 1: optional structured outcomes (not found, sign-in, rate limited, quality unavailable, server down) with app-bounded cooldowns, only script bugs turn an extension off; one set of hook budgets for the app and the CLI; a ring of play attempts with a Why this source sheet and masked export; CLI exit codes, one device only, ext.why; myspoti-ext test scenarios with injected faults, check is package validity only

kota-zob61311068876
diff --git a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
index 0e4ac442..531b51ec 100644
--- a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
+++ b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt
@@ -37,7 +37,9 @@ class MyspotiApplication : Application() {
// The report's header: the extensions installed, with their versions.
app.myspoti.host.android.Logbook.headerExtras = {
val all = com.music.spotui.extensions.Extensions.registry.value.extensions
- listOf("extensions" to (all.joinToString { "${it.id} ${it.version}${if (it.enabled) "" else " (off)"}" }.ifEmpty { "none" }))
+ listOf("extensions" to (all.joinToString { "${it.id} ${it.version}${if (it.enabled) "" else " (off)"}" }.ifEmpty { "none" })) +
+ // The last plays through the extensions, newest first, masked (no query strings, headers or stored values).
+ com.music.spotui.extensions.Extensions.attempts.last().map { "play attempt" to it.summary() }
}
prefetch()
}
diff --git a/base/app/src/main/java/com/music/spotui/cli/Cli.kt b/base/app/src/main/java/com/music/spotui/cli/Cli.kt
index 1904499f..a0cc1b23 100644
--- a/base/app/src/main/java/com/music/spotui/cli/Cli.kt
+++ b/base/app/src/main/java/com/music/spotui/cli/Cli.kt
@@ -30,6 +30,8 @@ sealed interface CliCommand {
data class ExtCall(val id: String, val hook: Hook, val input: String) : CliCommand
data class ExtLog(val id: String, val lines: Int) : CliCommand
data class ExtStorage(val id: String) : CliCommand
+ /** The last [n] play attempts through the extensions (debug builds only). */
+ data class ExtWhy(val n: Int) : CliCommand
data class Play(val uri: String, val context: String?) : CliCommand
data object Pause : CliCommand
data object Resume : CliCommand
@@ -44,7 +46,7 @@ object CliParser {
val COMMANDS = listOf(
"status", "ext.list", "ext.install <zip path>", "ext.uninstall <id>", "ext.enable <id>", "ext.disable <id>",
"ext.setting <id> <key> <value|null>", "ext.press <id> <key>", "ext.call <id> <hook> [json]",
- "ext.log <id> [lines]", "ext.storage <id>", "play <spotify uri> [context uri]", "pause", "resume", "next", "previous",
+ "ext.log <id> [lines]", "ext.storage <id>", "ext.why [n]", "play <spotify uri> [context uri]", "pause", "resume", "next", "previous",
"nav <route>",
)
@@ -87,6 +89,7 @@ object CliParser {
}
"ext.log" -> CliCommand.ExtLog(id(), args.getOrNull(1)?.let { it.toIntOrNull()?.coerceIn(1, 1000) ?: throw CliError("ext.log: [lines] is a number") } ?: 50).also { most(2) }
"ext.storage" -> CliCommand.ExtStorage(id()).also { most(1) }
+ "ext.why" -> CliCommand.ExtWhy(args.getOrNull(0)?.let { it.toIntOrNull()?.coerceIn(1, 20) ?: throw CliError("ext.why: [n] is a number") } ?: 1).also { most(1) }
"play" -> {
most(2)
val uri = arg(0, "spotify uri").also { if (!URI.matches(it)) throw CliError("play: not a spotify: uri") }
diff --git a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
index 0ca16007..5e947cf8 100644
--- a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
+++ b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
@@ -53,6 +53,8 @@ class CliReceiver : BroadcastReceiver() {
tmp.renameTo(File(dir, "$req.json"))
}.onFailure { Log.w(TAG, "$req: reply not written: $it") }
Log.i(TAG, "$req $cmd ${reply.take(3500)}")
+ // 1: the receiver answered (an absent or disabled one leaves 0), how tools/myspoti-cli tells them apart.
+ pending.resultCode = 1
pending.resultData = if (reply.length < 1000) reply else null
pending.finish()
}
@@ -172,6 +174,18 @@ class CliReceiver : BroadcastReceiver() {
val known = secrets(c.id)
JsonArray(Extensions.logLines(c.id).takeLast(c.lines).map { JsonPrimitive(CliMask.text(it, known)) })
}
+ is CliCommand.ExtWhy -> {
+ // Debug builds only: a beta's receiver answers that it is off here (the CLI's exit code 5).
+ if (!app.myspoti.engine.BuildConfig.DEBUG) throw CliError(DISABLED)
+ // The song playing now: what the decoder reports, read on the player's thread.
+ onMain {
+ val t = com.music.spotui.di.LocalPlayer.current()?.uri?.takeIf { it.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME }
+ val detected = com.music.spotui.ui.components.detectedLabel(com.music.spotui.di.LocalPlayer.audioFormat())
+ if (t != null && detected != null) Extensions.noteAttempt(t.lastPathSegment) { it.copy(detected = detected) }
+ }
+ val known = Extensions.registry.value.extensions.flatMap { secrets(it.id) }
+ CliMask.json(Extensions.attempts.toJson(c.n), known)
+ }
is CliCommand.ExtStorage -> {
installed(c.id)
val values = Extensions.storageValues(c.id)
@@ -210,6 +224,9 @@ class CliReceiver : BroadcastReceiver() {
companion object {
const val TAG = "MyspotiCli"
+ /** The error of a command this build does not have (tools/myspoti-cli exits with 5 on it). */
+ const val DISABLED = "disabled in this build"
+
/** Debug and beta builds; the manifest leaves the receiver off in the others too. */
val enabled: Boolean get() = app.myspoti.engine.BuildConfig.DEBUG || com.music.spotui.data.api.UpdateChecker.isBeta
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
index 22010c90..defd62df 100644
--- 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
@@ -153,20 +153,39 @@ object OfflineCrypto {
// player's loading thread, then read from where it says with its headers. An address
// the server refuses (expired or gone: 401, 403, 404, 410) is asked for once more.
if (dataSpec.uri.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME) {
- val length = com.music.spotui.extensions.AudioRoute.openStream(
- ask = { again -> com.music.spotui.extensions.ExtensionAudio.resolve(dataSpec.uri, again) },
- open = { stream ->
- try {
- if (stream.manifest != null) openDash(dataSpec, stream) else openUrl(dataSpec, stream)
- } catch (e: IOException) {
- // Closed before it is opened again (it keeps the source that failed).
- runCatching { net.close() }
- throw e
- }
- },
- status = { (it as? androidx.media3.datasource.HttpDataSource.InvalidResponseCodeException)?.responseCode },
- )
+ val status = { t: Throwable -> (t as? androidx.media3.datasource.HttpDataSource.InvalidResponseCodeException)?.responseCode }
+ // How its address opened, for the song's play attempt ("Why this source?").
+ val trackId = dataSpec.uri.lastPathSegment
+ val t0 = android.os.SystemClock.elapsedRealtime()
+ var tried: app.myspoti.extensions.AudioStream? = null
+ val length = try {
+ com.music.spotui.extensions.AudioRoute.openStream(
+ ask = { again -> com.music.spotui.extensions.ExtensionAudio.resolve(dataSpec.uri, again) },
+ open = { stream ->
+ tried = stream
+ try {
+ if (stream.manifest != null) openDash(dataSpec, stream) else openUrl(dataSpec, stream)
+ } catch (e: IOException) {
+ // Closed before it is opened again (it keeps the source that failed).
+ runCatching { net.close() }
+ throw e
+ }
+ },
+ status = status,
+ )
+ } catch (e: IOException) {
+ val code = generateSequence<Throwable>(e) { it.cause }.take(8).mapNotNull(status).firstOrNull()
+ com.music.spotui.extensions.Extensions.noteAttempt(trackId) {
+ it.copy(open = app.myspoti.extensions.PlayAttempt.Open(false, android.os.SystemClock.elapsedRealtime() - t0, code, e.message ?: e.javaClass.simpleName, tried?.url?.ifBlank { null }))
+ }
+ throw e
+ }
usingOther = dash == null
+ val code = if (dash == null && dataSpec.position == 0L) net.responseCode.takeIf { it > 0 } else null
+ com.music.spotui.extensions.Extensions.noteAttempt(trackId) {
+ if (it.open?.ok == true && dataSpec.position != 0L) it
+ else it.copy(open = app.myspoti.extensions.PlayAttempt.Open(true, android.os.SystemClock.elapsedRealtime() - t0, code, null, tried?.url?.ifBlank { null } ?: "dash manifest"))
+ }
return length
}
val file = dataSpec.uri.takeIf { it.scheme == "file" }?.path?.let(::File)
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 dc94ab85..4e456519 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
@@ -126,6 +126,7 @@ object LocalPlayer {
override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
log("error ${error.errorCodeName}: ${generic(error.cause?.toString() ?: error.message.orEmpty())}")
val item = p.currentMediaItem?.localConfiguration?.uri ?: return
+ if (item.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME) com.music.spotui.extensions.Extensions.noteAttempt(item.lastPathSegment) { it.copy(error = "${error.errorCodeName}: ${error.cause ?: error.message.orEmpty()}") }
if (item.scheme != com.music.spotui.extensions.ExtensionAudio.SCHEME) return
val t = current() ?: return
val noAudio = com.music.spotui.extensions.AudioRoute.isNoAudio(error)
@@ -769,6 +770,8 @@ object LocalPlayer {
fun playbackState(): String = if (CastPlayback.active) CastPlayback.state() else exo?.let { stateName(it.playbackState) } ?: "none"
fun position() = if (CastPlayback.active) CastPlayback.position() else exo?.currentPosition ?: 0L
fun duration() = exo?.duration?.takeIf { it > 0 } ?: current()?.durationMs ?: 0L
+ /** The format the decoder reports for the song playing (its input; Android may resample), or null. */
+ fun audioFormat(): androidx.media3.common.Format? = if (CastPlayback.active) null else exo?.audioFormat
/** The length the player knows of the audio itself (null: not known), never Spotify's. */
fun knownLength(): Long? = if (CastPlayback.active) null else exo?.duration?.takeIf { it != C.TIME_UNSET && it > 0 }
fun current(): LocalTrack? = exo?.currentMediaItemIndex?.let { tracks.getOrNull(it) }
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
index 69a81a4f..bc22c453 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAudio.kt
@@ -132,7 +132,11 @@ object ExtensionAudio {
*/
fun resolve(u: Uri, again: Boolean = false, ahead: Boolean = false): AudioStream? {
val key = u.lastPathSegment.orEmpty()
- if (again) known.remove(key)
+ if (again) {
+ known.remove(key)
+ // Its address was refused: the attempt says so, the new ask is an attempt of its own.
+ Extensions.noteAttempt(key) { it.copy(fallback = "asked the extensions again: its address was refused (expired or gone)") }
+ }
known[key]?.takeIf { it.fresh }?.let { return it.stream }
// The song skipped to while its ask ahead is still out: that answer is waited for rather
// than a second ask (which cost the source a request and the song seconds); only a miss
diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
index 9de17c1e..173d8eda 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
@@ -25,6 +25,11 @@ import app.myspoti.extensions.ExtensionException
import app.myspoti.extensions.ExtensionPackage
import app.myspoti.extensions.ExtensionRuntime
import app.myspoti.extensions.Hook
+import app.myspoti.extensions.HookBudgets
+import app.myspoti.extensions.Outcome
+import app.myspoti.extensions.PlayAttempt
+import app.myspoti.extensions.PlayAttempts
+import app.myspoti.extensions.SourceCooldown
import app.myspoti.extensions.Host
import app.myspoti.extensions.HttpRequest
import app.myspoti.extensions.HttpResponse
@@ -81,23 +86,24 @@ import java.util.concurrent.ConcurrentHashMap
* the sandbox does not expect), never the app.
*/
object Extensions {
- /** A lyrics hook call (as the desktop runner gives it). */
- const val LYRICS_MS = 8_000L
+ // Every hook's time is in [HookBudgets], shared with the desktop runner (`myspoti-ext`).
+ /** A lyrics hook call. */
+ const val LYRICS_MS = HookBudgets.LYRICS
/** An audio-source hook call. */
- const val AUDIO_MS = 15_000L
+ const val AUDIO_MS = HookBudgets.AUDIO
/** A download-source hook call (an extension may try several places). */
- const val DOWNLOAD_MS = 30_000L
- private const val TRACK_MS = 3_000L
+ const val DOWNLOAD_MS = HookBudgets.DOWNLOAD
+ private const val TRACK_MS = HookBudgets.TRACK
/** A block, tap or page-message hook call: the screen waits for it. */
- private const val BLOCKS_MS = 3_000L
- private const val PAGE_MS = 5_000L
+ private const val BLOCKS_MS = HookBudgets.BLOCKS
+ private const val PAGE_MS = HookBudgets.PAGE
/** An `online` event: the extension sends what waited. */
- private const val ONLINE_MS = 30_000L
+ private const val ONLINE_MS = HookBudgets.ONLINE
/** A `setting` event: a button may pair again with a server. */
- private const val SETTING_MS = 30_000L
+ private const val SETTING_MS = HookBudgets.SETTING
private const val SETTING_PAUSE_MS = 800L
/** An `auth` event. */
- internal const val AUTH_MS = 10_000L
+ internal const val AUTH_MS = HookBudgets.AUTH
private const val MAX_INDEX = 1024 * 1024
private lateinit var ctx: Application
@@ -660,13 +666,14 @@ object Extensions {
/**
* 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.
*/
suspend fun downloadFiles(track: TrackInfo, quality: String): Triple<String, String, List<DownloadFile>>? {
if (!isReady) return null
val input = DownloadQuery.toJson(track, quality)
probeStale(Hook.DOWNLOAD_SOURCE)
- return HookDispatch.firstInOrder(providing(Hook.DOWNLOAD_SOURCE)) { (id, rt) ->
- callHook(id, rt, Hook.DOWNLOAD_SOURCE, input, DOWNLOAD_MS) { DownloadFile.parseList(it).takeIf { l -> l.isNotEmpty() } }
+ return HookDispatch.firstInOrder(available(Hook.DOWNLOAD_SOURCE)) { (id, rt) ->
+ ask(id, rt, Hook.DOWNLOAD_SOURCE, input, DOWNLOAD_MS) { DownloadFile.parseList(it).takeIf { l -> l.isNotEmpty() } }.value
}?.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}")
@@ -678,20 +685,23 @@ object Extensions {
suspend fun lyrics(track: TrackInfo): Lyrics? {
if (!isReady) return null
val input = track.toJson()
- return HookDispatch.bestInOrder(providing(Hook.LYRICS), LyricsMerge::rank) { (id, rt) ->
- callHook(id, rt, Hook.LYRICS, input, LYRICS_MS) { LyricsResult.parse(it, rt.manifest.name) }?.let(LyricsMerge::toLyrics)
+ return HookDispatch.bestInOrder(available(Hook.LYRICS), LyricsMerge::rank) { (id, rt) ->
+ ask(id, rt, Hook.LYRICS, input, LYRICS_MS) { LyricsResult.parse(it, rt.manifest.name) }.value?.let(LyricsMerge::toLyrics)
}?.let { (c, l) -> log(c.first, "lyrics for ${track.title}: ${l.lines.size} lines"); did(Area.LYRICS, c.first, "Lyrics of ${track.title} from ${c.second.manifest.name}"); l }
}
/**
* Where [track]'s audio is, from the first extension (in priority order) that knows. [ahead]:
- * asked before the song plays (the next one of the queue), which the extension is told.
+ * asked before the song plays (the next one of the queue), which the extension is told. Each
+ * call is one [PlayAttempt] ([attempts]): the sources asked or skipped, and the one chosen.
*/
suspend fun audio(track: TrackInfo, timeoutMs: Long = AUDIO_MS, ahead: Boolean = false): AudioStream? {
if (!isReady) return null
+ val attempt = attempts.start(track.id, track.title, ahead)
// None had it a moment ago: not asked again (a queue reaching it, a replay, a resume).
if (misses.skips(track.id, ahead)) {
Logbook.log("audio: ${track.title}${if (ahead) " (ahead)" else ""} not asked again: no extension had it under a minute ago")
+ attempts.update(attempt) { it.copy(fallback = "Spotify: no extension had it under a minute ago, not asked again") }
return null
}
// Picked right after launch: the extensions still loading are waited for, not skipped.
@@ -703,25 +713,51 @@ object Extensions {
// The same song as a download asks with: its ISRC, which an extension matches recordings by.
val input = AudioQuery.toJson(withIsrc(track), ahead)
probeStale(Hook.AUDIO_SOURCE)
- val asked = providing(Hook.AUDIO_SOURCE)
+ val skipped = mutableListOf<PlayAttempt.Ask>()
_registry.value.extensions.filter { it.enabled && health.inactive(it.id) && runtimes[it.id]?.provides(Hook.AUDIO_SOURCE) == true }
- .forEach { Logbook.log("audio: ${it.id} skipped (inactive: ${health.last(it.id)?.detail ?: "no detail"})") }
- if (asked.isEmpty()) return null
+ .forEach {
+ val why = "inactive: ${health.last(it.id)?.detail ?: "no detail"}"
+ Logbook.log("audio: ${it.id} skipped ($why)")
+ skipped += PlayAttempt.Ask(it.id, Outcome.Skipped().key, 0, why)
+ }
+ val asked = available(Hook.AUDIO_SOURCE, skipped)
+ if (asked.isEmpty()) {
+ attempts.update(attempt) { it.copy(asked = skipped.toList(), fallback = "Spotify: no source to ask") }
+ return null
+ }
val label = "${track.title}${if (ahead) " (ahead)" else ""}"
Logbook.log("audio: asked ${asked.joinToString { it.first }} for $label")
val t0 = System.currentTimeMillis()
+ val answers = ConcurrentHashMap<String, PlayAttempt.Ask>()
val found = HookDispatch.firstInOrder(asked) { (id, rt) ->
- callHook(id, rt, Hook.AUDIO_SOURCE, input, timeoutMs, AudioStream::parse)
+ val a = ask(id, rt, Hook.AUDIO_SOURCE, input, timeoutMs, AudioStream::parse)
+ answers[id] = PlayAttempt.Ask(id, a.outcome.key, a.ms, detail = a.outcome.detail)
+ a.value
}
val ms = System.currentTimeMillis() - t0
- if (found == null) { Logbook.log("audio: no extension had $label ($ms ms)"); misses.record(track.id, ahead); return null }
+ // A source cut short because one above it answered was not needed.
+ val all = skipped + asked.map { (id, _) -> answers[id] ?: PlayAttempt.Ask(id, Outcome.Skipped().key, ms, "not needed: a source above answered") }
+ if (found == null) {
+ Logbook.log("audio: no extension had $label ($ms ms)"); misses.record(track.id, ahead)
+ attempts.update(attempt) { it.copy(asked = all, fallback = "Spotify: no extension had it") }
+ return null
+ }
misses.forget(track.id)
val (c, a) = found
log(c.first, "audio for ${track.title} ($ms ms)")
did(Area.AUDIO, c.first, "Audio of ${track.title} from ${c.second.manifest.name}")
+ attempts.update(attempt) { it.copy(asked = all, chosen = c.first, announced = a.qualityLabel()) }
return a.copy(providerId = c.first)
}
+ /** The last [PlayAttempt]s through the extensions (20), for "Why this source?" and the diagnostic report. */
+ val attempts = PlayAttempts(capacity = 20)
+
+ /** Notes what the player did with [trackId]'s latest attempt (its address opened, its format, an error). */
+ fun noteAttempt(trackId: String?, change: (PlayAttempt) -> PlayAttempt) {
+ if (!trackId.isNullOrBlank()) runCatching { attempts.updateLatest(trackId, change) }
+ }
+
/** The songs no extension had audio for lately, by Spotify id: forgotten when one is live again or changes. */
private val misses = AudioMisses()
@@ -742,42 +778,110 @@ object Extensions {
/** For the player's loading thread (never the main one). */
fun audioBlocking(track: TrackInfo, ahead: Boolean = false): AudioStream? = runBlocking(Dispatchers.IO) { audio(track, ahead = ahead) }
+ // ── How a source call ended: outcomes, cooldowns, sign-in ──
+
+ /** The sources set aside after a rate limit, a server down or network failures in a row. */
+ private val cooldown = SourceCooldown()
+
+ /** The extensions whose source said the user must sign in, with what it said ("" if nothing). */
+ private val _signIns = MutableStateFlow<Map<String, String>>(emptyMap())
+ val signIns: StateFlow<Map<String, String>> = _signIns.asStateFlow()
+
+ /** The user dismissed [id]'s sign-in notice (it comes back at its next `sign-in` answer). */
+ fun dismissSignIn(id: String) { _signIns.value = _signIns.value - id }
+
+ /** Why [id] is set aside now ("rate-limited, 42 s left"), or null. */
+ fun cooldownOf(id: String): String? = cooldown.reason(id)
+
+ /** [providing] without the sources set aside ([cooldown]); each one skipped is logged and added to [skipped]. */
+ private fun available(hook: Hook, skipped: MutableList<PlayAttempt.Ask>? = null): List<Pair<String, ExtensionRuntime>> =
+ providing(hook).filter { (id, _) ->
+ val why = cooldown.reason(id) ?: return@filter true
+ Logbook.log("${hook.key}: $id skipped (set aside: $why)")
+ skipped?.add(PlayAttempt.Ask(id, Outcome.Skipped().key, 0, "set aside: $why"))
+ false
+ }
+
+ /** What a hook call gave: its answer (null: none), how it ended, in how many ms. */
+ private class Answer<T>(val value: T?, val outcome: Outcome, val ms: Long)
+
private suspend fun <T : Any> callHook(id: String, rt: ExtensionRuntime, hook: Hook, input: String, timeoutMs: Long, parse: (String) -> T?): T? =
- runInterruptible(Dispatchers.IO) {
- busy.merge(id, 1, Int::plus)
- try {
- val raw = rt.call(hook, input, timeoutMs)
- // An answer the app cannot use is a failure too, said in its log (the sandbox logs its own).
- val out = try { raw?.let(parse) } catch (e: ExtensionException) { log(id, "failed: ${e.message}"); throw e }
- failures.succeeded(id)
- out
- } catch (e: app.myspoti.extensions.ExtensionBusy) {
- // It was still busy (a slow lookup before): not its fault, nothing counted.
- log(id, "${hook.key} skipped: ${e.message}")
- null
- } catch (e: app.myspoti.extensions.ExtensionFault) {
- // Out of memory, stack overflow, engine crash: turned off at once, the app goes on.
- if (!rt.closed) disable(id, e.message ?: "crashed the sandbox")
- null
- } catch (e: ExtensionException) {
- // Stopped meanwhile (updated, turned off): its cut-short call is not counted.
- if (!rt.closed) failed(id, e.message ?: "failed")
- null
- } catch (e: InterruptedException) {
- throw e
- } catch (t: Throwable) {
- // Not a failure the sandbox knows: the extension is stopped before it does it again.
- disable(id, t.toString())
- null
- } finally {
- busy.computeIfPresent(id) { _, n -> (n - 1).takeIf { it > 0 } }
+ ask(id, rt, hook, input, timeoutMs, parse).value
+
+ /**
+ * Calls [hook] of [id] and classifies how it ended ([Outcome]). A source hook's outcome is
+ * logged and may set the source aside ([cooldown]) or ask the user to sign in ([signIns]).
+ */
+ private suspend fun <T : Any> ask(id: String, rt: ExtensionRuntime, hook: Hook, input: String, timeoutMs: Long, parse: (String) -> T?): Answer<T> {
+ val t0 = System.currentTimeMillis()
+ val (value, outcome) = runInterruptible(Dispatchers.IO) { callNow(id, rt, hook, input, timeoutMs, parse) }
+ val ms = System.currentTimeMillis() - t0
+ if (hook in Outcome.HOOKS) noted(id, hook, outcome, ms)
+ return Answer(value, outcome, ms)
+ }
+
+ private fun <T : Any> callNow(id: String, rt: ExtensionRuntime, hook: Hook, input: String, timeoutMs: Long, parse: (String) -> T?): Pair<T?, Outcome> {
+ busy.merge(id, 1, Int::plus)
+ try {
+ val raw = rt.call(hook, input, timeoutMs)
+ // An outcome it states (`{ outcome }`, feature `results`): its script ran well, nothing is counted.
+ raw?.let { Outcome.parse(hook, it) }?.let { stated -> failures.succeeded(id); return null to stated }
+ // An answer the app cannot use is a failure too, said in its log (the sandbox logs its own).
+ val out = try { raw?.let(parse) } catch (e: ExtensionException) { log(id, "failed: ${e.message}"); throw e }
+ failures.succeeded(id)
+ return out to (if (out != null) Outcome.Found else Outcome.NotFound)
+ } catch (e: app.myspoti.extensions.ExtensionBusy) {
+ // It was still busy (a slow lookup before): not its fault, nothing counted.
+ log(id, "${hook.key} skipped: ${e.message}")
+ return null to Outcome.of(e)
+ } catch (e: app.myspoti.extensions.ExtensionFault) {
+ // Out of memory, stack overflow, engine crash: turned off at once, the app goes on.
+ if (!rt.closed) disable(id, e.message ?: "crashed the sandbox")
+ return null to Outcome.Bug(e.message)
+ } catch (e: ExtensionException) {
+ val o = Outcome.of(e)
+ // Stopped meanwhile (updated, turned off): its cut-short call is not counted. A timeout
+ // or a network error of its requests is the server's, not the script's: not counted either.
+ if (!rt.closed) {
+ if (o.counts) failed(id, e.message ?: "failed") else log(id, "${hook.key}: ${o.key}, not counted as a failure")
}
+ return null to o
+ } catch (e: InterruptedException) {
+ throw e
+ } catch (t: Throwable) {
+ // Not a failure the sandbox knows: the extension is stopped before it does it again.
+ disable(id, t.toString())
+ return null to Outcome.Bug(t.toString())
+ } finally {
+ busy.computeIfPresent(id) { _, n -> (n - 1).takeIf { it > 0 } }
}
+ }
+
+ /** Logs [o] of [id]'s [hook] call; sets the source aside or asks for a sign-in when it says so. */
+ private fun noted(id: String, hook: Hook, o: Outcome, ms: Long) {
+ log(id, "${hook.key}: ${o.describe()} ($ms ms)")
+ cooldown.note(id, o)?.let { log(id, "set aside for ${it / 1000} s (${o.key}): not asked meanwhile") }
+ when (o) {
+ is Outcome.SignIn -> signInNeeded(id, o.detail)
+ Outcome.Found -> if (id in _signIns.value) dismissSignIn(id)
+ else -> {}
+ }
+ }
+
+ private fun signInNeeded(id: String, detail: String?) {
+ val first = id !in _signIns.value
+ _signIns.value = _signIns.value + (id to detail.orEmpty())
+ if (!first) return
+ val name = _registry.value.find(id)?.name ?: id
+ main.post {
+ android.widget.Toast.makeText(ctx, ctx.getString(app.myspoti.engine.R.string.extension_sign_in_needed, name), android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
// ── Whether each extension's source answers: the `status` hook ──
/** A `status` call: a probe never holds a song's audio longer than this. */
- private const val STATUS_MS = 5_000L
+ private const val STATUS_MS = HookBudgets.STATUS
/** How long a command waits for the extensions the app is still starting. */
private const val START_WAIT_MS = 20_000L
/** How long a song picked right after launch waits for them (then plays from Spotify). */
@@ -1114,6 +1218,7 @@ object Extensions {
runningSha.remove(id)
runtimes.remove(id)?.close(); ExtensionAuth.cancel(id)
health.forget(id); _statuses.value = health.inactiveNow()
+ cooldown.forget(id); dismissSignIn(id)
misses.clear()
refreshProvided()
}
@@ -1122,6 +1227,7 @@ object Extensions {
internal fun authDone(id: String, result: app.myspoti.extensions.AuthResult) {
val rt = runtimes[id] ?: return
log(id, "sign-in ${result.id}: ${if (result.url != null) "reached the callback" else result.error}")
+ if (result.url != null) dismissSignIn(id)
val json = kotlinx.serialization.json.Json.encodeToString(app.myspoti.extensions.AuthResult.serializer(), result)
scope.launch { runCatching { runInterruptible { rt.emit(ExtensionRuntime.EVENT_AUTH, json, AUTH_MS) } }.onFailure { failed(id, it.toString()) } }
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index dda0392f..5d267b87 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -336,6 +336,15 @@ fun QualitySheet(onDismiss: () -> Unit) {
},
color = Green, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp),
)
+ // A song an extension gives: the sources asked for it, and why this one plays.
+ val extId = if (local) com.music.spotui.di.LocalPlayer.current()?.uri
+ ?.takeIf { it.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME }?.lastPathSegment else null
+ var why by remember { androidx.compose.runtime.mutableStateOf(false) }
+ if (extId != null) {
+ Text(stringResource(R.string.why_source_title), color = AppText, fontSize = 15.sp,
+ modifier = Modifier.fillMaxWidth().clickable { why = true }.padding(horizontal = 20.dp, vertical = 12.dp))
+ if (why) WhySourceSheet(extId, detectedLabel(com.music.spotui.di.LocalPlayer.audioFormat())) { why = false }
+ }
// The level of the network in use now (Wi-Fi and mobile data each keep their own).
if (!local) StreamingQualityPicker(Modifier.padding(top = 12.dp), cellular = com.music.spotui.data.DataSaver.metered,
title = if (com.music.spotui.data.DataSaver.metered) R.string.quality_streaming_cell_title else R.string.quality_streaming_wifi_title)
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/WhySourceSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/WhySourceSheet.kt
new file mode 100644
index 00000000..780f3a32
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/WhySourceSheet.kt
@@ -0,0 +1,100 @@
+package com.music.spotui.ui.components
+
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import app.myspoti.extensions.PlayAttempt
+import com.music.spotui.extensions.Extensions
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+import com.music.spotui.ui.theme.tone
+
+/**
+ * "Why this source?": the last [PlayAttempt] of the song [trackId] through the extensions: the
+ * sources asked and how each ended (and in how long), the ones skipped and why, the one chosen,
+ * how its address opened, the quality it announced against the one the player [detected], the
+ * fallback and the last error. Addresses are shown without their query.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun WhySourceSheet(trackId: String, detected: String?, onDismiss: () -> Unit) {
+ val a = remember(trackId) {
+ if (detected != null) Extensions.noteAttempt(trackId) { it.copy(detected = detected) }
+ Extensions.attempts.latest(trackId)
+ }
+ LookSheet(onDismissRequest = onDismiss, containerColor = tone(0xFF282828)) {
+ Column(Modifier.fillMaxWidth().navigationBarsPadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
+ Text(stringResource(R.string.why_source_title), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
+ if (a == null) {
+ Line(stringResource(R.string.why_source_none), muted = true)
+ return@Column
+ }
+ Head(stringResource(R.string.why_source_asked))
+ a.asked.forEach { s ->
+ val name = nameOf(s.extension)
+ val what = stringResource(R.string.why_source_ms, outcomeLabel(s.outcome), s.ms)
+ Line("$name — " + (s.skippedReason?.let { stringResource(R.string.why_source_skipped, PlayAttempt.maskText(it)) } ?: what) +
+ (s.detail?.let { " (${PlayAttempt.maskText(it)})" } ?: ""))
+ }
+ Line(a.chosen?.let { stringResource(R.string.why_source_chosen, nameOf(it)) } ?: stringResource(R.string.why_source_none_chosen))
+ a.open?.let { o ->
+ val http = o.httpStatus?.let { " · " + stringResource(R.string.why_source_http, it) } ?: ""
+ Line(if (o.ok) stringResource(R.string.why_source_open_ok, o.ms) + http
+ else stringResource(R.string.why_source_open_failed, o.ms, PlayAttempt.maskText(o.error ?: "?")) + http)
+ }
+ a.announced?.let { Line(stringResource(R.string.why_source_announced, it)) }
+ (detected ?: a.detected)?.let { Line(stringResource(R.string.why_source_detected, it)) }
+ a.fallback?.let { Line(stringResource(R.string.why_source_fallback, PlayAttempt.maskText(it)), muted = true) }
+ a.error?.let { Line(stringResource(R.string.why_source_error, PlayAttempt.maskText(it)), muted = true) }
+ }
+ }
+}
+
+private fun nameOf(id: String): String = Extensions.registry.value.find(id)?.name ?: id
+
+@Composable
+private fun outcomeLabel(key: String): String = stringResource(when (key) {
+ "found" -> R.string.outcome_found
+ "not-found" -> R.string.outcome_not_found
+ "sign-in" -> R.string.outcome_sign_in
+ "rate-limited" -> R.string.outcome_rate_limited
+ "quality-unavailable" -> R.string.outcome_quality_unavailable
+ "server-down" -> R.string.outcome_server_down
+ "network" -> R.string.outcome_network
+ "skipped" -> R.string.outcome_skipped
+ else -> R.string.outcome_bug
+})
+
+@Composable
+private fun Head(text: String) = Text(text, color = AppText, fontSize = 15.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 2.dp))
+
+@Composable
+private fun Line(text: String, muted: Boolean = false) = Text(text, color = if (muted) AppMuted else AppText, fontSize = 14.sp,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 3.dp))
+
+/** What the player's decoder reported ("audio/flac · 44.1 kHz · 2 ch"), or null: its input, not proof of a bit-perfect output. */
+fun detectedLabel(f: androidx.media3.common.Format?): String? {
+ f ?: return null
+ val parts = listOfNotNull(
+ f.sampleMimeType ?: f.codecs,
+ f.sampleRate.takeIf { it > 0 }?.let { r -> if (r % 1000 == 0) "${r / 1000} kHz" else "%.1f kHz".format(java.util.Locale.US, r / 1000.0) },
+ f.channelCount.takeIf { it > 0 }?.let { "$it ch" },
+ f.bitrate.takeIf { it > 0 }?.let { "${it / 1000} kbit/s" },
+ )
+ return parts.joinToString(" · ").ifBlank { null }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.kt
index a716c410..9e31e3e7 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionsScreen.kt
@@ -101,6 +101,7 @@ fun ImmersiveExtensionsScreen(navController: NavController) {
val registry by Extensions.registry.collectAsState()
val errors by Extensions.errors.collectAsState()
val statuses by Extensions.statuses.collectAsState()
+ val signIns by Extensions.signIns.collectAsState()
val repos by ExtensionStore.repos.collectAsState()
val busy by ExtensionStore.busy.collectAsState()
val pickFile = rememberPackagePicker()
@@ -219,6 +220,19 @@ fun ImmersiveExtensionsScreen(navController: NavController) {
ImmersiveButton(stringResource(R.string.extensions_browse_store), onClick = { tab = 0 })
}
}
+ // A source that said its account needs a sign-in: its page, where the extension offers it.
+ signIns.forEach { (id, detail) ->
+ immersiveBlock("sign-in-$id") {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(stringResource(R.string.extension_sign_in_needed, registry.find(id)?.name ?: id), style = Immersive.Subhead)
+ if (detail.isNotBlank()) Text(detail, style = Immersive.Caption)
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ ImmersiveButton(stringResource(R.string.extension_sign_in), onClick = { navController.navigate(installedRoute(id)) })
+ ImmersiveButton(stringResource(R.string.extension_sign_in_later), onClick = { Extensions.dismissSignIn(id) })
+ }
+ }
+ }
+ }
// By area: the extensions acting there, in order; an area without any is not listed.
Extensions.byArea().forEach { (area, list) ->
val inArea = list.filter(matches)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt
index 8efda033..9853b53a 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt
@@ -92,6 +92,7 @@ fun ExtensionsScreen(navController: NavController) {
val registry by Extensions.registry.collectAsState()
val errors by Extensions.errors.collectAsState()
val statuses by Extensions.statuses.collectAsState()
+ val signIns by Extensions.signIns.collectAsState()
val repos by ExtensionStore.repos.collectAsState()
val busy by ExtensionStore.busy.collectAsState()
val pickFile = rememberPackagePicker()
@@ -176,6 +177,20 @@ fun ExtensionsScreen(navController: NavController) {
Text(stringResource(R.string.extensions_browse_store), color = AppText)
}
}
+ // A source that said its account needs a sign-in: its page, where the extension offers it.
+ signIns.forEach { (id, detail) ->
+ val name = registry.find(id)?.name ?: id
+ Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp)) {
+ Text(stringResource(R.string.extension_sign_in_needed, name), color = AppText, fontSize = 14.sp)
+ if (detail.isNotBlank()) Text(detail, color = AppMuted, fontSize = 12.sp)
+ Row {
+ OutlinedButton(onClick = { navController.navigate(installedRoute(id)) }, border = BorderStroke(1.dp, AppMuted.copy(alpha = 0.6f))) {
+ Text(stringResource(R.string.extension_sign_in), color = AppText)
+ }
+ androidx.compose.material3.TextButton(onClick = { Extensions.dismissSignIn(id) }) { Text(stringResource(R.string.extension_sign_in_later), color = AppMuted) }
+ }
+ }
+ }
// By area: the extensions acting there, in order; an area without any is not listed.
val grouped = remember(registry) { Extensions.byArea() }
grouped.forEach { (area, list) ->
diff --git a/base/app/src/main/res/values-fr/extensions_strings.xml b/base/app/src/main/res/values-fr/extensions_strings.xml
index 9271a781..cd557365 100644
--- a/base/app/src/main/res/values-fr/extensions_strings.xml
+++ b/base/app/src/main/res/values-fr/extensions_strings.xml
@@ -213,4 +213,30 @@
<string name="ext_grants_title">Toujours autorisé</string>
<string name="ext_grants_note">Modifications Spotify que cette extension effectue sans vous demander. Révoquez-en une pour être à nouveau interrogé.</string>
<string name="ext_grant_revoke">Révoquer</string>
+ <string name="extension_sign_in_needed">%1$s : connectez-vous pour continuer à utiliser sa source</string>
+ <string name="extension_sign_in">Se connecter</string>
+ <string name="extension_sign_in_later">Plus tard</string>
+ <string name="why_source_title">Pourquoi cette source ?</string>
+ <string name="why_source_none">Aucune tentative d\'extension enregistrée pour ce titre.</string>
+ <string name="why_source_asked">Sources interrogées</string>
+ <string name="why_source_ms">%1$s · %2$d ms</string>
+ <string name="why_source_skipped">ignorée : %1$s</string>
+ <string name="why_source_chosen">Choisie : %1$s</string>
+ <string name="why_source_none_chosen">Aucune source ne l\'avait</string>
+ <string name="why_source_open_ok">Ouverte en %1$d ms</string>
+ <string name="why_source_open_failed">Échec de l\'ouverture après %1$d ms : %2$s</string>
+ <string name="why_source_http">HTTP %1$d</string>
+ <string name="why_source_announced">Annoncée par la source : %1$s</string>
+ <string name="why_source_detected">Détectée par le lecteur : %1$s</string>
+ <string name="why_source_fallback">Repli : %1$s</string>
+ <string name="why_source_error">Dernière erreur : %1$s</string>
+ <string name="outcome_found">trouvé</string>
+ <string name="outcome_not_found">introuvable</string>
+ <string name="outcome_sign_in">connexion requise</string>
+ <string name="outcome_rate_limited">limite de requêtes atteinte</string>
+ <string name="outcome_quality_unavailable">qualité indisponible</string>
+ <string name="outcome_server_down">serveur indisponible</string>
+ <string name="outcome_network">erreur réseau ou délai dépassé</string>
+ <string name="outcome_skipped">ignorée</string>
+ <string name="outcome_bug">erreur de l\'extension</string>
</resources>
diff --git a/base/app/src/main/res/values/extensions_strings.xml b/base/app/src/main/res/values/extensions_strings.xml
index c92432aa..ffb6bf8e 100644
--- a/base/app/src/main/res/values/extensions_strings.xml
+++ b/base/app/src/main/res/values/extensions_strings.xml
@@ -214,4 +214,30 @@
<string name="ext_grants_title">Always allowed</string>
<string name="ext_grants_note">Spotify changes this extension makes without asking you. Revoke one to be asked again.</string>
<string name="ext_grant_revoke">Revoke</string>
+ <string name="extension_sign_in_needed">%1$s: sign in to keep using its source</string>
+ <string name="extension_sign_in">Sign in</string>
+ <string name="extension_sign_in_later">Not now</string>
+ <string name="why_source_title">Why this source?</string>
+ <string name="why_source_none">No extension attempt recorded for this song yet.</string>
+ <string name="why_source_asked">Sources asked</string>
+ <string name="why_source_ms">%1$s · %2$d ms</string>
+ <string name="why_source_skipped">skipped: %1$s</string>
+ <string name="why_source_chosen">Chosen: %1$s</string>
+ <string name="why_source_none_chosen">No source had it</string>
+ <string name="why_source_open_ok">Opened in %1$d ms</string>
+ <string name="why_source_open_failed">Failed to open after %1$d ms: %2$s</string>
+ <string name="why_source_http">HTTP %1$d</string>
+ <string name="why_source_announced">Announced by the source: %1$s</string>
+ <string name="why_source_detected">Detected by the player: %1$s</string>
+ <string name="why_source_fallback">Fallback: %1$s</string>
+ <string name="why_source_error">Last error: %1$s</string>
+ <string name="outcome_found">found</string>
+ <string name="outcome_not_found">not found</string>
+ <string name="outcome_sign_in">sign-in needed</string>
+ <string name="outcome_rate_limited">rate limited</string>
+ <string name="outcome_quality_unavailable">quality unavailable</string>
+ <string name="outcome_server_down">server down</string>
+ <string name="outcome_network">network error or timeout</string>
+ <string name="outcome_skipped">skipped</string>
+ <string name="outcome_bug">extension error</string>
</resources>
diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
index 0477ef88..14afbeb8 100644
--- a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Run.kt
@@ -1,7 +1,6 @@
package app.myspoti.extensions.cli
import app.myspoti.extensions.Attestation
-import app.myspoti.extensions.AudioQuery
import app.myspoti.extensions.AudioStream
import app.myspoti.extensions.Blocks
import app.myspoti.extensions.PageContent
@@ -12,6 +11,8 @@ import app.myspoti.extensions.ExtensionPackage
import app.myspoti.extensions.ExtensionRuntime
import app.myspoti.extensions.ExtensionStatus
import app.myspoti.extensions.Hook
+import app.myspoti.extensions.HookBudgets
+import app.myspoti.extensions.Outcome
import app.myspoti.extensions.Host
import app.myspoti.extensions.LyricsResult
import app.myspoti.extensions.Manifest
@@ -20,7 +21,6 @@ import app.myspoti.extensions.SpotifyCall
import app.myspoti.extensions.SpotifyDispatcher
import app.myspoti.extensions.SpotifyRaw
import app.myspoti.extensions.DownloadFile
-import app.myspoti.extensions.DownloadQuery
import app.myspoti.extensions.PlaybackEvent
import app.myspoti.extensions.Storage
import app.myspoti.extensions.TrackInfo
@@ -41,8 +41,9 @@ import kotlin.system.exitProcess
private const val USAGE = """myspoti-ext: build and try Myspoti extensions on a computer.
- check <folder> the manifest's problems, whether the script loads, the actions the
- user is asked (icon, level, why), and the blocks each drawn hook answers
+ check <folder|zip> package validity only: the manifest's problems, whether the script
+ loads, the hooks it provides, the actions the user is asked (icon,
+ level, why). It never calls a hook (use run or test for that)
run <folder|zip> <hook> [options] calls a hook as the app would, prints what it answered
--title T --artist A [--album B] [--duration MS] [--id SPOTIFY_ID] [--isrc ISRC]
--set key=value a setting's value (repeatable)
@@ -56,11 +57,18 @@ private const val USAGE = """myspoti-ext: build and try Myspoti extensions on a
run <folder|zip> playback [options] delivers a play of the song: start, a progress every 10 s,
[--played MS] [--leave skip|end|stop] [--context URI] [--shuffle true] [--source local|spotify]
[--origin spotify|download|audio-source|local-file] [--provider EXTENSION_ID]
+ test <folder|zip> --scenario file.json [--state file.json]
+ runs a scenario: hook calls, events and page messages in order, with
+ the app's time limits, a request rule set that injects latency, 429 +
+ Retry-After, 5xx, DNS failures and resets, cancellation at a time,
+ storage kept across steps (and across runs with --state); checks each
+ step's outcome and time (docs/extensions/API.md §8). Exit 1 on a failure
pack <folder> [out-folder] builds <id>-<version>.zip and prints its index entry
index <folder-of-zips> <name> writes index.json for a repository of packages
Hooks: lyrics, audio-source, download-source, trackinfo, home, search (--query Q), menu (--kind track|album|
-playlist|artist), player, page, message (--data JSON), tap (--action ID), status (live or not, within 5 s). Everything the manifest asks is granted here. Without --cdp,
+playlist|artist), player, page, message (--data JSON), tap (--action ID), status (live or not). Each hook gets the
+app's own time limit (HookBudgets). Everything the manifest asks is granted here. Without --cdp,
myspoti.spotify has no account and its calls fail."""
fun main(args: Array<String>) {
@@ -68,6 +76,7 @@ fun main(args: Array<String>) {
try {
when (args[0]) {
"check" -> check(File(args.getOrElse(1) { usage() }))
+ "test" -> test(File(args.getOrElse(1) { usage() }), args.drop(2))
"run" -> run(File(args.getOrElse(1) { usage() }), args.getOrElse(2) { usage() }, args.drop(3))
"pack" -> pack(File(args.getOrElse(1) { usage() }), args.getOrNull(2)?.let(::File))
"index" -> index(File(args.getOrElse(1) { usage() }), args.getOrElse(2) { usage() })
@@ -166,33 +175,9 @@ private fun check(dir: File) {
println(" ${if (a.critical) "⚠" else "•"} [${act?.icon ?: "?"}] ${a.key} (${act?.label ?: "unknown"}, ${a.level.name.lowercase()})" +
(if (a.hosts.isNotEmpty()) " ${a.hosts}" else "") + " — ${a.why.ifBlank { "(no reason given)" }}")
}
- // Each drawn hook it provides, asked once with sample input: its blocks must parse.
- val sample = TrackInfo("4uLU6hMCjMI75M1A2tKUQC", "spotify:track:4uLU6hMCjMI75M1A2tKUQC", "Sample", "Artist", listOf("Artist"), "Album", 200_000)
- val asked = listOf(
- Triple(Hook.HOME, Surface.HOME, "{}"),
- Triple(Hook.SEARCH, Surface.SEARCH, """{"query":"sample"}"""),
- Triple(Hook.MENU, Surface.TRACK_MENU, """{"kind":"track","uri":"${sample.uri}","title":"Sample","subtitle":"Artist"}"""),
- Triple(Hook.PLAYER, Surface.PLAYER, sample.toJson()),
- Triple(Hook.TRACK_INFO, Surface.TRACK_INFO, sample.toJson()),
- )
- var bad = false
- asked.filter { rt.provides(it.first) }.forEach { (hook, surface, input) ->
- val out = runCatching { rt.call(hook, input, 5_000) }.getOrElse { println("✗ $hook: ${it.message}"); bad = true; return@forEach }
- if (out == null) println(" $hook: no blocks for the sample") else runCatching { Blocks.parse(out, surface) }
- .onSuccess { println("✓ ${hook.key}: ${it.size} block(s) (${it.joinToString { b -> b.javaClass.simpleName }})") }
- .onFailure { println("✗ ${hook.key}: ${it.message}"); bad = true }
- }
- if (rt.provides(Hook.PAGE)) runCatching { rt.call(Hook.PAGE, "{}", 5_000)?.let { PageContent.parse(it, m.name) } }
- .onSuccess { println(if (it == null) " page: no page" else "✓ page \"${it.title}\": ${it.html.length} characters of HTML") }
- .onFailure { println("✗ page: ${it.message}"); bad = true }
- ExtensionStatus.probe(rt, 5_000).let { s ->
- println(when (s.state) {
- "live" -> "✓ status: live${s.detail?.let { " ($it)" } ?: ""}"
- "inactive" -> "! status: inactive (${s.detail ?: "no detail"})"
- else -> "! status: no answer (${s.detail ?: "no detail"}): the app keeps using it"
- })
- }
- if (bad && problems.isEmpty()) exitProcess(1)
+ // Never a hook call here: what it answers depends on the network and the account (run, test).
+ Hook.entries.filter { it != Hook.STATUS && rt.provides(it) }.takeIf { it.isNotEmpty() }
+ ?.let { println("Hooks it provides: ${it.joinToString { h -> h.key }}") }
}
m.categoryWarning()?.let { println("! $it") }
println("In the store: ${m.category().key}${if (m.category == null) " (set \"category\" to choose)" else ""}" +
@@ -200,6 +185,19 @@ private fun check(dir: File) {
if (problems.isNotEmpty()) exitProcess(1)
}
+/** `test <dir> --scenario file.json [--state file.json]`: each step's result; exit 1 when one failed. */
+private fun test(path: File, rest: List<String>) {
+ val opts = rest.chunked(2).associate { it[0].removePrefix("--") to it.getOrElse(1) { usage() } }
+ val scenarioFile = File(opts["scenario"] ?: usage())
+ val (m, script) = load(path)
+ val scenario = runCatching { Scenario.parse(scenarioFile.readText()) }.getOrElse { System.err.println("✗ ${scenarioFile.name}: ${it.message}"); exitProcess(2) }
+ val results = ScenarioRunner(m, script, scenario, opts["state"]?.let(::File)).run()
+ results.forEach(::println)
+ val failed = results.count { !it.ok }
+ println(if (failed == 0) "✓ ${results.size} step(s) passed" else "✗ $failed of ${results.size} step(s) failed")
+ if (failed > 0) exitProcess(1)
+}
+
private fun run(path: File, hookName: String, rest: List<String>) {
val (m, script) = load(path)
val opts = HashMap<String, String>()
@@ -226,33 +224,17 @@ private fun run(path: File, hookName: String, rest: List<String>) {
private fun runScript(rt: ExtensionRuntime, m: Manifest, hookName: String, track: TrackInfo, opts: Map<String, String> = emptyMap()) {
rt.start()
if (hookName == ExtensionRuntime.EVENT_TRACK) {
- rt.emit(hookName, PlaybackEvent.trackEventJson(track, opts["origin"] ?: PlaybackEvent.ORIGIN_SPOTIFY, opts["provider"]))
+ rt.emit(hookName, PlaybackEvent.trackEventJson(track, opts["origin"] ?: PlaybackEvent.ORIGIN_SPOTIFY, opts["provider"]), HookBudgets.TRACK)
println("✓ delivered"); return
}
if (hookName == ExtensionRuntime.EVENT_PLAYBACK) { playback(rt, track, opts); return }
val hook = Hook.of(hookName) ?: usage()
if (!rt.provides(hook)) throw ExtensionException("this extension does not provide $hookName (or its action is not in the manifest)")
val started = System.currentTimeMillis()
- val input = when (hook) {
- Hook.DOWNLOAD_SOURCE -> DownloadQuery.toJson(track, opts["quality"] ?: "cd")
- Hook.AUDIO_SOURCE -> AudioQuery.toJson(track, opts["ahead"] == "true")
- Hook.SEARCH -> kotlinx.serialization.json.buildJsonObject { put("query", kotlinx.serialization.json.JsonPrimitive(opts["query"] ?: track.title)) }.toString()
- Hook.MENU -> kotlinx.serialization.json.buildJsonObject {
- put("kind", kotlinx.serialization.json.JsonPrimitive(opts["kind"] ?: "track"))
- put("uri", kotlinx.serialization.json.JsonPrimitive(track.uri)); put("title", kotlinx.serialization.json.JsonPrimitive(track.title))
- put("subtitle", kotlinx.serialization.json.JsonPrimitive(track.artist))
- }.toString()
- Hook.HOME, Hook.PAGE, Hook.STATUS -> "{}"
- Hook.MESSAGE -> opts["data"] ?: "null"
- Hook.TAP -> kotlinx.serialization.json.buildJsonObject {
- put("action", kotlinx.serialization.json.JsonPrimitive(opts["action"] ?: usage())); put("surface", kotlinx.serialization.json.JsonPrimitive("home"))
- put("context", kotlinx.serialization.json.JsonObject(emptyMap()))
- }.toString()
- else -> track.toJson()
- }
+ val input = hookInput(hook, track, opts) ?: usage()
if (hook == Hook.STATUS) {
// As the app asks it: only live: false is inactive; a failure or a late answer proves nothing.
- val s = ExtensionStatus.probe(rt, 5_000)
+ val s = ExtensionStatus.probe(rt, HookBudgets.STATUS)
val ms = System.currentTimeMillis() - started
println(when (s.state) {
"live" -> "✓ live${s.detail?.let { ": $it" } ?: ""} ($ms ms)"
@@ -261,9 +243,11 @@ private fun runScript(rt: ExtensionRuntime, m: Manifest, hookName: String, track
})
return
}
- val out = rt.call(hook, input, when (hook) { Hook.LYRICS -> 8_000; Hook.DOWNLOAD_SOURCE -> 30_000; else -> 15_000 })
+ val out = rt.call(hook, input, HookBudgets.of(hook))
val ms = System.currentTimeMillis() - started
if (out == null) { println("— no answer ($ms ms): the app goes on without this extension"); return }
+ // `{ outcome }` (feature `results`): why it has nothing, as the app reads it.
+ Outcome.parse(hook, out)?.let { o -> println("— outcome ${o.describe()} ($ms ms)"); return }
val surface = when (hook) {
Hook.HOME -> Surface.HOME; Hook.SEARCH -> Surface.SEARCH; Hook.PLAYER -> Surface.PLAYER; Hook.TRACK_INFO -> Surface.TRACK_INFO
Hook.MENU -> when (opts["kind"]) { "album" -> Surface.ALBUM_MENU; "playlist" -> Surface.PLAYLIST_MENU; "artist" -> Surface.ARTIST_MENU; else -> Surface.TRACK_MENU }
@@ -332,7 +316,7 @@ private fun playback(rt: ExtensionRuntime, track: TrackInfo, opts: Map<String, S
}
}
events.forEach { e ->
- rt.emit(ExtensionRuntime.EVENT_PLAYBACK, e.toJson(), 15_000)
+ rt.emit(ExtensionRuntime.EVENT_PLAYBACK, e.toJson(), HookBudgets.TRACK)
println("✓ ${e.type}${e.reason?.let { " ($it)" } ?: ""} at ${e.positionMs} ms")
}
}
diff --git a/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt
new file mode 100644
index 00000000..138ea248
--- /dev/null
+++ b/base/extensions-cli/src/main/kotlin/app/myspoti/extensions/cli/Scenario.kt
@@ -0,0 +1,323 @@
+package app.myspoti.extensions.cli
+
+import app.myspoti.extensions.AudioQuery
+import app.myspoti.extensions.AudioStream
+import app.myspoti.extensions.BasicHttp
+import app.myspoti.extensions.DownloadFile
+import app.myspoti.extensions.DownloadQuery
+import app.myspoti.extensions.ExtensionException
+import app.myspoti.extensions.ExtensionRuntime
+import app.myspoti.extensions.ExtensionStatus
+import app.myspoti.extensions.Hook
+import app.myspoti.extensions.HookBudgets
+import app.myspoti.extensions.Host
+import app.myspoti.extensions.HttpRequest
+import app.myspoti.extensions.HttpResponse
+import app.myspoti.extensions.LyricsResult
+import app.myspoti.extensions.Manifest
+import app.myspoti.extensions.MemoryStorage
+import app.myspoti.extensions.Outcome
+import app.myspoti.extensions.PlaybackEvent
+import app.myspoti.extensions.Storage
+import app.myspoti.extensions.TrackInfo
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.longOrNull
+import kotlinx.serialization.json.put
+import java.io.File
+import java.io.IOException
+import java.net.SocketTimeoutException
+import java.net.URI
+import java.net.UnknownHostException
+
+/** The input the app gives [hook] for [track] ([opts]: `quality`, `ahead`, `query`, `kind`, `data`, `action`); null: `tap` without an action. */
+internal fun hookInput(hook: Hook, track: TrackInfo, opts: Map<String, String>): String? = when (hook) {
+ Hook.DOWNLOAD_SOURCE -> DownloadQuery.toJson(track, opts["quality"] ?: "cd")
+ Hook.AUDIO_SOURCE -> AudioQuery.toJson(track, opts["ahead"] == "true")
+ Hook.SEARCH -> buildJsonObject { put("query", opts["query"] ?: track.title) }.toString()
+ Hook.MENU -> buildJsonObject {
+ put("kind", opts["kind"] ?: "track"); put("uri", track.uri); put("title", track.title); put("subtitle", track.artist)
+ }.toString()
+ Hook.HOME, Hook.PAGE, Hook.STATUS -> "{}"
+ Hook.MESSAGE -> opts["data"] ?: "null"
+ Hook.TAP -> opts["action"]?.let { a ->
+ buildJsonObject { put("action", a); put("surface", "home"); put("context", JsonObject(emptyMap())) }.toString()
+ }
+ else -> track.toJson()
+}
+
+/**
+ * How the app reads [raw], [hook]'s answer: a stated `{ outcome }`, else found or not found as its
+ * parser reads it. An answer the app cannot use is a [Outcome.Bug].
+ */
+internal fun classify(hook: Hook, raw: String?, name: String): Outcome = try {
+ when {
+ raw == null -> Outcome.NotFound
+ else -> Outcome.parse(hook, raw) ?: when (hook) {
+ Hook.AUDIO_SOURCE -> if (AudioStream.parse(raw) != null) Outcome.Found else Outcome.NotFound
+ Hook.DOWNLOAD_SOURCE -> if (DownloadFile.parseList(raw).isNotEmpty()) Outcome.Found else Outcome.NotFound
+ Hook.LYRICS -> if (LyricsResult.parse(raw, name) != null) Outcome.Found else Outcome.NotFound
+ else -> Outcome.Found
+ }
+ }
+} catch (e: ExtensionException) {
+ Outcome.Bug(e.message)
+}
+
+/**
+ * One request rule of a scenario: requests whose URL contains [match] (`*`: all) wait [latencyMs],
+ * then fail as [dns] (no such host), [reset] (connection reset), or answer [status] (with
+ * `Retry-After: `[retryAfter] s; 429 when only [retryAfter] is given), [headers] and [body].
+ * [times]: how many requests it applies to (null: all of them).
+ */
+data class HttpRule(
+ val match: String,
+ val latencyMs: Long = 0,
+ val status: Int? = null,
+ val retryAfter: Long? = null,
+ val headers: Map<String, String> = emptyMap(),
+ val body: String = "",
+ val dns: Boolean = false,
+ val reset: Boolean = false,
+ var times: Int? = null,
+) {
+ fun matches(url: String) = match == "*" || url.contains(match)
+}
+
+/**
+ * A scenario file (`myspoti-ext test <dir> --scenario file.json`):
+ * `{ settings?, track?, offline?, http?: [rule], steps: [step] }`. A step is one of
+ * `{ hook, input?, track?, quality?, ahead?, cancelAtMs?, expect? }`, `{ event, input? }`,
+ * `{ message, expect? }` (its web page posting to it), `{ http: [rule] }` (the rules from then on),
+ * `{ wait: ms }` or `{ storage: { key: value|null } }` (what its storage holds). `expect`:
+ * `{ outcome?, maxMs?, minMs?, contains?, posted? }`.
+ */
+class Scenario(val root: JsonObject) {
+ val steps: List<JsonObject> = (root["steps"] as? JsonArray)?.map { it as? JsonObject ?: throw IllegalArgumentException("each step is an object") }
+ ?: throw IllegalArgumentException("a scenario has \"steps\": [ … ]")
+ val offline: Boolean = (root["offline"] as? JsonPrimitive)?.booleanOrNull ?: false
+ val settings: Map<String, String> = (root["settings"] as? JsonObject).orEmpty().mapValues { it.value.toString() }
+ val track: TrackInfo = trackOf(root["track"] as? JsonObject, null)
+
+ companion object {
+ fun parse(text: String) = Scenario(Json.parseToJsonElement(text).jsonObject)
+
+ fun rules(e: JsonElement?): List<HttpRule> = (e as? JsonArray).orEmpty().map { r ->
+ val o = r.jsonObject
+ fun s(k: String) = (o[k] as? JsonPrimitive)?.contentOrNull
+ fun l(k: String) = (o[k] as? JsonPrimitive)?.longOrNull
+ fun b(k: String) = (o[k] as? JsonPrimitive)?.booleanOrNull ?: false
+ HttpRule(
+ match = s("match") ?: "*", latencyMs = l("latencyMs") ?: 0, status = (o["status"] as? JsonPrimitive)?.intOrNull,
+ retryAfter = l("retryAfter"), headers = (o["headers"] as? JsonObject).orEmpty().mapValues { (it.value as? JsonPrimitive)?.contentOrNull.orEmpty() },
+ body = o["body"]?.let { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content ?: it.toString() } ?: "",
+ dns = b("dns"), reset = b("reset"), times = (o["times"] as? JsonPrimitive)?.intOrNull,
+ )
+ }
+
+ fun trackOf(o: JsonObject?, base: TrackInfo?): TrackInfo {
+ fun s(k: String) = (o?.get(k) as? JsonPrimitive)?.contentOrNull
+ val artist = s("artist") ?: base?.artists?.joinToString(",") ?: "Artist"
+ val id = s("id") ?: base?.id ?: "4uLU6hMCjMI75M1A2tKUQC"
+ return TrackInfo(
+ id = id, uri = if (id.isEmpty()) "" else "spotify:track:$id", title = s("title") ?: base?.title ?: "Sample",
+ artist = artist.substringBefore(",").trim(), artists = artist.split(",").map { it.trim() }.filter { it.isNotEmpty() },
+ album = s("album") ?: base?.album ?: "Album", durationMs = s("durationMs")?.toLongOrNull() ?: base?.durationMs ?: 200_000,
+ isrc = s("isrc") ?: base?.isrc,
+ )
+ }
+ }
+}
+
+/**
+ * The runner's [Host]: requests go through the scenario's [rules] (latency, 429 with Retry-After,
+ * 5xx, a DNS failure, a reset), the others to the network ([offline]: none, as a DNS failure);
+ * storage is kept across steps and in [stateFile] across runs; what it posts to its page is kept.
+ */
+class FaultHost(
+ @Volatile var rules: List<HttpRule>,
+ private val offline: Boolean,
+ private val settings: Map<String, String>,
+ private val track: TrackInfo?,
+ private val stateFile: File?,
+ private val echo: (String) -> Unit = { System.err.println(it) },
+) : Host {
+ private val store = MemoryStorage()
+ val posted = java.util.concurrent.CopyOnWriteArrayList<String>()
+ val requests = java.util.concurrent.CopyOnWriteArrayList<String>()
+
+ init {
+ stateFile?.takeIf { it.isFile }?.let { f ->
+ Json.parseToJsonElement(f.readText()).jsonObject.forEach { (k, v) -> store.set(k, v.toString()) }
+ }
+ }
+
+ /** Writes the storage to [stateFile] (one JSON object). */
+ fun saveState() {
+ val f = stateFile ?: return
+ f.absoluteFile.parentFile?.mkdirs()
+ f.writeText(JsonObject(store.snapshot().mapValues { runCatching { Json.parseToJsonElement(it.value) }.getOrElse { _ -> JsonNull } }).toString())
+ }
+
+ fun stored(key: String): String? = store.get(key)
+
+ override fun http(extensionId: String, request: HttpRequest): HttpResponse {
+ requests += "${request.method} ${request.url}"
+ val rule = synchronized(this) {
+ rules.firstOrNull { it.matches(request.url) && (it.times ?: 1) > 0 }?.also { r -> r.times = r.times?.minus(1) }
+ }
+ val host = runCatching { URI(request.url).host }.getOrNull() ?: request.url
+ if (rule == null) {
+ if (offline) throw UnknownHostException("$host (offline scenario: no rule for it)")
+ return BasicHttp.send(request, userAgent(extensionId))
+ }
+ if (rule.latencyMs > 0) {
+ if (rule.latencyMs >= request.timeout) { Thread.sleep(request.timeout.toLong()); throw SocketTimeoutException("timeout after ${request.timeout} ms") }
+ Thread.sleep(rule.latencyMs)
+ }
+ if (rule.dns) throw UnknownHostException("$host: no such host")
+ if (rule.reset) throw IOException("connection reset by $host")
+ val status = rule.status ?: if (rule.retryAfter != null) 429 else 200
+ val headers = rule.headers + (rule.retryAfter?.let { mapOf("Retry-After" to it.toString()) } ?: emptyMap())
+ return HttpResponse(status, headers, rule.body)
+ }
+
+ override fun log(extensionId: String, message: String) = echo("[$extensionId] $message")
+ override fun storage(extensionId: String): Storage = store
+ override fun setting(extensionId: String, key: String): String? = settings[key]
+ override fun nowPlaying(): String? = track?.toJson()
+ override fun postToPage(extensionId: String, json: String) { posted += json }
+ override fun notify(extensionId: String, text: String) = echo("[$extensionId] notify: $text")
+}
+
+/** One step's result: [ok] false with [problems] when an expectation failed. */
+data class StepResult(val index: Int, val what: String, val outcome: String?, val ms: Long, val problems: List<String>) {
+ val ok: Boolean get() = problems.isEmpty()
+ override fun toString(): String = "${if (ok) "✓" else "✗"} $index $what" + (outcome?.let { ": $it" } ?: "") + " ($ms ms)" +
+ problems.joinToString("") { "\n $it" }
+}
+
+/** Runs [scenario] on the extension [manifest] / [script], every hook within the app's [HookBudgets]. */
+class ScenarioRunner(
+ private val manifest: Manifest,
+ private val script: String,
+ private val scenario: Scenario,
+ private val stateFile: File? = null,
+ private val echo: (String) -> Unit = { System.err.println(it) },
+) {
+ fun run(): List<StepResult> {
+ val host = FaultHost(Scenario.rules(scenario.root["http"]), scenario.offline, scenario.settings, scenario.track, stateFile, echo)
+ val out = ArrayList<StepResult>()
+ try {
+ ExtensionRuntime(manifest, script, host, manifest.asks().map { it.key }.toSet()).use { rt ->
+ rt.start()
+ scenario.steps.forEachIndexed { i, step -> out += step(i + 1, step, rt, host) }
+ }
+ } finally {
+ host.saveState()
+ }
+ return out
+ }
+
+ private fun step(index: Int, s: JsonObject, rt: ExtensionRuntime, host: FaultHost): StepResult {
+ fun str(k: String) = (s[k] as? JsonPrimitive)?.contentOrNull
+ val expect = s["expect"] as? JsonObject
+ val t0 = System.currentTimeMillis()
+ fun ms() = System.currentTimeMillis() - t0
+ when {
+ s["hook"] != null -> {
+ val name = str("hook").orEmpty()
+ val hook = Hook.of(name) ?: return StepResult(index, "hook $name", null, 0, listOf("unknown hook (${Hook.entries.joinToString { it.key }})"))
+ if (!rt.provides(hook)) return StepResult(index, "hook $name", null, 0, listOf("this extension does not provide $name"))
+ val track = Scenario.trackOf(s["track"] as? JsonObject, scenario.track)
+ val opts = buildMap {
+ str("quality")?.let { put("quality", it) }; str("ahead")?.let { put("ahead", it) }
+ s["data"]?.let { put("data", it.toString()) }; str("action")?.let { put("action", it) }; str("query")?.let { put("query", it) }
+ }
+ val input = s["input"]?.toString() ?: hookInput(hook, track, opts) ?: return StepResult(index, "hook $name", null, 0, listOf("tap needs \"action\""))
+ val cancelAt = (s["cancelAtMs"] as? JsonPrimitive)?.longOrNull
+ val budget = HookBudgets.of(hook).let { b -> cancelAt?.coerceAtMost(b) ?: b }
+ if (hook == Hook.STATUS) {
+ val st = ExtensionStatus.probe(rt, budget)
+ return check(index, "status", st.state, ms(), expect, null, host)
+ }
+ var raw: String? = null
+ val outcome = try {
+ raw = rt.call(hook, input, budget)
+ classify(hook, raw, manifest.name)
+ } catch (e: ExtensionException) {
+ Outcome.of(e)
+ }
+ // Ended at the cancel time: its deadline, or a request cut by it.
+ val shown = if (cancelAt != null && outcome is Outcome.Network) "cancelled" else outcome.key
+ val elapsed = ms()
+ val problems = ArrayList<String>()
+ if (elapsed > HookBudgets.of(hook) + 500) problems += "took $elapsed ms, over the app's ${HookBudgets.of(hook)} ms for $name"
+ return check(index, "hook $name", shown, elapsed, expect, raw, host, problems, outcome)
+ }
+ s["event"] != null -> {
+ val event = str("event").orEmpty()
+ val input = s["input"]?.toString() ?: when (event) {
+ ExtensionRuntime.EVENT_TRACK -> PlaybackEvent.trackEventJson(scenario.track, PlaybackEvent.ORIGIN_SPOTIFY, null)
+ else -> "{}"
+ }
+ rt.emit(event, input, HookBudgets.ofEvent(event))
+ return check(index, "event $event", null, ms(), expect, null, host)
+ }
+ s["message"] != null -> {
+ val before = host.posted.size
+ val outcome = try {
+ rt.call(Hook.MESSAGE, s["message"].toString(), HookBudgets.BLOCKS)?.let { host.posted += it }
+ Outcome.Found
+ } catch (e: ExtensionException) {
+ Outcome.of(e)
+ }
+ val reply = host.posted.drop(before).joinToString("\n")
+ return check(index, "message", outcome.key, ms(), expect, reply, host, posted = host.posted.size - before)
+ }
+ s["http"] != null -> {
+ host.rules = Scenario.rules(s["http"])
+ return StepResult(index, "http rules: ${host.rules.size}", null, 0, emptyList())
+ }
+ s["wait"] != null -> {
+ Thread.sleep((s["wait"] as? JsonPrimitive)?.longOrNull ?: 0)
+ return StepResult(index, "wait", null, ms(), emptyList())
+ }
+ s["storage"] != null -> {
+ val problems = (s["storage"] as? JsonObject).orEmpty().mapNotNull { (k, v) ->
+ val have = host.stored(k)?.let { runCatching { Json.parseToJsonElement(it) }.getOrNull() } ?: JsonNull
+ if (have == v) null else "storage \"$k\": expected $v, has $have"
+ }
+ return StepResult(index, "storage", null, 0, problems)
+ }
+ else -> return StepResult(index, "?", null, 0, listOf("a step has hook, event, message, http, wait or storage"))
+ }
+ }
+
+ private fun check(
+ index: Int, what: String, outcome: String?, ms: Long, expect: JsonObject?, answer: String?, host: FaultHost,
+ problems: MutableList<String> = ArrayList(), stated: Outcome? = null, posted: Int? = null,
+ ): StepResult {
+ if (expect != null) {
+ fun l(k: String) = (expect[k] as? JsonPrimitive)?.longOrNull
+ (expect["outcome"] as? JsonPrimitive)?.contentOrNull?.let { want ->
+ if (want != outcome) problems += "expected $want, got $outcome${stated?.detail?.let { " ($it)" } ?: ""}"
+ }
+ l("maxMs")?.let { if (ms > it) problems += "took $ms ms, more than $it" }
+ l("minMs")?.let { if (ms < it) problems += "took $ms ms, less than $it" }
+ (expect["contains"] as? JsonPrimitive)?.contentOrNull?.let { if (answer?.contains(it) != true) problems += "the answer does not contain \"$it\"" }
+ l("posted")?.let { want -> if (posted != null && posted.toLong() != want) problems += "posted $posted message(s) to the page, expected $want" }
+ l("retryAfterMs")?.let { want -> if ((stated as? Outcome.RateLimited)?.retryAfterMs != want) problems += "retryAfterMs: expected $want, got ${(stated as? Outcome.RateLimited)?.retryAfterMs}" }
+ }
+ return StepResult(index, what, outcome?.let { o -> stated?.let { it.describe().replaceFirst(it.key, o) } ?: o }, ms, problems)
+ }
+}
diff --git a/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/ScenarioRunnerTest.kt b/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/ScenarioRunnerTest.kt
new file mode 100644
index 00000000..2a0da029
--- /dev/null
+++ b/base/extensions-cli/src/test/kotlin/app/myspoti/extensions/cli/ScenarioRunnerTest.kt
@@ -0,0 +1,65 @@
+package app.myspoti.extensions.cli
+
+import app.myspoti.extensions.Hook
+import app.myspoti.extensions.HookBudgets
+import app.myspoti.extensions.Manifest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+
+class ScenarioRunnerTest {
+ private fun res(name: String) = File(javaClass.classLoader.getResource(name)!!.toURI())
+ private val dir = res("sample-ext")
+ private val manifest = Manifest.parse(File(dir, "manifest.json").readText())
+ private val script = File(dir, manifest.main).readText()
+
+ private fun run(scenario: String, state: File? = null) =
+ ScenarioRunner(manifest, script, Scenario.parse(scenario), state, echo = {}).run()
+
+ @Test fun sampleScenarioPasses() {
+ val results = ScenarioRunner(manifest, script, Scenario.parse(res("sample-scenario.json").readText()), echo = {}).run()
+ results.filter { !it.ok }.forEach { println(it) }
+ assertTrue(results.all { it.ok })
+ assertEquals(listOf("found", "rate-limited", "server-down", "network", "cancelled"),
+ results.filter { it.what.startsWith("hook") }.map { it.outcome!!.substringBefore(':').substringBefore(' ') })
+ }
+
+ @Test fun aWrongExpectationFails() {
+ val r = run("""{ "offline": true, "steps": [ { "hook": "audio-source", "expect": { "outcome": "found" } } ] }""")
+ assertFalse(r.single().ok)
+ assertEquals("network", r.single().outcome!!.substringBefore(':'))
+ }
+
+ @Test fun aRuleAppliesTheNumberOfTimesGiven() {
+ val r = run("""{ "offline": true, "http": [
+ { "match": "api.example.com", "status": 500, "times": 1 },
+ { "match": "api.example.com", "body": "{\"url\":\"https://cdn.example.com/b.flac\"}" } ],
+ "steps": [ { "hook": "audio-source", "expect": { "outcome": "server-down" } },
+ { "hook": "audio-source", "expect": { "outcome": "found" } } ] }""")
+ assertTrue(r.joinToString("\n"), r.all { it.ok })
+ }
+
+ @Test fun storageOutlivesARunWithAStateFile() {
+ val state = File.createTempFile("state", ".json").apply { delete(); deleteOnExit() }
+ val scenario = """{ "offline": true, "http": [ { "match": "*", "status": 404 } ],
+ "steps": [ { "hook": "audio-source", "expect": { "outcome": "not-found" } } ] }"""
+ run(scenario, state); run(scenario, state)
+ assertTrue(state.readText(), state.readText().contains("\"asked\":2"))
+ val after = run("""{ "steps": [ { "storage": { "asked": 2, "lastTitle": "Sample" } } ] }""", state)
+ assertTrue(after.joinToString(), after.single().ok)
+ }
+
+ @Test fun theRunnerUsesTheAppsBudgets() {
+ // A request slower than the app gives audio-source ends as a network error, not a bug.
+ val r = run("""{ "offline": true, "http": [ { "match": "*", "latencyMs": ${HookBudgets.AUDIO + 5_000} } ],
+ "steps": [ { "hook": "audio-source", "cancelAtMs": 200 } ] }""")
+ assertEquals("cancelled", r.single().outcome!!.substringBefore(':'))
+ assertEquals(15_000L, HookBudgets.of(Hook.AUDIO_SOURCE))
+ }
+
+ @Test fun anUnknownStepIsReported() {
+ assertFalse(run("""{ "steps": [ { "nothing": 1 } ] }""").single().ok)
+ }
+}
diff --git a/base/extensions-cli/src/test/resources/sample-ext/main.js b/base/extensions-cli/src/test/resources/sample-ext/main.js
new file mode 100644
index 00000000..2aa36d13
--- /dev/null
+++ b/base/extensions-cli/src/test/resources/sample-ext/main.js
@@ -0,0 +1,14 @@
+// Answers where a song is from api.example.com, and why not when it cannot (feature "results").
+var results = myspoti.features && myspoti.features.indexOf('results') >= 0;
+
+myspoti.provide('audio-source', function (track) {
+ myspoti.storage.set('lastTitle', track.title);
+ var n = myspoti.storage.get('asked') || 0;
+ myspoti.storage.set('asked', n + 1);
+ var r = myspoti.http.get('https://api.example.com/find?title=' + encodeURIComponent(track.title), { timeout: 15000 });
+ if (r.status === 429 && results) return { outcome: 'rate-limited', retryAfterMs: 1000 * Number(r.headers['retry-after'] || r.headers['Retry-After'] || 60) };
+ if (r.status === 401 && results) return { outcome: 'sign-in', detail: 'Sign in again' };
+ if (r.status >= 500 && results) return { outcome: 'server-down' };
+ if (!r.ok) return null;
+ return { url: r.json().url, mimeType: 'audio/flac' };
+});
diff --git a/base/extensions-cli/src/test/resources/sample-ext/manifest.json b/base/extensions-cli/src/test/resources/sample-ext/manifest.json
new file mode 100644
index 00000000..a5e5f8fe
--- /dev/null
+++ b/base/extensions-cli/src/test/resources/sample-ext/manifest.json
@@ -0,0 +1,12 @@
+{
+ "id": "io.github.test.sample",
+ "name": "Sample Source",
+ "version": "1.0.0",
+ "author": "Test",
+ "description": "A tiny audio source for the scenario runner's tests.",
+ "actions": [
+ { "name": "audio.source", "why": "Plays songs from api.example.com" },
+ { "name": "storage", "why": "Remembers the last song asked" },
+ { "name": "network", "hosts": ["api.example.com", "cdn.example.com"], "why": "Asks api.example.com where a song is" }
+ ]
+}
diff --git a/base/extensions-cli/src/test/resources/sample-scenario.json b/base/extensions-cli/src/test/resources/sample-scenario.json
new file mode 100644
index 00000000..5cb576bc
--- /dev/null
+++ b/base/extensions-cli/src/test/resources/sample-scenario.json
@@ -0,0 +1,17 @@
+{
+ "offline": true,
+ "track": { "title": "Papaoutai", "artist": "Stromae" },
+ "http": [ { "match": "api.example.com/find", "body": { "url": "https://cdn.example.com/a.flac" } } ],
+ "steps": [
+ { "hook": "audio-source", "expect": { "outcome": "found", "maxMs": 5000, "contains": "cdn.example.com" } },
+ { "http": [ { "match": "api.example.com", "retryAfter": 30 } ] },
+ { "hook": "audio-source", "expect": { "outcome": "rate-limited", "retryAfterMs": 30000 } },
+ { "http": [ { "match": "api.example.com", "status": 503 } ] },
+ { "hook": "audio-source", "expect": { "outcome": "server-down" } },
+ { "http": [ { "match": "api.example.com", "dns": true } ] },
+ { "hook": "audio-source", "expect": { "outcome": "network" } },
+ { "http": [ { "match": "*", "latencyMs": 10000 } ] },
+ { "hook": "audio-source", "cancelAtMs": 300, "expect": { "outcome": "cancelled", "maxMs": 3000 } },
+ { "storage": { "lastTitle": "Papaoutai" } }
+ ]
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt
new file mode 100644
index 00000000..ab10ebb1
--- /dev/null
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/HookBudgets.kt
@@ -0,0 +1,46 @@
+package app.myspoti.extensions
+
+/**
+ * How long each hook call and event may run, in ms: one table for the app and the desktop runner
+ * (`myspoti-ext`), so an extension tried on a computer meets the times it gets on the phone.
+ */
+object HookBudgets {
+ /** A lyrics hook call. */
+ const val LYRICS = 8_000L
+ /** An audio-source hook call. */
+ const val AUDIO = 15_000L
+ /** A download-source hook call (an extension may try several places). */
+ const val DOWNLOAD = 30_000L
+ /** A block, tap or page-message hook call: the screen waits for it. */
+ const val BLOCKS = 3_000L
+ /** Its web page. */
+ const val PAGE = 5_000L
+ /** A `status` probe: it never holds a song's audio longer than this. */
+ const val STATUS = 5_000L
+ /** A `track` or `playback` event. */
+ const val TRACK = 3_000L
+ /** An `online` event: the extension sends what waited. */
+ const val ONLINE = 30_000L
+ /** A `setting` event: a button may pair again with a server. */
+ const val SETTING = 30_000L
+ /** An `auth` event. */
+ const val AUTH = 10_000L
+
+ /** The budget of a call to [hook]. */
+ fun of(hook: Hook): Long = when (hook) {
+ Hook.LYRICS -> LYRICS
+ Hook.AUDIO_SOURCE -> AUDIO
+ Hook.DOWNLOAD_SOURCE -> DOWNLOAD
+ Hook.PAGE -> PAGE
+ Hook.STATUS -> STATUS
+ Hook.TRACK_INFO, Hook.HOME, Hook.SEARCH, Hook.MENU, Hook.PLAYER, Hook.MESSAGE, Hook.TAP -> BLOCKS
+ }
+
+ /** The budget of [event] (`ExtensionRuntime.EVENT_*`); an unknown one gets [TRACK]. */
+ fun ofEvent(event: String): Long = when (event) {
+ ExtensionRuntime.EVENT_ONLINE -> ONLINE
+ ExtensionRuntime.EVENT_SETTING -> SETTING
+ ExtensionRuntime.EVENT_AUTH -> AUTH
+ else -> TRACK
+ }
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Outcome.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Outcome.kt
new file mode 100644
index 00000000..35a06a63
--- /dev/null
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Outcome.kt
@@ -0,0 +1,122 @@
+package app.myspoti.extensions
+
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.longOrNull
+
+/**
+ * How a source hook call (`audio-source`, `download-source`, `lyrics`) ended. An extension tells
+ * why it has nothing with `{ outcome, retryAfterMs?, untilMs?, detail?, available? }` (feature
+ * `results` in `myspoti.features`); the app classifies what it did not say ([of]). Only [Bug]
+ * counts toward turning an extension off: a slow, rate-limited or down server never does.
+ */
+sealed class Outcome {
+ /** The wire name, for logs, diagnostics and `{ outcome }`. */
+ abstract val key: String
+ /** What the extension or the app said about it, or null. */
+ open val detail: String? get() = null
+
+ /** It answered with something to use. */
+ object Found : Outcome() { override val key = "found" }
+
+ /** It has nothing for this (null, or `{ outcome: "not-found" }`). */
+ object NotFound : Outcome() { override val key = "not-found" }
+
+ /** Its account needs the user to sign in ([detail]: what to tell them). */
+ data class SignIn(override val detail: String? = null) : Outcome() { override val key = "sign-in" }
+
+ /** Its server asks to wait [retryAfterMs] (bounded by the app, [SourceCooldown]). */
+ data class RateLimited(val retryAfterMs: Long? = null, override val detail: String? = null) : Outcome() { override val key = "rate-limited" }
+
+ /** It has the song, not in the quality asked; [available]: the ones it has. */
+ data class QualityUnavailable(val available: List<String> = emptyList(), override val detail: String? = null) : Outcome() { override val key = "quality-unavailable" }
+
+ /** Its server is down until [untilMs] (wall-clock ms, bounded by the app), or for a while. */
+ data class ServerDown(val untilMs: Long? = null, override val detail: String? = null) : Outcome() { override val key = "server-down" }
+
+ /** A timeout or a network error of its requests: not counted against it. */
+ data class Network(override val detail: String? = null) : Outcome() { override val key = "network" }
+
+ /** Not asked ([detail]: why: busy, cooling down, inactive). */
+ data class Skipped(override val detail: String? = null) : Outcome() { override val key = "skipped" }
+
+ /** Its script threw, or answered something unusable: counted toward turning it off. */
+ data class Bug(override val detail: String? = null) : Outcome() { override val key = "bug" }
+
+ /** Whether it counts as a failure of the extension ([Bug] only). */
+ val counts: Boolean get() = this is Bug
+
+ /** `key` and its detail, for one log line. */
+ fun describe(): String = key + (detail?.let { ": $it" } ?: "") + when (this) {
+ is RateLimited -> retryAfterMs?.let { " (retry after $it ms)" } ?: ""
+ is ServerDown -> untilMs?.let { " (until $it)" } ?: ""
+ is QualityUnavailable -> if (available.isEmpty()) "" else " (has ${available.joinToString()})"
+ else -> ""
+ }
+
+ companion object {
+ const val MAX_DETAIL = 120
+ private const val MAX_AVAILABLE = 10
+
+ /** The hooks whose answer may be an outcome. */
+ val HOOKS = setOf(Hook.AUDIO_SOURCE, Hook.DOWNLOAD_SOURCE, Hook.LYRICS)
+
+ /**
+ * The outcome [json] states, or null when it is an ordinary answer (no string `outcome`
+ * at its root, or [hook] not one of [HOOKS]). [now]: the clock, turning a `retryAfterMs`
+ * of `server-down` into its end. An unknown outcome is a [Bug].
+ */
+ fun parse(hook: Hook, json: String, now: Long = System.currentTimeMillis()): Outcome? {
+ if (hook !in HOOKS) return null
+ val o = runCatching { ExtJson.parseToJsonElement(json) as? JsonObject }.getOrNull() ?: return null
+ val name = (o["outcome"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.lowercase() ?: return null
+ fun long(k: String) = (o[k] as? JsonPrimitive)?.let { p -> p.longOrNull ?: p.contentOrNull?.toDoubleOrNull()?.toLong() }?.takeIf { it >= 0 }
+ val detail = (o["detail"] as? JsonPrimitive)?.contentOrNull?.replace(Regex("\\s+"), " ")?.trim()?.take(MAX_DETAIL)?.ifBlank { null }
+ return when (name) {
+ "not-found", "notfound", "none" -> NotFound
+ "sign-in", "signin" -> SignIn(detail)
+ "rate-limited", "ratelimited" -> RateLimited(long("retryAfterMs"), detail)
+ "quality-unavailable" -> QualityUnavailable(
+ (o["available"] as? JsonArray).orEmpty().mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim()?.take(40)?.ifBlank { null } }.take(MAX_AVAILABLE),
+ detail,
+ )
+ "server-down" -> ServerDown(long("untilMs") ?: long("retryAfterMs")?.let { now + it }, detail)
+ "network" -> Network(detail)
+ "error", "bug" -> Bug(detail ?: "the extension said it failed")
+ else -> Bug("${hook.key}: unknown outcome \"${name.take(40)}\"")
+ }
+ }
+
+ /**
+ * What a call that threw [e] means: still busy ([Skipped]), a timeout or an error of its
+ * `http` requests ([Network]), else its own failure ([Bug]). A request the sandbox refused
+ * (a host not declared, a local address, plain http) is the extension's bug.
+ */
+ fun of(e: ExtensionException): Outcome {
+ val m = e.message ?: e.javaClass.simpleName
+ return when {
+ e is ExtensionBusy -> Skipped("busy: $m")
+ e is ExtensionFault -> Bug(m)
+ e is ExtensionTimeout -> Network("timeout: $m")
+ networkError(m) -> Network(m)
+ else -> Bug(m)
+ }
+ }
+
+ /** The sandbox's own refusals of a request: written by the extension, so its bug. */
+ private val REFUSALS = listOf(
+ "is a local address", "not in this extension's network hosts", "https only", "not a URL", "no host in",
+ "unreadable request", "is not allowed",
+ )
+
+ /** [message] is an `http:` error that is not a refusal (DNS, connection, timeout, too large). */
+ internal fun networkError(message: String): Boolean {
+ val at = message.indexOf("http: ")
+ if (at < 0) return false
+ val rest = message.substring(at + 6)
+ return REFUSALS.none { rest.contains(it, ignoreCase = true) }
+ }
+ }
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.kt
new file mode 100644
index 00000000..9bfd45ef
--- /dev/null
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.kt
@@ -0,0 +1,146 @@
+package app.myspoti.extensions
+
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+
+/**
+ * One try to play a song through the extensions, for "Why this source?" and the diagnostic report:
+ * the sources asked and how each ended, the one chosen, how its address opened, the quality it
+ * announced and the one the player detected, and the fallback taken.
+ */
+data class PlayAttempt(
+ val id: Long,
+ val at: Long,
+ val trackId: String,
+ val title: String,
+ /** The quality asked, when the app asks one (download-source; audio-source asks none yet). */
+ val requestedQuality: String? = null,
+ /** Asked before the song plays (the next one of the queue). */
+ val ahead: Boolean = false,
+ val asked: List<Ask> = emptyList(),
+ /** The extension whose answer plays, or null (none had it). */
+ val chosen: String? = null,
+ /** What the chosen one announced ("FLAC · 24-bit · 96 kHz"), or null. */
+ val announced: String? = null,
+ /** How its address opened in the player (the last try). */
+ val open: Open? = null,
+ /** What the player's decoder reported ("audio/flac · 44.1 kHz · 2 ch"), or null. */
+ val detected: String? = null,
+ /** What the app fell back to ("asked again: HTTP 403", "Spotify"), or null. */
+ val fallback: String? = null,
+ /** The last error the player reported for it. */
+ val error: String? = null,
+) {
+ /** One source: [outcome] ([Outcome.key]) after [ms]; [skippedReason] when it was not asked. */
+ data class Ask(val extension: String, val outcome: String, val ms: Long, val skippedReason: String? = null, val detail: String? = null)
+
+ /** Opening the chosen address: [url] is kept without its query (it may carry a token). */
+ data class Open(val ok: Boolean, val ms: Long, val httpStatus: Int? = null, val error: String? = null, val url: String? = null)
+
+ /** As JSON, every address without user info, query or fragment, and every text with its addresses masked. */
+ fun toJson(): JsonObject = JsonObject(buildMap {
+ put("id", JsonPrimitive(id))
+ put("at", JsonPrimitive(at))
+ put("track", JsonPrimitive(trackId))
+ put("title", JsonPrimitive(title))
+ requestedQuality?.let { put("requestedQuality", JsonPrimitive(it)) }
+ if (ahead) put("ahead", JsonPrimitive(true))
+ put("asked", JsonArray(asked.map { a ->
+ JsonObject(buildMap {
+ put("extension", JsonPrimitive(a.extension))
+ put("outcome", JsonPrimitive(a.outcome))
+ put("ms", JsonPrimitive(a.ms))
+ a.skippedReason?.let { put("skippedReason", JsonPrimitive(maskText(it))) }
+ a.detail?.let { put("detail", JsonPrimitive(maskText(it))) }
+ })
+ }))
+ put("chosen", chosen?.let(::JsonPrimitive) ?: JsonNull)
+ announced?.let { put("announced", JsonPrimitive(it)) }
+ open?.let { o ->
+ put("open", JsonObject(buildMap<String, JsonElement> {
+ put("ok", JsonPrimitive(o.ok))
+ put("ms", JsonPrimitive(o.ms))
+ o.httpStatus?.let { put("httpStatus", JsonPrimitive(it)) }
+ o.error?.let { put("error", JsonPrimitive(maskText(it))) }
+ o.url?.let { put("url", JsonPrimitive(maskUrl(it))) }
+ }))
+ }
+ detected?.let { put("detected", JsonPrimitive(it)) }
+ fallback?.let { put("fallback", JsonPrimitive(maskText(it))) }
+ error?.let { put("error", JsonPrimitive(maskText(it))) }
+ })
+
+ /** One masked line, for the diagnostic report's header. */
+ fun summary(): String = buildString {
+ append("#$id ${title.take(60)}")
+ if (ahead) append(" (ahead)")
+ requestedQuality?.let { append(" wanted $it") }
+ append(": ")
+ append(asked.joinToString { a -> "${a.extension}=${a.outcome}" + (a.skippedReason?.let { " (${maskText(it)})" } ?: " ${a.ms} ms") }.ifEmpty { "none asked" })
+ append(chosen?.let { " -> $it" } ?: " -> none")
+ open?.let { o -> append("; open ${if (o.ok) "ok" else "failed"} ${o.ms} ms" + (o.httpStatus?.let { " HTTP $it" } ?: "") + (o.error?.let { " ${maskText(it).take(120)}" } ?: "")) }
+ announced?.let { append("; announced $it") }
+ detected?.let { append("; detected $it") }
+ fallback?.let { append("; fallback ${maskText(it)}") }
+ error?.let { append("; error ${maskText(it).take(160)}") }
+ }
+
+ companion object {
+ private val URL = Regex("""(?i)\b(?:https?|wss?)://[^\s"'<>]+""")
+
+ /** [url] without user info, query or fragment ([SafeNet.redact]); not an address: its part before `?`/`#`. */
+ fun maskUrl(url: String): String =
+ url.toHttpUrlOrNull()?.let(SafeNet::redact) ?: url.substringBefore('?').substringBefore('#')
+
+ /** [text] with each address in it masked ([maskUrl]). */
+ fun maskText(text: String): String = URL.replace(text) { maskUrl(it.value) }
+ }
+}
+
+/** The last [capacity] [PlayAttempt]s, newest last. Thread-safe. */
+class PlayAttempts(private val capacity: Int = 20, private val clock: () -> Long = System::currentTimeMillis) {
+ private val ring = ArrayDeque<PlayAttempt>()
+ private var nextId = 1L
+
+ /** A new attempt for [trackId], its id. */
+ @Synchronized
+ fun start(trackId: String, title: String, ahead: Boolean = false, requestedQuality: String? = null): Long {
+ val id = nextId++
+ ring.addLast(PlayAttempt(id, clock(), trackId, title, requestedQuality, ahead))
+ while (ring.size > capacity) ring.removeFirst()
+ return id
+ }
+
+ /** Changes the attempt [id] (gone from the ring: nothing). */
+ @Synchronized
+ fun update(id: Long, change: (PlayAttempt) -> PlayAttempt) {
+ val i = ring.indexOfFirst { it.id == id }
+ if (i >= 0) ring[i] = change(ring[i])
+ }
+
+ /** Changes the latest attempt of [trackId] that chose a source, else its latest (none: nothing). */
+ @Synchronized
+ fun updateLatest(trackId: String, change: (PlayAttempt) -> PlayAttempt) {
+ val i = ring.indexOfLast { it.trackId == trackId && it.chosen != null }.takeIf { it >= 0 }
+ ?: ring.indexOfLast { it.trackId == trackId }.takeIf { it >= 0 } ?: return
+ ring[i] = change(ring[i])
+ }
+
+ /** The latest attempt for [trackId] (one that chose a source first), or null. */
+ @Synchronized
+ fun latest(trackId: String): PlayAttempt? = ring.lastOrNull { it.trackId == trackId && it.chosen != null } ?: ring.lastOrNull { it.trackId == trackId }
+
+ /** The last [n] attempts, newest first. */
+ @Synchronized
+ fun last(n: Int = capacity): List<PlayAttempt> = ring.toList().asReversed().take(n.coerceAtLeast(0))
+
+ /** The last [n] as a masked JSON array, newest first. */
+ fun toJson(n: Int = capacity): JsonArray = JsonArray(last(n).map(PlayAttempt::toJson))
+
+ @Synchronized
+ fun clear() = ring.clear()
+}
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Status.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Status.kt
index e5f14ad9..1a56d6f0 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Status.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Status.kt
@@ -70,3 +70,63 @@ class StatusBook(private val clock: () -> Long = System::currentTimeMillis) {
/** The inactive ones, with what they said. */
fun inactiveNow(): Map<String, ExtensionStatus> = entries.filterValues { !it.status.live }.mapValues { it.value.status }
}
+
+/**
+ * The sources set aside for a while after their server said to wait ([Outcome.RateLimited]), said
+ * it is down ([Outcome.ServerDown]) or failed on the network [NETWORK_IN_A_ROW] times in a row: they
+ * are skipped, not asked, until then. What an extension asks is bounded by the app ([MIN_MS] to
+ * [MAX_MS]), so it can neither hammer a server nor set itself aside for good.
+ */
+class SourceCooldown(private val clock: () -> Long = System::currentTimeMillis) {
+ private class Entry(val until: Long, val reason: String)
+ private val entries = ConcurrentHashMap<String, Entry>()
+ private val networkInARow = ConcurrentHashMap<String, Int>()
+
+ /**
+ * Notes [outcome] of [id]'s call; the delay it is now set aside for (ms), or null. An answer
+ * (found, not found, sign-in, quality) ends a cooldown and the network streak.
+ */
+ fun note(id: String, outcome: Outcome): Long? {
+ val now = clock()
+ val delay = when (outcome) {
+ is Outcome.RateLimited -> bounded(outcome.retryAfterMs ?: RATE_LIMITED_MS)
+ is Outcome.ServerDown -> bounded(outcome.untilMs?.let { it - now } ?: SERVER_DOWN_MS)
+ is Outcome.Network -> {
+ val n = networkInARow.merge(id, 1, Int::plus) ?: 1
+ if (n < NETWORK_IN_A_ROW) return null
+ bounded(MIN_MS shl (n - NETWORK_IN_A_ROW).coerceAtMost(5))
+ }
+ is Outcome.Skipped, is Outcome.Bug -> return null
+ else -> { networkInARow.remove(id); entries.remove(id); return null }
+ }
+ if (outcome !is Outcome.Network) networkInARow.remove(id)
+ entries[id] = Entry(now + delay, outcome.key)
+ return delay
+ }
+
+ /** Why [id] is set aside now ("rate-limited, 42 s left"), or null (it may be asked). */
+ fun reason(id: String): String? {
+ val e = entries[id] ?: return null
+ val left = e.until - clock()
+ if (left <= 0) { entries.remove(id, e); return null }
+ return "${e.reason}, ${(left + 999) / 1000} s left"
+ }
+
+ /** When [id] may be asked again (wall-clock ms), or null. */
+ fun until(id: String): Long? = entries[id]?.until?.takeIf { it > clock() }
+
+ fun forget(id: String) { entries.remove(id); networkInARow.remove(id) }
+
+ companion object {
+ const val MIN_MS = 30_000L
+ const val MAX_MS = 15 * 60_000L
+ /** A rate limit without a delay. */
+ const val RATE_LIMITED_MS = 60_000L
+ /** A server down without an end. */
+ const val SERVER_DOWN_MS = 5 * 60_000L
+ /** Network failures in a row before a source is set aside (then 30 s, doubling up to [MAX_MS]). */
+ const val NETWORK_IN_A_ROW = 3
+
+ fun bounded(ms: Long): Long = ms.coerceIn(MIN_MS, MAX_MS)
+ }
+}
diff --git a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
index 5f398be9..91fa2be9 100644
--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
@@ -122,9 +122,9 @@
/**
* 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", "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 }), "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.
*/
- features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64'].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'].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
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/OutcomeTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/OutcomeTest.kt
new file mode 100644
index 00000000..2435248c
--- /dev/null
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/OutcomeTest.kt
@@ -0,0 +1,133 @@
+package app.myspoti.extensions
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class OutcomeTest {
+ @Test fun anOrdinaryAnswerIsNoOutcome() {
+ assertNull(Outcome.parse(Hook.AUDIO_SOURCE, """{"url":"https://a.example/x.flac"}"""))
+ assertNull(Outcome.parse(Hook.AUDIO_SOURCE, "[1,2]"))
+ assertNull(Outcome.parse(Hook.AUDIO_SOURCE, """{"outcome":3}"""))
+ // Only the source hooks may answer an outcome.
+ assertNull(Outcome.parse(Hook.HOME, """{"outcome":"rate-limited"}"""))
+ }
+
+ @Test fun statedOutcomesAreParsed() {
+ assertEquals(Outcome.NotFound, Outcome.parse(Hook.LYRICS, """{"outcome":"not-found"}"""))
+ assertEquals(Outcome.SignIn("Sign in again"), Outcome.parse(Hook.AUDIO_SOURCE, """{"outcome":"sign-in","detail":" Sign in again "}"""))
+ assertEquals(Outcome.RateLimited(30_000), Outcome.parse(Hook.DOWNLOAD_SOURCE, """{"outcome":"rate-limited","retryAfterMs":30000}"""))
+ assertEquals(Outcome.RateLimited(null), Outcome.parse(Hook.DOWNLOAD_SOURCE, """{"outcome":"rate-limited","retryAfterMs":-5}"""))
+ assertEquals(Outcome.QualityUnavailable(listOf("cd", "small")),
+ Outcome.parse(Hook.DOWNLOAD_SOURCE, """{"outcome":"quality-unavailable","available":["cd"," small ",""]}"""))
+ assertEquals(Outcome.ServerDown(5_000), Outcome.parse(Hook.AUDIO_SOURCE, """{"outcome":"server-down","untilMs":5000}"""))
+ assertEquals(Outcome.ServerDown(1_000 + 60_000), Outcome.parse(Hook.AUDIO_SOURCE, """{"outcome":"server-down","retryAfterMs":60000}""", now = 1_000))
+ assertEquals("network", Outcome.parse(Hook.AUDIO_SOURCE, """{"outcome":"network"}""")!!.key)
+ val unknown = Outcome.parse(Hook.AUDIO_SOURCE, """{"outcome":"maybe"}""")
+ assertTrue(unknown is Outcome.Bug)
+ assertEquals(Outcome.MAX_DETAIL, (Outcome.parse(Hook.LYRICS, """{"outcome":"sign-in","detail":"${"x".repeat(500)}"}""") as Outcome.SignIn).detail!!.length)
+ }
+
+ @Test fun failuresAreClassified() {
+ assertEquals("network", Outcome.of(ExtensionTimeout("took longer than 15000 ms")).key)
+ assertEquals("network", Outcome.of(ExtensionException("Error: http: api.example.com: no such host (main.js:3)")).key)
+ assertEquals("network", Outcome.of(ExtensionException("Error: http: timeout (main.js:3)")).key)
+ // A request the sandbox refused is the extension's own bug.
+ assertEquals("bug", Outcome.of(ExtensionException("Error: http: evil.example is not in this extension's network hosts (main.js:3)")).key)
+ assertEquals("bug", Outcome.of(ExtensionException("Error: http: 10.0.0.1 is a local address (main.js:3)")).key)
+ assertEquals("bug", Outcome.of(ExtensionException("TypeError: x is undefined (main.js:9)")).key)
+ assertEquals("bug", Outcome.of(ExtensionFault("out of memory")).key)
+ assertEquals("skipped", Outcome.of(ExtensionBusy("busy")).key)
+ }
+
+ @Test fun onlyBugsCount() {
+ assertTrue(Outcome.Bug("x").counts)
+ listOf(Outcome.Found, Outcome.NotFound, Outcome.SignIn(), Outcome.RateLimited(), Outcome.QualityUnavailable(),
+ Outcome.ServerDown(), Outcome.Network(), Outcome.Skipped()).forEach { assertFalse(it.key, it.counts) }
+ }
+}
+
+class SourceCooldownTest {
+ private var now = 1_000_000L
+ private val c = SourceCooldown { now }
+
+ @Test fun aRateLimitIsBounded() {
+ assertEquals(SourceCooldown.MIN_MS, c.note("a", Outcome.RateLimited(1)))
+ assertEquals(SourceCooldown.MAX_MS, c.note("b", Outcome.RateLimited(24 * 3600_000L)))
+ assertEquals(SourceCooldown.RATE_LIMITED_MS, c.note("c", Outcome.RateLimited(null)))
+ assertEquals(90_000L, c.note("d", Outcome.RateLimited(90_000)))
+ assertTrue(c.reason("d")!!.startsWith("rate-limited, 90 s left"))
+ now += 90_000
+ assertNull(c.reason("d"))
+ }
+
+ @Test fun aServerDownIsBounded() {
+ assertEquals(SourceCooldown.MAX_MS, c.note("a", Outcome.ServerDown(now + 7 * 24 * 3600_000L)))
+ assertEquals(SourceCooldown.MIN_MS, c.note("b", Outcome.ServerDown(now - 1)))
+ assertEquals(SourceCooldown.SERVER_DOWN_MS, c.note("c", Outcome.ServerDown(null)))
+ }
+
+ @Test fun networkErrorsInARowSetASourceAside() {
+ assertNull(c.note("a", Outcome.Network()))
+ assertNull(c.note("a", Outcome.Network()))
+ assertEquals(SourceCooldown.MIN_MS, c.note("a", Outcome.Network()))
+ assertEquals(2 * SourceCooldown.MIN_MS, c.note("a", Outcome.Network()))
+ repeat(20) { c.note("a", Outcome.Network()) }
+ assertEquals(SourceCooldown.MAX_MS, c.note("a", Outcome.Network()))
+ // An answer ends it.
+ assertNull(c.note("a", Outcome.NotFound))
+ assertNull(c.reason("a"))
+ assertNull(c.note("a", Outcome.Network()))
+ }
+
+ @Test fun bugsAndSkipsChangeNothing() {
+ assertNull(c.note("a", Outcome.Bug("x")))
+ assertNull(c.note("a", Outcome.Skipped("busy")))
+ assertNull(c.reason("a"))
+ }
+}
+
+class HookBudgetsTest {
+ @Test fun everyHookHasABudget() {
+ Hook.entries.forEach { assertTrue(it.key, HookBudgets.of(it) in 1_000L..30_000L) }
+ assertEquals(8_000L, HookBudgets.of(Hook.LYRICS))
+ assertEquals(15_000L, HookBudgets.of(Hook.AUDIO_SOURCE))
+ assertEquals(30_000L, HookBudgets.of(Hook.DOWNLOAD_SOURCE))
+ assertEquals(3_000L, HookBudgets.of(Hook.HOME))
+ assertEquals(HookBudgets.SETTING, HookBudgets.ofEvent(ExtensionRuntime.EVENT_SETTING))
+ assertEquals(HookBudgets.TRACK, HookBudgets.ofEvent(ExtensionRuntime.EVENT_PLAYBACK))
+ }
+}
+
+class PlayAttemptTest {
+ @Test fun addressesAreMasked() {
+ val a = PlayAttempt(
+ 1, 0, "t1", "Song",
+ asked = listOf(PlayAttempt.Ask("x.ext", "network", 120, detail = "Error: http: https://api.example.com/find?token=SECRET failed")),
+ chosen = "x.ext",
+ open = PlayAttempt.Open(false, 300, 403, "refused https://cdn.example.com/a.flac?sig=SECRET&exp=1", "https://user:[email protected]/a.flac?sig=SECRET#frag"),
+ error = "source error at https://cdn.example.com/a.flac?sig=SECRET",
+ )
+ val json = a.toJson().toString()
+ assertFalse(json, json.contains("SECRET"))
+ assertFalse(json, json.contains("pw@"))
+ assertTrue(json, json.contains("https://cdn.example.com/a.flac"))
+ assertFalse(a.summary(), a.summary().contains("SECRET"))
+ assertEquals("not a url", PlayAttempt.maskUrl("not a url?x=1"))
+ }
+
+ @Test fun theRingKeepsTheLastOnes() {
+ val r = PlayAttempts(capacity = 3)
+ val ids = (1..5).map { r.start("t$it", "S$it") }
+ assertEquals(listOf("t5", "t4", "t3"), r.last().map { it.trackId })
+ r.update(ids[0]) { it.copy(chosen = "gone") }
+ r.updateLatest("t4") { it.copy(chosen = "a") }
+ r.updateLatest("t4") { it.copy(open = PlayAttempt.Open(true, 10)) }
+ assertEquals("a", r.latest("t4")!!.chosen)
+ assertTrue(r.latest("t4")!!.open!!.ok)
+ assertNull(r.latest("t1"))
+ assertEquals(2, r.toJson(2).size)
+ }
+}
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt
index 0566bf35..f82b5267 100644
--- a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt
@@ -199,7 +199,7 @@ class SandboxTest {
}
@Test fun featuresNameWhatThisAppUnderstands() {
- assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64"}""", eval("return myspoti.features.join(',');"))
+ assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64,results"}""", eval("return myspoti.features.join(',');"))
}
@Test fun localMuteFeatureIsListedOnlyWhenMirrorIsGranted() {
diff --git a/docs/cli.md b/docs/cli.md
index 919d8b48..e61724ac 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -12,9 +12,13 @@ Each command is one broadcast (`<package>.CLI`, held to the adb shell by the `DU
The app writes its JSON reply to `/sdcard/Android/data/<package>/files/cli/<request>.json` and to
logcat under `MyspotiCli`; the script reads it back, prints the `result`, and deletes the file.
-Exit codes: `0` ok, `1` the app answered an error (on stderr), `2` no reply (not installed, a
-stable build, timeout), `3` adb failed. `ADB`, `ANDROID_SERIAL` and `MYSPOTI_PACKAGE` override the
-defaults (the beta is `-p app.myspoti`).
+Exit codes: `0` ok, `1` the command failed (the app answered an error, on stderr, or no reply in
+time), `2` device unreachable (`adb get-state` is not `device`, or several devices and none named),
+`3` adb failed, `4` the app is not installed (`pm path`), `5` disabled in this build (a stable build
+has no CLI receiver: it leaves the broadcast's result at 0, where the receiver sets 1; `ext.why` is
+debug only). The script always targets one device: `-s` or `ANDROID_SERIAL`, else the only one adb
+lists; with several and none named it refuses. `ADB`, `ANDROID_SERIAL` and `MYSPOTI_PACKAGE` override
+the defaults (the beta is `-p app.myspoti`).
## Commands
@@ -30,6 +34,7 @@ defaults (the beta is `-p app.myspoti`).
| `ext.call <id> <hook> [json]` | Calls one hook of that extension alone (`lyrics`, `audio-source`, `download-source`, `trackinfo`, `home`, `search`, `menu`, `player`, `page`, `message`, `tap`, `status`) and prints its answer, masked; `null` when its script provides no such hook. Asked while the app starts, it waits for the extensions to load. |
| `ext.log <id> [lines]` | Its log's last lines (50 by default), masked. |
| `ext.storage <id>` | Its storage's keys and size, never the values. |
+| `ext.why [n]` | The last `n` (1 by default, 20 at most) plays through the extensions: sources asked, outcome and time, skipped and why, chosen, how its address opened, announced and detected quality, fallback, error. Addresses without query, masked. Debug builds only. |
| `play <spotify:…> [context]`, `pause`, `resume`, `next`, `previous` | The player's own commands. |
| `nav <route>` | The open screen navigates to a route (`settings`, `extensions`, `extension/<id>`, `queue`…). |
diff --git a/docs/extensions/API.md b/docs/extensions/API.md
index 56bd5a95..7d30755b 100644
--- a/docs/extensions/API.md
+++ b/docs/extensions/API.md
@@ -189,9 +189,12 @@ player.buttons action in the manifest`):
The lyrics, song details, Home, search, menu and player hooks are **additive**: every extension is
asked, 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
-`null`/`undefined` means "no answer": the app goes on without this extension. A throw or a timeout
-is a failure (recorded as the extension's last error, shown on its page). Calls are synchronous:
-return the answer, do not return a promise.
+`null`/`undefined` means "no answer": the app goes on without this extension. A throw is a
+failure (recorded as the extension's last error, shown on its page; 3 in a row turn it off). A
+timeout, or an `http` error your script did not catch (DNS, connection, timeout), is a **network**
+error: logged, never counted as a failure, so a slow or rate-limited server never turns an extension
+off. `lyrics`, `audio-source` and `download-source` may also say why they have nothing with an
+outcome (section 3, "Outcomes"). Calls are synchronous: return the answer, do not return a promise.
The input of every hook, and of the `track` event, is this track:
@@ -338,8 +341,8 @@ a real FLAC file (its header is read), an `m4a` or `mp3` must hold an audio trac
read, 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 at once; the first one installed that answers wins. Time limit: 30 s (the
-desktop runner: the same).
+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).
### `status`
@@ -369,6 +372,43 @@ myspoti.provide('status', function () {
- Without a `status` hook an extension is always live. Check
`myspoti.features.indexOf('status') >= 0`: an older Myspoti never asks it.
+### Outcomes (`results`)
+
+`lyrics`, `audio-source` and `download-source` may answer **why** they have nothing instead of
+`null`, when `myspoti.features.indexOf('results') >= 0` (an older Myspoti reads such an answer as no
+answer, or as a malformed one: check the feature first):
+
+```js
+myspoti.provide('audio-source', function (track) {
+ var r = myspoti.http.get('https://api.example.com/find?isrc=' + track.isrc);
+ var results = myspoti.features && myspoti.features.indexOf('results') >= 0;
+ if (r.status === 429 && results) return { outcome: 'rate-limited', retryAfterMs: 1000 * Number(r.headers['retry-after'] || 60) };
+ if (r.status === 401 && results) return { outcome: 'sign-in', detail: 'Sign in again in the settings' };
+ if (!r.ok) return null;
+ return { url: r.json().url };
+});
+```
+
+| `outcome` | Fields | What the app does |
+|---|---|---|
+| `not-found` | | Same as `null`. |
+| `sign-in` | `detail?` | A notice "sign in to keep using its source" with a **Sign in** button that opens your extension's page (offer the sign-in there: a setting button, your page). Gone at your next answer with audio, or after a sign-in page reached its callback. |
+| `rate-limited` | `retryAfterMs?` | Your source is set aside (not asked) for `retryAfterMs`, bounded to 30 s – 15 min (60 s without it). |
+| `server-down` | `untilMs?` (wall-clock ms) or `retryAfterMs?` | Set aside until then, bounded to 30 s – 15 min (5 min without either). |
+| `quality-unavailable` | `available?: ["cd", …]` | Logged and shown in "Why this source?"; the next source is asked. |
+| `network` | `detail?` | A network error you caught: logged, not counted. |
+| `error` | `detail?` | A failure you caught: logged, not counted (an uncaught throw is). |
+
+Every field is optional; `detail` is trimmed to 120 characters. An unknown `outcome` is a failure.
+Every outcome, the ones the app classifies itself too (`found`, `not-found`, `network` for a timeout
+or an `http` error, `bug` for a throw), is written to your extension's log with its time. Three
+network errors in a row also set a source aside (30 s, doubling up to 15 min). While a source is set
+aside the next one is asked, or the song plays from Spotify. The player's sound quality sheet has
+**Why this source?**: for the song playing, each source asked with its outcome and time, the ones
+skipped and why, the one chosen, how its address opened (time, HTTP status, error), the quality it
+announced and the one the player's decoder reports (its input, not proof of a bit-perfect output).
+Addresses are shown without their query string.
+
### `track` event
`myspoti.on('track', function (track) { ... })` is called for each new song, with the song's fields
@@ -668,7 +708,7 @@ A script that throws while loading fails to load, with `file:line` in the messag
|---|---|
| `myspoti.apiVersion` | `1`. |
| `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), `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"), `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`. |
@@ -1118,9 +1158,10 @@ is. `playlists.setCover` takes a JPEG as base64.
| What | Limit |
|---|---|
| Loading the script (its top level; compiling it is not counted) | 3 s |
-| A hook call | Set by the app per call (the app and the desktop runner: 8 s for `lyrics`, 15 s for `audio-source`, 30 s for `download-source`) |
+| A hook call | One table for the app and the desktop runner (`HookBudgets`): 8 s for `lyrics`, 15 s for `audio-source`, 30 s for `download-source`, 3 s for blocks hooks, `tap` and `message`, 5 s for `page` and `status` |
| A `track` or `playback` event | 3 s |
-| A `setting` event | 30 s |
+| A `setting` or `online` event | 30 s |
+| An `auth` event | 10 s |
| 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 |
@@ -1150,14 +1191,15 @@ to the confirmation prompt below. Give absolute paths.)
| Command | Does |
|---|---|
-| `check <folder>` | Prints the manifest's problems (`✗ ...`, e.g. a missing or too long `why`), says when it is an old manifest, loads the script, prints each action as the user sees it (icon name, label, level, why), then asks each blocks hook it provides once with a sample and checks the blocks (and the page). Exit 1 on a problem. |
+| `check <folder\|zip>` | Package validity only: prints the manifest's problems (`✗ ...`, e.g. a missing or too long `why`), says when it is an old manifest, loads the script, prints the hooks it provides and each action as the user sees it (icon name, label, level, why). It never calls a hook. Exit 1 on a problem. |
+| `test <folder\|zip> --scenario file.json [--state file.json]` | Runs a scenario (below): hook calls, events and page messages in order with the app's time limits, requests answered or broken by rules, storage kept across steps. Prints each step (`✓`/`✗`, outcome, time); exit 1 when a step failed. |
| `run <folder\|zip> lyrics --title T --artist A [options]` | Calls the hook and prints what it answered, parsed the way the app parses it (lines, `synced`, `word by word`, or the audio URL and headers). |
| `run <folder\|zip> audio-source ...` | Same for the audio hook. |
| `run <folder\|zip> download-source ... [--quality hi-res\|cd\|small]` | Same for the download hook: prints the files, best first, as the app reads them (default quality `cd`). |
| `run <folder\|zip> audio-source ... [--ahead true]` | Asks for a song's audio (with `ahead: true` when given) and prints the answer as the app reads it: address or manifest, `expiresInMs`, quality. |
| `run <folder\|zip> home\|search\|menu\|player\|trackinfo ...` | Calls a blocks hook (`--query Q` for search, `--kind track\|album\|playlist\|artist` for menu) and prints the blocks as the app reads them. |
| `run <folder\|zip> page\|message\|tap ...` | The page hook (prints title and HTML), a page message (`--data JSON`), a tap (`--action ID`). |
-| `run <folder\|zip> status --title T` | Asks `status` as the app does (5 s) and prints live, or inactive and why (`check` prints it too). |
+| `run <folder\|zip> status --title T` | Asks `status` as the app does (5 s) and prints live, or inactive and why. |
| `run <folder\|zip> track ...` | Delivers the `track` event. |
| `run <folder\|zip> playback ... [--played MS] [--leave skip\|end\|stop]` | Delivers a play of the song as `playback` events, at once, with the times they would have had: `start`, a `progress` every 10 s up to `--played` (default 40000), then `skip` (forward), `end` (finished) or `end` (stop). Also `--context URI`, `--shuffle true`, `--source local\|spotify`, `--origin spotify\|download\|audio-source\|local-file` and `--provider ID` (also for `track`). |
| `pack <folder> [out-folder]` | Checks, builds `<id>-<version>.zip`, prints its sha256 and its index entry. |
@@ -1168,7 +1210,9 @@ to the confirmation prompt below. Give absolute paths.)
`--set key=value` (a setting; repeat; `true`, `false` and numbers are passed as such, anything else
as text; unset ones use the manifest `default`).
-What the runner does: every right the manifest asks is granted. Storage is in memory for the run.
+What the runner does: every right the manifest asks is granted. Each hook and event gets the app's
+own time limit (section 7). An answer `{ outcome }` is printed as the app reads it. Storage is in
+memory for the run (`test --state` keeps it in a file).
`myspoti.attest` works with a software key kept between runs (section 10).
`log`, `console`, `notify` and failures go to stderr as `[id] message`. `player` controls print
`player: <action>` and answer `true`. `myspoti.player.current()` returns the `--title` track.
@@ -1203,6 +1247,47 @@ or a `myspoti.spotify` call fail only under `run`. A top-level call to `myspoti.
`check`. `run ... track` prints `delivered` even if the listener threw: read the `failed: ...` line
on stderr.
+### 8.1 Scenarios (`test`)
+
+A scenario is a JSON file:
+
+```json
+{
+ "offline": true,
+ "settings": { "region": "eu" },
+ "track": { "title": "Papaoutai", "artist": "Stromae", "isrc": "BEUM71300139" },
+ "http": [ { "match": "api.example.com/find", "body": { "url": "https://cdn.example.com/a.flac" } } ],
+ "steps": [
+ { "hook": "audio-source", "expect": { "outcome": "found", "maxMs": 2000 } },
+ { "http": [ { "match": "api.example.com", "status": 429, "retryAfter": 30 } ] },
+ { "hook": "audio-source", "expect": { "outcome": "rate-limited", "retryAfterMs": 30000 } },
+ { "http": [ { "match": "*", "latencyMs": 20000 } ] },
+ { "hook": "audio-source", "cancelAtMs": 500, "expect": { "outcome": "cancelled" } },
+ { "event": "online" },
+ { "message": { "type": "hello" }, "expect": { "posted": 1, "contains": "hi" } },
+ { "storage": { "lastIsrc": "BEUM71300139" } }
+ ]
+}
+```
+
+- **`http` rules** (at the top, or as a step that replaces them from then on): a request whose URL
+ contains `match` (`*`: all) waits `latencyMs` (past the request's timeout: a timeout), then fails
+ with `dns: true` (no such host) or `reset: true` (connection reset), or answers `status` (200 by
+ default; 429 when only `retryAfter` is given, in seconds, sent as `Retry-After`), `headers` and
+ `body` (text, or JSON written as text). `times: n` applies a rule to n requests only. Requests no
+ rule matches go to the network, or fail as a DNS error with `"offline": true`.
+- **Steps**: `{ hook, input?, track?, quality?, ahead?, data?, action?, query?, cancelAtMs? }` calls
+ a hook (the input is built as the app builds it unless `input` is given); `cancelAtMs` ends the
+ call at that time (outcome `cancelled`). `{ event, input? }` delivers an event. `{ message }` is
+ your page posting to you; what you answer or post back is the page's. `{ wait: ms }` waits.
+ `{ storage: { key: value \| null } }` checks your storage.
+- **`expect`**: `outcome` (`found`, `not-found`, `sign-in`, `rate-limited`, `quality-unavailable`,
+ `server-down`, `network`, `bug`, `skipped`, `cancelled`; `live`/`inactive`/`unknown` for `status`),
+ `maxMs`, `minMs`, `retryAfterMs`, `contains` (a text the answer contains), `posted` (messages posted
+ to the page). A hook call over the app's time limit fails too.
+- **`--state file.json`**: your storage is read from it before the run and written back after, so
+ a run can start where the last one ended (a token, a cache).
+
## 9. GitHub: install, updates, store, publishing
### 9.1 What the app does with a repository
diff --git a/tools/myspoti-cli b/tools/myspoti-cli
index 0df892a9..bc4f6601 100755
--- a/tools/myspoti-cli
+++ b/tools/myspoti-cli
@@ -4,15 +4,27 @@
tools/myspoti-cli status
tools/myspoti-cli ext.install path/to/extension.zip # a local zip is pushed first
tools/myspoti-cli ext.call my.ext lyrics '{"title":"…"}'
+ tools/myspoti-cli ext.why 3 # the last 3 plays through extensions (debug builds)
Each command is one broadcast to the app's CliReceiver; the app writes its JSON reply to
-<external files>/cli/<request>.json, which this reads back (bounded wait). Exit codes:
-0 ok, 1 the app answered an error, 2 no reply (app not installed, release build, timeout), 3 adb failed.
+<external files>/cli/<request>.json, which this reads back (bounded wait).
+
+It always targets one device: -s SERIAL or $ANDROID_SERIAL, else the only device adb lists; with
+several devices on this adb server and none named, it refuses.
+
+Exit codes:
+ 0 ok
+ 1 the command failed (the app answered an error, or no reply in time)
+ 2 device unreachable (not listed by adb, offline, unauthorized; or several devices and none named)
+ 3 adb itself failed
+ 4 the app is not installed on that device
+ 5 the command is disabled in this build (a release build has no CLI receiver; ext.why is debug only)
"""
import argparse
import base64
import json
import os
+import re
import shlex
import subprocess
import shutil
@@ -38,6 +50,39 @@ def shell(serial, line, check=True):
return adb(serial, "shell", line, check=check)
+# What a receiver that answered sets (CliReceiver): a missing or disabled one leaves 0.
+ANSWERED = 1
+DISABLED = "disabled in this build"
+
+
+def pick_serial(serial):
+ """The one device to drive: the one named, else the only one listed. Exit 2 otherwise."""
+ if serial:
+ r = adb(serial, "get-state", check=False)
+ if r.returncode != 0 or r.stdout.strip() != "device":
+ sys.stderr.write(f"device {serial} unreachable: {(r.stderr.strip() or r.stdout.strip() or 'no state')}\n")
+ sys.exit(2)
+ return serial
+ r = adb(None, "devices", check=False)
+ if r.returncode != 0:
+ sys.stderr.write(f"adb failed: devices: {r.stderr.strip()}\n")
+ sys.exit(3)
+ rows = [l.split() for l in r.stdout.splitlines()[1:] if l.strip() and not l.startswith("*")]
+ if len(rows) > 1:
+ sys.stderr.write("several devices on this adb server: name one with -s SERIAL or ANDROID_SERIAL ("
+ + ", ".join(row[0] for row in rows) + ")\n")
+ sys.exit(2)
+ if not rows or rows[0][1:2] != ["device"]:
+ sys.stderr.write("no device reachable" + (f" ({rows[0][0]} is {rows[0][1]})" if rows and len(rows[0]) > 1 else "") + "\n")
+ sys.exit(2)
+ return rows[0][0]
+
+
+def installed(serial, pkg):
+ r = shell(serial, f"pm path {shlex.quote(pkg)}", check=False)
+ return r.returncode == 0 and "package:" in r.stdout
+
+
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("-p", "--package", default=os.environ.get("MYSPOTI_PACKAGE", "app.myspoti.dev"))
@@ -50,6 +95,10 @@ def main():
pkg, args = o.package, list(o.args)
files = f"/sdcard/Android/data/{pkg}/files/cli"
+ o.serial = pick_serial(o.serial)
+ if not installed(o.serial, pkg):
+ sys.stderr.write(f"{pkg} is not installed on {o.serial} (-p PACKAGE or MYSPOTI_PACKAGE for another build)\n")
+ sys.exit(4)
# A zip on this computer goes to a folder the app reads without any permission.
if o.cmd == "ext.install" and args and os.path.isfile(args[0]):
@@ -65,9 +114,14 @@ def main():
"am", "broadcast", "-a", f"{pkg}.CLI", "-p", pkg,
"--es", "cmd", o.cmd, "--es", "args64", args64, "--es", "req", req,
])
- shell(o.serial, line)
-
- deadline = time.monotonic() + o.timeout
+ # `am broadcast` returns once the receiver finished: "Broadcast completed: result=1" when it answered.
+ sent = shell(o.serial, line)
+ m = re.search(r"result=(-?\d+)", sent.stdout)
+ answered = m is not None and int(m.group(1)) == ANSWERED
+ # No answer: a release build (receiver off); an older build that wrote its reply anyway is still read.
+ wait = o.timeout if answered or m is None else min(o.timeout, 2.0)
+
+ deadline = time.monotonic() + wait
text = None
while time.monotonic() < deadline:
r = shell(o.serial, f"cat {shlex.quote(reply_path)} 2>/dev/null", check=False)
@@ -76,23 +130,25 @@ def main():
break
time.sleep(0.25)
if text is None:
- sys.stderr.write(f"no reply from {pkg} after {o.timeout:g} s (installed? a debug or beta build? "
- f"adb logcat -s MyspotiCli)\n")
- sys.exit(2)
+ if not answered and m is not None:
+ sys.stderr.write(f"{pkg} has no CLI in this build (a release build: use a debug or beta one)\n")
+ sys.exit(5)
+ sys.stderr.write(f"no reply from {pkg} after {o.timeout:g} s (adb logcat -s MyspotiCli)\n")
+ sys.exit(1)
shell(o.serial, f"rm -f {shlex.quote(reply_path)}", check=False)
try:
reply = json.loads(text)
except ValueError:
sys.stderr.write(f"unreadable reply: {text[:500]}\n")
- sys.exit(2)
+ sys.exit(1)
if o.raw:
print(text)
elif reply.get("ok"):
print(json.dumps(reply.get("result"), indent=2, ensure_ascii=False))
if not reply.get("ok"):
sys.stderr.write(f"error: {reply.get('error')}\n")
- sys.exit(1)
+ sys.exit(5 if reply.get("error") == DISABLED else 1)
if __name__ == "__main__":