Skip to content

Commit

Permalink
scope use
Browse files Browse the repository at this point in the history
  • Loading branch information
1zun4 committed Jan 2, 2025
1 parent b9452a7 commit a5dacfe
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 108 deletions.
4 changes: 2 additions & 2 deletions src/main/kotlin/net/ccbluex/liquidbounce/LiquidBounce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
*/
package net.ccbluex.liquidbounce

import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.models.auth.ClientAccount
import net.ccbluex.liquidbounce.api.services.auth.OAuthClient
import net.ccbluex.liquidbounce.api.services.client.ClientUpdate.gitInfo
import net.ccbluex.liquidbounce.api.services.client.ClientUpdate.hasUpdate
import net.ccbluex.liquidbounce.api.thirdparty.IpInfoApi
Expand Down Expand Up @@ -261,7 +261,7 @@ object LiquidBounce : EventListener {

// Check if client account is available
if (ClientAccountManager.clientAccount != ClientAccount.EMPTY_ACCOUNT) {
OAuthClient.runWithScope {
withScope {
runCatching {
ClientAccountManager.clientAccount.renew()
}.onFailure {
Expand Down
12 changes: 6 additions & 6 deletions src/main/kotlin/net/ccbluex/liquidbounce/api/core/BaseApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ abstract class BaseApi(protected val baseUrl: String) {
protected suspend inline fun <reified T> request(
endpoint: String,
method: HttpMethod,
noinline headers: Headers.Builder.() -> Unit = {},
crossinline headers: Headers.Builder.() -> Unit = {},
body: RequestBody? = null
): T = HttpClient.request("$baseUrl$endpoint", method, headers = {
add("X-Session-Token", SESSION_TOKEN)
Expand All @@ -56,30 +56,30 @@ abstract class BaseApi(protected val baseUrl: String) {

protected suspend inline fun <reified T> get(
endpoint: String,
noinline headers: Headers.Builder.() -> Unit = {}
crossinline headers: Headers.Builder.() -> Unit = {}
): T = request(endpoint, HttpMethod.GET, headers)

protected suspend inline fun <reified T> post(
endpoint: String,
body: RequestBody? = null,
noinline headers: Headers.Builder.() -> Unit = {}
crossinline headers: Headers.Builder.() -> Unit = {}
): T = request(endpoint, HttpMethod.POST, headers, body)

protected suspend inline fun <reified T> put(
endpoint: String,
body: RequestBody? = null,
noinline headers: Headers.Builder.() -> Unit = {}
crossinline headers: Headers.Builder.() -> Unit = {}
): T = request(endpoint, HttpMethod.PUT, headers, body)

protected suspend inline fun <reified T> patch(
endpoint: String,
body: RequestBody? = null,
noinline headers: Headers.Builder.() -> Unit = {}
crossinline headers: Headers.Builder.() -> Unit = {}
): T = request(endpoint, HttpMethod.PATCH, headers, body)

protected suspend inline fun <reified T> delete(
endpoint: String,
noinline headers: Headers.Builder.() -> Unit = {}
crossinline headers: Headers.Builder.() -> Unit = {}
): T = request(endpoint, HttpMethod.DELETE, headers)

}
10 changes: 9 additions & 1 deletion src/main/kotlin/net/ccbluex/liquidbounce/api/core/HttpClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
*/
package net.ccbluex.liquidbounce.api.core

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import net.ccbluex.liquidbounce.LiquidBounce
import net.ccbluex.liquidbounce.config.gson.util.decode
import net.minecraft.client.texture.NativeImage
Expand All @@ -34,6 +38,10 @@ import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

fun withScope(block: suspend CoroutineScope.() -> Unit) = scope.launch { block() }

object HttpClient {

val DEFAULT_AGENT = "${LiquidBounce.CLIENT_NAME}/${LiquidBounce.clientVersion}" +
Expand Down Expand Up @@ -131,4 +139,4 @@ suspend inline fun <reified T> Response.parse(): T {
fun String.asJson() = toRequestBody(HttpClient.JSON_MEDIA_TYPE)
fun String.asForm() = toRequestBody(HttpClient.FORM_MEDIA_TYPE)

class HttpException(val code: Int, message: String) : Exception(message)
class HttpException(val code: Int, message: String) : Exception("HTTP $code: $message")
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,9 @@ import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.http.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import net.ccbluex.liquidbounce.api.core.AUTH_AUTHORIZE_URL
import net.ccbluex.liquidbounce.api.core.AUTH_CLIENT_ID
import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.models.auth.ClientAccount
import net.ccbluex.liquidbounce.api.models.auth.OAuthSession
import java.net.InetSocketAddress
Expand All @@ -44,16 +41,10 @@ import kotlin.coroutines.suspendCoroutine
*/
object OAuthClient {

private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())

private var serverPort: Int? = null
@Volatile
private var authCodeContinuation: Continuation<String>? = null

fun runWithScope(block: suspend CoroutineScope.() -> Unit) {
scope.launch { block() }
}

/**
* Start the OAuth authentication flow
*
Expand Down Expand Up @@ -89,7 +80,7 @@ object OAuthClient {
}

private suspend fun startNettyServer(): Int = suspendCoroutine { cont ->
scope.launch {
withScope {
runCatching {
val bossGroup = NioEventLoopGroup(1)
val workerGroup = NioEventLoopGroup()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
*
* Copyright (c) 2015 - 2025 CCBlueX
*
* LiquidBounce is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LiquidBounce is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
*/
package net.ccbluex.liquidbounce.api.thirdparty

import net.ccbluex.liquidbounce.api.core.BaseApi

object MojangApi : BaseApi("https://api.mojang.com") {

suspend fun getNames(uuidAsString: String): List<UsernameRecord> =
get<List<UsernameRecord>>("/user/profiles/$uuidAsString/names")

data class UsernameRecord(val name: String, val changedToAt: Int?)

}
12 changes: 4 additions & 8 deletions src/main/kotlin/net/ccbluex/liquidbounce/config/AutoConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import com.google.gson.JsonObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import net.ccbluex.liquidbounce.LiquidBounce
import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.models.client.AutoSettings
import net.ccbluex.liquidbounce.api.services.client.ClientApi
import net.ccbluex.liquidbounce.api.types.enums.AutoSettingsStatusType
Expand All @@ -35,7 +36,6 @@ import net.ccbluex.liquidbounce.features.module.ModuleManager
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleClickGui
import net.ccbluex.liquidbounce.utils.client.*
import net.minecraft.util.Formatting
import net.minecraft.util.Util
import java.io.Writer
import java.text.SimpleDateFormat
import java.util.*
Expand Down Expand Up @@ -73,8 +73,6 @@ object AutoConfig {
}
}

fun startLoaderTask(task: Runnable) = Util.getDownloadWorkerExecutor().execute(task)

inline fun withLoading(block: () -> Unit) {
loadingNow = true
try {
Expand All @@ -84,13 +82,11 @@ object AutoConfig {
}
}

fun loadAutoConfig(autoConfig: AutoSettings) = startLoaderTask {
fun loadAutoConfig(autoConfig: AutoSettings) = withScope {
withLoading {
runCatching {
runBlocking(Dispatchers.IO) {
ClientApi.requestSettingsScript(autoConfig.settingId).apply {
ConfigSystem.deserializeConfigurable(ModuleManager.modulesConfigurable, reader(), publicGson)
}
ClientApi.requestSettingsScript(autoConfig.settingId).apply {
ConfigSystem.deserializeConfigurable(ModuleManager.modulesConfigurable, reader(), publicGson)
}
}.onFailure {
notification("Auto Config", "Failed to load config ${autoConfig.name}.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@
*/
package net.ccbluex.liquidbounce.features.command.commands.client

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import net.ccbluex.liquidbounce.api.core.HttpClient
import net.ccbluex.liquidbounce.api.core.HttpMethod
import net.ccbluex.liquidbounce.api.core.parse
import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.services.client.ClientApi
import net.ccbluex.liquidbounce.config.AutoConfig
import net.ccbluex.liquidbounce.config.AutoConfig.configs
Expand Down Expand Up @@ -149,16 +148,14 @@ object CommandConfig : CommandFactory {
val modules = ModuleManager.parseModulesFromParameter(moduleNames)

// Load the config in a separate thread to prevent the client from freezing
AutoConfig.startLoaderTask {
withScope {
runCatching {
runBlocking(Dispatchers.IO) {
if (name.startsWith("http")) {
// Load the config from the specified URL
HttpClient.request(name, HttpMethod.GET).parse<String>().reader()
} else {
// Get online config from API
ClientApi.requestSettingsScript(name).reader()
}
if (name.startsWith("http")) {
// Load the config from the specified URL
HttpClient.request(name, HttpMethod.GET).parse<String>().reader()
} else {
// Get online config from API
ClientApi.requestSettingsScript(name).reader()
}
}.onSuccess { sourceReader ->
AutoConfig.withLoading {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package net.ccbluex.liquidbounce.features.command.commands.client.client

import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.models.auth.ClientAccount.Companion.EMPTY_ACCOUNT
import net.ccbluex.liquidbounce.api.services.auth.OAuthClient
import net.ccbluex.liquidbounce.api.services.auth.OAuthClient.startAuth
import net.ccbluex.liquidbounce.config.ConfigSystem
import net.ccbluex.liquidbounce.features.command.builder.CommandBuilder
Expand All @@ -28,7 +28,7 @@ object CommandClientAccountSubcommand {
}

chat(regular("Getting user information..."))
OAuthClient.runWithScope {
withScope {
runCatching {
val account = ClientAccountManager.clientAccount
account.updateInfo()
Expand All @@ -53,7 +53,7 @@ object CommandClientAccountSubcommand {
}

chat(regular("Logging out..."))
OAuthClient.runWithScope {
withScope {
ClientAccountManager.clientAccount = EMPTY_ACCOUNT
ConfigSystem.storeConfigurable(ClientAccountManager)
chat(regular("Successfully logged out."))
Expand All @@ -68,7 +68,7 @@ object CommandClientAccountSubcommand {
}

chat(regular("Starting OAuth authorization process..."))
OAuthClient.runWithScope {
withScope {
val account = startAuth { Util.getOperatingSystem().open(it) }
ClientAccountManager.clientAccount = account
ConfigSystem.storeConfigurable(ClientAccountManager)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@
*/
package net.ccbluex.liquidbounce.features.cosmetic

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.Job
import net.ccbluex.liquidbounce.api.core.withScope
import net.ccbluex.liquidbounce.api.models.auth.ClientAccount
import net.ccbluex.liquidbounce.api.models.cosmetics.Cosmetic
import net.ccbluex.liquidbounce.api.models.cosmetics.CosmeticCategory
import net.ccbluex.liquidbounce.api.services.auth.OAuthClient
import net.ccbluex.liquidbounce.api.services.cosmetics.CosmeticApi
import net.ccbluex.liquidbounce.config.types.Configurable
import net.ccbluex.liquidbounce.event.EventListener
Expand All @@ -36,9 +35,7 @@ import net.ccbluex.liquidbounce.utils.client.mc
import net.ccbluex.liquidbounce.utils.client.player
import net.ccbluex.liquidbounce.utils.kotlin.toMD5
import net.minecraft.client.session.Session
import net.minecraft.util.Util
import java.util.*
import java.util.concurrent.Future

/**
* A more reliable, safer and stress reduced cosmetics service
Expand All @@ -63,7 +60,7 @@ object CosmeticService : EventListener, Configurable("Cosmetics") {
internal var carriersCosmetics = hashMapOf<UUID, Set<Cosmetic>>()

private val lastUpdate = Chronometer()
private var task: Future<*>? = null
private var task: Job? = null

/**
* Refresh cosmetic carriers if needed from the API in a MD5-hashed UUID set
Expand All @@ -75,11 +72,9 @@ object CosmeticService : EventListener, Configurable("Cosmetics") {
if (task == null) {
// Check if the required time in milliseconds has passed of the REFRESH_DELAY
if (lastUpdate.hasElapsed(REFRESH_DELAY) || force) {
task = Util.getDownloadWorkerExecutor().service.submit {
task = withScope {
runCatching {
carriers = runBlocking(Dispatchers.IO) {
CosmeticApi.getCarriers()
}
carriers = CosmeticApi.getCarriers()
task = null

// Reset timer and start once again
Expand Down Expand Up @@ -112,11 +107,11 @@ object CosmeticService : EventListener, Configurable("Cosmetics") {
clientAccount.cosmetics = emptySet()

// Update cosmetics
OAuthClient.runWithScope {
withScope {
clientAccount.updateCosmetics()

clientAccount.cosmetics?.let { cosmetics ->
done(cosmetics.find { cosmetic -> cosmetic.category == category } ?: return@runWithScope)
done(cosmetics.find { cosmetic -> cosmetic.category == category } ?: return@withScope)
}
}
return
Expand All @@ -136,11 +131,9 @@ object CosmeticService : EventListener, Configurable("Cosmetics") {
// Pre-allocate a set to prevent multiple requests
carriersCosmetics[uuid] = emptySet()

Util.getDownloadWorkerExecutor().execute {
withScope {
runCatching {
val cosmetics = runBlocking(Dispatchers.IO) {
CosmeticApi.getCarrierCosmetics(uuid)
}
val cosmetics = CosmeticApi.getCarrierCosmetics(uuid)
carriersCosmetics[uuid] = cosmetics

done(cosmetics.find { cosmetic -> cosmetic.category == category } ?: return@runCatching)
Expand Down Expand Up @@ -178,7 +171,7 @@ object CosmeticService : EventListener, Configurable("Cosmetics") {
return
}

OAuthClient.runWithScope {
withScope {
runCatching {
clientAccount.transferTemporaryOwnership(uuid)
}.onSuccess {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ data class Head(val name: String, val uuid: UUID, val value: String) {
*/
const val HEAD_DB_API = "https://headdb.org/api/category/all"

val headsCollection by lazy {
val headsCollection by lazy(LazyThreadSafetyMode.NONE) {
runCatching {
logger.info("Loading heads...")
// Load heads from service
Expand Down
Loading

0 comments on commit a5dacfe

Please sign in to comment.