Skip to content

Native Android client for Spotify, built with Jetpack Compose

Extensions in the user's language: a manifest's translations (by language tag) give its name, description, changelog, welcome, action reasons and setting labels and option labels, shown in the language picked in Myspoti with no action to ask; the values and the reasons weighed for consent stay the written ones, and sign-in pages are asked in that language (Accept-Language)

kota-zo2e151df561cc
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAuth.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAuth.kt
index 10ca737a..911ce7cd 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionAuth.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionAuth.kt
@@ -172,6 +172,9 @@ private fun AuthPage(current: ExtensionAuth.Open) {
@SuppressLint("SetJavaScriptEnabled")
private fun authView(ctx: android.content.Context, o: ExtensionAuth.Open, onHost: (String) -> Unit): WebView {
val view = WebView(ctx)
+ // The sign-in page in the app's language when its site offers it (the WebView's own header
+ // follows the phone, not a language picked in Myspoti).
+ val language = mapOf("Accept-Language" to Extensions.language().let { if (it.contains('-')) "$it,${it.substringBefore('-')};q=0.9" else it } + ",en;q=0.5")
// Before anything else touches it: this view's cookies and storage are the extension's profile.
val profile = ExtensionAuth.profile(o.extensionId)
ProfileStore.getInstance().getOrCreateProfile(profile)
@@ -231,7 +234,7 @@ private fun authView(ctx: android.content.Context, o: ExtensionAuth.Open, onHost
if (taken) return
taken = true
probe.stopLoading()
- if (!reached(url) && !refused(android.net.Uri.parse(url))) view.loadUrl(url)
+ if (!reached(url) && !refused(android.net.Uri.parse(url))) view.loadUrl(url, language)
probe.post { probe.destroy() }
}
override fun shouldOverrideUrlLoading(v: WebView, request: WebResourceRequest): Boolean { take(request.url.toString()); return true }
@@ -242,6 +245,6 @@ private fun authView(ctx: android.content.Context, o: ExtensionAuth.Open, onHost
return true
}
}
- view.loadUrl(o.request.url)
+ view.loadUrl(o.request.url, language)
return view
}
diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt
index a60ccbd4..e8c90e4f 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt
@@ -129,7 +129,7 @@ object ExtensionStore {
gate.withPermit {
runCatching {
val text = f.manifestUrl()?.let { ExtensionUpdates.cached(it, Discovery.CACHE_MS, force = force) } ?: return@runCatching null
- Manifest.parse(text).takeIf { it.problems().isEmpty() }?.let { Discovery.entry(f, it) }
+ Manifest.parse(text).takeIf { it.problems().isEmpty() }?.let { Discovery.entry(f, it.localized(Extensions.language())) }
}.getOrNull()
}
}
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 5ba91246..1b36639f 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
@@ -287,9 +287,18 @@ object Extensions {
fun manifest(id: String): Manifest? = pkg(id)?.manifest
- fun pkg(id: String): ExtensionPackage? = packages[id] ?: runCatching {
+ fun pkg(id: String): ExtensionPackage? = (packages[id] ?: runCatching {
ExtensionPackage.read(File(dir, "$id/package.zip").readBytes())
- }.getOrNull()?.let { packages.putIfAbsent(id, it) ?: it } // an install's newer package is never replaced by an older read
+ }.getOrNull()?.let { packages.putIfAbsent(id, it) ?: it }) // an install's newer package is never replaced by an older read
+ ?.let { p -> val tag = language(); if (p.manifest.shownIn == tag) p else p.localized(tag).also { packages.replace(id, p, it) } }
+
+ /**
+ * The language the app shows, as a BCP 47 tag: the one picked in the settings, else the app's
+ * configuration (the phone's, or on Android 13+ the per-app one). What `myspoti.locale` gives
+ * and what manifests are shown in ([Manifest.localized]).
+ */
+ fun language(): String = if (!::ctx.isInitialized) java.util.Locale.getDefault().toLanguageTag()
+ else com.music.spotui.data.AppLanguage.current(ctx).ifEmpty { ctx.resources.configuration.locales[0].toLanguageTag() }
fun isRunning(id: String) = runtimes.containsKey(id)
@@ -1509,8 +1518,7 @@ object Extensions {
// 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 locale(): String = language()
override fun control(extensionId: String, action: String, argument: Long?): Boolean {
if (!arbitrate(extensionId, action)) return false
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.kt
index d205b9c9..f84a0c21 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/SectionSettings.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/SectionSettings.kt
@@ -46,6 +46,6 @@ object SectionSettings {
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"
+ return "${s.label}: ${s.optionLabel(v)}"
}
}
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.kt
index 71f7d736..6e98171e 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
@@ -179,7 +179,7 @@ fun ImmersiveExtensionEntryScreen(navController: NavController, id: String) {
item(key = "ext:clash") {
incompatibleWith(e, registry)?.let { Text(it, style = Immersive.Subhead.copy(color = Warning), modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp)) }
}
- val asks = m.asks().sortedByDescending { it.critical }
+ val asks = m.asksShown().sortedByDescending { it.critical }
immersiveGroup("actions", headerRes = R.string.actions_title) {
asks.forEach { a -> row { Box(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { ActionRow(a) } } }
}
@@ -244,7 +244,7 @@ fun ImmersiveExtensionScreen(navController: NavController, id: String) {
val refused = Grants.refused(e, m)
if (refused.isNotEmpty()) item(key = "ext:refused") {
Box(CardInset) {
- RefusedNeedsOk(m.asks().filter { it.key in refused }) {
+ RefusedNeedsOk(m.asksShown().filter { it.key in refused }) {
scope.launch { Extensions.acceptAll(id); enable(id, true) }
}
}
@@ -293,7 +293,7 @@ fun ImmersiveExtensionScreen(navController: NavController, id: String) {
}
immersiveGroup("actions", headerRes = R.string.actions_title) {
- m.asks().sortedByDescending { it.critical }.forEach { a -> row { Box(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { ActionRow(a) } } }
+ m.asksShown().sortedByDescending { it.critical }.forEach { a -> row { Box(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { ActionRow(a) } } }
}
// Writes allowed for good from a confirmation ("Always"): each one revocable here.
if (e.rawGrants.isNotEmpty()) immersiveGroup("grants", headerRes = R.string.ext_grants_title, footerRes = R.string.ext_grants_note) {
@@ -419,7 +419,7 @@ private fun SettingRow(id: String, s: Setting) {
Text(s.label, style = Immersive.Body)
if (s.description.isNotBlank()) Text(s.description, style = Immersive.Caption)
}
- s.options.forEach { o -> ImmersiveChoiceRow(o, selected = value == o, onClick = { save(o) }) }
+ s.options.forEach { o -> ImmersiveChoiceRow(s.optionLabel(o), selected = value == o, onClick = { save(o) }) }
}
else -> Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp)) {
Text(s.label, style = Immersive.Caption)
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.kt
index 9f23f00a..ef12512e 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
@@ -188,7 +188,7 @@ fun ExtensionEntryScreen(navController: NavController, id: String) {
Text(e.changelog, color = AppText, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp))
}
incompatibleWith(e, registry)?.let { Text(it, color = Warning, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp)) }
- ActionsList(m.asks())
+ ActionsList(m.asksShown())
ExtDivider()
ExtSection(R.string.extension_details)
e.updatedAt?.let { Detail(R.string.extension_detail_updated, it.take(10)) }
@@ -239,7 +239,7 @@ fun ExtensionScreen(navController: NavController, id: String) {
// A GitHub update that asks more than the user accepted: what it changes, Accept / Keep current.
// Unticked actions left from before installs granted everything: paused until one OK.
val refused = Grants.refused(e, m)
- if (refused.isNotEmpty()) RefusedNeedsOk(m.asks().filter { it.key in refused }) {
+ if (refused.isNotEmpty()) RefusedNeedsOk(m.asksShown().filter { it.key in refused }) {
scope.launch { Extensions.acceptAll(id); enable(id, true) }
}
e.pendingUpdate?.let { p -> UpdateNeedsOk(e.name, e.version, p, onAccept = { scope.launch { runCatching { ExtensionUpdates.accept(id) }.onFailure { toastError(ctx, it) } } },
@@ -280,7 +280,7 @@ fun ExtensionScreen(navController: NavController, id: String) {
if (Extensions.hasPage(id)) OutlinedButton(onClick = { navController.navigate(extensionPageRoute(id)) }, border = BorderStroke(1.dp, AppAccent.copy(alpha = 0.6f)),
modifier = Modifier.padding(horizontal = 20.dp, vertical = 4.dp)) { Text(stringResource(R.string.ext_open_page), color = AppAccent) }
ExtSection(R.string.actions_title)
- Column(Modifier.padding(horizontal = 20.dp)) { m.asks().sortedByDescending { it.critical }.forEach { a -> ActionRow(a) } }
+ Column(Modifier.padding(horizontal = 20.dp)) { m.asksShown().sortedByDescending { it.critical }.forEach { a -> ActionRow(a) } }
// Writes allowed for good from a confirmation ("Always"): each one revocable here.
if (e.rawGrants.isNotEmpty()) {
Text(stringResource(R.string.ext_grants_title), color = AppText, fontSize = 14.sp, modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 10.dp))
@@ -429,7 +429,7 @@ private fun SettingEditor(id: String, s: Setting) {
s.options.forEach { o ->
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().toggleable(value == o, role = Role.RadioButton) { save(o) }) {
RadioButton(selected = value == o, onClick = null)
- Text(o, color = AppText, modifier = Modifier.padding(start = 8.dp))
+ Text(s.optionLabel(o), color = AppText, modifier = Modifier.padding(start = 8.dp))
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt
index 3f2c8bec..b9157eb7 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionParts.kt
@@ -131,7 +131,7 @@ internal fun toastError(ctx: Context, t: Throwable) {
/** Reads [zip] and opens the install prompt; a refused package says why. */
internal fun offer(ctx: Context, zip: ByteArray, source: String, origin: app.myspoti.extensions.Origin? = null) {
- runCatching { ExtensionPackage.read(zip) }
+ runCatching { ExtensionPackage.read(zip).localized(Extensions.language()) }
.onSuccess { p -> pending.value = PendingInstall(zip, p, source, Extensions.plan(p), origin) }
.onFailure { toastError(ctx, it) }
}
@@ -221,7 +221,7 @@ internal fun InstallPrompt() {
else -> {
PromptHeader(R.string.actions_title)
// An update lists only what changes: what it asks anew, and what was unticked before.
- val asks = m.asks().filter { plan !is InstallPlan.Update || it.key in newKeys || it.key in plan.refused }.sortedByDescending { it.critical }
+ val asks = m.asksShown().filter { plan !is InstallPlan.Update || it.key in newKeys || it.key in plan.refused }.sortedByDescending { it.critical }
asks.forEach { a -> ActionRow(a, new = a.key in newKeys) }
if (asks.any { it.critical }) Text(stringResource(R.string.actions_critical_warning), color = Warning, fontSize = 13.sp, modifier = Modifier.padding(top = 8.dp))
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt
index 2906f58d..260ecafb 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SourceOrder.kt
@@ -147,7 +147,7 @@ private fun SourceRow(
AnimatedVisibility(open) {
Column(Modifier.fillMaxWidth().padding(start = 86.dp, end = 20.dp, bottom = 6.dp)) {
Text(stringResource(R.string.sources_detail_version, e.version, e.author.ifBlank { "—" }), style = look.line)
- pkg?.manifest?.declared()?.firstOrNull { it.name == action.key }?.why?.takeIf { it.isNotBlank() }?.let {
+ pkg?.manifest?.let { m -> m.declared().firstOrNull { it.name == action.key }?.let(m::whyShown) }?.takeIf { it.isNotBlank() }?.let {
Text(it, style = look.line, maxLines = 3, overflow = TextOverflow.Ellipsis)
}
last?.let {
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt
index c9bd1001..0e41bb87 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Manifest.kt
@@ -1,6 +1,7 @@
package app.myspoti.extensions
import kotlinx.serialization.Serializable
+import kotlinx.serialization.Transient
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
@@ -68,6 +69,17 @@ data class Manifest(
val replaces: List<String> = emptyList(),
/** Extensions (ids) that must not run with this one: the user is asked which to keep. */
val conflictsWith: List<String> = emptyList(),
+ /**
+ * The texts shown to people in other languages, by BCP 47 tag (`"fr"`, `"pt-BR"`): any of
+ * `name`, `description`, `changelog`, `welcome`, an action's reason (`actions`: name → why) and
+ * a setting's `label`, `description` and `options` (`settings`: key → texts; the options' labels,
+ * the values stay the manifest's). Missing ones fall back to the manifest's own ([localized]).
+ */
+ val translations: Map<String, Translation> = emptyMap(),
+ /** The manifest as written, when this one is [localized] (texts swapped for one language). */
+ @Transient private val written: Manifest? = null,
+ /** The language this one is [localized] in, or null: the manifest's own texts. */
+ @Transient val shownIn: String? = null,
) {
/** True for a manifest written before actions (`provides` and `permissions`): still loaded, mapped to actions. */
val isLegacy: Boolean get() = actions.isEmpty() && (provides.isNotEmpty() || permissions.isNotEmpty())
@@ -117,6 +129,52 @@ data class Manifest(
else Ask(a.key, a.level, r.why, r.hosts + (if (a == Action.AUDIO_SOURCE || a == Action.DOWNLOAD_SOURCE) media?.hosts.orEmpty() else emptyList()) + if (a == Action.SPOTIFY_RAW) declaredWrites().map { it.toString() } else emptyList(), a)
}
+ /**
+ * This manifest with the texts people see in [tag] (the app's language) where [translations]
+ * has them: `"pt-BR"` takes `pt-BR`, then `pt`, then another `pt-…`. Ids, actions, hosts and
+ * setting values never change; an action's reason stays the written one for what was accepted
+ * ([asks]) and is shown through [whyShown]. Calling it again on the result starts from the
+ * written texts, so a language change needs only a new call.
+ */
+ fun localized(tag: String): Manifest {
+ val base = written ?: this
+ val t = base.translationFor(tag) ?: return if (written == null) this else base
+ return base.copy(
+ name = t.name?.takeIf { it.isNotBlank() } ?: base.name,
+ description = t.description ?: base.description,
+ changelog = t.changelog ?: base.changelog,
+ welcome = t.welcome ?: base.welcome,
+ settings = base.settings.map { s ->
+ val st = t.settings[s.key] ?: return@map s
+ s.copy(
+ label = st.label?.takeIf { it.isNotBlank() } ?: s.label,
+ description = st.description ?: s.description,
+ optionLabels = st.options.takeIf { it.size == s.options.size }.orEmpty(),
+ )
+ },
+ written = base,
+ shownIn = tag,
+ )
+ }
+
+ /** The reason for action [r] shown to people: its translation in [shownIn], else the written one. */
+ fun whyShown(r: ActionRequest): String =
+ shownIn?.let { (written ?: this).translationFor(it) }?.actions?.get(r.name)?.takeIf { it.isNotBlank() } ?: r.why
+
+ private fun translationFor(tag: String): Translation? {
+ if (translations.isEmpty() || tag.isBlank()) return null
+ val byTag = translations.entries.associate { it.key.lowercase() to it.value }
+ val wanted = tag.lowercase().replace('_', '-')
+ val lang = wanted.substringBefore('-')
+ return byTag[wanted] ?: byTag[lang] ?: byTag.entries.firstOrNull { it.key.substringBefore('-') == lang }?.value
+ }
+
+ /** [asks] with each reason as shown to people ([whyShown]): for screens, never to weigh what was accepted. */
+ fun asksShown(): List<Ask> {
+ val byName = declared().associateBy { it.name }
+ return asks().map { a -> byName[a.action?.key ?: a.key]?.let { a.copy(why = whyShown(it)) } ?: a }
+ }
+
/** True when the user is shown the warning and has to tick that they accept the risk. */
fun isCritical(): Boolean = asks().any { it.level == Level.CRITICAL }
@@ -160,6 +218,28 @@ data class Manifest(
ids.filterNot { ID.matches(it) }.forEach { add("$field \"$it\": an extension id (io.github.you.name)") }
if (id in ids) add("$field: not its own id")
}
+ if (translations.size > 80) add("translations: 80 languages at most")
+ val actionNames = declared().map { it.name }.toSet()
+ translations.forEach { (tag, t) ->
+ val at = "translations \"$tag\""
+ if (!LANG.matches(tag)) add("$at: a language tag like fr or pt-BR")
+ t.name?.let { if (it.length > 40) add("$at.name: 40 characters at most") }
+ t.description?.let { if (it.length > 500) add("$at.description: 500 characters at most") }
+ t.changelog?.let { if (it.length > 2000) add("$at.changelog: 2000 characters at most") }
+ t.welcome?.let { w ->
+ if (w.message.length > 600) add("$at.welcome.message: 600 characters at most")
+ if (w.steps.size > 5 || w.steps.any { it.isBlank() || it.length > 160 }) add("$at.welcome.steps: 5 at most, each 1 to 160 characters")
+ }
+ t.actions.forEach { (name, why) ->
+ if (name !in actionNames) add("$at.actions \"$name\": not an action of this manifest")
+ if (why.length > Action.WHY_MAX) add("$at.actions \"$name\": ${Action.WHY_MAX} characters at most")
+ }
+ t.settings.forEach { (key, st) ->
+ val s = settings.firstOrNull { it.key == key }
+ if (s == null) add("$at.settings \"$key\": not a setting of this manifest")
+ else if (st.options.isNotEmpty() && st.options.size != s.options.size) add("$at.settings \"$key\".options: one label per option (${s.options.size})")
+ }
+ }
}
/** The rules of `actions`: known names, once each, a why of 1 to 80 characters each, network's hosts. */
@@ -273,12 +353,30 @@ data class Manifest(
private val HOST = Regex("^(\\*|(\\*\\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+)$")
private val KEY = Regex("^[A-Za-z0-9_]{1,40}$")
private val TAG = Regex("^[a-z0-9][a-z0-9 -]{0,23}$")
+ private val LANG = Regex("^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8}){0,2}$")
private const val MAX_WRITES = 8
fun parse(text: String): Manifest = ExtJson.decodeFromString(serializer(), text)
}
}
+/** One language of [Manifest.translations]: each text left out keeps the manifest's own. */
+@Serializable
+data class Translation(
+ val name: String? = null,
+ val description: String? = null,
+ val changelog: String? = null,
+ val welcome: Welcome? = null,
+ /** Action name → its reason, shown before install. */
+ val actions: Map<String, String> = emptyMap(),
+ /** Setting key → its texts. */
+ val settings: Map<String, SettingText> = emptyMap(),
+)
+
+/** A setting's texts in one language: [options] are the labels of the choice's options, in their order. */
+@Serializable
+data class SettingText(val label: String? = null, val description: String? = null, val options: List<String> = emptyList())
+
/**
* `welcome`: a few words after the first install, for what the extension does ([message]) and the
* little the user still has to do ([steps], in order: "Pair your account in Settings → Extensions").
@@ -323,7 +421,12 @@ data class Setting(
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 labels of [options] in the language shown ([Manifest.localized]); empty: the options themselves. */
+ @Transient val optionLabels: List<String> = emptyList(),
) {
+ /** What the user sees for option [value] of a choice. */
+ fun optionLabel(value: String): String = optionLabels.getOrNull(options.indexOf(value))?.takeIf { it.isNotBlank() } ?: value
+
/** 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)
diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Package.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Package.kt
index 95d5543e..e2437bce 100644
--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Package.kt
+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Package.kt
@@ -14,6 +14,9 @@ import java.util.zip.ZipOutputStream
* `LICENSE`. Nothing else is read.
*/
class ExtensionPackage(val manifest: Manifest, val script: String, val icon: ByteArray?, val sha256: String) {
+ /** The same package with its manifest's texts in [tag] ([Manifest.localized]). */
+ fun localized(tag: String): ExtensionPackage = manifest.localized(tag).let { if (it === manifest) this else ExtensionPackage(it, script, icon, sha256) }
+
companion object {
const val MAX_ZIP = 2 * 1024 * 1024
const val MAX_SCRIPT = 1024 * 1024
diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/ManifestTranslationsTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/ManifestTranslationsTest.kt
new file mode 100644
index 00000000..2cec2a02
--- /dev/null
+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/ManifestTranslationsTest.kt
@@ -0,0 +1,69 @@
+package app.myspoti.extensions
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertSame
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ManifestTranslationsTest {
+ private val text = """
+ {
+ "id": "io.github.someone.music",
+ "name": "Some music",
+ "version": "1.0.0",
+ "author": "someone",
+ "description": "Music from example.com.",
+ "actions": [
+ { "name": "audio.source", "why": "Plays songs from example.com" },
+ { "name": "settings.page", "why": "Its quality" }
+ ],
+ "settings": [{ "key": "quality", "type": "choice", "label": "Quality", "options": ["lossless", "high"] }],
+ "translations": {
+ "fr": {
+ "description": "De la musique d'example.com.",
+ "actions": { "audio.source": "Lit les titres d'example.com" },
+ "settings": { "quality": { "label": "Qualité", "options": ["Sans perte", "Haute"] } }
+ },
+ "pt-BR": { "description": "Música do example.com." }
+ }
+ }
+ """.trimIndent()
+
+ @Test fun theTextsFollowTheLanguageAndTheValuesStay() {
+ val m = Manifest.parse(text)
+ assertEquals(emptyList<String>(), m.problems())
+ val fr = m.localized("fr-FR")
+ assertEquals("De la musique d'example.com.", fr.description)
+ assertEquals("Some music", fr.name)
+ val q = fr.settings.single()
+ assertEquals("Qualité", q.label)
+ assertEquals(listOf("lossless", "high"), q.options)
+ assertEquals("Sans perte", q.optionLabel("lossless"))
+ assertEquals("Lit les titres d'example.com", fr.whyShown(fr.actions[0]))
+ assertEquals("Its quality", fr.whyShown(fr.actions[1]))
+ }
+
+ @Test fun whatWasAcceptedIsWeighedOnTheWrittenReasons() {
+ val m = Manifest.parse(text)
+ val fr = m.localized("fr")
+ assertEquals(m.asks(), fr.asks())
+ assertEquals("Lit les titres d'example.com", fr.asksShown().first { it.key == "audio.source" }.why)
+ }
+
+ @Test fun aRegionFallsBackToItsLanguageAndBackToTheWrittenTexts() {
+ val m = Manifest.parse(text)
+ assertEquals("Música do example.com.", m.localized("pt").description)
+ assertEquals("Música do example.com.", m.localized("pt-PT").description)
+ val back = m.localized("fr").localized("de")
+ assertEquals("Music from example.com.", back.description)
+ assertEquals("Quality", back.settings.single().label)
+ assertSame(m, m.localized("de"))
+ }
+
+ @Test fun aTranslationOfWhatIsNotThereIsAProblem() {
+ val bad = Manifest.parse(text.replace("\"audio.source\": \"Lit", "\"lyrics.provide\": \"Lit").replace("[\"Sans perte\", \"Haute\"]", "[\"Sans perte\"]"))
+ val problems = bad.problems()
+ assertTrue(problems.toString(), problems.any { "lyrics.provide" in it })
+ assertTrue(problems.toString(), problems.any { "one label per option" in it })
+ }
+}
diff --git a/docs/extensions/API.md b/docs/extensions/API.md
index d81f9ae5..7b67fdc4 100644
--- a/docs/extensions/API.md
+++ b/docs/extensions/API.md
@@ -128,6 +128,34 @@ extensions did there ("Lyrics of X from Y", "Skipped by Z") with a one-tap Turn
| `minAppVersion` | string | none | The oldest Myspoti it works on (`"2.0.2"`, `"2.0.2-beta.4"`), compared like semantic versions (a release is newer than its betas). An older Myspoti shows "Requires Myspoti 2.0.2 or newer" and does not install it. |
| `changelog` | string | `""` | What changed in this version, 2000 characters at most: shown on the store page and before an update. |
| `welcome` | object | none | `{ "message": "...", "steps": ["...", "..."] }`, shown once right after the first install (not on updates): what the extension does (600 characters at most) and what is left to do (5 steps at most, 160 characters each). Older apps ignore it. |
+| `translations` | object | `{}` | The texts people see, in other languages, by language tag (`"fr"`, `"pt-BR"`; 80 at most). Below. Older apps ignore it. |
+
+`translations` lets the store, the install prompt and the extension's page speak the user's
+language, with no action to ask. Each language may give any of `name`, `description`,
+`changelog`, `welcome`, `actions` (an action's name → its reason, 80 characters) and `settings`
+(a setting's key → `{ "label", "description", "options" }`, `options` being the labels of a
+choice's options in their order). What a language leaves out stays the manifest's own text.
+Myspoti shows the language picked in its settings (the phone's when it follows the phone): `pt-BR`
+takes `pt-BR`, then `pt`, then another `pt-…`, then the manifest's own texts. A choice's values do
+not change: `myspoti.settings.get('quality')` still gives `"lossless"` when the user ticked
+"Sans perte". The reasons the user accepted are weighed on the manifest's own `why`, so a new
+translation never asks the user again. An action or a setting the manifest does not have, or a
+number of option labels that is not the number of options, refuses the package.
+
+```json
+"translations": {
+ "fr": {
+ "description": "Des paroles synchronisées d'example.com.",
+ "actions": { "lyrics.provide": "Paroles synchronisées d'example.com" },
+ "settings": { "quality": { "label": "Qualité", "options": ["Sans perte", "Haute"] } }
+ },
+ "pt-BR": { "description": "Letras sincronizadas do example.com." }
+}
+```
+
+Texts your script makes (blocks, outcomes, `notify`, your page) follow `myspoti.locale` (section 3),
+also with no action to ask. A sign-in page opened with `myspoti.auth.open` is asked in the same
+language (`Accept-Language`), so a site that has it shows it.
An action entry: `{ "name": "...", "why": "...", "hosts": [...] }`.