some performance shit #2 and loading non present players, Refactoring project

This commit is contained in:
Hiajen Hiajen 2021-06-21 19:02:28 +02:00
parent 8fea7f4701
commit 9af6f4c073
12 changed files with 339 additions and 200 deletions

View file

@ -28,7 +28,8 @@ dependencies {
include group: 'mysql', name: 'mysql-connector-java', version: '8.0.25' include group: 'mysql', name: 'mysql-connector-java', version: '8.0.25'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.25' implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.25'
//modImplementation(group: 'mysql', name: 'mysql-connector-java', version: '8.0.25') //modImplementation(group: 'mysql', name: 'mysql-connector-java', version: '8.0.25')
include group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
// Fabric API. This is technically optional, but you probably want it anyway. // Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"

View file

@ -8,7 +8,7 @@ org.gradle.jvmargs=-Xmx1G
loader_version=0.11.3 loader_version=0.11.3
# Mod Properties # Mod Properties
mod_version = 1.0.0 mod_version = 1.0.1
maven_group = net.saltymc.eaa maven_group = net.saltymc.eaa
archives_base_name = EAA_MOD archives_base_name = EAA_MOD

View file

@ -1,22 +1,14 @@
package net.saltymc.eaa.commands; package net.saltymc.eaa.commands;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient; import net.saltymc.eaa.function.LobbyFunction;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.text.Text;
import net.saltymc.eaa.util.database.DB_Player;
import net.saltymc.eaa.util.database.DB_Tag; import net.saltymc.eaa.util.database.DB_Tag;
import net.saltymc.eaa.util.mojangApi.PlayerInfo;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal;
public class CheckLobbyCommand extends EaaModCommand{ public class CheckLobbyCommand extends EaaModCommand{
@ -28,39 +20,7 @@ public class CheckLobbyCommand extends EaaModCommand{
public int run(CommandContext<FabricClientCommandSource> context) { public int run(CommandContext<FabricClientCommandSource> context) {
FabricClientCommandSource source = context.getSource(); FabricClientCommandSource source = context.getSource();
try { LobbyFunction.checkLobby(source);
List<String> uuids = new ArrayList<>();
MinecraftClient.getInstance().getNetworkHandler().getPlayerList().forEach(x -> uuids.add(x.getProfile().getId().toString()));
int dangerLvl = 0; // 0 = nothing; 1 = idiot; 2 = hacker
for (String uuid: uuids){
TagCommand.loadPlayer(uuid, false);
if (TagCommand.getHashMap().containsKey(uuid)){
DB_Tag.Type type = TagCommand.getHashMap().get(uuid).getType();
if (type == DB_Tag.Type.HACKER){
dangerLvl = 2;
break;
} else if (type == DB_Tag.Type.IDIOT){
dangerLvl = 1;
}
}
}
switch (dangerLvl){
case 0:
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.WORLD_BACKUP, Text.of("OKAY!"), Text.of("No Hackers found"));
break;
case 1:
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.TUTORIAL_HINT, Text.of("MEH!"), Text.of("There is an Idiot!"));
break;
case 2:
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.WORLD_ACCESS_FAILURE, Text.of("ALARM!"), Text.of("There is a Hacker!"));
}
} catch (Exception e) {
source.sendFeedback(Text.of(e.toString()));
}
return 1; return 1;
} }

View file

@ -4,57 +4,21 @@ import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.argument.EntityArgumentType; import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.text.Text; import net.saltymc.eaa.function.CheckFunction;
import net.saltymc.eaa.util.database.DB_Player;
import net.saltymc.eaa.util.database.DB_Tag;
import net.saltymc.eaa.util.mojangApi.PlayerInfo;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal;
public class CheckPlayerCommand extends EaaModCommand{ public class CheckPlayerCommand extends EaaModCommand{
private static final Map<String, DB_Tag> player_tags = new HashMap<>();
public static final SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
@Override @Override
public int run(CommandContext<FabricClientCommandSource> context) { public int run(CommandContext<FabricClientCommandSource> context) {
FabricClientCommandSource source = context.getSource(); FabricClientCommandSource source = context.getSource();
String player = StringArgumentType.getString(context,"player"); String player = StringArgumentType.getString(context,"player");
try { CheckFunction.checkPlayer(player, source);
String playerUUID = MinecraftClient.getInstance().getNetworkHandler().getPlayerListEntry(player).getProfile().getId().toString();
TagCommand.loadPlayer(playerUUID, true);
List<String> names = PlayerInfo.playerUUIDToNames(playerUUID);
for (int i = 1; i <= names.size(); i++)
source.sendFeedback(Text.of(i + ". " + names.get(i-1)));
List<DB_Tag> tags = DB_Tag.getTagsFromPlayer(DB_Player.getPlayer(playerUUID));
if (tags.size() > 0) {
ListIterator<DB_Tag> it = tags.listIterator(tags.size());
while (it.hasPrevious()) {
DB_Tag curr = it.previous();
source.sendFeedback(Text.of(
dateformat.format(curr.getTagDate()) + " | " + curr.getType().getTag() + " (" + curr.getGrade() + ")"
));
}
} else {
source.sendFeedback(Text.of("Nothing to appeal"));
}
} catch (Exception e) {
source.sendFeedback(Text.of(e.toString()));
}
return 1; return 1;
} }

View file

@ -4,6 +4,7 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.text.Text; import net.minecraft.text.Text;
import net.saltymc.eaa.function.TagFunction;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal;
@ -15,7 +16,7 @@ public class ReloadCommand extends EaaModCommand{
FabricClientCommandSource source = context.getSource(); FabricClientCommandSource source = context.getSource();
try { try {
TagCommand.getHashMap().clear(); TagFunction.getHashMap().clear();
source.sendFeedback(Text.of("Reloaded!")); source.sendFeedback(Text.of("Reloaded!"));
} catch (Exception e) { } catch (Exception e) {

View file

@ -5,26 +5,16 @@ import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.command.argument.EntityArgumentType; import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.text.Text;
import net.saltymc.eaa.util.database.DB_Player; import net.saltymc.eaa.function.TagFunction;
import net.saltymc.eaa.util.database.DB_Tag; import net.saltymc.eaa.util.database.DB_Tag;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument;
import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal;
public class TagCommand extends EaaModCommand{ public class TagCommand extends EaaModCommand{
private static final Map<String, DB_Tag> player_tags = new HashMap<>();
private static volatile boolean free = true;
@Override @Override
public int run(CommandContext<FabricClientCommandSource> context) { public int run(CommandContext<FabricClientCommandSource> context) {
FabricClientCommandSource source = context.getSource(); FabricClientCommandSource source = context.getSource();
@ -33,19 +23,8 @@ public class TagCommand extends EaaModCommand{
DB_Tag.Type tag = DB_Tag.Type.valueOf(StringArgumentType.getString(context,"tag")); DB_Tag.Type tag = DB_Tag.Type.valueOf(StringArgumentType.getString(context,"tag"));
int grade = IntegerArgumentType.getInteger(context, "grade"); int grade = IntegerArgumentType.getInteger(context, "grade");
try { // does the magic
String playerUUID = MinecraftClient.getInstance().getNetworkHandler().getPlayerListEntry(player).getProfile().getId().toString(); TagFunction.tagPlayer(player, tag, grade, source);
DB_Player db_player = DB_Player.getPlayer(playerUUID, true);
new DB_Tag(db_player, tag, grade).put();
loadPlayer(playerUUID, true);
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.TUTORIAL_HINT, Text.of("Player Tagged"),
Text.of(player + " | " + tag.name() + " | " + grade));
} catch (Exception e) {
source.sendFeedback(Text.of(e.toString()));
}
return 1; return 1;
} }
@ -67,67 +46,4 @@ public class TagCommand extends EaaModCommand{
.executes(this) .executes(this)
))); )));
} }
public static void loadPlayer(String uuid, boolean reload){
if ( (!player_tags.containsKey(uuid) || reload)) {
new Thread(new LoadTag(uuid)).start();
}
}
public static Map<String, DB_Tag> getHashMap(){
return player_tags;
}
public static DB_Tag.Type getScoreboardTag(String uuid){
if (player_tags.containsKey(uuid))
return player_tags.get(uuid).getType();
else {
if (free) {
free = false;
loadPlayer(uuid, false);
}
}
return DB_Tag.Type.NOTLOADED;
}
public static class CustomText {
private final Text text;
private final int color;
public CustomText(Text text, int color) {
this.text = text;
this.color = color;
}
public Text getText() {
return text;
}
public int getColor() {
return color;
}
}
private static class LoadTag implements Runnable{
String uuid;
public LoadTag(String uuid){
this.uuid = uuid;
}
@Override
public void run() {
DB_Player db_player = DB_Player.getPlayer(uuid);
if (db_player == null) {
player_tags.put(uuid, new DB_Tag(null, DB_Tag.Type.NOTTAGGED, 0));
} else {
List<DB_Tag> tag = DB_Tag.getTagsFromPlayer(db_player);
if (tag.size() > 0)
player_tags.put(uuid, tag.get(tag.size() - 1));
}
free = true;
}
}
} }

