Plex/src/main/java/dev/plex/util/MojangUtils.java

62 lines
2.1 KiB
Java
Raw Normal View History

package dev.plex.util;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
2022-01-27 21:23:01 +00:00
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
2022-02-07 05:06:55 +00:00
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
public class MojangUtils
{
2022-02-07 05:06:55 +00:00
public static AshconInfo getInfo(String nameOrUuid)
{
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("https://api.ashcon.app/mojang/v2/user/" + nameOrUuid);
try
{
HttpResponse response = client.execute(get);
2022-02-07 05:06:55 +00:00
if (response == null || response.getEntity() == null)
{
return null;
}
String json = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
JSONObject object = new JSONObject(json);
2022-02-07 05:06:55 +00:00
if (!object.isNull("code") && object.getInt("code") == 404)
{
return null;
}
client.close();
2022-02-07 05:59:26 +00:00
AshconInfo ashconInfo = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>)(json1, typeOfT, context) ->
2022-02-07 05:06:55 +00:00
LocalDateTime.ofInstant(Instant.from(DateTimeFormatter.ISO_INSTANT.parse(json1.getAsJsonPrimitive().getAsString())), ZoneId.systemDefault())).create().fromJson(json, AshconInfo.class);
2022-02-07 05:59:26 +00:00
Arrays.sort(ashconInfo.getUsernameHistories(), (o1, o2) ->
{
2022-02-07 05:06:55 +00:00
if (o1.getLocalDateTime() == null || o2.getLocalDateTime() == null)
{
2022-02-07 05:06:55 +00:00
return 1;
}
2022-02-07 05:06:55 +00:00
return o1.getLocalDateTime().compareTo(o2.getLocalDateTime());
});
2022-02-07 05:06:55 +00:00
return ashconInfo;
2022-01-30 21:03:47 +00:00
}
catch (IOException e)
{
e.printStackTrace();
2022-02-07 05:06:55 +00:00
return null;
}
}
}