From dc21e3278e10f1a034dc264aad517c130cda9615 Mon Sep 17 00:00:00 2001 From: Sin-Kang Date: Mon, 16 Nov 2026 11:29:42 +0900 Subject: [PATCH 1/3] feat(android): share OTA localization across apps --- android/README.md | 10 +- android/dds-compose/build.gradle.kts | 2 + .../compose/localization/CatalogRepository.kt | 135 ++++++++++++ .../compose/localization/OtaLocalization.kt | 201 ++++++++++++++++++ .../localization/TranslationCatalog.kt | 102 +++++++++ .../localization/CatalogRepositoryTest.kt | 71 +++++++ .../localization/TranslationCatalogTest.kt | 59 +++++ android/gradle.properties | 2 +- android/gradle/libs.versions.toml | 4 + 9 files changed, 583 insertions(+), 3 deletions(-) create mode 100644 android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt create mode 100644 android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt create mode 100644 android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt create mode 100644 android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt create mode 100644 android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/TranslationCatalogTest.kt diff --git a/android/README.md b/android/README.md index 466fc1b8..6cf57a67 100644 --- a/android/README.md +++ b/android/README.md @@ -26,8 +26,8 @@ dependencies { ```kotlin dependencies { - implementation("kr.devslab:dds-compose:0.10.1") - androidTestImplementation("kr.devslab:dds-compose-testing:0.10.1") + implementation("kr.devslab:dds-compose:0.11.0") + androidTestImplementation("kr.devslab:dds-compose-testing:0.11.0") } ``` @@ -92,6 +92,12 @@ The host controls availability and progress. Its auth layer configures OAuth, li In 0.10.1, the `DdsSocialSignInCustomization` overload lets the host control sheet visibility and supply its own method controls, overflow trigger, or sheet with retry content. DDS still arranges the first three methods and the remaining list in order. The `method` slot receives `pending`, `enabled`, and `inSheet`, plus the guarded selection callback. A custom `sheet` can apply the supplied button width to its content so the rows line up with the main column. Custom buttons can use `DdsSocialProviderIcon` to draw the bundled marks. +### OTA localization + +Applications can create a single `OtaLocalization` with their app ID and a function that maps Android resources to a supported BCP 47 tag. Wrap the Compose root in `ProvideOtaLocalization` and use `localizedString` and `localizedPlural` for eligible UI resources. The provider checks for updates on foreground entry and when the selected language changes. Supply `allowResource` when only certain app strings should use the catalog. + +The default HTTPS path is `https://devslab.kr/ota-locales/v1//.json`. Schema 1 contains `schema`, `app`, `locale`, `strings`, and `plurals`. The client reuses the last valid catalog for that app and locale, and falls back to bundled resources for absent or incompatible text. The host application owns the list of supported languages and the bundled translations. + The bundled assets cover Google, Kakao, Naver, LINE, Microsoft, LinkedIn, GitHub, Discord, Figma, Notion, X, Slack, and Zoom. GitLab uses text by default. Apps can supply approved artwork or a dedicated provider button for Apple, Facebook, and WeChat. Android uses the original full Naver green icon from `NAVER_login_KR/NAVER_login_Light_KR_green_icon_H56.png`. SVG marks from Kakao, Microsoft, GitHub, and Slack are rasterized with their original colors. The dark variants keep the original GitHub and Kakao marks on a white backing and use X’s white artwork. For the official sources and original checksums, see the [shared provider asset provenance](../packages/dds-auth/assets/provenance.json). diff --git a/android/dds-compose/build.gradle.kts b/android/dds-compose/build.gradle.kts index 78e0db15..15fa8d39 100644 --- a/android/dds-compose/build.gradle.kts +++ b/android/dds-compose/build.gradle.kts @@ -45,6 +45,8 @@ dependencies { api(libs.compose.animation) api(libs.compose.material3) implementation(libs.lifecycle.runtime.compose) + implementation(libs.jvm.okhttp) + implementation(libs.kotlinx.serialization.json) api(libs.activity.compose) testImplementation(libs.junit) diff --git a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt new file mode 100644 index 00000000..6d06e2c8 --- /dev/null +++ b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt @@ -0,0 +1,135 @@ +package kr.devslab.dds.compose.localization + +import okhttp3.CookieJar +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.net.URI +import java.nio.file.Files +import java.nio.file.StandardCopyOption.ATOMIC_MOVE +import java.nio.file.StandardCopyOption.REPLACE_EXISTING +import java.util.concurrent.TimeUnit +import java.util.Locale + +internal class CatalogRepository( + private val app: String, + private val directory: File, + catalogBaseUrl: String, + private val download: (String, String?) -> Download?, +) { + constructor(app: String, directory: File, catalogBaseUrl: String) : + this(app, directory, catalogBaseUrl, ::fetch) + + private val baseUrl = URI(catalogBaseUrl) + + init { + require(app.length <= 128 && APP_ID.matches(app)) { "Invalid OTA catalog app ID" } + require( + baseUrl.scheme == "https" && !baseUrl.host.isNullOrBlank() && + baseUrl.userInfo == null && baseUrl.rawQuery == null && baseUrl.rawFragment == null && + baseUrl.rawPath.endsWith('/'), + ) { "OTA catalog base URL must be an HTTPS directory URL" } + } + + private val etags = mutableMapOf() + + /** Call from a worker thread. The host app supplies a locale from its supported list. */ + @Synchronized + fun cached(locale: String): TranslationCatalog? { + val file = cacheFile(locale) + return try { + file.inputStream().use { input -> input.readCatalog()?.let { TranslationCatalog.parse(it, app, locale) } } + } catch (_: IOException) { + null + } + } + + @Synchronized + fun refresh(locale: String): TranslationCatalog? { + val file = cacheFile(locale) + val url = baseUrl.resolve("$locale.json").toASCIIString() + val result = download(url, etags[locale]) ?: return null + val catalog = TranslationCatalog.parse(result.bytes, app, locale) ?: return null + result.etag?.let { etags[locale] = it } ?: etags.remove(locale) + save(file, result.bytes) + return catalog + } + + private fun cacheFile(locale: String): File { + require(isCanonicalCatalogLocale(locale)) + return File(directory, "$app/$locale.json") + } + + private fun save(file: File, bytes: ByteArray) { + try { + val parent = checkNotNull(file.parentFile).toPath() + Files.createDirectories(parent) + val pending = Files.createTempFile(parent, "catalog-", ".json") + try { + Files.write(pending, bytes) + Files.move(pending, file.toPath(), ATOMIC_MOVE, REPLACE_EXISTING) + } finally { + Files.deleteIfExists(pending) + } + } catch (_: IOException) { + // A disk error leaves the previous catalog available. + } + } + + internal data class Download(val bytes: ByteArray, val etag: String?) + + private companion object { + val APP_ID = Regex("[a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)*") + val HTTP = OkHttpClient.Builder() + .cookieJar(CookieJar.NO_COOKIES) + .followRedirects(false) + .followSslRedirects(false) + .retryOnConnectionFailure(false) + .callTimeout(5, TimeUnit.SECONDS) + .build() + + fun fetch(url: String, etag: String?): Download? { + val request = Request.Builder().url(url) + .header("Accept", "application/json") + .header("Cache-Control", "no-cache") + .header("User-Agent", "DevsLab-Translations/1") + if (etag != null) request.header("If-None-Match", etag) + return try { + HTTP.newCall(request.build()).execute().use { response -> + if (response.code != 200) return null + val body = response.body + val mediaType = body.contentType() + if (mediaType?.type != "application" || mediaType.subtype != "json") return null + if (body.contentLength() > TranslationCatalog.MAX_BYTES) return null + val bytes = body.byteStream().readCatalog() ?: return null + val nextEtag = response.header("ETag")?.takeIf { value -> + value.length <= 200 && value.all { it in ' '..'~' } + } + Download(bytes, nextEtag) + } + } catch (_: IOException) { + null + } + } + + fun InputStream.readCatalog(): ByteArray? { + val result = ByteArrayOutputStream() + val buffer = ByteArray(8_192) + while (true) { + val read = read(buffer) + if (read < 0) return result.toByteArray() + if (result.size() + read > TranslationCatalog.MAX_BYTES) return null + result.write(buffer, 0, read) + } + } + } +} + +private val localeTagPattern = Regex("[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8})*") + +internal fun isCanonicalCatalogLocale(tag: String): Boolean = + tag.length <= 64 && tag != "und" && localeTagPattern.matches(tag) && + Locale.forLanguageTag(tag).toLanguageTag() == tag diff --git a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt new file mode 100644 index 00000000..4e5009bb --- /dev/null +++ b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt @@ -0,0 +1,201 @@ +package kr.devslab.dds.compose.localization + +import android.content.Context +import android.content.res.Resources +import android.icu.text.PluralRules +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.ui.platform.LocalResources +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.repeatOnLifecycle +import java.io.File +import java.util.Locale +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Keeps a validated OTA translation catalog for the app's current locale. + * + * Create one instance per application. [localeTag] returns the app's canonical BCP 47 tag + * or null to use bundled resources. [allowResource] filters resource entry names before + * looking up remote overrides. + */ +public class OtaLocalization( + context: Context, + appId: String, + private val localeTag: (Resources) -> String?, + private val allowResource: (String) -> Boolean = { true }, + catalogBaseUrl: String = "https://devslab.kr/ota-locales/v1/$appId/", +) { + private val resourcePackages = setOf(context.applicationContext.packageName, appId) + private val repository = CatalogRepository( + appId, + File(context.applicationContext.noBackupFilesDir, "ota-locales"), + catalogBaseUrl, + ) + private val worker = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val sync = Mutex() + private val requestLock = Any() + private var currentRequest: Request? = null + private val activeCatalog = MutableStateFlow(null) + internal val catalog = activeCatalog.asStateFlow() + + /** Loads the selected locale from cache, then revalidates it in the background. */ + public fun refresh(resources: Resources): Unit = refreshLocale(selectedLocale(resources)) + + /** Reads a string from the active catalog or the same bundled Android resource. */ + public fun localizedString(resources: Resources, @StringRes id: Int, vararg args: Any): String = + stringFrom(resources, activeCatalog.value, id, *args) + + /** Reads a plural from the active catalog or the same bundled Android resource. */ + public fun localizedPlural( + resources: Resources, + @PluralsRes id: Int, + quantity: Int, + vararg args: Any, + ): String = pluralFrom(resources, activeCatalog.value, id, quantity, *args) + + internal fun selectedLocale(resources: Resources): String? = + localeTag(resources)?.takeIf(::isCanonicalCatalogLocale) + + internal fun refreshLocale(tag: String?) { + synchronized(requestLock) { + val previous = currentRequest + if (previous?.locale == tag && previous?.job?.isActive == true) return + previous?.job?.cancel() + if (tag == null) { + currentRequest = null + activeCatalog.value = null + return + } + val request = Request(tag) + currentRequest = request + request.job = worker.launch { + sync.withLock { + ensureActive() + if (activeCatalog.value?.locale != tag) publish(request, repository.cached(tag)) + ensureActive() + repository.refresh(tag)?.let { publish(request, it) } + } + } + } + } + + internal fun stringFrom( + resources: Resources, + catalog: TranslationCatalog?, + @StringRes id: Int, + vararg args: Any, + ): String { + val bundled = resources.getString(id) + val current = catalog?.takeIf { it.locale == selectedLocale(resources) } + val name = current?.let { resourceName(resources, id) } + if (current != null && name != null) { + TranslationCatalog.format( + current.string(name), bundled, Locale.forLanguageTag(current.locale), *args, + )?.let { return it } + } + return if (args.isEmpty()) bundled else resources.getString(id, *args) + } + + internal fun pluralFrom( + resources: Resources, + catalog: TranslationCatalog?, + @PluralsRes id: Int, + quantity: Int, + vararg args: Any, + ): String { + val bundled = resources.getQuantityString(id, quantity) + val current = catalog?.takeIf { it.locale == selectedLocale(resources) } + val name = current?.let { resourceName(resources, id) } + if (current != null && name != null) { + val locale = Locale.forLanguageTag(current.locale) + val category = PluralRules.forLocale(locale).select(quantity.toDouble()) + TranslationCatalog.format(current.plural(name, category), bundled, locale, *args) + ?.let { return it } + } + return if (args.isEmpty()) bundled else resources.getQuantityString(id, quantity, *args) + } + + private fun resourceName(resources: Resources, id: Int): String? { + if (resources.getResourcePackageName(id) !in resourcePackages) return null + return resources.getResourceEntryName(id).takeIf(allowResource) + } + + private fun publish(request: Request, catalog: TranslationCatalog?) { + synchronized(requestLock) { + if (currentRequest === request) activeCatalog.value = catalog + } + } + + private class Request(val locale: String) { + var job: Job? = null + } +} + +private data class OtaLocalizationScope( + val localization: OtaLocalization, + val catalog: TranslationCatalog?, +) + +private val LocalOtaLocalization = compositionLocalOf { null } + +/** Applies OTA lookups and revalidates on foreground entry and locale changes. */ +@Composable +public fun ProvideOtaLocalization( + localization: OtaLocalization, + content: @Composable () -> Unit, +) { + val resources = LocalResources.current + val locale = localization.selectedLocale(resources) + val lifecycle = LocalLifecycleOwner.current.lifecycle + val catalog by localization.catalog.collectAsStateWithLifecycle() + LaunchedEffect(localization, lifecycle, locale) { + lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { + localization.refreshLocale(locale) + } + } + CompositionLocalProvider( + LocalOtaLocalization provides OtaLocalizationScope(localization, catalog), + content = content, + ) +} + +/** Like [androidx.compose.ui.res.stringResource], with a verified OTA override when available. */ +@Composable +public fun localizedString(@StringRes id: Int, vararg args: Any): String { + val resources = LocalResources.current + val ota = LocalOtaLocalization.current + return when { + ota != null -> ota.localization.stringFrom(resources, ota.catalog, id, *args) + args.isEmpty() -> resources.getString(id) + else -> resources.getString(id, *args) + } +} + +/** Like [androidx.compose.ui.res.pluralStringResource], with the same-resource OTA override. */ +@Composable +public fun localizedPlural(@PluralsRes id: Int, quantity: Int, vararg args: Any): String { + val resources = LocalResources.current + val ota = LocalOtaLocalization.current + return when { + ota != null -> ota.localization.pluralFrom(resources, ota.catalog, id, quantity, *args) + args.isEmpty() -> resources.getQuantityString(id, quantity) + else -> resources.getQuantityString(id, quantity, *args) + } +} diff --git a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt new file mode 100644 index 00000000..c7b8c4ff --- /dev/null +++ b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt @@ -0,0 +1,102 @@ +package kr.devslab.dds.compose.localization + +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.intOrNull +import java.nio.charset.CharacterCodingException +import java.util.Locale + +internal class TranslationCatalog private constructor( + val locale: String, + private val strings: JsonObject, + private val plurals: JsonObject, +) { + fun string(name: String): String? = strings[name].text() + + fun plural(name: String, category: String): String? { + val choices = plurals[name] as? JsonObject ?: return null + return choices[category].text() ?: choices["other"].text() + } + + companion object { + internal const val MAX_BYTES = 256 * 1024 + private const val MAX_TRANSLATION_LENGTH = 2_000 + private val formatToken = Regex("""%%|%[1-9][0-9]*\$[a-zA-Z]|%""") + private val namedToken = Regex("""\{[A-Za-z][A-Za-z0-9_]*}""") + + internal fun parse(bytes: ByteArray, app: String, locale: String): TranslationCatalog? { + if (bytes.size > MAX_BYTES) return null + val text = try { + bytes.decodeToString(throwOnInvalidSequence = true) + } catch (_: CharacterCodingException) { + return null + } + if (!hasBoundedNesting(text)) return null + val data = try { + Json.parseToJsonElement(text) as? JsonObject ?: return null + } catch (_: SerializationException) { + return null + } + val schema = data["schema"] as? JsonPrimitive ?: return null + if (schema.isString || schema.intOrNull != 1) return null + if (data["app"].text() != app || data["locale"].text() != locale) return null + val strings = data["strings"] as? JsonObject ?: return null + val plurals = data["plurals"] as? JsonObject ?: return null + if (strings.values.any { it.text() == null }) return null + if (plurals.values.any { choices -> + choices !is JsonObject || choices["other"].text() == null || + choices.values.any { it.text() == null } + }) return null + return TranslationCatalog(locale, strings, plurals) + } + + fun format(translation: String?, bundled: String, locale: Locale, vararg args: Any): String? { + if (translation.isNullOrBlank() || translation.length > MAX_TRANSLATION_LENGTH) return null + if (namedArguments(translation) != namedArguments(bundled)) return null + val translatedTokens = arguments(translation) + if (args.isEmpty()) { + val bundledTokens = arguments(bundled) + return translation.takeIf { + translatedTokens.filterNot { token -> token == "%" } == + bundledTokens.filterNot { token -> token == "%" } + } + } + if ("%" in translatedTokens || translatedTokens != arguments(bundled)) return null + return try { + String.format(locale, translation, *args) + } catch (_: IllegalArgumentException) { + null + } + } + + private fun arguments(template: String) = + formatToken.findAll(template).map { it.value }.filter { it != "%%" }.sorted().toList() + + private fun namedArguments(template: String) = + namedToken.findAll(template).map { it.value }.sorted().toList() + + private fun hasBoundedNesting(text: String): Boolean { + var depth = 0 + var quoted = false + var escaped = false + for (char in text) { + if (quoted) { + if (!escaped && char == '"') quoted = false + escaped = !escaped && char == '\\' + } else { + when (char) { + '"' -> quoted = true + '{', '[' -> if (++depth > 4) return false + '}', ']' -> if (--depth < 0) return false + } + } + } + return depth == 0 && !quoted + } + } +} + +private fun kotlinx.serialization.json.JsonElement?.text(): String? = + (this as? JsonPrimitive)?.takeIf { it.isString }?.content diff --git a/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt b/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt new file mode 100644 index 00000000..36a64b74 --- /dev/null +++ b/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt @@ -0,0 +1,71 @@ +package kr.devslab.dds.compose.localization + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class CatalogRepositoryTest { + @get:Rule + val files = TemporaryFolder() + + @Test + fun replacesCatalogOnlyWhenTheResponseMatchesTheAppAndLocale() { + val directory = files.newFolder() + val pending = mutableListOf( + CatalogRepository.Download(catalog("fr", "First"), "\"v1\""), + CatalogRepository.Download(catalog("en", "Wrong locale"), "\"v2\""), + CatalogRepository.Download(catalog("fr", "Corrected"), "\"v3\""), + null, + ) + val requests = mutableListOf>() + val repository = CatalogRepository(APP, directory, BASE_URL) { url, etag -> + requests += url to etag + pending.removeAt(0) + } + + assertNull(repository.cached("fr")) + assertEquals("First", repository.refresh("fr")?.string("heading")) + assertNull(repository.refresh("fr")) + assertEquals("First", repository.cached("fr")?.string("heading")) + assertEquals("Corrected", repository.refresh("fr")?.string("heading")) + assertNull(repository.refresh("fr")) + + val reopened = CatalogRepository(APP, directory, BASE_URL) + assertEquals("Corrected", reopened.cached("fr")?.string("heading")) + assertNull(reopened.cached("en")) + assertNull(CatalogRepository("com.example.other", directory, BASE_URL).cached("fr")) + assertEquals(listOf(null, "\"v1\"", "\"v1\"", "\"v3\""), requests.map { it.second }) + assertEquals( + listOf("https://devslab.kr/ota-locales/v1/$APP/fr.json"), + requests.map { it.first }.distinct(), + ) + } + + @Test + fun onlyAcceptsCanonicalLocaleTags() { + listOf("fr", "zh-Hans", "en-CA", "sr-Latn-RS", "es-419", "fil").forEach { + assertTrue(it, isCanonicalCatalogLocale(it)) + } + listOf("und", "en-ca", "en_CA", "../fr", "fr/CA", "fr?x=y").forEach { + assertFalse(it, isCanonicalCatalogLocale(it)) + } + } + + @Test(expected = IllegalArgumentException::class) + fun rejectsInsecureCatalogEndpoints() { + CatalogRepository(APP, files.newFolder(), "http://devslab.kr/ota-locales/v1/$APP/") + } + + private fun catalog(locale: String, value: String) = + """{"schema":1,"app":"$APP","locale":"$locale","strings":{"heading":"$value"},"plurals":{}}""" + .encodeToByteArray() + + private companion object { + const val APP = "kr.devslab.authenticator" + const val BASE_URL = "https://devslab.kr/ota-locales/v1/$APP/" + } +} diff --git a/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/TranslationCatalogTest.kt b/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/TranslationCatalogTest.kt new file mode 100644 index 00000000..1b0a3f2c --- /dev/null +++ b/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/TranslationCatalogTest.kt @@ -0,0 +1,59 @@ +package kr.devslab.dds.compose.localization + +import java.util.Locale +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class TranslationCatalogTest { + private val app = "kr.devslab.authenticator" + private val catalog = """ + {"schema":1,"app":"kr.devslab.authenticator","locale":"fr","strings":{"heading":"Nouveau"}, + "plurals":{"count":{"one":"Un élément","other":"%1${'$'}d éléments"}}} + """.trimIndent().toByteArray() + + @Test + fun acceptsOnlyTheExpectedVersionAndLocale() { + val parsed = requireNotNull(TranslationCatalog.parse(catalog, app, "fr")) + assertEquals("Nouveau", parsed.string("heading")) + assertNull(parsed.string("missing")) + assertEquals("Un élément", parsed.plural("count", "one")) + assertEquals("%1${'$'}d éléments", parsed.plural("count", "few")) + assertNull(TranslationCatalog.parse(catalog, app, "ko")) + assertNull(TranslationCatalog.parse(catalog, "com.example.other", "fr")) + assertNull(TranslationCatalog.parse(catalog.toString(Charsets.UTF_8).replace("\"schema\":1", "\"schema\":2").toByteArray(), app, "fr")) + assertNull(TranslationCatalog.parse(ByteArray(TranslationCatalog.MAX_BYTES + 1), app, "fr")) + } + + @Test + fun validatesFormatArgumentsAndPreservesTheirOrderSemantics() { + val bundled = "%1${'$'}s chose %2${'$'}d" + assertEquals("42 choisi par Alex", TranslationCatalog.format("%2${'$'}d choisi par %1${'$'}s", bundled, Locale.FRENCH, "Alex", 42)) + assertNull(TranslationCatalog.format("%1${'$'}s", bundled, Locale.FRENCH, "Alex", 42)) + assertNull(TranslationCatalog.format("Incorrect %1${'$'}d %2${'$'}s", bundled, Locale.FRENCH, "Alex", 42)) + assertNull(TranslationCatalog.format("%1${'$'}s %2${'$'}d %q", bundled, Locale.FRENCH, "Alex", 42)) + } + + @Test + fun ignoresBlankOrNonTextOverrides() { + assertNull(TranslationCatalog.format(" ", "Bundled", Locale.ENGLISH)) + val bytes = """{"schema":1,"app":"kr.devslab.authenticator","locale":"en","strings":{"heading":12},"plurals":{}}""".toByteArray() + assertNull(TranslationCatalog.parse(bytes, app, "en")) + } + + @Test + fun preservesNamedTokensWithoutBlockingLiteralPercentages() { + assertEquals( + "10% avec {terms}", + TranslationCatalog.format("10% avec {terms}", "10% with {terms}", Locale.FRENCH), + ) + assertNull(TranslationCatalog.format("Sans lien", "Read {terms}", Locale.FRENCH)) + assertNull(TranslationCatalog.format("Texte %1${'$'}s", "Read only", Locale.FRENCH)) + } + + @Test + fun rejectsInvalidUtf8AndExcessivelyNestedInput() { + assertNull(TranslationCatalog.parse(byteArrayOf(0xc3.toByte(), 0x28), app, "fr")) + assertNull(TranslationCatalog.parse("[[[[[[]]]]]]".encodeToByteArray(), app, "fr")) + } +} diff --git a/android/gradle.properties b/android/gradle.properties index eb58ee0c..180deea1 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -8,4 +8,4 @@ kotlin.code.style=official # Android releases are versioned apart from the web packages (docs/decisions.md D-048). # The release workflow overrides VERSION_NAME from the android-v* tag. GROUP=kr.devslab -VERSION_NAME=0.10.1 +VERSION_NAME=0.11.0 diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index 1002b383..00edc259 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -16,6 +16,8 @@ espresso = "3.7.0" # Tests only: the navigation library JeongsanNow and Qooroo use, at their version. navigation3 = "1.1.2" mavenPublish = "0.34.0" +okhttp = "5.1.0" +kotlinxSerialization = "1.9.0" compileSdk = "36" minSdk = "26" @@ -32,6 +34,8 @@ compose-material3 = { module = "androidx.compose.material3:material3" } activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "splashscreen" } +jvm-okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerialization" } junit = { module = "junit:junit", version.ref = "junit" } compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4" } compose-ui-test-junit4-accessibility = { module = "androidx.compose.ui:ui-test-junit4-accessibility" } From e316524a48575ed3b4121d33e8d107ce432676b3 Mon Sep 17 00:00:00 2001 From: Sin-Kang Date: Mon, 16 Nov 2026 11:42:26 +0900 Subject: [PATCH 2/3] fix(android): preserve OTA cache and locale formatting --- .../compose/localization/CatalogRepository.kt | 10 ++++++---- .../compose/localization/OtaLocalization.kt | 7 +++++-- .../localization/CatalogRepositoryTest.kt | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt index 6d06e2c8..5cf81f40 100644 --- a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt +++ b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/CatalogRepository.kt @@ -53,8 +53,9 @@ internal class CatalogRepository( val url = baseUrl.resolve("$locale.json").toASCIIString() val result = download(url, etags[locale]) ?: return null val catalog = TranslationCatalog.parse(result.bytes, app, locale) ?: return null - result.etag?.let { etags[locale] = it } ?: etags.remove(locale) - save(file, result.bytes) + if (save(file, result.bytes)) { + result.etag?.let { etags[locale] = it } ?: etags.remove(locale) + } return catalog } @@ -63,7 +64,7 @@ internal class CatalogRepository( return File(directory, "$app/$locale.json") } - private fun save(file: File, bytes: ByteArray) { + private fun save(file: File, bytes: ByteArray): Boolean = try { val parent = checkNotNull(file.parentFile).toPath() Files.createDirectories(parent) @@ -74,10 +75,11 @@ internal class CatalogRepository( } finally { Files.deleteIfExists(pending) } + true } catch (_: IOException) { // A disk error leaves the previous catalog available. + false } - } internal data class Download(val bytes: ByteArray, val etag: String?) diff --git a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt index 4e5009bb..6c2f870c 100644 --- a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt +++ b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/OtaLocalization.kt @@ -107,7 +107,7 @@ public class OtaLocalization( val name = current?.let { resourceName(resources, id) } if (current != null && name != null) { TranslationCatalog.format( - current.string(name), bundled, Locale.forLanguageTag(current.locale), *args, + current.string(name), bundled, formatLocale(resources, current), *args, )?.let { return it } } return if (args.isEmpty()) bundled else resources.getString(id, *args) @@ -124,7 +124,7 @@ public class OtaLocalization( val current = catalog?.takeIf { it.locale == selectedLocale(resources) } val name = current?.let { resourceName(resources, id) } if (current != null && name != null) { - val locale = Locale.forLanguageTag(current.locale) + val locale = formatLocale(resources, current) val category = PluralRules.forLocale(locale).select(quantity.toDouble()) TranslationCatalog.format(current.plural(name, category), bundled, locale, *args) ?.let { return it } @@ -137,6 +137,9 @@ public class OtaLocalization( return resources.getResourceEntryName(id).takeIf(allowResource) } + private fun formatLocale(resources: Resources, catalog: TranslationCatalog): Locale = + resources.configuration.locales[0] ?: Locale.forLanguageTag(catalog.locale) + private fun publish(request: Request, catalog: TranslationCatalog?) { synchronized(requestLock) { if (currentRequest === request) activeCatalog.value = catalog diff --git a/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt b/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt index 36a64b74..5ebddf08 100644 --- a/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt +++ b/android/dds-compose/src/test/kotlin/kr/devslab/dds/compose/localization/CatalogRepositoryTest.kt @@ -45,6 +45,25 @@ class CatalogRepositoryTest { ) } + @Test + fun doesNotRevalidateAgainstAnEditionThatCouldNotBeCached() { + val directory = files.newFolder() + val brokenFolder = directory.resolve(APP) + assertTrue(brokenFolder.createNewFile()) + val etags = mutableListOf() + val repository = CatalogRepository(APP, directory, BASE_URL) { _, etag -> + etags += etag + CatalogRepository.Download(catalog("fr", "Updated"), "\"new\"") + } + + assertEquals("Updated", repository.refresh("fr")?.string("heading")) + assertNull(repository.cached("fr")) + assertTrue(brokenFolder.delete()) + assertEquals("Updated", repository.refresh("fr")?.string("heading")) + assertEquals("Updated", repository.cached("fr")?.string("heading")) + assertEquals(listOf(null, null), etags) + } + @Test fun onlyAcceptsCanonicalLocaleTags() { listOf("fr", "zh-Hans", "en-CA", "sr-Latn-RS", "es-419", "fil").forEach { From a14d53000cbb2595c14ad6d922c77726041d543e Mon Sep 17 00:00:00 2001 From: Sin-Kang Date: Mon, 16 Nov 2026 11:53:58 +0900 Subject: [PATCH 3/3] fix(android): make translation placeholder regex compatible with Android ICU --- .../kr/devslab/dds/compose/localization/TranslationCatalog.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt index c7b8c4ff..f092c6ef 100644 --- a/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt +++ b/android/dds-compose/src/main/kotlin/kr/devslab/dds/compose/localization/TranslationCatalog.kt @@ -24,7 +24,7 @@ internal class TranslationCatalog private constructor( internal const val MAX_BYTES = 256 * 1024 private const val MAX_TRANSLATION_LENGTH = 2_000 private val formatToken = Regex("""%%|%[1-9][0-9]*\$[a-zA-Z]|%""") - private val namedToken = Regex("""\{[A-Za-z][A-Za-z0-9_]*}""") + private val namedToken = Regex("""\{[A-Za-z][A-Za-z0-9_]*\}""") internal fun parse(bytes: ByteArray, app: String, locale: String): TranslationCatalog? { if (bytes.size > MAX_BYTES) return null