Skip to content

Commit

Permalink
Fix image loading timeout and expired translator token
Browse files Browse the repository at this point in the history
  • Loading branch information
choppeh committed Dec 10, 2024
1 parent 6094235 commit efbc6ad
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ data class Source(val lang: String, val target: String = lang, val origin: Strin
private val languageList = listOf(
Source("en"),
Source("es"),
Source("id"),
Source("it"),
Source("pt-BR", "pt"),
)
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class Snowmtl(

override val client = network.cloudflareClient.newBuilder()
.rateLimit(2)
.readTimeout(2, TimeUnit.MINUTES)
.addInterceptor(TranslationInterceptor(source, translator))
.addInterceptor(ComposedImageInterceptor(baseUrl, super.client))
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,18 @@ class TranslationInterceptor(
translator.translate(source.origin, source.target, token).split(delimiter)
}

return tokens.mapNotNull { token ->
val list = token.parseAs<List<String>>()
val key = list.first()
val text = list.last()
return replaceDialoguesWithTranslations(tokens, mapping)
}

mapping[key]?.second?.dialog?.copy(text = text)
}
private fun replaceDialoguesWithTranslations(
tokens: List<String>,
mapping: Map<String, Pair<String, AssociatedDialog>>,
) = tokens.mapNotNull { token ->
val list = token.parseAs<List<String>>()
val key = list.first()
val text = list.last()

mapping[key]?.second?.dialog?.copy(text = text)
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class BingTranslator(private val client: OkHttpClient, private val headers: Head

private val json: Json by injectLazy()

private val tokens: TokenGroup by lazy { loadTokens() }
private var tokens = loadTokens()

override val capacity: Int = MAX_CHARS_ALLOW

Expand All @@ -36,12 +36,22 @@ class BingTranslator(private val client: OkHttpClient, private val headers: Head
return text
}

val dto = client
.newCall(translatorRequest(from, to, text))
.execute()
.parseAs<List<TranslateDto>>()

return dto.firstOrNull()?.text ?: text
var attempts = 0
do {
try {
val dto = client
.newCall(translatorRequest(from, to, text))
.execute()
.parseAs<List<TranslateDto>>()

return dto.firstOrNull()?.text ?: text
} catch (e: Exception) {
tokens = loadTokens()
attempts++
}
} while (attempts < 3)

return text
}

private fun translatorRequest(from: String, to: String, text: String): Request {
Expand Down

0 comments on commit efbc6ad

Please sign in to comment.