2021-01-06 19:02:35 +01:00
|
|
|
package net.minestom.server.utils.mojang;
|
|
|
|
|
2021-06-20 22:32:06 +02:00
|
|
|
import com.github.benmanes.caffeine.cache.Cache;
|
|
|
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
2021-01-06 19:02:35 +01:00
|
|
|
import com.google.gson.JsonObject;
|
|
|
|
import com.google.gson.JsonParser;
|
2021-01-19 18:25:54 +01:00
|
|
|
import net.minestom.server.MinecraftServer;
|
2021-01-06 19:02:35 +01:00
|
|
|
import net.minestom.server.utils.url.URLUtils;
|
2021-11-07 11:59:10 +01:00
|
|
|
import org.jetbrains.annotations.Blocking;
|
2021-01-06 19:02:35 +01:00
|
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
import org.jetbrains.annotations.Nullable;
|
|
|
|
|
|
|
|
import java.io.IOException;
|
2021-03-05 23:03:18 +01:00
|
|
|
import java.util.concurrent.TimeUnit;
|
2021-01-06 19:02:35 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Utils class using mojang API.
|
|
|
|
*/
|
|
|
|
public final class MojangUtils {
|
2021-11-07 14:46:26 +01:00
|
|
|
private static final String FROM_UUID_URL = "https://sessionserver.mojang.com/session/minecraft/profile/%s?unsigned=false";
|
|
|
|
private static final String FROM_USERNAME_URL = "https://api.mojang.com/users/profiles/minecraft/%s";
|
|
|
|
private static final Cache<String, JsonObject> URL_CACHE = Caffeine.newBuilder()
|
2021-03-05 23:03:18 +01:00
|
|
|
.expireAfterWrite(30, TimeUnit.SECONDS)
|
|
|
|
.softValues()
|
|
|
|
.build();
|
|
|
|
|
2021-11-07 11:59:10 +01:00
|
|
|
@Blocking
|
|
|
|
public static @Nullable JsonObject fromUuid(@NotNull String uuid) {
|
2021-11-08 08:49:25 +01:00
|
|
|
return retrieve(String.format(FROM_UUID_URL, uuid));
|
2021-01-06 19:02:35 +01:00
|
|
|
}
|
|
|
|
|
2021-11-07 11:59:10 +01:00
|
|
|
@Blocking
|
|
|
|
public static @Nullable JsonObject fromUsername(@NotNull String username) {
|
2021-11-08 08:49:25 +01:00
|
|
|
return retrieve(String.format(FROM_USERNAME_URL, username));
|
2021-03-05 23:03:18 +01:00
|
|
|
}
|
|
|
|
|
2021-11-08 08:49:25 +01:00
|
|
|
private static @Nullable JsonObject retrieve(@NotNull String url) {
|
|
|
|
return URL_CACHE.get(url, s -> {
|
2021-11-07 14:46:26 +01:00
|
|
|
try {
|
|
|
|
// Retrieve from the rate-limited Mojang API
|
|
|
|
final String response = URLUtils.getText(url);
|
2021-11-15 19:23:20 +01:00
|
|
|
// If our response is "", that means the url did not get a proper object from the url
|
|
|
|
// So the username or UUID was invalid, and therefore we return null
|
|
|
|
if(response.isEmpty()) {
|
|
|
|
return null;
|
|
|
|
}
|
2021-11-07 14:46:26 +01:00
|
|
|
return JsonParser.parseString(response).getAsJsonObject();
|
|
|
|
} catch (IOException e) {
|
|
|
|
MinecraftServer.getExceptionManager().handleException(e);
|
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
});
|
2021-01-06 19:02:35 +01:00
|
|
|
}
|
|
|
|
}
|