Skip to content

Commit

Permalink
fix: send fake requests to the Mojang API to prevent 429 errors
Browse files Browse the repository at this point in the history
  • Loading branch information
My-Name-Is-Jeff committed Feb 9, 2024
1 parent 674be29 commit 178decb
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/main/kotlin/gg/skytils/skytilsmod/utils/MojangUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import gg.essential.lib.caffeine.cache.Caffeine
import gg.skytils.skytilsmod.Skytils.Companion.client
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.Serializable
import net.minecraft.client.entity.EntityOtherPlayerMP
Expand All @@ -32,11 +33,14 @@ import net.minecraftforge.fml.common.eventhandler.EventPriority
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.fixedRateTimer


object MojangUtil {
private val uuidToUsername: Cache<UUID, String>
private val usernameToUuid: Cache<String, UUID>
private val requestCount = AtomicInteger()

init {
Caffeine.newBuilder()
Expand Down Expand Up @@ -64,7 +68,7 @@ object MojangUtil {
suspend fun getUUIDFromUsername(name: String): UUID? {
val username = name.lowercase()
return usernameToUuid.getIfPresent(username) ?: run {
client.get("https://api.mojang.com/users/profiles/minecraft/$username").let {
makeMojangRequest("https://api.mojang.com/users/profiles/minecraft/$username").let {
when (it.status) {
HttpStatusCode.OK -> {
val (id, _) = it.body<ProfileResponse>()
Expand All @@ -82,7 +86,7 @@ object MojangUtil {

suspend fun getUsernameFromUUID(uuid: UUID): String? {
return uuidToUsername.getIfPresent(uuid) ?: run {
client.get("https://api.minecraftservices.com/minecraft/profile/lookup/${uuid}").let {
makeMojangRequest("https://api.minecraftservices.com/minecraft/profile/lookup/${uuid}").let {
when (it.status) {
HttpStatusCode.OK -> {
val (_, name) = it.body<ProfileResponse>()
Expand All @@ -99,6 +103,22 @@ object MojangUtil {
}
}

init {
fixedRateTimer("Mojang-Fake-Requests-Insert", startAt = Date((System.currentTimeMillis() / 60000) * 60000 + 48000), period = 60_000L) {
requestCount.set(0)
}
}

/**
* @see <a href="https://bugs.mojang.com/browse/WEB-6830">WEB-6830</a>
*/
private suspend fun makeMojangRequest(url: String): HttpResponse {
if (requestCount.incrementAndGet() % 6 == 0) {
client.get("https://api.mojang.com/users/profiles/minecraft/SlashSlayer?ts=${System.currentTimeMillis()}")
}
return client.get(url)
}

@Serializable
private data class ProfileResponse(
@Serializable(with = UUIDAsString::class) val id: UUID,
Expand Down

0 comments on commit 178decb

Please sign in to comment.