Skip to content

Native Android client for Spotify, built with Jetpack Compose

Extensions can read the app language: myspoti.locale is the BCP 47 tag the app shows (the phone's when it follows the phone, never empty), read again at each use so a language change needs no reload, and documented in the extension API

kota-zo4b73995b9faa
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 2a247566..2d25afe6 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
@@ -1465,6 +1465,11 @@ object Extensions {
override fun nowPlaying(): String? = currentTrack()?.toJson()
+ // The language picked in the settings, else the app's configuration: the phone's, or on
+ // Android 13+ the per-app one when no screen is open to answer for AppCompat.
+ override fun locale(): String = com.music.spotui.data.AppLanguage.current(ctx)
+ .ifEmpty { ctx.resources.configuration.locales[0].toLanguageTag() }
+
override fun control(extensionId: String, action: String, argument: Long?): Boolean {
if (!arbitrate(extensionId, action)) return false
main.post {
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt
index 729bb430..3a0417ca 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/ExtensionRuntime.kt
@@ -304,6 +304,8 @@ class ExtensionRuntime(
fun str(args: Array<Any?>, i: Int): String = args.getOrNull(i)?.takeUnless { it is Undefined }?.let { Context.toString(it) }.orEmpty()
def("info", 0) { ExtJson.encodeToString(Info.serializer(), Info(manifest.id, manifest.name, manifest.version, has(Action.PLAYBACK_MIRROR), has(Action.ATTEST))) }
+ // No action needed; a host that fails or answers nothing gives the JVM's, never "".
+ def("locale", 0) { runCatching { host.locale() }.getOrNull()?.takeIf { it.isNotBlank() } ?: java.util.Locale.getDefault().toLanguageTag() }
def("mayProvide", 1) { a ->
val key = str(a, 0)
val hook = Hook.of(key) ?: throw error("unknown hook \"$key\" (known: ${Hook.entries.joinToString { it.key }})")
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt
index 82324a6e..fa3ffe31 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Host.kt
@@ -30,6 +30,12 @@ interface Host {
/** The song playing now, as the hooks receive a track (JSON), or null. */
fun nowPlaying(): String? = null
+ /**
+ * `myspoti.locale`: the language the app shows, as a BCP 47 tag ("fr", "pt-BR"), read again at
+ * each use. The phone's when the app follows it; never empty. This one is the JVM's.
+ */
+ fun locale(): String = java.util.Locale.getDefault().toLanguageTag()
+
/**
* play, pause, next, previous, seek (argument: milliseconds), asked by [extensionId]. False when
* it could not be done, or the app's [PlaybackArbiter] dropped it.
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 25487743..23ed4534 100644
--- a/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
+++ b/base/extensions/src/main/resources/app/myspoti/extensions/prelude.js
@@ -54,6 +54,8 @@
var myspoti = {
apiVersion: 1,
+ /** The language the app shows, as a BCP 47 tag ('fr', 'pt-BR'): asked at each read, so it follows a change of language. */
+ get locale() { return String(host.locale()); },
extension: Object.freeze(parse(host.info())),
/**
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/LocaleTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/LocaleTest.kt
new file mode 100644
index 00000000..d1e04b5c
--- /dev/null
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/LocaleTest.kt
@@ -0,0 +1,39 @@
+package app.myspoti.extensions
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class LocaleTest {
+ private val track = TrackInfo("abc", "spotify:track:abc", "Song", "Artist", listOf("Artist"), "Album", 180_000)
+
+ private class LocaleHost(@Volatile var tag: String) : Host {
+ override fun log(extensionId: String, message: String) {}
+ override fun storage(extensionId: String): Storage = MemoryStorage()
+ override fun setting(extensionId: String, key: String): String? = null
+ override fun locale(): String = tag
+ }
+
+ private val manifest = Manifest("io.github.test.ext", "Test", "1.0", author = "me", provides = listOf("lyrics"))
+
+ private fun runtime(host: Host, script: String = "myspoti.provide('lyrics', function () { return { v: myspoti.locale }; });") =
+ ExtensionRuntime(manifest, script, host, manifest.asks().map { it.key }.toSet()).also { it.start() }
+
+ @Test fun localeFollowsTheAppLanguageWithoutAReload() {
+ val host = LocaleHost("it")
+ runtime(host).use {
+ assertEquals("""{"v":"it"}""", it.call(Hook.LYRICS, track.toJson(), 3_000))
+ host.tag = "pt-BR"
+ assertEquals("""{"v":"pt-BR"}""", it.call(Hook.LYRICS, track.toJson(), 3_000))
+ }
+ }
+
+ @Test fun localeIsNeverEmpty() {
+ val fallback = java.util.Locale.getDefault().toLanguageTag()
+ runtime(LocaleHost("")).use { assertEquals("""{"v":"$fallback"}""", it.call(Hook.LYRICS, track.toJson(), 3_000)) }
+ }
+
+ @Test fun localeCannotBeReplacedAndNeedsNoAction() {
+ val js = "try { myspoti.locale = 'xx'; } catch (e) {} myspoti.provide('lyrics', function () { return { v: myspoti.locale + ' ' + typeof myspoti.apiVersion }; });"
+ runtime(LocaleHost("fr"), js).use { assertEquals("""{"v":"fr number"}""", it.call(Hook.LYRICS, track.toJson(), 3_000)) }
+ }
+}
diff --git a/docs/extensions/API.md b/docs/extensions/API.md
index 05f6b01d..aec9ffcb 100644
--- a/docs/extensions/API.md
+++ b/docs/extensions/API.md
@@ -791,6 +791,7 @@ A script that throws while loading fails to load, with `file:line` in the messag
| Call | Notes |
|---|---|
| `myspoti.apiVersion` | `1`. |
+| `myspoti.locale` | The language Myspoti shows, as a BCP 47 tag: `"fr"`, `"pt-BR"`, `"zh-TW"`. Below. |
| `myspoti.extension` | `{ id, name, version }` from the manifest. |
| `myspoti.features` | What this Myspoti understands beyond the first API: `audio.manifest`, `audio.expires`, `audio.quality`, `audio.ahead` (section 3, `audio-source`), `http.all`, `status` (section 3), `results` (section 3, "Outcomes"), `settings.section` (section 2: a setting's `section`, `role`, `perNetwork`), `attest` (section 10, only when the user granted it). Missing on an older Myspoti: test `myspoti.features && myspoti.features.indexOf(name) >= 0`. |
| `myspoti.provide(hook, fn)` | Section 3. |
@@ -819,6 +820,15 @@ A script that throws while loading fails to load, with `file:line` in the messag
| `myspoti.util.md5(s)`, `sha1(s)`, `sha256(s)` | Lower-case hex. |
| `myspoti.util.hmacSha256(key, text)` | Lower-case hex. |
+`myspoti.locale` needs no action. It is the language picked in Myspoti's settings, or the
+phone's when the app follows the phone, so it is never empty. It is read again each time you
+read it: after the user changes the language, the next read gives the new one, without a reload.
+Read it where you build text (a block, a setting's answer, your page's first message) rather
+than once at load. It is the app's language, not the lyrics translation target, which the
+reader picks apart (section 3, `translationLanguage`). An older Myspoti has no `locale` (`undefined`), so fall
+back: `var lang = myspoti.locale || 'en';`. Compare its first part to pick your strings:
+`lang.split('-')[0]`.
+
`myspoti.player` (needs `playback.events` / `playback.control`) is Myspoti's own player. The
Spotify account's player (what the Web Player is playing) is `myspoti.spotify.player`, with the
playback actions.