View file

@ -26,7 +26,7 @@ import net.minecraft.scoreboard.Team;
import net.minecraft.text.OrderedText; import net.minecraft.text.OrderedText;
import net.minecraft.text.Text; import net.minecraft.text.Text;
import net.minecraft.world.GameMode; import net.minecraft.world.GameMode;
import net.saltymc.eaa.commands.TagCommand; import net.saltymc.eaa.function.TagFunction;
import net.saltymc.eaa.util.database.DB_Tag; import net.saltymc.eaa.util.database.DB_Tag;
/** /**
@ -165,7 +165,7 @@ public final class CustomPlayerListHud {
* PLAYER TAG * PLAYER TAG
*/ */
int offset_tag_playername = aa; int offset_tag_playername = aa;
DB_Tag.Type playerTAG = TagCommand.getScoreboardTag(player.getProfile().getId().toString()); DB_Tag.Type playerTAG = TagFunction.getScoreboardTag(player.getProfile().getId().toString());
mc.textRenderer.drawWithShadow(stack, playerTAG.getTag(), (float)aa, (float)ab, playerTAG.getColor()); mc.textRenderer.drawWithShadow(stack, playerTAG.getTag(), (float)aa, (float)ab, playerTAG.getColor());
offset_tag_playername += mc.textRenderer.getWidth(playerTAG.getTag()) + 2; offset_tag_playername += mc.textRenderer.getWidth(playerTAG.getTag()) + 2;

