Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Extensions can show their settings in Settings → Playback and → Downloads: a setting with "section" appears there under "<extension> settings", drawn as on its page, while the extension is the first source of that order (above Spotify for playback, where Spotify's Wi-Fi and mobile data quality then leave the screen and come back with Spotify on top; the first downloader, whose "role": "quality" takes the place of the app's download quality, still sent as quality to every extension); that quality is cited in "Why this source?" and Stats for nerds, a "perNetwork" setting has a Wi-Fi and a mobile data value, get gives the current network's and the setting event comes with network: true when the network changes it, and myspoti-ext check checks the new fields (an unknown section or role is only a warning) [skip ci]
kota-zob5540b5cce5c
diff --git a/base/app/src/main/java/com/music/spotui/data/DataSaver.kt b/base/app/src/main/java/com/music/spotui/data/DataSaver.ktindex aaa08ef4..4be303dd 100644--- a/base/app/src/main/java/com/music/spotui/data/DataSaver.kt+++ b/base/app/src/main/java/com/music/spotui/data/DataSaver.kt@@ -69,13 +69,13 @@ object DataSaver {metered = !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)if (was && !metered) com.music.spotui.data.offline.OfflineCollections.onUnmetered(app)// Wi-Fi and mobile data each have their own streaming level.- if (was != metered) com.music.spotui.data.preferences.applyStreamingQuality(app)+ if (was != metered) { com.music.spotui.data.preferences.applyStreamingQuality(app); com.music.spotui.extensions.Extensions.networkChanged() }changed()}override fun onLost(network: Network) {val was = meteredmetered = cm.isActiveNetworkMetered- if (was != metered) com.music.spotui.data.preferences.applyStreamingQuality(app)+ if (was != metered) { com.music.spotui.data.preferences.applyStreamingQuality(app); com.music.spotui.extensions.Extensions.networkChanged() }changed()}})diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.ktindex 8d4cd3bb..3127dbe5 100644--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt@@ -337,6 +337,7 @@ object OfflineDownloader {albumId = meta.albumId, durationMs = meta.durationMs, coverUrl = meta.coverUrl,file = out.name, cover = cover, source = file.provider, verified = file.isrcMatched,bytes = out.length(), addedAt = System.currentTimeMillis(), providerId = file.extensionId,+ extensionQuality = com.music.spotui.extensions.Extensions.qualityLine(file.extensionId, app.myspoti.extensions.SettingSection.DOWNLOADS),)}} finally {diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.ktindex 3a50dc69..e2370561 100644--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt@@ -39,6 +39,11 @@ data class OfflineTrack(* podcast episode, or a download made before this field existed.*/val providerId: String? = null,+ /**+ * The download-source extension's own quality setting when the file was fetched+ * ("Quality: FLAC", manifest `role: quality`), for Stats for nerds; null without one.+ */+ val extensionQuality: String? = null,) {val isEpisode: Boolean get() = kind == KIND_PODCAST@@ -48,6 +53,7 @@ data class OfflineTrack(.put("file", file).put("cover", cover).put("source", source).put("verified", verified).put("bytes", bytes).put("added", addedAt).put("kind", kind).apply { providerId?.let { put("providerId", it) } }+ .apply { extensionQuality?.let { put("extQuality", it) } }companion object {const val KIND_MUSIC = "MUSIC"@@ -63,6 +69,7 @@ data class OfflineTrack(kind = o.optString("kind").ifBlank { KIND_MUSIC },// Absent in an index written before it was kept: unknown.providerId = o.optString("providerId").ifBlank { null },+ extensionQuality = o.optString("extQuality").ifBlank { null },)}}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.ktindex d4daecde..e88f0b40 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@@ -408,13 +408,44 @@ object Extensions {fun settingValues(id: String): Map<String, String> = settingsOf(id).all()- /** [json]: the value as JSON text, null to go back to the manifest's default. */+ /**+ * [json]: the value as JSON text, null to go back to the manifest's default. [key] may be a+ * per-network setting's mobile data value ([app.myspoti.extensions.Setting.cellKey]): the+ * extension hears of its own key.+ */fun setSetting(id: String, key: String, json: String?) {val s = settingsOf(id)if (json == null) s.remove(key) else s.set(key, json)+ val base = app.myspoti.extensions.Setting.baseKey(key)// Typing changes a text field at each key: the extension hears of it once the user pauses.- settingJobs.remove("$id\u0000$key")?.cancel()- settingJobs["$id\u0000$key"] = scope.launch { kotlinx.coroutines.delay(SETTING_PAUSE_MS); sendSetting(id, key, pressed = false) }+ settingJobs.remove("$id\u0000$base")?.cancel()+ settingJobs["$id\u0000$base"] = scope.launch { kotlinx.coroutines.delay(SETTING_PAUSE_MS); sendSetting(id, base, pressed = false) }+ }++ /**+ * The phone went from Wi-Fi to mobile data or back ([com.music.spotui.data.DataSaver.metered]):+ * each extension hears `{ key, network: true }` for its per-network settings whose value it+ * reads changed with it.+ */+ fun networkChanged() {+ _registry.value.extensions.filter { it.enabled }.forEach { e ->+ val keys = manifest(e.id)?.networkKeys(settingsOf(e.id)::get).orEmpty()+ if (keys.isNotEmpty()) scope.launch { keys.forEach { sendSetting(e.id, it, pressed = false, network = true) } }+ }+ }++ /**+ * The extension settings shown in [section] of Settings, and whether the app's own quality+ * gives way to them ([SectionSettings]); null: the section is as it always was.+ */+ fun sectionPlacement(section: app.myspoti.extensions.SettingSection): SectionPlacement? = _registry.value.let { r ->+ SectionSettings.place(section, line(r, section.action), { r.find(it)?.enabled == true }, ::manifest)+ }++ /** What [id]'s own quality setting for [section] is now ("Quality: FLAC"), or null without one. */+ fun qualityLine(id: String?, section: app.myspoti.extensions.SettingSection): String? {+ val m = id?.let(::manifest) ?: return null+ return runCatching { SectionSettings.qualityLine(m, section, settingsOf(id)::get, com.music.spotui.data.DataSaver.metered) }.getOrNull()}/** A button setting was pressed: the extension does what it says (pair again…). */@@ -425,11 +456,12 @@ object Extensions {private val settingJobs = ConcurrentHashMap<String, kotlinx.coroutines.Job>()- private suspend fun sendSetting(id: String, key: String, pressed: Boolean) {+ private suspend fun sendSetting(id: String, key: String, pressed: Boolean, network: Boolean = false) {val rt = runtimes[id]?.takeIf { it.listens(ExtensionRuntime.EVENT_SETTING) } ?: returnval json = kotlinx.serialization.json.buildJsonObject {put("key", kotlinx.serialization.json.JsonPrimitive(key))if (pressed) put("pressed", kotlinx.serialization.json.JsonPrimitive(true))+ if (network) put("network", kotlinx.serialization.json.JsonPrimitive(true))}.toString()runCatching { runInterruptible { rt.emit(ExtensionRuntime.EVENT_SETTING, json, SETTING_MS) } }.onSuccess { recheckAfterEvent(id, rt) }.onFailure { failed(id, it.toString()) }}@@ -773,7 +805,8 @@ object Extensions {val (c, a) = foundlog(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()) }+ val own = qualityLine(c.first, app.myspoti.extensions.SettingSection.PLAYBACK)+ attempts.update(attempt) { it.copy(asked = all, chosen = c.first, announced = a.qualityLabel(), sourceQuality = own) }return a.copy(providerId = c.first)}@@ -1331,6 +1364,8 @@ object Extensions {override fun setting(extensionId: String, key: String): String? = settingsOf(extensionId).get(key)+ override fun metered(): Boolean = com.music.spotui.data.DataSaver.metered+override fun nowPlaying(): String? = currentTrack()?.toJson()override fun control(extensionId: String, action: String, argument: Long?): Boolean {diff --git a/base/app/src/main/java/com/music/spotui/extensions/SectionSettings.kt b/base/app/src/main/java/com/music/spotui/extensions/SectionSettings.ktnew file mode 100644index 00000000..d205b9c9--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/extensions/SectionSettings.kt@@ -0,0 +1,51 @@+package com.music.spotui.extensions++import app.myspoti.extensions.Manifest+import app.myspoti.extensions.Setting+import app.myspoti.extensions.SettingSection++/**+ * The settings an extension announces in a section of the app's Settings (manifest `section`):+ * those of [extensionId] ([name]), and whether the app's own quality gives way to them+ * ([hidesAppQuality]; it keeps its value and is used as before).+ */+data class SectionPlacement(+ val extensionId: String,+ val name: String,+ val settings: List<Setting>,+ val quality: Setting?,+ val hidesAppQuality: Boolean,+)++/**+ * Who shows settings in Settings → Playback and → Downloads. Only the first source of the order+ * does: in Playback the first of the audio order, and only when it is an extension (above+ * Spotify), then Spotify's Wi-Fi and mobile data quality leave the screen; in Downloads the first+ * extension of the download order, and the app's download quality leaves only for its+ * `role: quality`. An extension turned off is not a source: the next one leads. Nothing when the+ * leader announces nothing in that section, so an extension without `section` changes nothing.+ */+object SectionSettings {+ /** The first source of [line] that is asked: Spotify, or an extension turned on. */+ fun leader(line: List<String>, enabled: (String) -> Boolean): String? =+ line.firstOrNull { it == SPOTIFY_SOURCE || enabled(it) }++ fun place(section: SettingSection, line: List<String>, enabled: (String) -> Boolean, manifest: (String) -> Manifest?): SectionPlacement? {+ val lead = leader(line, enabled)?.takeIf { it != SPOTIFY_SOURCE } ?: return null+ val m = manifest(lead) ?: return null+ val shown = m.settingsIn(section).takeIf { it.isNotEmpty() } ?: return null+ val quality = m.qualitySetting(section)+ return SectionPlacement(lead, m.name, shown, quality, hidesAppQuality = section == SettingSection.PLAYBACK || quality != null)+ }++ /**+ * The quality the extension [m] is set to for [section], "Quality: FLAC" (its label, its+ * value), as `myspoti.settings.get` reads it now; null without a `role: quality` there.+ */+ fun qualityLine(m: Manifest, section: SettingSection, stored: (String) -> String?, metered: Boolean): String? {+ val s = m.qualitySetting(section) ?: return null+ val v = s.value(stored, metered)?.let { runCatching { kotlinx.serialization.json.Json.parseToJsonElement(it) }.getOrNull() }+ ?.let { runCatching { (it as kotlinx.serialization.json.JsonPrimitive).content }.getOrNull() } ?: return null+ return "${s.label}: $v"+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/StatsForNerdsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/StatsForNerdsSheet.ktindex 6d044077..1e8613a9 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/StatsForNerdsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/StatsForNerdsSheet.kt@@ -103,6 +103,8 @@ internal object NerdStats {val stream = id?.let(ExtensionAudio::streamOf)row(R.string.nerd_delivery, id?.let(ExtensionAudio::deliveryOf))row(R.string.nerd_announced, id?.let(ExtensionAudio::qualityOf))+ // The extension's own quality setting (manifest role quality) when it played or fetched the song.+ row(R.string.nerd_ext_quality, id?.let { Extensions.attempts.latest(it)?.sourceQuality } ?: download?.extensionQuality)val f = LocalPlayer.audioFormat()if (f == null) {if (!CastPlayback.active) row(R.string.nerd_codec, c.getString(R.string.nerd_format_unknown))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.ktindex 780f3a32..6ae965ef 100644--- 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@@ -57,6 +57,7 @@ fun WhySourceSheet(trackId: String, detected: String?, onDismiss: () -> Unit) {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)) }+ a.sourceQuality?.let { q -> a.chosen?.let { Line(stringResource(R.string.why_source_ext_quality, q, nameOf(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) }diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.ktindex 655d09cb..75628d60 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveExtensionDetail.kt@@ -309,7 +309,7 @@ fun ImmersiveExtensionScreen(navController: NavController, id: String) {}}if (m.settings.isNotEmpty()) immersiveGroup("settings", headerRes = R.string.extension_settings) {- m.settings.forEach { s -> row { SettingRow(id, s) } }+ m.settings.forEach { s -> row { Column { com.music.spotui.ui.screens.networkEditors(id, s).forEach { SettingRow(id, it) } } } }}immersiveGroup("details", headerRes = R.string.extension_details) {@@ -395,6 +395,15 @@ fun ImmersiveExtensionScreen(navController: NavController, id: String) {InstallPrompt()}+/**+ * An extension's settings announced in Settings → Playback or Downloads (manifest `section`), as a+ * card under a discreet [header] ("<name> settings"), drawn as on its page.+ */+internal fun androidx.compose.foundation.lazy.LazyListScope.extensionSectionGroup(p: com.music.spotui.extensions.SectionPlacement, header: String) =+ immersiveGroup("ext-section:${p.extensionId}", header = header) {+ p.settings.forEach { s -> row { Column { com.music.spotui.ui.screens.networkEditors(p.extensionId, s).forEach { SettingRow(p.extensionId, it) } } } }+ }+/** One of the extension's options (manifest `settings`), saved as JSON as it changes (see `saveSetting`). */@Composableprivate fun SettingRow(id: String, s: Setting) {diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.ktindex 87859fd9..4dcf630b 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt@@ -211,8 +211,14 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> Uvar keepPlaying by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.keepsPlayingOnClose(ctx)) }var wordSync by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsWordSync(ctx)) }val crossfade = com.music.spotui.data.preferences.CrossfadePref.seconds+ // The first source of the audio order, when it is an extension announcing settings here:+ // they show, and Spotify's quality (kept, still used for what Spotify plays) leaves the screen.+ val registry by com.music.spotui.extensions.Extensions.registry.collectAsStateWithLifecycle()+ val ext = remember(registry) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.PLAYBACK) }+ val extHeader = ext?.let { stringResource(R.string.ext_section_settings, it.name) }ImmersivePage(title = stringResource(R.string.settings_section_playback), onBack = back) {- immersiveGroup("quality", footerRes = R.string.quality_streaming_detail) {+ if (ext != null && extHeader != null) extensionSectionGroup(ext, extHeader)+ if (ext?.hidesAppQuality != true) immersiveGroup("quality", footerRes = R.string.quality_streaming_detail) {row { ImmersiveGroupRow(stringResource(R.string.quality_streaming_wifi_title), value = stringResource(label(wifi)), chevron = true, onClick = { open(SettingsPage.StreamingWifi) }) }row { ImmersiveGroupRow(stringResource(R.string.quality_streaming_cell_title), value = stringResource(label(cell)), chevron = true, onClick = { open(SettingsPage.StreamingCell) }) }}@@ -352,14 +358,20 @@ private fun DownloadsPage(navController: NavController, open: (SettingsPage) ->val quality = getDownloadQuality(ctx)var ask by remember { mutableStateOf(false) }val size = android.text.format.Formatter.formatShortFileSize(ctx, com.music.spotui.data.offline.OfflineStore.totalBytes())+ // The first extension of the download order, when it announces settings here; its role quality+ // takes the place of the app's (kept, and still passed to every extension as `quality`).+ val registry by com.music.spotui.extensions.Extensions.registry.collectAsStateWithLifecycle()+ val ext = remember(registry) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.DOWNLOADS) }+ val extHeader = ext?.let { stringResource(R.string.ext_section_settings, it.name) }ImmersivePage(title = stringResource(R.string.settings_section_downloads), onBack = back) {- immersiveGroup("quality", footerRes = R.string.quality_download_detail) {+ if (ext?.hidesAppQuality != true) immersiveGroup("quality", footerRes = R.string.quality_download_detail) {row {ImmersiveGroupRow(stringResource(R.string.quality_download_title),value = stringResource(DownloadChoices.first { it.first == quality }.second), chevron = true,onClick = { open(SettingsPage.DownloadQuality) })}}+ if (ext != null && extHeader != null) extensionSectionGroup(ext, extHeader)// Where downloads come from: the download-source extensions, in the order they are asked.sourcesGroup(app.myspoti.extensions.Action.DOWNLOAD_SOURCE, navController)if (com.music.spotui.extensions.Extensions.sources(app.myspoti.extensions.Action.DOWNLOAD_SOURCE).isEmpty()) immersiveGroup("source") {diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.ktindex 054aa7de..9f23f00a 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionDetail.kt@@ -295,7 +295,7 @@ fun ExtensionScreen(navController: NavController, id: String) {if (m.settings.isNotEmpty()) {ExtDivider()ExtSection(R.string.extension_settings)- m.settings.forEach { s -> SettingEditor(id, s) }+ m.settings.forEach { s -> networkEditors(id, s).forEach { SettingEditor(id, it) } }}ExtDivider()ExtSection(R.string.extension_details)@@ -383,6 +383,32 @@ internal fun saveSetting(id: String, s: Setting, v: String) {Extensions.setSetting(id, s.key, json)}+/**+ * A setting as the editors it is shown with: itself, or for a per-network one+ * ([Setting.splitsByNetwork]) its Wi-Fi value (kept under its key) and its mobile data value (kept+ * under [Setting.cellKey], showing the Wi-Fi value until it is set, as `myspoti.settings.get` reads it).+ */+@Composable+internal fun networkEditors(id: String, s: Setting): List<Setting> {+ if (!s.splitsByNetwork) return listOf(s)+ val wifi = Extensions.settingValues(id)[s.key]?.let { runCatching { kotlinx.serialization.json.Json.parseToJsonElement(it) }.getOrNull() }+ return listOf(+ s.copy(label = stringResource(R.string.ext_setting_wifi, s.label)),+ s.copy(key = Setting.cellKey(s.key), label = stringResource(R.string.ext_setting_cell, s.label), default = wifi ?: s.default),+ )+}++/**+ * An extension's settings announced in Settings → Playback or Downloads (manifest `section`),+ * under a discreet "<name> settings", drawn as on its page.+ */+@Composable+internal fun ExtensionSectionSettings(p: com.music.spotui.extensions.SectionPlacement) {+ Text(stringResource(R.string.ext_section_settings, p.name), color = AppMuted, fontSize = 12.sp,+ modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 12.dp, bottom = 2.dp))+ p.settings.forEach { s -> networkEditors(p.extensionId, s).forEach { SettingEditor(p.extensionId, it) } }+}+/** One of the extension's options (manifest `settings`), saved as JSON as it changes. */@Composableprivate fun SettingEditor(id: String, s: Setting) {diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex 16182d3d..cdf40cf5 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -93,10 +93,17 @@ fun SettingsScreen(navController: NavController) {}}Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).navigationBarsPadding()) {+ // The first source of each order, when it is an extension announcing settings in that tab.+ val registry by com.music.spotui.extensions.Extensions.registry.collectAsStateWithLifecycle()if (tab == 0) {Section(R.string.settings_section_playback)- StreamingQualityPicker(title = R.string.quality_streaming_wifi_title)- StreamingQualityPicker(cellular = true, title = R.string.quality_streaming_cell_title)+ // An extension above Spotify: its settings, and Spotify's quality (kept, still used for what Spotify plays) leaves.+ val ext = remember(registry) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.PLAYBACK) }+ ext?.let { ExtensionSectionSettings(it) }+ if (ext?.hidesAppQuality != true) {+ StreamingQualityPicker(title = R.string.quality_streaming_wifi_title)+ StreamingQualityPicker(cellular = true, title = R.string.quality_streaming_cell_title)+ }var canvasWifiOnly by remember { mutableStateOf(com.music.spotui.data.preferences.isCanvasWifiOnly(ctx)) }OptionRow(label = stringResource(R.string.canvas_wifi_only),@@ -216,7 +223,10 @@ fun SettingsScreen(navController: NavController) {}if (tab == 1) {Section(R.string.settings_section_downloads)- DownloadQualityPicker()+ // Its role quality takes the place of the app's (kept, and still passed to every extension as `quality`).+ val ext = remember(registry) { com.music.spotui.extensions.Extensions.sectionPlacement(app.myspoti.extensions.SettingSection.DOWNLOADS) }+ if (ext?.hidesAppQuality != true) DownloadQualityPicker()+ ext?.let { ExtensionSectionSettings(it) }// Where downloads come from: the download-source extensions, in the order they are asked.if (com.music.spotui.extensions.Extensions.sources(app.myspoti.extensions.Action.DOWNLOAD_SOURCE).isNotEmpty())SourcesBlock(app.myspoti.extensions.Action.DOWNLOAD_SOURCE, navController)diff --git a/base/app/src/main/res/values/extensions_strings.xml b/base/app/src/main/res/values/extensions_strings.xmlindex ffb6bf8e..4dfff03a 100644--- a/base/app/src/main/res/values/extensions_strings.xml+++ b/base/app/src/main/res/values/extensions_strings.xml@@ -240,4 +240,11 @@<string name="outcome_network">network error or timeout</string><string name="outcome_skipped">skipped</string><string name="outcome_bug">extension error</string>+ <!-- An extension's settings shown in Settings → Playback or Downloads (manifest "section"): %1$s is its name. -->+ <string name="ext_section_settings">%1$s settings</string>+ <!-- A per-network setting (manifest "perNetwork"): %1$s is its label. -->+ <string name="ext_setting_wifi">%1$s · Wi-Fi</string>+ <string name="ext_setting_cell">%1$s · Mobile data</string>+ <!-- "Why this source?": the chosen extension's own quality setting; %1$s is "Quality: FLAC", %2$s the extension. -->+ <string name="why_source_ext_quality">Its setting: %1$s (%2$s)</string></resources>diff --git a/base/app/src/main/res/values/nerd_strings.xml b/base/app/src/main/res/values/nerd_strings.xmlindex e0bb667d..b084f74e 100644--- a/base/app/src/main/res/values/nerd_strings.xml+++ b/base/app/src/main/res/values/nerd_strings.xml@@ -11,6 +11,7 @@<string name="nerd_source_file">File on this phone</string><string name="nerd_delivery">Delivery</string><string name="nerd_announced">Announced by the source</string>+ <string name="nerd_ext_quality">Extension\'s quality setting</string><string name="nerd_codec">Codec</string><string name="nerd_container">Container</string><string name="nerd_sample_rate">Sample rate</string>diff --git a/base/app/src/test/java/com/music/spotui/extensions/SectionSettingsTest.kt b/base/app/src/test/java/com/music/spotui/extensions/SectionSettingsTest.ktnew file mode 100644index 00000000..66b42b84--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/extensions/SectionSettingsTest.kt@@ -0,0 +1,79 @@+package com.music.spotui.extensions++import app.myspoti.extensions.ActionRequest+import app.myspoti.extensions.Manifest+import app.myspoti.extensions.Setting+import app.myspoti.extensions.SettingSection+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/** Which source shows its settings in Settings → Playback and → Downloads, and when the app's quality leaves. */+class SectionSettingsTest {+ private fun manifest(id: String, action: String, vararg settings: Setting) = Manifest(id, id.substringAfterLast('.'), "1", author = "me",+ actions = listOf(ActionRequest(action, "Gives songs"), ActionRequest("settings.page", "Options")), settings = settings.toList())++ private val quality = Setting("q", "choice", "Quality", options = listOf("FLAC", "MP3"), default = kotlinx.serialization.json.JsonPrimitive("FLAC"), section = "playback", role = "quality")+ private val hifi = manifest("io.github.a.hifi", "audio.source", quality, Setting("server", "text", "Server", section = "playback"), Setting("token", "secret", "Token"))+ private val plain = manifest("io.github.a.plain", "audio.source", Setting("token", "secret", "Token"))+ private val dl = manifest("io.github.a.dl", "download.source", quality.copy(section = "downloads"))+ private val dlOther = manifest("io.github.a.other", "download.source", Setting("folder", "text", "Folder", section = "downloads"))+ private val manifests = listOf(hifi, plain, dl, dlOther).associateBy { it.id }+ private val on = { _: String -> true }++ private fun playback(line: List<String>, enabled: (String) -> Boolean = on) = SectionSettings.place(SettingSection.PLAYBACK, line, enabled, manifests::get)+ private fun downloads(line: List<String>, enabled: (String) -> Boolean = on) = SectionSettings.place(SettingSection.DOWNLOADS, line, enabled, manifests::get)++ @Test fun theFirstSourceLeads() {+ assertEquals(SPOTIFY_SOURCE, SectionSettings.leader(listOf(SPOTIFY_SOURCE, hifi.id), on))+ assertEquals(hifi.id, SectionSettings.leader(listOf(hifi.id, SPOTIFY_SOURCE), on))+ // Turned off, it is not a source: the next one leads.+ assertEquals(SPOTIFY_SOURCE, SectionSettings.leader(listOf(hifi.id, SPOTIFY_SOURCE), { it != hifi.id }))+ assertNull(SectionSettings.leader(emptyList(), on))+ }++ @Test fun anExtensionAboveSpotifyShowsItsPlaybackSettingsAndHidesSpotifysQuality() {+ val p = playback(listOf(hifi.id, SPOTIFY_SOURCE, plain.id))!!+ assertEquals(hifi.id, p.extensionId)+ assertEquals(listOf("q", "server"), p.settings.map { it.key })+ assertEquals("q", p.quality?.key)+ assertTrue(p.hidesAppQuality)+ }++ @Test fun spotifyFirstIsTheScreenAsBefore() {+ // Spotify moved back to the top: the extension's settings stay on its page, Spotify's quality is back.+ assertNull(playback(listOf(SPOTIFY_SOURCE, hifi.id)))+ // Only the first source counts: an extension under another one shows nothing here.+ assertNull(playback(listOf(plain.id, hifi.id, SPOTIFY_SOURCE)))+ // Turned off: as if it were not there.+ assertNull(playback(listOf(hifi.id, SPOTIFY_SOURCE), { it != hifi.id }))+ // Not installed (no manifest): nothing.+ assertNull(playback(listOf("io.github.a.gone", SPOTIFY_SOURCE)))+ }++ @Test fun anExtensionWithoutSectionChangesNothing() {+ assertNull(playback(listOf(plain.id, SPOTIFY_SOURCE)))+ }++ @Test fun theFirstDownloaderHidesTheDownloadQualityOnlyForItsRoleQuality() {+ val p = downloads(listOf(dl.id, dlOther.id))!!+ assertEquals(dl.id, p.extensionId)+ assertTrue(p.hidesAppQuality)+ val other = downloads(listOf(dlOther.id, dl.id))!!+ assertEquals(listOf("folder"), other.settings.map { it.key })+ assertFalse(other.hidesAppQuality)+ assertEquals(dl.id, downloads(listOf(dlOther.id, dl.id), { it != dlOther.id })?.extensionId)+ assertNull(downloads(emptyList()))+ }++ @Test fun theQualityLineSaysTheValueOfTheCurrentNetwork() {+ val split = manifest("io.github.a.split", "audio.source", quality.copy(perNetwork = true))+ val stored = mapOf("q" to "\"MP3\"", Setting.cellKey("q") to "\"FLAC\"")+ assertEquals("Quality: MP3", SectionSettings.qualityLine(split, SettingSection.PLAYBACK, stored::get, metered = false))+ assertEquals("Quality: FLAC", SectionSettings.qualityLine(split, SettingSection.PLAYBACK, stored::get, metered = true))+ assertEquals("Quality: FLAC", SectionSettings.qualityLine(hifi, SettingSection.PLAYBACK, emptyMap<String, String>()::get, metered = false))+ assertNull(SectionSettings.qualityLine(plain, SettingSection.PLAYBACK, stored::get, metered = false))+ }+}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.ktindex 69d5df89..96cf7e53 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@@ -46,7 +46,8 @@ private const val USAGE = """myspoti-ext: build and try Myspoti extensions on alevel, 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)+ --set key=value a setting's value (repeatable; key@cell=value: a perNetwork setting's mobile data value)+ --network wifi|cell the network the phone is on, for perNetwork settings (default wifi)--cdp PORT|URL myspoti.spotify works on the account signed in to the Web Playerof a Chrome started with --remote-debugging-port=PORT; a changethat removes something (delete, remove, unfollow, clear) asks@@ -94,7 +95,9 @@ private class DesktopHost(private val settings: Map<String, String>,private val track: TrackInfo?,private val spotify: SpotifyDispatcher? = null,+ private val cell: Boolean = false,) : Host {+ override fun metered(): Boolean = cellprivate val store = MemoryStorage()override suspend fun spotify(extensionId: String, call: SpotifyCall): String =spotify?.execute(call) ?: super.spotify(extensionId, call)@@ -163,6 +166,10 @@ private fun load(path: File): Pair<Manifest, String> = if (path.isDirectory) {private fun check(dir: File) {val (m, script) = load(dir)val problems = m.problems()+ // section, role and perNetwork: refused by the check only; the app shows such a setting on its page, as one value.+ val fieldProblems = m.settingFieldProblems()+ fieldProblems.forEach { println("✗ $it") }+ m.settingFieldWarnings().forEach { println("! $it") }problems.forEach { println("✗ $it") }if (m.isLegacy) println("! old format (provides + permissions): it still installs, mapped to actions; write \"actions\" instead (docs/extensions/API.md §2)")val granted = m.asks().map { it.key }.toSet()@@ -182,7 +189,7 @@ private fun check(dir: File) {m.categoryWarning()?.let { println("! $it") }println("In the store: ${m.category().key}${if (m.category == null) " (set \"category\" to choose)" else ""}" +(m.minAppVersion?.let { ", Myspoti $it or newer" } ?: "") + (if (m.tags.isNotEmpty()) ", tags ${m.tags}" else ""))- if (problems.isNotEmpty()) exitProcess(1)+ if (problems.isNotEmpty() || fieldProblems.isNotEmpty()) exitProcess(1)}/** `test <dir> --scenario file.json [--state file.json]`: each step's result; exit 1 when one failed. */@@ -216,7 +223,7 @@ private fun run(path: File, hookName: String, rest: List<String>) {album = opts["album"] ?: "", durationMs = opts["duration"]?.toLongOrNull() ?: 0, isrc = opts["isrc"],)val account = opts["cdp"]?.let { Account(it) }- ExtensionRuntime(m, script, DesktopHost(settings, track, account?.dispatcher), m.asks().map { it.key }.toSet()).use { rt ->+ ExtensionRuntime(m, script, DesktopHost(settings, track, account?.dispatcher, cell = opts["network"] == "cell"), m.asks().map { it.key }.toSet()).use { rt ->account.use { runScript(rt, m, hookName, track, opts) }}}diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.ktindex 46c23eb4..729bb430 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt@@ -338,7 +338,9 @@ class ExtensionRuntime(def("storageRemove", 1) { a -> need(Action.STORAGE); host.storage(id).remove(str(a, 0)); null }def("setting", 1) { a ->val key = str(a, 0)- host.setting(id, key) ?: manifest.settings.firstOrNull { it.key == key }?.default?.toString()+ val s = manifest.settings.firstOrNull { it.key == key }+ // A per-network setting: the value of the network the phone is on (one value, as any get).+ if (s == null) host.setting(id, key) else s.value({ host.setting(id, it) }, s.splitsByNetwork && host.metered())}def("nowPlaying", 0) { need(Action.PLAYBACK_EVENTS); host.nowPlaying() }def("control", 2) { a ->@@ -670,7 +672,10 @@ class ExtensionRuntime(const val EVENT_AUTH = "auth"/** The network is there after [Host.whenOnline]: the time to send what waited. */const val EVENT_ONLINE = "online"- /** One of its settings changed (`{ key }`), or a button setting was pressed (`{ key, pressed: true }`). */+ /**+ * One of its settings changed (`{ key }`), a button setting was pressed (`{ key, pressed: true }`),+ * or the network changed the value of a per-network setting (`{ key, network: true }`).+ */const val EVENT_SETTING = "setting"/** Each event, and the action an extension needs to receive it. */val EVENTS: Map<String, Action> = mapOf(diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.ktindex fe17b8ec..82324a6e 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt@@ -24,6 +24,9 @@ interface Host {/** The user's value for one of the extension's settings, as JSON text, or null when unset. */fun setting(extensionId: String, key: String): String?+ /** The phone is on mobile data (a metered network), as the app's own streaming quality reads it: a per-network setting then gives its mobile value. */+ fun metered(): Boolean = false+/** The song playing now, as the hooks receive a track (JSON), or null. */fun nowPlaying(): String? = nulldiff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.ktindex a4c93b8b..c9bd1001 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt@@ -217,6 +217,43 @@ data class Manifest(.forEach { add("\"${it.key}\" is a critical action: say why the extension needs it in \"why\" (15 to 80 characters), the user reads it before installing") }}+ /** Its settings shown in [section] of the app's Settings, in the manifest's order. */+ fun settingsIn(section: SettingSection): List<Setting> = settings.filter { it.sectionOf == section }++ /** Its quality for [section] (`role: quality`), the first if it lists more (the check refuses that). */+ fun qualitySetting(section: SettingSection): Setting? = settingsIn(section).firstOrNull { it.isQuality }++ /**+ * The keys of its per-network settings whose value differs between Wi-Fi and mobile data:+ * the ones a network change changes, for the `setting` event `{ key, network: true }`.+ */+ fun networkKeys(stored: (String) -> String?): List<String> =+ settings.filter { it.splitsByNetwork && it.value(stored, false) != it.value(stored, true) }.map { it.key }++ /**+ * What is wrong with the settings' `section`, `role` and `perNetwork`, for `myspoti-ext check`.+ * Never a reason to refuse the package: the app shows such a setting on its page only, as one value.+ */+ fun settingFieldProblems(): List<String> = buildList {+ settings.forEach { s ->+ if (s.role == Setting.ROLE_QUALITY && s.type != "choice") add("setting \"${s.key}\": role quality is a choice (its options are the qualities)")+ if (s.role == Setting.ROLE_QUALITY && s.section == null) add("setting \"${s.key}\": role quality needs a section (playback or downloads)")+ if (s.perNetwork && s.type !in Setting.NETWORK_TYPES) add("setting \"${s.key}\": perNetwork is for ${Setting.NETWORK_TYPES.joinToString()}, not ${s.type}")+ }+ SettingSection.entries.forEach { sec ->+ if (settingsIn(sec).count { it.role == Setting.ROLE_QUALITY } > 1) add("settings: one role quality per section at most (${sec.key} has more)")+ }+ }++ /** Values of `section` and `role` this Myspoti does not know, and a section the extension can never lead: told, not refused. */+ fun settingFieldWarnings(): List<String> = buildList {+ settings.forEach { s ->+ if (s.section != null && s.sectionOf == null) add("setting \"${s.key}\": section \"${s.section}\" unknown (known: ${SettingSection.entries.joinToString { it.key }}), shown on the extension's page only")+ if (s.role != null && s.role !in Setting.ROLES) add("setting \"${s.key}\": role \"${s.role}\" unknown (known: ${Setting.ROLES.joinToString()}), ignored")+ s.sectionOf?.let { sec -> if (sec.action !in actionSet()) add("setting \"${s.key}\": section ${sec.key} is shown only for an extension with ${sec.action.key}, which this one does not ask") }+ }+ }+/** Where the store files it: the declared category if its actions fit it, else [Category.OTHER]. */fun category(): Category = Category.of(category, actionSet())@@ -276,9 +313,61 @@ data class Setting(val default: JsonElement? = null,/** choice only. */val options: List<String> = emptyList(),+ /**+ * `playback` or `downloads`: also shown in that section of the app's Settings, under the+ * extension's name, while it is the first source there ([SettingSection]). Absent: its page only.+ * Any other value: its page only too (`myspoti-ext check` warns).+ */+ val section: String? = null,+ /** `quality` (a choice): the extension's quality, shown in the place of the app's own. Any other value is ignored. */+ val role: String? = null,+ /** One value on Wi-Fi and one on mobile data (choice, toggle, number, text); `get` gives the current network's. */+ val perNetwork: Boolean = false,) {+ /** The section of Settings it is also shown in, or null (none, or one this Myspoti does not know). */+ val sectionOf: SettingSection? get() = SettingSection.of(section)++ /** It is the extension's quality for its section: `role: quality` on a choice. */+ val isQuality: Boolean get() = role == ROLE_QUALITY && type == "choice" && sectionOf != null++ /** It has a Wi-Fi and a mobile data value: `perNetwork` on a type that has a value to split. */+ val splitsByNetwork: Boolean get() = perNetwork && type in NETWORK_TYPES++ /**+ * The value `myspoti.settings.get` reads, as JSON text: on mobile data ([metered]) the mobile+ * value of a [splitsByNetwork] setting, else (and while it has none) the Wi-Fi one, which is+ * the one any setting has; else [default]. As the app's own streaming quality: mobile data+ * follows Wi-Fi until it is set.+ */+ fun value(stored: (String) -> String?, metered: Boolean): String? =+ (if (metered && splitsByNetwork) stored(cellKey(key)) else null) ?: stored(key) ?: default?.toString()+companion object {val TYPES = listOf("text", "secret", "toggle", "number", "choice", "button")+ const val ROLE_QUALITY = "quality"+ val ROLES = listOf(ROLE_QUALITY)+ /** The types `perNetwork` splits: a secret or a button has no value per network. */+ val NETWORK_TYPES = listOf("choice", "toggle", "number", "text")+ /** Suffix of the stored mobile data value; never in a declared key (letters, digits, _). */+ private const val CELL = "@cell"++ /** Where the mobile data value of [key] is kept, next to its Wi-Fi value (kept under [key]). */+ fun cellKey(key: String) = key + CELL++ /** The declared key a stored key belongs to ([cellKey] undone). */+ fun baseKey(stored: String) = stored.removeSuffix(CELL)+ }+}++/** `section` of a setting: the section of the app's Settings it is also shown in, and the source order that decides. */+enum class SettingSection(val key: String, val action: Action) {+ /** Settings → Playback, while the extension is the first source of the audio order (above Spotify). */+ PLAYBACK("playback", Action.AUDIO_SOURCE),+ /** Settings → Downloads, while it is the first extension of the download order. */+ DOWNLOADS("downloads", Action.DOWNLOAD_SOURCE);++ companion object {+ fun of(key: String?) = entries.firstOrNull { it.key == key }}}diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.ktindex 9bfd45ef..e23f29bc 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/PlayAttempt.kt@@ -26,6 +26,8 @@ data class PlayAttempt(val chosen: String? = null,/** What the chosen one announced ("FLAC · 24-bit · 96 kHz"), or null. */val announced: String? = null,+ /** The chosen one's own quality setting (`role: quality`) when it played, "Quality: FLAC", or null. */+ val sourceQuality: 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. */@@ -60,6 +62,7 @@ data class PlayAttempt(}))put("chosen", chosen?.let(::JsonPrimitive) ?: JsonNull)announced?.let { put("announced", JsonPrimitive(it)) }+ sourceQuality?.let { put("sourceQuality", JsonPrimitive(it)) }open?.let { o ->put("open", JsonObject(buildMap<String, JsonElement> {put("ok", JsonPrimitive(o.ok))@@ -84,6 +87,7 @@ data class PlayAttempt(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") }+ sourceQuality?.let { append("; its setting $it") }detected?.let { append("; detected $it") }fallback?.let { append("; fallback ${maskText(it)}") }error?.let { append("; error ${maskText(it).take(160)}") }diff --git a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.jsindex 3a62a096..25487743 100644--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js@@ -71,7 +71,8 @@/*** Listens to the app: on('track' | 'playback', fn) needs playback.events, on('auth', fn)* webview.auth, on('online', fn) network, on('setting', fn) settings.page ({ key } when one of- * its settings changed, { key, pressed: true } for a button setting).+ * its settings changed, { key, pressed: true } for a button setting, { key, network: true } when the+ * network changed a perNetwork setting's value).*/on: function (event, fn) {if (typeof fn !== 'function') throw new TypeError('on("' + event + '", fn): fn must be a function');@@ -122,12 +123,12 @@/*** What this app understands beyond the first API, for an extension to adapt to: "audio.manifest",- * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "results" (source hooks may answer { outcome }), "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.+ * "audio.expires", "audio.quality", "audio.source", "audio.ahead", "http.all", "status", "raw.base64", "results" (source hooks may answer { outcome }), "settings.section" (manifest section, role, perNetwork), "player.localMute" only when the user granted playback.mirror, and "attest" only when it granted attest.*/sources: Object.freeze({ race: function (hook, query, lanes) {return parse(host.sourceRace(String(hook),JSON.stringify(query),JSON.stringify(lanes)));} }),- features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'results', 'download.transform', 'audio.transform', 'sources.race'].concat(parse(host.info()).mirror ? ['player.localMute'] : [], parse(host.info()).attest ? ['attest'] : [])),+ features: Object.freeze(['audio.manifest', 'audio.expires', 'audio.quality', 'audio.source', 'audio.ahead', 'http.all', 'status', 'raw.base64', 'results', 'download.transform', 'audio.transform', 'sources.race', 'settings.section'].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 itsdiff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/SandboxTest.ktindex c408ce2f..c6165fb3 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,results,download.transform,audio.transform,sources.race"}""", eval("return myspoti.features.join(',');"))+ assertEquals("""{"v":"audio.manifest,audio.expires,audio.quality,audio.source,audio.ahead,http.all,status,raw.base64,results,download.transform,audio.transform,sources.race,settings.section"}""", eval("return myspoti.features.join(',');"))}@Test fun localMuteFeatureIsListedOnlyWhenMirrorIsGranted() {diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/SettingSectionTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/SettingSectionTest.ktnew file mode 100644index 00000000..8ce0ef0d--- /dev/null+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/SettingSectionTest.kt@@ -0,0 +1,131 @@+package app.myspoti.extensions++import kotlinx.serialization.json.JsonPrimitive+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/** A setting's `section`, `role` and `perNetwork`: read, checked, and the value `get` gives on each network. */+class SettingSectionTest {+ private val audio = """+ {+ "id": "io.github.someone.hifi", "name": "Hi-Fi", "version": "1.0", "author": "someone",+ "actions": [{ "name": "audio.source", "why": "Plays songs in lossless" }, { "name": "settings.page", "why": "Its quality" }],+ "settings": [+ { "key": "quality", "type": "choice", "label": "Quality", "options": ["FLAC", "MP3"], "default": "FLAC",+ "section": "playback", "role": "quality", "perNetwork": true },+ { "key": "server", "type": "text", "label": "Server", "section": "playback" },+ { "key": "token", "type": "secret", "label": "Token" }+ ]+ }+ """.trimIndent()++ @Test fun anOldManifestReadsAsBefore() {+ val text = """{ "id": "io.github.a.b", "name": "A", "version": "1", "author": "a",+ "actions": [{ "name": "settings.page", "why": "Options" }],+ "settings": [{ "key": "lang", "type": "choice", "label": "Language", "options": ["en", "fr"] }] }"""+ val m = Manifest.parse(text)+ val s = m.settings.single()+ assertEquals(Setting("lang", "choice", "Language", options = listOf("en", "fr")), s)+ assertNull(s.sectionOf); assertFalse(s.isQuality); assertFalse(s.splitsByNetwork)+ assertEquals(emptyList<String>(), m.problems())+ assertEquals(emptyList<String>(), m.settingFieldProblems())+ assertEquals(emptyList<String>(), m.settingFieldWarnings())+ SettingSection.entries.forEach { assertEquals(emptyList<Setting>(), m.settingsIn(it)); assertNull(m.qualitySetting(it)) }+ // Its value is read as before: stored, else default, on any network.+ val stored = mapOf("lang" to "\"fr\"")+ assertEquals("\"fr\"", s.value(stored::get, metered = true))+ assertEquals(emptyList<String>(), m.networkKeys(stored::get))+ }++ @Test fun theNewFieldsAreRead() {+ val m = Manifest.parse(audio)+ assertEquals(emptyList<String>(), m.problems())+ assertEquals(emptyList<String>(), m.settingFieldProblems())+ assertEquals(emptyList<String>(), m.settingFieldWarnings())+ assertEquals(listOf("quality", "server"), m.settingsIn(SettingSection.PLAYBACK).map { it.key })+ assertEquals("quality", m.qualitySetting(SettingSection.PLAYBACK)?.key)+ assertNull(m.qualitySetting(SettingSection.DOWNLOADS))+ assertTrue(m.settings[0].splitsByNetwork)+ }++ @Test fun unknownValuesAreWarnedNotRefused() {+ val m = Manifest.parse(audio.replace("\"section\": \"playback\" }", "\"section\": \"lyrics\", \"role\": \"accent\" }"))+ assertEquals(emptyList<String>(), m.problems())+ assertEquals(emptyList<String>(), m.settingFieldProblems())+ val w = m.settingFieldWarnings().joinToString("\n")+ assertTrue(w, "section \"lyrics\" unknown" in w)+ assertTrue(w, "role \"accent\" unknown" in w)+ // Kept on its page, shown nowhere else.+ assertEquals(listOf("quality"), m.settingsIn(SettingSection.PLAYBACK).map { it.key })+ assertEquals(3, m.settings.size)+ }++ @Test fun theRulesOfTheNewFields() {+ val m = Manifest.parse(audio).let { m ->+ m.copy(settings = listOf(+ Setting("a", "text", "A", section = "playback", role = "quality"),+ Setting("b", "choice", "B", options = listOf("x"), section = "playback", role = "quality"),+ Setting("c", "secret", "C", perNetwork = true),+ Setting("d", "button", "D", perNetwork = true),+ Setting("e", "choice", "E", options = listOf("x"), role = "quality"),+ Setting("f", "choice", "F", options = listOf("x"), section = "downloads"),+ ))+ }+ val p = m.settingFieldProblems().joinToString("\n")+ assertTrue(p, "\"a\": role quality is a choice" in p)+ assertTrue(p, "\"c\": perNetwork is for" in p)+ assertTrue(p, "\"d\": perNetwork is for" in p)+ assertTrue(p, "\"e\": role quality needs a section" in p)+ assertTrue(p, "playback has more" in p)+ // Still installs: these are the check's, never the install's.+ assertFalse(m.problems().any { "role" in it || "perNetwork" in it })+ // The app ignores what does not hold: a text is no quality, a secret one value.+ assertEquals("b", m.qualitySetting(SettingSection.PLAYBACK)?.key)+ assertFalse(m.settings[2].splitsByNetwork)+ // A downloads section on an extension that gives no downloads can never be shown.+ assertTrue(m.settingFieldWarnings().any { "\"f\"" in it && "download.source" in it })+ }++ @Test fun aPerNetworkValueFollowsTheNetwork() {+ val s = Manifest.parse(audio).settings[0]+ val stored = HashMap<String, String>()+ // Nothing set: the default on both.+ assertEquals("\"FLAC\"", s.value(stored::get, false))+ assertEquals("\"FLAC\"", s.value(stored::get, true))+ // Wi-Fi set: mobile data follows it until set, as the app's own streaming quality.+ stored["quality"] = "\"MP3\""+ assertEquals("\"MP3\"", s.value(stored::get, true))+ stored[Setting.cellKey("quality")] = "\"FLAC\""+ assertEquals("\"MP3\"", s.value(stored::get, false))+ assertEquals("\"FLAC\"", s.value(stored::get, true))+ assertEquals("quality", Setting.baseKey(Setting.cellKey("quality")))+ assertEquals(listOf("quality"), Manifest.parse(audio).networkKeys(stored::get))+ // Without perNetwork the mobile value is never read.+ assertEquals("\"MP3\"", s.copy(perNetwork = false).value(stored::get, true))+ }++ private class NetHost(var cell: Boolean, val values: Map<String, String>) : Host {+ override fun log(extensionId: String, message: String) {}+ override fun storage(extensionId: String): Storage = MemoryStorage()+ override fun setting(extensionId: String, key: String): String? = values[key]+ override fun metered(): Boolean = cell+ }++ @Test fun getGivesTheCurrentNetworksValue() {+ val m = Manifest.parse(audio).copy(actions = Manifest.parse(audio).actions + ActionRequest("lyrics.provide", "Test"))+ val host = NetHost(false, mapOf("quality" to "\"MP3\"", Setting.cellKey("quality") to "\"FLAC\"", "server" to "\"s\""))+ val script = "myspoti.provide('lyrics', function (t) { return { v: myspoti.settings.get('quality') + '/' + myspoti.settings.get('server') + '/' + myspoti.settings.get('token') }; });"+ val track = TrackInfo("abc", "spotify:track:abc", "Song", "Artist", listOf("Artist"), "Album", 180_000).toJson()+ ExtensionRuntime(m, script, host, m.asks().map { it.key }.toSet()).use { rt ->+ rt.start()+ assertTrue(rt.call(Hook.LYRICS, track, 3_000)!!.contains("MP3/s/undefined"))+ host.cell = true+ assertTrue(rt.call(Hook.LYRICS, track, 3_000)!!.contains("FLAC/s/undefined"))+ }+ // A default stays a plain value.+ assertEquals(JsonPrimitive("FLAC"), m.settings[0].default)+ }+}diff --git a/docs/extensions/API.md b/docs/extensions/API.mdindex dfa4361a..05f6b01d 100644--- a/docs/extensions/API.md+++ b/docs/extensions/API.md@@ -142,7 +142,7 @@ An action entry: `{ "name": "...", "why": "...", "hosts": [...] }`.**Old manifests** (before actions: `provides` + `permissions`) still load and install, mapped toactions (section 4.1); `myspoti-ext check` says so. `actions` cannot be mixed with them.-A setting: `{ "key", "type", "label", "description", "default", "options" }`.+A setting: `{ "key", "type", "label", "description", "default", "options", "section"?, "role"?, "perNetwork"? }`.- `key`: letters, digits, `_`, 1 to 40 characters.- `type`: `text` (default), `secret` (a password field, never logged), `toggle`, `number`, `choice`, `button`.@@ -153,6 +153,35 @@ A setting: `{ "key", "type", "label", "description", "default", "options" }`.Pressing it sends the `setting` event with `pressed: true` (section 3). Typical uses: pair againwith a server, clear a cache, sign in again.- Read it with `myspoti.settings.get(key)`: the user's value, else `default`, else `undefined`.+- `section` (optional): `"playback"` or `"downloads"`. The setting is also shown in the app's+ Settings → Playback or Settings → Downloads, in a card headed "<your extension's name> settings",+ drawn as on your page (same value: changing it in one place changes it in the other). Only the+ **first source** of the user's order shows its settings there:+ - Playback: the first source of the audio order (section 3, `audio-source`), when it is your+ extension, above Spotify, and turned on. Spotify's own Wi-Fi and mobile data quality then leave+ that screen (they keep their value, and Spotify still uses it for the songs it plays); moving+ Spotify back to the top brings them back and your settings stay on your page only.+ - Downloads: the first extension of the download order, turned on. The app's own download+ quality leaves that screen only for your `role: quality` setting; the app still sends its own+ value as `quality` to every extension in `download-source`.+ An extension below the first one, turned off or not installed shows nothing there. Without+ `section`, a setting is on your page only, as always. An unknown value is ignored (your page only);+ `myspoti-ext check` warns. A section is only ever shown for an extension that asks the matching+ action (`audio.source`, `download.source`).+- `role` (optional): `"quality"`, on a `choice` with a `section`, one per section at most: your+ extension's quality. Shown first-class in that section (in the place of the app's), and its value+ when the song was played or downloaded is cited in "Why this source?" and in Stats for nerds+ ("Quality: FLAC", your label and option). Any other value is ignored (check warns).+- `perNetwork` (optional, `true`; for `choice`, `toggle`, `number`, `text`): one value on Wi-Fi and+ one on mobile data, both shown ("<label> · Wi-Fi", "<label> · Mobile data").+ `myspoti.settings.get(key)` still gives one plain value: the one of the network the phone is on,+ by the app's own rule for Spotify's streaming quality (a metered network is mobile data, Wi-Fi+ otherwise). Until the user sets the mobile data value it is the Wi-Fi one, then `default`. When+ the phone changes network and the value `get` gives changes with it, the `setting` event comes+ with `{ key, network: true }` (section 3). Ignored on `secret` and `button` (check refuses it).++`myspoti.features` contains `settings.section` on a Myspoti that knows these three fields; an older+one ignores them (the setting is on your page, one value), so a manifest using them stays valid there.Settings are shown on the extension's page. Every installed extension that declares settings is alsolisted in the app's Settings screen, in the section "Extensions", and each row opens its page.@@ -166,6 +195,39 @@ A downloader with a quality choice and a button (its manifest also lists `settin]```+A sound source (actions `audio.source` and `settings.page`) that shows its quality, one per+network, and a switch in Settings → Playback while it is above Spotify:++```json+"settings": [+ { "key": "quality", "type": "choice", "label": "Quality", "options": ["Hi-Res", "FLAC", "AAC 256"],+ "default": "FLAC", "section": "playback", "role": "quality", "perNetwork": true },+ { "key": "gapless", "type": "toggle", "label": "Gapless albums", "default": true, "section": "playback" },+ { "key": "token", "type": "secret", "label": "Account token" }+]+```++```js+myspoti.provide('audio-source', function (t) {+ var q = myspoti.settings.get('quality'); // "FLAC" on Wi-Fi, "AAC 256" on mobile data if the user set so+ // ...+});+myspoti.on('setting', function (e) {+ if (e.key === 'quality') myspoti.log((e.network ? 'network changed: ' : '') + 'quality ' + myspoti.settings.get('quality'));+});+```++A downloader (actions `download.source` and `settings.page`) whose quality replaces the app's in+Settings → Downloads while it is the first downloader:++```json+"settings": [+ { "key": "format", "type": "choice", "label": "Format", "options": ["FLAC 24-bit", "FLAC 16-bit", "MP3 320"],+ "default": "FLAC 16-bit", "section": "downloads", "role": "quality" },+ { "key": "folder", "type": "text", "label": "Album folder name", "section": "downloads" }+]+```+`myspoti-ext check` prints every problem in plain words.## 3. Hooks@@ -612,6 +674,9 @@ extension's settings (section 2):- `{ key }` when a setting changed. For a text field, it comes once the user stops typing for amoment. Read the new value with `myspoti.settings.get(key)`. The event carries only the key.- `{ key, pressed: true }` when the user presses a `button` setting.+- `{ key, network: true }` when the phone went from Wi-Fi to mobile data or back and a `perNetwork`+ setting's value (what `myspoti.settings.get(key)` gives) changed with it. Changing either of its+ two values by hand sends `{ key }`, as any setting.It needs `settings.page` in the manifest (checked when you call `on`). Time limit 30 s per delivery.@@ -727,7 +792,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), `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.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `results` (section 3, "Outcomes"), `settings.section` (section 2: a setting's `section`, `role`, `perNetwork`), `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. || `myspoti.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`. |@@ -1227,7 +1292,14 @@ to the confirmation prompt below. Give absolute paths.)`run` options: `--title T` (required), `--artist "A, B"` (comma-separated; the first one is`artist`), `--album B`, `--duration MS`, `--id SPOTIFY_ID` (also sets `uri`), `--isrc ISRC`,`--set key=value` (a setting; repeat; `true`, `false` and numbers are passed as such, anything else-as text; unset ones use the manifest `default`).+as text; unset ones use the manifest `default`; `--set key@cell=value` is a `perNetwork` setting's+mobile data value), `--network cell` (the phone is on mobile data, for `perNetwork` settings; default+Wi-Fi).++`check` also checks `section`, `role` and `perNetwork`: `role: quality` on a non-`choice`, without+a section or twice in a section, and `perNetwork` on a `secret` or `button` are problems (✗, exit 1);+an unknown `section` or `role`, or a section the extension's actions can never lead, are warnings (!).+The app itself never refuses such a package: it shows the setting on its page, as one value.What the runner does: every right the manifest asks is granted. Each hook and event gets the app'sown time limit (section 7). An answer `{ outcome }` is printed as the app reads it. Storage is in