Skip to content

Commit

Permalink
refactor(legacy): improve downloads
Browse files Browse the repository at this point in the history
1. fix StaffDetector incorrect use
2. preload SRG remapper file
3. HTTP code cleanup
  • Loading branch information
MukjepScarlet committed Feb 6, 2025
1 parent a548ec6 commit b2741c8
Show file tree
Hide file tree
Showing 15 changed files with 296 additions and 375 deletions.
5 changes: 5 additions & 0 deletions src/main/java/net/ccbluex/liquidbounce/LiquidBounce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import net.ccbluex.liquidbounce.utils.inventory.InventoryManager
import net.ccbluex.liquidbounce.utils.inventory.InventoryUtils
import net.ccbluex.liquidbounce.utils.inventory.SilentHotbar
import net.ccbluex.liquidbounce.utils.io.MiscUtils
import net.ccbluex.liquidbounce.utils.io.MiscUtils.showErrorPopup
import net.ccbluex.liquidbounce.utils.kotlin.SharedScopes
import net.ccbluex.liquidbounce.utils.movement.BPSUtils
import net.ccbluex.liquidbounce.utils.movement.MovementUtils
Expand Down Expand Up @@ -140,6 +141,9 @@ object LiquidBounce {
// Load alt generators
loadActiveGenerators()

// Load SRG file
loadSrg()

LOGGER.info("Preload tasks of $CLIENT_NAME are completed!")

future.complete(Unit)
Expand Down Expand Up @@ -259,6 +263,7 @@ object LiquidBounce {
FileManager.loadBackground()
} catch (e: Exception) {
LOGGER.error("Failed to start client: ${e.message}")
e.showErrorPopup()
} finally {
// Set is starting status
isStarting = false
Expand Down
62 changes: 17 additions & 45 deletions src/main/java/net/ccbluex/liquidbounce/api/ClientApi.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package net.ccbluex.liquidbounce.api

import net.ccbluex.liquidbounce.LiquidBounce
import net.ccbluex.liquidbounce.utils.io.HttpUtils.applyBypassHttps
import net.ccbluex.liquidbounce.utils.io.applyBypassHttps
import net.ccbluex.liquidbounce.utils.io.decodeJson
import net.ccbluex.liquidbounce.utils.io.get
import net.ccbluex.liquidbounce.utils.io.post
import net.ccbluex.liquidbounce.utils.kotlin.RandomUtils
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
Expand Down Expand Up @@ -49,71 +51,46 @@ object ClientApi {

fun getNewestBuild(branch: String = HARD_CODED_BRANCH, release: Boolean = false): Build {
val url = "$API_V1_ENDPOINT/version/newest/$branch${if (release) "/release" else "" }"
val request = Request.Builder()
.url(url)
.get()
.build()

client.newCall(request).execute().use { response ->
client.get(url).use { response ->
if (!response.isSuccessful) error("Request failed: ${response.code}")
return response.body!!.charStream().decodeJson()
return response.body.charStream().decodeJson()
}
}

fun getMessageOfTheDay(branch: String = HARD_CODED_BRANCH): MessageOfTheDay {
val url = "$API_V1_ENDPOINT/client/$branch/motd"
val request = Request.Builder()
.url(url)
.get()
.build()

client.newCall(request).execute().use { response ->
client.get(url).use { response ->
if (!response.isSuccessful) error("Request failed: ${response.code}")
return response.body!!.charStream().decodeJson()
return response.body.charStream().decodeJson()
}
}

fun getSettingsList(branch: String = HARD_CODED_BRANCH): List<AutoSettings> {
val url = "$API_V1_ENDPOINT/client/$branch/settings"
val request = Request.Builder()
.url(url)
.get()
.build()

client.newCall(request).execute().use { response ->
client.get(url).use { response ->
if (!response.isSuccessful) error("Request failed: ${response.code}")
return response.body!!.charStream().decodeJson()
return response.body.charStream().decodeJson()
}
}

fun getSettingsScript(branch: String = HARD_CODED_BRANCH, settingId: String): String {
val url = "$API_V1_ENDPOINT/client/$branch/settings/$settingId"
val request = Request.Builder()
.url(url)
.get()
.build()

client.newCall(request).execute().use { response ->
client.get(url).use { response ->
if (!response.isSuccessful) error("Request failed: ${response.code}")
return response.body!!.string()
return response.body.string()
}
}

// TODO: backend not implemented yet
@Deprecated("Removed API")
fun reportSettings(branch: String = HARD_CODED_BRANCH, settingId: String): ReportResponse {
val url = "$API_V1_ENDPOINT/client/$branch/settings/report/$settingId"
val request = Request.Builder()
.url(url)
.get()
.build()

client.newCall(request).execute().use { response ->
client.get(url).use { response ->
if (!response.isSuccessful) error("Request failed: ${response.code}")
return response.body!!.charStream().decodeJson()
return response.body.charStream().decodeJson()
}
}

// TODO: backend not implemented yet
@Deprecated("Removed API")
fun uploadSettings(
branch: String = HARD_CODED_BRANCH,
name: RequestBody,
Expand All @@ -128,14 +105,9 @@ object ClientApi {
.addPart(settingsFile)
.build()

val request = Request.Builder()
.url(url)
.post(requestBody)
.build()

client.newCall(request).execute().use { response ->
client.post(url, requestBody).use { response ->
if (!response.isSuccessful) error("Request failed: ${response.code}")
return response.body!!.charStream().decodeJson()
return response.body.charStream().decodeJson()
}
}
}
50 changes: 25 additions & 25 deletions src/main/java/net/ccbluex/liquidbounce/cape/CapeService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ import net.ccbluex.liquidbounce.event.SessionUpdateEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.utils.client.ClientUtils.LOGGER
import net.ccbluex.liquidbounce.utils.client.MinecraftInstance
import net.ccbluex.liquidbounce.utils.io.HttpUtils
import net.ccbluex.liquidbounce.utils.io.*
import net.ccbluex.liquidbounce.utils.kotlin.SharedScopes
import net.ccbluex.liquidbounce.utils.login.UserUtils
import net.ccbluex.liquidbounce.utils.io.HttpUtils.get
import net.ccbluex.liquidbounce.utils.io.decodeJson
import net.ccbluex.liquidbounce.utils.io.parseJson
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.internal.commonEmptyRequestBody
import java.util.*
import java.util.concurrent.atomic.AtomicLong

Expand Down Expand Up @@ -71,8 +69,6 @@ object CapeService : Listenable, MinecraftInstance {
private val lastUpdate = AtomicLong(0L)
private var refreshJob: Job? = null

private val client = HttpUtils.httpClient

/**
* Refresh cape carriers, capture from the API.
* It will take a list of (uuid, cape_name) tuples.
Expand All @@ -84,19 +80,20 @@ object CapeService : Listenable, MinecraftInstance {
refreshJob = SharedScopes.IO.launch {
runCatching {
// Capture data from API and parse JSON
val (json, code) = get(CAPE_CARRIERS_URL)
if (code != 200) throw RuntimeException("Failed to get cape carriers. Status code: $code")

// Should be a JSON Array. It will fail if not.
// Format: [["8f617b6a-bea0-4af5-8e4b-d026d8fa9de8", "marco"], ...]
capeCarriers = json.parseJson().asJsonArray.associate { objInArray ->
// Should be a JSON Array. It will fail if not.
val arrayInArray = objInArray.asJsonArray
// 1. is UUID 2. is name of cape
val uuid = arrayInArray[0].asString
val name = arrayInArray[1].asString

UUID.fromString(uuid) to name
HttpClient.get(CAPE_CARRIERS_URL).use {
if (!it.isSuccessful) {
throw RuntimeException("Failed to get cape carriers. Status code: ${it.code}")
}

it.body.charStream().readJson().asJsonArray.associate { objInArray ->
// Should be a JSON Array. It will fail if not.
val arrayInArray = objInArray.asJsonArray
// 1. is UUID 2. is name of cape
val uuid = arrayInArray[0].asString
val name = arrayInArray[1].asString

UUID.fromString(uuid) to name
}
}

lastUpdate.set(currentTime)
Expand Down Expand Up @@ -137,10 +134,13 @@ object CapeService : Listenable, MinecraftInstance {
.addHeader("Authorization", token)
.build()

client.newCall(request).execute().use { response ->
HttpClient.newCall(request).execute().use { response ->
if (response.isSuccessful) {
val json = response.body?.charStream()?.decodeJson<LoginResponse>()
?: throw RuntimeException("Failed to decode JSON of self cape. Response: ${response.body?.string()}")
val json = try {
response.body.charStream().decodeJson<LoginResponse>()
} catch (e: Exception) {
throw RuntimeException("Failed to decode JSON of self cape. Response: ${response.body.string()}", e)
}

clientCapeUser = CapeSelfUser(token, json.enabled, json.uuid, json.cape)
LOGGER.info("Logged in successfully. Cape: ${json.cape}")
Expand All @@ -167,14 +167,14 @@ object CapeService : Listenable, MinecraftInstance {
.url(SELF_CAPE_URL)
.apply {
if (capeUser.enabled) delete()
else put("".toRequestBody(null))
else put(commonEmptyRequestBody)
}
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", capeUser.token)
.build()

try {
val statusCode = client.newCall(request).execute().use { response ->
val statusCode = HttpClient.newCall(request).execute().use { response ->
response.code
}

Expand Down Expand Up @@ -216,7 +216,7 @@ object CapeService : Listenable, MinecraftInstance {
.addHeader("Authorization", capeUser.token)
.build()

client.newCall(request).execute().use { response ->
HttpClient.newCall(request).execute().use { response ->
if (response.code == 204) { // HTTP 204 No Content
capeUser.uuid = uuid
LOGGER.info("[Donator Cape] Successfully transferred cape to $uuid ($username)")
Expand Down
32 changes: 15 additions & 17 deletions src/main/java/net/ccbluex/liquidbounce/config/SettingsUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
*/
package net.ccbluex.liquidbounce.config

import kotlinx.coroutines.runBlocking
import net.ccbluex.liquidbounce.LiquidBounce.moduleManager
import net.ccbluex.liquidbounce.api.ClientApi
import net.ccbluex.liquidbounce.features.module.Module
import net.ccbluex.liquidbounce.file.FileManager
import net.ccbluex.liquidbounce.utils.attack.EntityUtils.Targets
import net.ccbluex.liquidbounce.utils.client.chat
import net.ccbluex.liquidbounce.utils.io.HttpUtils
import net.ccbluex.liquidbounce.utils.io.HttpClient
import net.ccbluex.liquidbounce.utils.io.get
import net.ccbluex.liquidbounce.utils.kotlin.StringUtils
import net.ccbluex.liquidbounce.utils.render.ColorUtils.translateAlternateColorCodes
import org.lwjgl.input.Keyboard
Expand All @@ -23,6 +23,18 @@ import kotlin.reflect.KMutableProperty0
*/
object SettingsUtils {

fun loadFromUrl(url: String) = if (url.startsWith("http")) {
HttpClient.get(url).use {
if (!it.isSuccessful) {
error(it.message)
}

it.body.string()
}
} else {
ClientApi.getSettingsScript(settingId = url)
}

/**
* Execute settings script.
* @param script The script to apply.
Expand Down Expand Up @@ -64,21 +76,7 @@ object SettingsUtils {
"load" -> {
val url = StringUtils.toCompleteString(args, 1)
runCatching {
val settings = if (url.startsWith("http")) {
val (text, code) = HttpUtils.get(url)

if (code != 200) {
error(text)
}

text
} else {
runBlocking {
ClientApi.getSettingsScript(settingId = url)
}
}

applyScript(settings)
applyScript(loadFromUrl(url))
}.onSuccess {
chat("§7[§3§lAutoSettings§7] §7Loaded settings §a§l$url§7.")
}.onFailure {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import net.ccbluex.liquidbounce.features.command.Command
import net.ccbluex.liquidbounce.ui.client.hud.HUD.addNotification
import net.ccbluex.liquidbounce.ui.client.hud.element.elements.Notification
import net.ccbluex.liquidbounce.utils.client.ClientUtils.LOGGER
import net.ccbluex.liquidbounce.utils.io.HttpUtils.get
import net.ccbluex.liquidbounce.utils.io.MiscUtils
import net.ccbluex.liquidbounce.utils.kotlin.SharedScopes
import net.ccbluex.liquidbounce.utils.kotlin.StringUtils
Expand Down Expand Up @@ -68,16 +67,7 @@ object SettingsCommand : Command("autosettings", "autosetting", "settings", "set
}

try {
val settings = if (args[2].startsWith("http")) {
val (text, code) = get(args[2])
if (code != 200) {
error(text)
}

text
} else {
runBlocking { ClientApi.getSettingsScript(settingId = args[2]) }
}
val settings = SettingsUtils.loadFromUrl(args[2])

chat("Applying settings...")
SettingsUtils.applyScript(settings)
Expand Down
Loading

0 comments on commit b2741c8

Please sign in to comment.