View file

@ -0,0 +1,82 @@
package net.saltymc.eaa.function;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.saltymc.eaa.util.database.DB_Player;
import net.saltymc.eaa.util.database.DB_Tag;
import net.saltymc.eaa.util.mojangApi.PlayerInfo;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ListIterator;
public class CheckFunction {
public static final SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
public static void checkPlayer(String player, FabricClientCommandSource source){
new Thread(new Check(player, source)).start();
}
private static class Check implements Runnable {
String player;
FabricClientCommandSource source;
public Check(String player, FabricClientCommandSource source) {
this.player = player;
this.source = source;
}
@Override
public void run() {
try {
String playerUUID = PlayerInfo.playerNameToUUID(player);
if (playerUUID == null){
SystemToast.add(MinecraftClient.getInstance().getToastManager(), SystemToast.Type.WORLD_ACCESS_FAILURE,
Text.of("ERROR!"), Text.of("Player does not exist"));
return;
}
TagFunction.loadPlayer(playerUUID, true);
List<String> names = PlayerInfo.playerUUIDToNames(playerUUID);
for (int i = 1; i <= names.size(); i++)
source.sendFeedback(Text.of(i + ". " + names.get(i-1)));
List<DB_Tag> tags = DB_Tag.getTagsFromPlayer(DB_Player.getPlayer(playerUUID));
if (tags.size() > 0) {
ListIterator<DB_Tag> it = tags.listIterator(tags.size());
while (it.hasPrevious()) {
DB_Tag curr = it.previous();
source.sendFeedback(new LiteralText(dateformat.format(curr.getTagDate())).formatted(Formatting.GRAY)
.append(new LiteralText(" | "))
.append(new LiteralText(curr.getType().getTag()).formatted(curr.getType().getFormatting()))
.append(new LiteralText(" (" + curr.getGrade() + ") ").formatted(getScaleFormat(curr.getGrade())))
);
}
} else {
source.sendFeedback(Text.of("No Tags Set!"));
}
} catch (Exception e) {
source.sendFeedback(Text.of(e.toString()));
}
}
}
private static Formatting getScaleFormat(int grade){
if (grade <= 5)
return Formatting.WHITE;
else if (grade < 9)
return Formatting.DARK_AQUA;
else
return Formatting.BLUE;
}
}

View file

