Skip to content

Commit

Permalink
Revert "LEGACY: Optimize ClientAPI Code & Etc (CCBlueX#2791)" (CCBlue…
Browse files Browse the repository at this point in the history
  • Loading branch information
EclipsesDev committed Apr 13, 2024
1 parent 4ef81ea commit c3f4319
Show file tree
Hide file tree
Showing 47 changed files with 320 additions and 432 deletions.
177 changes: 87 additions & 90 deletions src/main/java/net/ccbluex/liquidbounce/LiquidBounce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
*/
package net.ccbluex.liquidbounce

import kotlinx.coroutines.runBlocking
import net.ccbluex.liquidbounce.api.ClientUpdate.gitInfo
import net.ccbluex.liquidbounce.api.loadSettings
import net.ccbluex.liquidbounce.api.messageOfTheDay
Expand Down Expand Up @@ -89,118 +88,116 @@ object LiquidBounce {
* Execute if client will be started
*/
fun startClient() {
runBlocking {
isStarting = true

LOGGER.info("Starting $CLIENT_NAME $clientVersionText $clientCommit, by $CLIENT_CREATOR")

// Load languages
loadLanguages()

// Register listeners
registerListener(RotationUtils)
registerListener(ClientFixes)
registerListener(BungeeCordSpoof)
registerListener(CapeService)
registerListener(InventoryUtils)
registerListener(MiniMapRegister)
registerListener(TickedActions)
registerListener(MovementUtils)
registerListener(PacketUtils)
registerListener(TimerBalanceUtils)

// Load client fonts
loadFonts()

// Load settings
loadSettings(false) {
LOGGER.info("Successfully loaded ${it.size} settings.")
}

// Register commands
registerCommands()
isStarting = true

LOGGER.info("Starting $CLIENT_NAME $clientVersionText $clientCommit, by $CLIENT_CREATOR")

// Load languages
loadLanguages()

// Register listeners
registerListener(RotationUtils)
registerListener(ClientFixes)
registerListener(BungeeCordSpoof)
registerListener(CapeService)
registerListener(InventoryUtils)
registerListener(MiniMapRegister)
registerListener(TickedActions)
registerListener(MovementUtils)
registerListener(PacketUtils)
registerListener(TimerBalanceUtils)

// Load client fonts
loadFonts()

// Load settings
loadSettings(false) {
LOGGER.info("Successfully loaded ${it.size} settings.")
}

// Setup module manager and register modules
registerModules()
// Register commands
registerCommands()

try {
// Remapper
loadSrg()
// Setup module manager and register modules
registerModules()

if (!Remapper.mappingsLoaded) {
error("Failed to load SRG mappings.")
}
try {
// Remapper
loadSrg()

// ScriptManager
loadScripts()
enableScripts()
} catch (throwable: Throwable) {
LOGGER.error("Failed to load scripts.", throwable)
if (!Remapper.mappingsLoaded) {
error("Failed to load SRG mappings.")
}

// Load configs
loadAllConfigs()
// ScriptManager
loadScripts()
enableScripts()
} catch (throwable: Throwable) {
LOGGER.error("Failed to load scripts.", throwable)
}

// Update client window
updateClientWindow()
// Load configs
loadAllConfigs()

// Tabs (Only for Forge!)
if (hasForge()) {
BlocksTab()
ExploitsTab()
HeadsTab()
}
// Update client window
updateClientWindow()

// Disable optifine fastrender
disableFastRender()
// Tabs (Only for Forge!)
if (hasForge()) {
BlocksTab()
ExploitsTab()
HeadsTab()
}

// Load alt generators
loadActiveGenerators()
// Disable optifine fastrender
disableFastRender()

// Load message of the day
messageOfTheDay?.message?.let { LOGGER.info("Message of the day: $it") }
// Load alt generators
loadActiveGenerators()

// Setup Discord RPC
if (showRichPresenceValue) {
thread {
try {
clientRichPresence.setup()
} catch (throwable: Throwable) {
LOGGER.error("Failed to setup Discord RPC.", throwable)
}
}
}
// Load message of the day
messageOfTheDay?.message?.let { LOGGER.info("Message of the day: $it") }

// Login into known token if not empty
if (CapeService.knownToken.isNotBlank()) {
runCatching {
CapeService.login(CapeService.knownToken)
}.onFailure {
LOGGER.error("Failed to login into known cape token.", it)
}.onSuccess {
LOGGER.info("Successfully logged in into known cape token.")
// Setup Discord RPC
if (showRichPresenceValue) {
thread {
try {
clientRichPresence.setup()
} catch (throwable: Throwable) {
LOGGER.error("Failed to setup Discord RPC.", throwable)
}
}
}

// Refresh cape service
CapeService.refreshCapeCarriers {
LOGGER.info("Successfully loaded ${CapeService.capeCarriers.size} cape carriers.")
}

// Load background
// Login into known token if not empty
if (CapeService.knownToken.isNotBlank()) {
runCatching {
FileManager.loadBackground()
CapeService.login(CapeService.knownToken)
}.onFailure {
LOGGER.error("Failed to load background.", it)
LOGGER.error("Failed to login into known cape token.", it)
}.onSuccess {
LOGGER.info("Successfully loaded background.")
LOGGER.info("Successfully logged in into known cape token.")
}
}

// Set is starting status
isStarting = false
// Refresh cape service
CapeService.refreshCapeCarriers {
LOGGER.info("Successfully loaded ${CapeService.capeCarriers.size} cape carriers.")
}

callEvent(StartupEvent())
// Load background
runCatching {
FileManager.loadBackground()
}.onFailure {
LOGGER.error("Failed to load background.", it)
}.onSuccess {
LOGGER.info("Successfully loaded background.")
}

// Set is starting status
isStarting = false

callEvent(StartupEvent())
}

/**
Expand Down
93 changes: 18 additions & 75 deletions src/main/java/net/ccbluex/liquidbounce/api/ClientApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
package net.ccbluex.liquidbounce.api

import com.google.gson.annotations.SerializedName
import kotlinx.coroutines.*
import net.ccbluex.liquidbounce.LiquidBounce
import net.ccbluex.liquidbounce.LiquidBounce.CLIENT_NAME
import net.ccbluex.liquidbounce.file.FileManager.PRETTY_GSON
import net.ccbluex.liquidbounce.utils.misc.HttpUtils.post

import net.ccbluex.liquidbounce.utils.misc.HttpUtils.request
import net.ccbluex.liquidbounce.utils.misc.RandomUtils
Expand Down Expand Up @@ -38,26 +37,26 @@ object ClientApi {
*/
private const val HARD_CODED_BRANCH = "legacy"

suspend fun requestNewestBuildEndpoint(branch: String = HARD_CODED_BRANCH, release: Boolean = false) = endpointRequest<Build>("version/newest/$branch${if (release) "/release" else "" }")
fun requestNewestBuildEndpoint(branch: String = HARD_CODED_BRANCH, release: Boolean = false) = endpointRequest<Build>("version/newest/$branch${if (release) "/release" else "" }")

suspend fun requestMessageOfTheDayEndpoint(branch: String = HARD_CODED_BRANCH) = endpointRequest<MessageOfTheDay>("client/$branch/motd")
fun requestMessageOfTheDayEndpoint(branch: String = HARD_CODED_BRANCH) = endpointRequest<MessageOfTheDay>("client/$branch/motd")


suspend fun requestSettingsList(branch: String = HARD_CODED_BRANCH) = endpointRequest<Array<AutoSettings>>("client/$branch/settings")
fun requestSettingsList(branch: String = HARD_CODED_BRANCH) = endpointRequest<Array<AutoSettings>>("client/$branch/settings")

suspend fun requestSettingsScript(settingId: String, branch: String = HARD_CODED_BRANCH) = textEndpointRequest("client/$branch/settings/$settingId")
fun requestSettingsScript(settingId: String, branch: String = HARD_CODED_BRANCH) = textEndpointRequest("client/$branch/settings/$settingId")

/**
* Reports settings for any reason
*
* todo: add reason and change to POST instead of GET
*/
suspend fun reportSettings(settingId: String, branch: String = HARD_CODED_BRANCH) = endpointRequest<ReportResponse>("client/$branch/settings/report/$settingId")
fun reportSettings(settingId: String, branch: String = HARD_CODED_BRANCH) = endpointRequest<ReportResponse>("client/$branch/settings/report/$settingId")

/**
* Uploads settings to the API
*/
suspend fun uploadSettings(name: String, contributors: String, script: String, branch: String = HARD_CODED_BRANCH): UploadResponse {
fun uploadSettings(name: String, contributors: String, script: String, branch: String = HARD_CODED_BRANCH): UploadResponse {
val res = textEndpointPost("client/$branch/settings/upload") {
// Create http entity with settings_file as file, name as string, contributors as string to form body

Expand All @@ -81,7 +80,7 @@ object ClientApi {
/**
* Request endpoint and parse JSON to data class
*/
private suspend inline fun <reified T> endpointRequest(endpoint: String): T = parse(textEndpointRequest(endpoint))
private inline fun <reified T> endpointRequest(endpoint: String): T = parse(textEndpointRequest(endpoint))

/**
* Parse JSON to data class
Expand All @@ -92,19 +91,7 @@ object ClientApi {
* User agent
* LiquidBounce/<version> (<commit>, <branch>, <build-type>, <platform>)
*/
private suspend fun getEndpointAgent(): String {
return GlobalScope.async {
"$CLIENT_NAME/${LiquidBounce.clientVersionText} " +
"(${LiquidBounce.clientCommit}, ${LiquidBounce.clientBranch}, " +
"${if (LiquidBounce.IN_DEV) "dev" else "release"}, ${System.getProperty("os.name")})"
}.await()
}

private val ENDPOINT_AGENT: String by lazy {
runBlocking {
getEndpointAgent()
}
}
private val ENDPOINT_AGENT = "${LiquidBounce.CLIENT_NAME}/${LiquidBounce.clientVersionText} (${LiquidBounce.clientCommit}, ${LiquidBounce.clientBranch}, ${if (LiquidBounce.IN_DEV) "dev" else "release"}, ${System.getProperty("os.name")})"

/**
* Session token
Expand All @@ -116,9 +103,9 @@ object ClientApi {
/**
* Request to endpoint with custom agent and session token
*/
private suspend fun textEndpointRequest(endpoint: String): String {
val (response, code) = fetchDataAsync(
url = "$API_ENDPOINT/$endpoint",
private fun textEndpointRequest(endpoint: String): String {
val (response, code) = request(
"$API_ENDPOINT/$endpoint",
method = "GET",
agent = ENDPOINT_AGENT,
headers = arrayOf("X-Session-Token" to SESSION_TOKEN)
Expand All @@ -131,56 +118,12 @@ object ClientApi {
}
}

private suspend fun textEndpointPost(endpoint: String, entity: suspend () -> HttpEntity): String {
val response = fetchEntityAsync(
url = "$API_ENDPOINT/$endpoint",
method = "POST",
agent = ENDPOINT_AGENT,
headers = arrayOf("X-Session-Token" to SESSION_TOKEN)
) { entity.invoke() }

if (response.second != 200) {
error(response.first)
} else {
return response.first
}
}

private suspend fun fetchDataAsync(
url: String,
method: String,
agent: String,
headers: Array<Pair<String, String>>
): Pair<String, Int> = coroutineScope {
async(Dispatchers.IO) {
val (response, code) = request(url, method, agent, headers)
response to code
}.await()
}

private suspend fun fetchEntityAsync(
url: String,
method: String,
agent: String,
headers: Array<Pair<String, String>>,
function: suspend () -> HttpEntity
): Pair<String, Int> = coroutineScope {
async(Dispatchers.IO) {
val (response, code) = request(url, method, agent, headers, function)
response to code
}.await()
}

private suspend fun request(
url: String,
method: String,
agent: String = ENDPOINT_AGENT,
headers: Array<Pair<String, String>> = emptyArray(),
function: suspend () -> HttpEntity
): Pair<String, Int> = coroutineScope {
val entity = function()
request(url, method, agent, headers) { entity }
}
private fun textEndpointPost(endpoint: String, entity: () -> HttpEntity) = post(
"$API_ENDPOINT/$endpoint",
agent = ENDPOINT_AGENT,
headers = arrayOf("X-Session-Token" to SESSION_TOKEN),
entity = entity
)

}

Expand Down
Loading

0 comments on commit c3f4319

Please sign in to comment.