Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions android/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
```

Expand Down Expand Up @@ -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/<app-id>/<locale>.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).
Expand Down
2 changes: 2 additions & 0 deletions android/dds-compose/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
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<String, String>()

/** 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
if (save(file, result.bytes)) {
result.etag?.let { etags[locale] = it } ?: etags.remove(locale)
}
return catalog
}

private fun cacheFile(locale: String): File {
require(isCanonicalCatalogLocale(locale))
return File(directory, "$app/$locale.json")
}

private fun save(file: File, bytes: ByteArray): Boolean =
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)
}
true
} catch (_: IOException) {
// A disk error leaves the previous catalog available.
false
}

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
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<TranslationCatalog?>(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, formatLocale(resources, current), *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 = formatLocale(resources, current)
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 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
}
}

private class Request(val locale: String) {
var job: Job? = null
}
}

private data class OtaLocalizationScope(
val localization: OtaLocalization,
val catalog: TranslationCatalog?,
)

private val LocalOtaLocalization = compositionLocalOf<OtaLocalizationScope?> { 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)
}
}
Loading
Loading