@ -0,0 +1,63 @@
package net.saltymc.eaa.function;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.text.Text;
import net.saltymc.eaa.util.database.DB_Tag;
import java.util.ArrayList;
import java.util.List;
public class LobbyFunction {
public static void checkLobby(FabricClientCommandSource source){
new Thread(new CheckLobby(source)).start();
}
private static class CheckLobby implements Runnable {
FabricClientCommandSource source;
public CheckLobby(FabricClientCommandSource source) {
this.source = source;
}
@Override
public void run() {
try {
List<String> uuids = new ArrayList<>();
MinecraftClient.getInstance().getNetworkHandler().getPlayerList().forEach(x -> uuids.add(x.getProfile().getId().toString()));
int dangerLvl = 0; // 0 = nothing; 1 = idiot; 2 = hacker
for (String uuid: uuids){
TagFunction.loadPlayer(uuid, false);
if (TagFunction.getHashMap().containsKey(uuid)){
DB_Tag.Type type = TagFunction.getHashMap().get(uuid).getType();
if (type == DB_Tag.Type.HACKER){
dangerLvl = 2;
break;
} else if (type == DB_Tag.Type.IDIOT){
dangerLvl = 1;
}
}
}
switch (dangerLvl){
case 0:
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.WORLD_BACKUP, Text.of("OKAY!"), Text.of("No Hackers found"));
break;
case 1:
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.TUTORIAL_HINT, Text.of("MEH!"), Text.of("There is an Idiot!"));
break;
case 2:
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.WORLD_ACCESS_FAILURE, Text.of("ALARM!"), Text.of("There is a Hacker!"));
}
} catch (Exception e) {
source.sendFeedback(Text.of(e.toString()));
}
}
}
}

View file

@ -0,0 +1,125 @@
package net.saltymc.eaa.function;
import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.text.Text;
import net.saltymc.eaa.util.database.DB_Player;
import net.saltymc.eaa.util.database.DB_Tag;
import net.saltymc.eaa.util.mojangApi.PlayerInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TagFunction {
private static final Map<String, DB_Tag> player_tags = new HashMap<>();
private static volatile boolean free = true;
public static void loadPlayer(String uuid, boolean reload){
if ( (!player_tags.containsKey(uuid) || reload)) {
new Thread(new LoadTag(uuid)).start();
}
}
public static DB_Tag.Type getScoreboardTag(String uuid){
if (player_tags.containsKey(uuid))
return player_tags.get(uuid).getType();
else {
if (free) {
free = false;
loadPlayer(uuid, false);
}
}
return DB_Tag.Type.NOTLOADED;
}
public static void tagPlayer(String player, DB_Tag.Type tag, int grade, FabricClientCommandSource source){
new Thread(new TagPlayer(player, tag, grade, source)).start();
}
/*
*
* GETTER SETTER
*
*/
public static Map<String, DB_Tag> getHashMap(){
return player_tags;
}
/*
*
* THREADS
*
*/
/**
* Thread for Tagging a Player
*/
private static class TagPlayer implements Runnable {
String player;
DB_Tag.Type tag;
int grade;
FabricClientCommandSource source;
public TagPlayer(String player, DB_Tag.Type tag, int grade, FabricClientCommandSource source) {
this.player = player;
this.tag = tag;
this.grade = grade;
this.source = source;
}
@Override
public void run() {
try {
String playerUUID = PlayerInfo.playerNameToUUID(player);
if (playerUUID != null) {
DB_Player db_player = DB_Player.getPlayer(playerUUID, true);
new DB_Tag(db_player, tag, grade).put();
loadPlayer(playerUUID, true);
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.TUTORIAL_HINT,
Text.of("Player Tagged"), Text.of(player + " | " + tag.name() + " | " + grade));
} else {
SystemToast.add(source.getClient().getToastManager(), SystemToast.Type.WORLD_ACCESS_FAILURE,
Text.of("ERROR!"), Text.of("Player does not exist"));
}
} catch (Exception e) {
source.sendFeedback(Text.of(e.toString()));
}
}
}
/**
* Thread for loading a tag of a player in to hashmap
*/
private static class LoadTag implements Runnable {
String uuid;
public LoadTag(String uuid){
this.uuid = uuid;
}
@Override
public void run() {
DB_Player db_player = DB_Player.getPlayer(uuid);
if (db_player == null) {
player_tags.put(uuid, new DB_Tag(null, DB_Tag.Type.NOTTAGGED, 0));
} else {
List<DB_Tag> tag = DB_Tag.getTagsFromPlayer(db_player);
if (tag.size() > 0)
player_tags.put(uuid, tag.get(tag.size() - 1));
}
free = true;
}
}
}

View file

