diff options
Diffstat (limited to 'src/main/java/at/hannibal2/skyhanni')
5 files changed, 74 insertions, 145 deletions
diff --git a/src/main/java/at/hannibal2/skyhanni/features/chat/Translator.kt b/src/main/java/at/hannibal2/skyhanni/features/chat/Translator.kt index 29d30d355..ffa7d53ec 100644 --- a/src/main/java/at/hannibal2/skyhanni/features/chat/Translator.kt +++ b/src/main/java/at/hannibal2/skyhanni/features/chat/Translator.kt @@ -1,33 +1,22 @@ package at.hannibal2.skyhanni.features.chat import at.hannibal2.skyhanni.SkyHanniMod -import at.hannibal2.skyhanni.events.LorenzChatEvent import at.hannibal2.skyhanni.SkyHanniMod.Companion.coroutineScope -import at.hannibal2.skyhanni.test.command.CopyErrorCommand +import at.hannibal2.skyhanni.events.LorenzChatEvent +import at.hannibal2.skyhanni.utils.APIUtil import at.hannibal2.skyhanni.utils.LorenzUtils +import at.hannibal2.skyhanni.utils.LorenzUtils.transformIf import at.hannibal2.skyhanni.utils.OSUtils import at.hannibal2.skyhanni.utils.StringUtils.getPlayerName import at.hannibal2.skyhanni.utils.StringUtils.removeColor -import com.google.gson.* -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.launch import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import com.google.gson.JsonParser -import com.google.gson.JsonSyntaxException +import kotlinx.coroutines.launch import net.minecraft.event.ClickEvent import net.minecraft.event.HoverEvent import net.minecraft.util.ChatComponentText import net.minecraft.util.ChatStyle import net.minecraftforge.fml.common.eventhandler.EventPriority import net.minecraftforge.fml.common.eventhandler.SubscribeEvent -import org.apache.http.client.config.RequestConfig -import org.apache.http.client.methods.HttpGet -import org.apache.http.impl.client.HttpClientBuilder -import org.apache.http.impl.client.HttpClients -import org.apache.http.message.BasicHeader -import org.apache.http.util.EntityUtils import java.net.URLDecoder import java.net.URLEncoder @@ -43,8 +32,7 @@ class Translator { val message = event.message if (message.getPlayerName() == "-") return - val editedComponent = - if (event.chatComponent.siblings.size > 0) event.chatComponent.siblings.last() else event.chatComponent + val editedComponent = event.chatComponent.transformIf({ siblings.size > 0 }) { siblings.last() } val clickStyle = createClickStyle(message.removeColor(), editedComponent.chatStyle) editedComponent.setChatStyle(clickStyle) @@ -70,22 +58,6 @@ class Translator { companion object { private val config get() = SkyHanniMod.feature.chat - // Using my own getJSONResponse because of 1 line of difference. - private val parser = JsonParser() - private val builder: HttpClientBuilder = - HttpClients.custom().setUserAgent("SkyHanni/${SkyHanniMod.version}") - .setDefaultHeaders( - mutableListOf( - BasicHeader("Pragma", "no-cache"), - BasicHeader("Cache-Control", "no-cache") - ) - ) - .setDefaultRequestConfig( - RequestConfig.custom() - .build() - ) - .useSystemProperties() - /* * Simplified version of the JSON response: * [ @@ -100,114 +72,67 @@ class Translator { * ] * ], * null, - * '"target language as a two letter code following ISO 639-1"', + * '"target language as a two-letter code following ISO 639-1"', * ] */ - private fun getJSONResponse(urlString: String, silentError: Boolean = false): JsonElement { - val client = builder.build() - try { - client.execute(HttpGet(urlString)).use { response -> - val entity = response.entity - if (entity != null) { - val retSrc = EntityUtils.toString(entity) - try { - return parser.parse(retSrc) - } catch (e: JsonSyntaxException) { - if (e.message?.contains("Use JsonReader.setLenient(true)") == true) { - println("MalformedJsonException: Use JsonReader.setLenient(true)") - println(" - getJSONResponse: '$urlString'") - LorenzUtils.debug("MalformedJsonException: Use JsonReader.setLenient(true)") - } else if (retSrc.contains("<center><h1>502 Bad Gateway</h1></center>")) { - e.printStackTrace() - - } else { - CopyErrorCommand.logError( - Error("Google Translate API error for url: '$urlString'", e), - "Failed to load data from Google API" - ) - } - } - } - } - } catch (throwable: Throwable) { - if (silentError) { - throw throwable - } else { - CopyErrorCommand.logError( - Error("Google Translate API error for url: '$urlString'", throwable), - "Failed to load data from Google API" - ) - } - } finally { - client.close() + private fun getJSONResponse(urlString: String) = + APIUtil.getJSONResponseAsElement(urlString, false, "Google Translate API") + + private fun getTranslationToEnglish(message: String): String { + val url = + "https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=" + URLEncoder.encode( + message, + "UTF-8" + ) + + var messageToSend = "" + val layer1 = getJSONResponse(url).asJsonArray + if (layer1.size() <= 2) return "Error!" + + val language = layer1[2].toString() + if (language == "\"en\"") return "Unable to translate!" + if (language.length != 4) return "Error!" + + val layer2 = try { + layer1[0] as JsonArray + } catch (_: Exception) { + return "Error!" } - return JsonObject() + + for (layer3 in layer2) { + val arrayLayer3 = layer3 as? JsonArray ?: continue + val sentence = arrayLayer3[0].toString() + val sentenceWithoutQuotes = sentence.substring(1, sentence.length - 1) + messageToSend = "$messageToSend$sentenceWithoutQuotes" + } + messageToSend = "$messageToSend §7(Language: $language)" + + return URLDecoder.decode(messageToSend, "UTF-8").replace("\\", "") } - private fun getTranslationToEnglish(message: String): CompletableDeferred<String> { - val returnValue = CompletableDeferred<String>() - coroutineScope.launch { - val url = - "https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=" + URLEncoder.encode( - message, - "UTF-8" - ) - - var messageToSend = "" - val layer1 = getJSONResponse(url).asJsonArray - if (layer1.size() <= 2) returnValue.complete("Error!") - - val language = layer1[2].toString() - if (language == "\"en\"") returnValue.complete("Unable to translate!") - if (language.length != 4) returnValue.complete("Error!") - - var layer2 = JsonArray() - try { - layer2 = layer1[0] as JsonArray - } catch (_: Exception) { - returnValue.complete("Error!") - } + private fun getTranslationFromEnglish(message: String, lang: String): String { + val url = + "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=$lang&dt=t&q=" + URLEncoder.encode( + message, + "UTF-8" + ) + + val layer1 = getJSONResponse(url).asJsonArray + if (layer1.size() < 1) return "Error!" + val layer2 = layer1[0] as? JsonArray - for (layer3 in layer2) { - val arrayLayer3 = layer3 as? JsonArray ?: continue - val sentence = arrayLayer3[0].toString() + val firstSentence = (layer2?.get(0) as? JsonArray)?.get(0).toString() + var messageToSend = firstSentence.substring(0, firstSentence.length - 1) + if (layer2 != null) { + for (sentenceIndex in 1..<layer2.size()) { + val sentence = (layer2.get(sentenceIndex) as JsonArray).get(0).toString() val sentenceWithoutQuotes = sentence.substring(1, sentence.length - 1) messageToSend = "$messageToSend$sentenceWithoutQuotes" } - messageToSend = "$messageToSend §7(Language: $language)" - - returnValue.complete(URLDecoder.decode(messageToSend, "UTF-8").replace("\\", "")) - } - return returnValue - } - - private fun getTranslationFromEnglish(message: String, lang: String): CompletableDeferred<String> { - val returnValue = CompletableDeferred<String>() - coroutineScope.launch { - val url = - "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=$lang&dt=t&q=" + URLEncoder.encode( - message, - "UTF-8" - ) - - val layer1 = getJSONResponse(url).asJsonArray - if (layer1.size() < 1) returnValue.complete("Error!") - val layer2 = layer1[0] as? JsonArray - - val firstSentence = (layer2?.get(0) as? JsonArray)?.get(0).toString() - var messageToSend = firstSentence.substring(0, firstSentence.length - 1) - if (layer2 != null) { - for (sentenceIndex in 1..<layer2.size()) { - val sentence = (layer2.get(sentenceIndex) as JsonArray).get(0).toString() - val sentenceWithoutQuotes = sentence.substring(1, sentence.length - 1) - messageToSend = "$messageToSend$sentenceWithoutQuotes" - } - } // The first translated sentence only has 1 extra char at the end, but sentences after it need 1 at the front and 1 at the end removed in the substring - messageToSend = messageToSend.substring(1, messageToSend.length) - returnValue.complete(URLDecoder.decode(messageToSend, "UTF-8").replace("\\", "")) - } - return returnValue + } // The first translated sentence only has 1 extra char at the end, but sentences after it need 1 at the front and 1 at the end removed in the substring + messageToSend = messageToSend.substring(1, messageToSend.length) + return URLDecoder.decode(messageToSend, "UTF-8").replace("\\", "") } fun toEnglish(args: Array<String>) { @@ -218,7 +143,7 @@ class Translator { } coroutineScope.launch { - val translation = getTranslationToEnglish(message).await() + val translation = getTranslationToEnglish(message) if (translation == "Unable to translate!") LorenzUtils.chat("§c[SkyHanni] Unable to translate message :( (is it in English?)") else LorenzUtils.chat("§e[SkyHanni] Found translation: §f$translation") } @@ -237,7 +162,7 @@ class Translator { } coroutineScope.launch { - val translation = getTranslationFromEnglish(message, language).await() + val translation = getTranslationFromEnglish(message, language) LorenzUtils.chat("§e[SkyHanni] Copied translation to clipboard: $translation") OSUtils.copyToClipboard(translation) } diff --git a/src/main/java/at/hannibal2/skyhanni/test/command/CopyScoreboardCommand.kt b/src/main/java/at/hannibal2/skyhanni/test/command/CopyScoreboardCommand.kt index c4c262f0a..bcc0cfc35 100644 --- a/src/main/java/at/hannibal2/skyhanni/test/command/CopyScoreboardCommand.kt +++ b/src/main/java/at/hannibal2/skyhanni/test/command/CopyScoreboardCommand.kt @@ -11,11 +11,11 @@ object CopyScoreboardCommand { val resultList = mutableListOf<String>() val noColor = args.size == 1 && args[0] == "true" resultList.add("Title:") - resultList.add(ScoreboardData.objectiveTitle.transformIf(noColor) { removeColor() }) + resultList.add(ScoreboardData.objectiveTitle.transformIf({noColor}) { removeColor() }) resultList.add("") for (line in ScoreboardData.sidebarLinesFormatted) { - val scoreboardLine = line.transformIf(noColor) { removeColor() } + val scoreboardLine = line.transformIf({noColor}) { removeColor() } resultList.add("'$scoreboardLine'") } diff --git a/src/main/java/at/hannibal2/skyhanni/test/command/CopyTabListCommand.kt b/src/main/java/at/hannibal2/skyhanni/test/command/CopyTabListCommand.kt index 9a745cc11..a4f287e5b 100644 --- a/src/main/java/at/hannibal2/skyhanni/test/command/CopyTabListCommand.kt +++ b/src/main/java/at/hannibal2/skyhanni/test/command/CopyTabListCommand.kt @@ -14,7 +14,7 @@ object CopyTabListCommand { val resultList = mutableListOf<String>() val noColor = args.size == 1 && args[0] == "true" for (line in TabListData.getTabList()) { - val tabListLine = line.transformIf(noColor) { removeColor() } + val tabListLine = line.transformIf({ noColor }) { removeColor() } if (tabListLine != "") resultList.add("'$tabListLine'") } val tabList = Minecraft.getMinecraft().ingameGUI.tabList as AccessorGuiPlayerTabOverlay diff --git a/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt b/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt index 917243b47..7f9de6685 100644 --- a/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt +++ b/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt @@ -2,6 +2,7 @@ package at.hannibal2.skyhanni.utils import at.hannibal2.skyhanni.SkyHanniMod import at.hannibal2.skyhanni.test.command.CopyErrorCommand +import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import com.google.gson.JsonSyntaxException @@ -39,7 +40,10 @@ object APIUtil { ) .useSystemProperties() - fun getJSONResponse(urlString: String, silentError: Boolean = false): JsonObject { + fun getJSONResponse(urlString: String, silentError: Boolean = false) = + getJSONResponseAsElement(urlString, silentError) as JsonObject + + fun getJSONResponseAsElement(urlString: String, silentError: Boolean = false, apiName: String = "Hypixel API"): JsonElement { val client = builder.build() try { client.execute(HttpGet(urlString)).use { response -> @@ -47,14 +51,14 @@ object APIUtil { if (entity != null) { val retSrc = EntityUtils.toString(entity) try { - return parser.parse(retSrc) as JsonObject + return parser.parse(retSrc) } catch (e: JsonSyntaxException) { if (e.message?.contains("Use JsonReader.setLenient(true)") == true) { println("MalformedJsonException: Use JsonReader.setLenient(true)") println(" - getJSONResponse: '$urlString'") LorenzUtils.debug("MalformedJsonException: Use JsonReader.setLenient(true)") } else if (retSrc.contains("<center><h1>502 Bad Gateway</h1></center>")) { - if (showApiErrors) { + if (showApiErrors && apiName == "Hypixel API") { LorenzUtils.clickableChat( "[SkyHanni] Problems with detecting the Hypixel API. §eClick here to hide this message for now.", "shtogglehypixelapierrors" @@ -64,8 +68,8 @@ object APIUtil { } else { CopyErrorCommand.logError( - Error("Hypixel API error for url: '$urlString'", e), - "Failed to load data from Hypixel API" + Error("$apiName error for url: '$urlString'", e), + "Failed to load data from $apiName" ) } } @@ -76,8 +80,8 @@ object APIUtil { throw throwable } else { CopyErrorCommand.logError( - Error("Hypixel API error for url: '$urlString'", throwable), - "Failed to load data from Hypixel API" + Error("$apiName error for url: '$urlString'", throwable), + "Failed to load data from $apiName" ) } } finally { diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt index d2c4075ff..3ad8e3fe9 100644 --- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt +++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt @@ -535,8 +535,8 @@ object LorenzUtils { val JsonPrimitive.asIntOrNull get() = takeIf { it.isNumber }?.asInt - fun <T> T.transformIf(condition: Boolean, transofmration: T.() -> T) = - if (condition) transofmration(this) else this + fun <T> T.transformIf(condition: T.() -> Boolean, transofmration: T.() -> T) = + if (condition()) transofmration(this) else this fun <T> T.conditionalTransform(condition: Boolean, ifTrue: T.() -> Any, ifFalse: T.() -> Any) = if (condition) ifTrue(this) else ifFalse(this) |