Move the pullTranslations script into the codebase as kotlin.

This commit is contained in:
Greyson Parrelli
2025-12-31 13:51:07 -05:00
committed by jeffrey-signal
parent fe1755f250
commit 3031d68863
4 changed files with 232 additions and 67 deletions

View File

@@ -9,6 +9,7 @@ import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.util.concurrent.TimeUnit
/**
* Client for interacting with the Smartling translation API.
@@ -19,7 +20,12 @@ class SmartlingClient(
private val projectId: String
) {
private val client = OkHttpClient()
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
private val jsonParser = JsonSlurper()
/**
@@ -82,5 +88,52 @@ class SmartlingClient(
return responseBody
}
/**
* Gets the list of locales that have translations for a given file.
*/
@Suppress("UNCHECKED_CAST")
fun getLocales(authToken: String, fileUri: String): List<String> {
val request = Request.Builder()
.url("https://api.smartling.com/files-api/v2/projects/$projectId/file/status?fileUri=$fileUri")
.header("Authorization", "Bearer $authToken")
.get()
.build()
val response = client.newCall(request).execute()
val responseBody = response.body.string()
if (!response.isSuccessful) {
throw SmartlingException("Failed to get locales with code ${response.code}: $responseBody")
}
val json = jsonParser.parseText(responseBody) as Map<String, Any>
val responseObj = json["response"] as? Map<String, Any>
val data = responseObj?.get("data") as? Map<String, Any>
val items = data?.get("items") as? List<Map<String, Any>>
return items?.mapNotNull { it["localeId"] as? String }
?: throw SmartlingException("Failed to extract locales from response: $responseBody")
}
/**
* Downloads the translated file for a specific locale.
*/
fun downloadFile(authToken: String, fileUri: String, locale: String): String {
val request = Request.Builder()
.url("https://api.smartling.com/files-api/v2/projects/$projectId/locales/$locale/file?fileUri=$fileUri")
.header("Authorization", "Bearer $authToken")
.get()
.build()
val response = client.newCall(request).execute()
val responseBody = response.body.string()
if (!response.isSuccessful) {
throw SmartlingException("Failed to download file for locale $locale with code ${response.code}: $responseBody")
}
return responseBody
}
class SmartlingException(message: String) : RuntimeException(message)
}