@ -1,5 +1,7 @@
package net.saltymc.eaa.util.database; package net.saltymc.eaa.util.database;
import net.minecraft.util.Formatting;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -94,26 +96,28 @@ public class DB_Tag {
public enum Type { public enum Type {
HACKER( HACKER(
"HAX", "PLayer who hacks", 0xaa0000 "HAX", "PLayer who hacks", 0xaa0000, Formatting.RED
), FRIENDLY( ), FRIENDLY(
"FND", "Player you like", 0x55ff55 "FND", "Player you like", 0x55ff55, Formatting.GREEN
), GOODPLAYER( ), GOODPLAYER(
"PRO", "Fair player with good skill", 0xffaa00 "PRO", "Fair player with good skill", 0xffaa00, Formatting.GOLD
), IDIOT( ), IDIOT(
"BAD", "Person who is annoying and bad", 0x55ffff "BAD", "Person who is annoying and bad", 0x55ffff, Formatting.AQUA
), NOTTAGGED( ), NOTTAGGED(
"NaN", "Player is not tagged", 0x555555 "NaN", "Player is not tagged", 0x555555, Formatting.DARK_GRAY
), NOTLOADED( ), NOTLOADED(
"---", "PLayer not loaded", 0xffffff "---", "PLayer not loaded", 0xffffff, Formatting.WHITE
); );
String tag, description; String tag, description;
int color; int color;
Formatting formatting;
Type(String tag, String description, int color){ Type(String tag, String description, int color, Formatting formatting){
this.tag = tag; this.tag = tag;
this.description = description; this.description = description;
this.color = color; this.color = color;
this.formatting = formatting;
} }
@ -128,5 +132,9 @@ public class DB_Tag {
public int getColor() { public int getColor() {
return color; return color;
} }
public Formatting getFormatting(){
return formatting;
}
} }
} }

View file

@ -1,45 +1,63 @@
package net.saltymc.eaa.util.mojangApi; package net.saltymc.eaa.util.mojangApi;
import com.google.gson.JsonElement; import net.minecraft.client.MinecraftClient;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.client.network.PlayerListEntry;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
public class PlayerInfo { public class PlayerInfo {
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
public static String playerNameToUUID(String playerName) throws MojangUtilException { @Nullable
public static String playerNameToUUID(String playerName) {
String playerUUID = null;
HttpClient httpClient = HttpClientBuilder.create().build();
try { try {
HttpPost request = new HttpPost("https://api.mojang.com/profiles/minecraft"); playerUUID = MinecraftClient.getInstance().getNetworkHandler().getPlayerListEntry(playerName).getProfile().getId().toString();
StringEntity params = new StringEntity("[\"" + playerName + "\"]"); } catch (NullPointerException e) {
request.addHeader("Content-Type", "application/json"); try {
request.setEntity(params); playerUUID = playerNameToUUIDbyAPI(playerName);
} catch (MojangUtilException ex){
//TODO:
}
}
return playerUUID;
}
@Nullable
private static String playerNameToUUIDbyAPI(String playerName) throws MojangUtilException {
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://api.mojang.com/users/profiles/minecraft/" + playerName);
HttpResponse response = httpClient.execute(request); HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != 200)
return null;
// take the response body as a json formatted string // take the response body as a json formatted string
JsonObject responseJSON = new JsonParser().parse(EntityUtils.toString(response.getEntity())).getAsJsonArray().get(0).getAsJsonObject(); JSONObject responseJSON = (JSONObject) new JSONParser().parse(EntityUtils.toString(response.getEntity()));
//doublecheck correct name //doublecheck correct name
if (!responseJSON.get("name").getAsString().equalsIgnoreCase(playerName)) if (responseJSON.containsKey("name") && ! ((String)responseJSON.get("name")).equalsIgnoreCase(playerName))
throw new Exception("Api response provided wrong player!"); return null;
return responseJSON.get("id").getAsString(); return (String) responseJSON.get("id");
} catch (Exception ex) { } catch (Exception ex) {
LOGGER.error("Error parsing playername to UUID while contacting API: ", ex); LOGGER.error("Error parsing playername to UUID while contacting API: ", ex);
@ -50,14 +68,15 @@ public class PlayerInfo {
public static List<String> playerUUIDToNames(String playerUUID) throws MojangUtilException { public static List<String> playerUUIDToNames(String playerUUID) throws MojangUtilException {
try { try {
HttpClient httpClient = HttpClientBuilder.create().build(); HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://api.mojang.com/user/profiles/" + playerUUID.toString().replaceAll("-", "") + "/names"); HttpGet request = new HttpGet("https://api.mojang.com/user/profiles/" + playerUUID.replaceAll("-", "") + "/names");
HttpResponse response = httpClient.execute(request); HttpResponse response = httpClient.execute(request);
List<String> ret = new ArrayList<>(); List<String> ret = new ArrayList<>();
// take the response body as a json formatted string // take the response body as a json formatted string
for (JsonElement responseJSON : new JsonParser().parse(EntityUtils.toString(response.getEntity())).getAsJsonArray()) for (Object responseJSON : (JSONArray) new JSONParser().parse(EntityUtils.toString(response.getEntity()))) {
ret.add(responseJSON.getAsJsonObject().get("name").getAsString()); ret.add((String) ((JSONObject)responseJSON).get("name"));
}
return ret; return ret;