From b9b1294882b68e2d85aec0c1d28570f5d68359b9 Mon Sep 17 00:00:00 2001 From: Torui <44932079+ToruiDev@users.noreply.github.com> Date: Sat, 21 May 2022 16:11:01 +0200 Subject: initial implementation (#38) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * rewrite everything * Add replace and insert methods for tooltips * Add sleep bcz hypixel doesnt want a prefilled chest * Commit requested changes * Fix messed up item stacks for stackables * Move handlers to handlers package * Empty hashmap on gui close * merge conflixt fix * Fix index out of bound exception * Fix bcz forge * fix messed slot assigns when there is empoty inventory slot * Make tooltips respect mod settings * Fix typo * save tab contents * optimise description loading & fix tab Co-authored-by: HackedOS <63157139+HackedOS@users.noreply.github.com> Co-authored-by: Äkwav --- src/main/java/de/torui/coflsky/CoflSky.java | 3 +- src/main/java/de/torui/coflsky/EventHandler.java | 191 ----------------- src/main/java/de/torui/coflsky/EventRegistry.java | 217 ------------------- .../java/de/torui/coflsky/WSCommandHandler.java | 2 +- .../de/torui/coflsky/commands/CommandType.java | 2 + .../torui/coflsky/configuration/Configuration.java | 5 +- .../torui/coflsky/configuration/LocalConfig.java | 6 +- .../torui/coflsky/handlers/DescriptionHandler.java | 182 ++++++++++++++++ .../de/torui/coflsky/handlers/EventHandler.java | 198 +++++++++++++++++ .../de/torui/coflsky/handlers/EventRegistry.java | 238 +++++++++++++++++++++ .../torui/coflsky/network/QueryServerCommands.java | 49 ++++- 11 files changed, 674 insertions(+), 419 deletions(-) delete mode 100644 src/main/java/de/torui/coflsky/EventHandler.java delete mode 100644 src/main/java/de/torui/coflsky/EventRegistry.java create mode 100644 src/main/java/de/torui/coflsky/handlers/DescriptionHandler.java create mode 100644 src/main/java/de/torui/coflsky/handlers/EventHandler.java create mode 100644 src/main/java/de/torui/coflsky/handlers/EventRegistry.java (limited to 'src/main/java/de/torui/coflsky') diff --git a/src/main/java/de/torui/coflsky/CoflSky.java b/src/main/java/de/torui/coflsky/CoflSky.java index 7ecccf0..9811ec7 100644 --- a/src/main/java/de/torui/coflsky/CoflSky.java +++ b/src/main/java/de/torui/coflsky/CoflSky.java @@ -10,6 +10,7 @@ import java.nio.file.Paths; import com.google.gson.Gson; import de.torui.coflsky.configuration.LocalConfig; +import de.torui.coflsky.handlers.EventRegistry; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.lwjgl.input.Keyboard; @@ -44,7 +45,7 @@ public class CoflSky "ws://sky-mod.coflnet.com/modsocket", }; - public static String CommandUri = "https://sky-commands.coflnet.com/api/mod/commands"; + public static String CommandUri = "https://sky.coflnet.com/api/mod/commands"; @EventHandler public void preInit(FMLPreInitializationEvent event) { String configString = null; diff --git a/src/main/java/de/torui/coflsky/EventHandler.java b/src/main/java/de/torui/coflsky/EventHandler.java deleted file mode 100644 index 55bd4ba..0000000 --- a/src/main/java/de/torui/coflsky/EventHandler.java +++ /dev/null @@ -1,191 +0,0 @@ -package de.torui.coflsky; - -import de.torui.coflsky.commands.Command; -import de.torui.coflsky.commands.CommandType; -import de.torui.coflsky.configuration.Configuration; -import net.minecraft.client.Minecraft; -import net.minecraft.client.network.NetworkPlayerInfo; -import net.minecraft.event.ClickEvent; -import net.minecraft.scoreboard.Score; -import net.minecraft.scoreboard.ScoreObjective; -import net.minecraft.scoreboard.ScorePlayerTeam; -import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.ChatStyle; -import net.minecraft.util.EnumChatFormatting; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static de.torui.coflsky.CoflSky.config; - -public class EventHandler { - - public static boolean isInSkyblock = false; - public static boolean isInTheCatacombs = false; - private static int purse = 0; - private static int bits = 0; - private static String location = ""; - private static String server = ""; - - public static void TabMenuData() { - if (isInSkyblock && CoflSky.Wrapper.isRunning && Configuration.getInstance().collectTab){ - List tabdata = getTabList(); - int size = tabdata.size() - 1; - for (int i = 0; i < tabdata.size(); i++) { - String line = tabdata.get(size - i).toLowerCase(); - ProcessTabMenu(line); - } - } - } - public static void ScoreboardData() { - String s; - try { - Scoreboard scoreboard = Minecraft.getMinecraft().theWorld.getScoreboard(); - ScoreObjective objective = scoreboard.getObjectiveInDisplaySlot(1); - s = EnumChatFormatting.getTextWithoutFormattingCodes(objective.getDisplayName()); - } catch (Exception e) { - s = ""; - } - checkIfInSkyblock(s); - if (isInSkyblock && CoflSky.Wrapper.isRunning) { - List scoreBoardLines = getScoreboard(); - int size = scoreBoardLines.size() - 1; - boolean hasFoundCatacombs = false; - for (int i = 0; i < scoreBoardLines.size(); i++) { - String line = EnumChatFormatting.getTextWithoutFormattingCodes(scoreBoardLines.get(size - i).toLowerCase()); - if (line.contains("the catacombs")) { - hasFoundCatacombs = true; - } - if (Configuration.getInstance().collectScoreboard) { - ProcessScoreboard(line); - } - - } - if (hasFoundCatacombs && !isInTheCatacombs) { - Command data = new Command<>(CommandType.set, "disableFlips true"); - CoflSky.Wrapper.SendMessage(data); - isInTheCatacombs = true; - } - if (isInTheCatacombs && !hasFoundCatacombs) { - Command data = new Command<>(CommandType.set, "disableFlips false"); - CoflSky.Wrapper.SendMessage(data); - isInTheCatacombs = false; - } - } - } - private static List getScoreboard() { - ArrayList scoreboardAsText = new ArrayList<>(); - if (Minecraft.getMinecraft() == null || Minecraft.getMinecraft().theWorld == null) { - return scoreboardAsText; - } - Scoreboard scoreboard = Minecraft.getMinecraft().theWorld.getScoreboard(); - ScoreObjective sideBarObjective = scoreboard.getObjectiveInDisplaySlot(1); - if (sideBarObjective == null) { - return scoreboardAsText; - } - String scoreboardTitle = sideBarObjective.getDisplayName(); - scoreboardTitle = EnumChatFormatting.getTextWithoutFormattingCodes(scoreboardTitle); - scoreboardAsText.add(scoreboardTitle); - Collection scoreboardLines = scoreboard.getSortedScores(sideBarObjective); - for (Score line : scoreboardLines) { - String playerName = line.getPlayerName(); - if (playerName == null || playerName.startsWith("#")) { - continue; - } - ScorePlayerTeam scorePlayerTeam = scoreboard.getPlayersTeam(playerName); - String lineText = EnumChatFormatting.getTextWithoutFormattingCodes( - ScorePlayerTeam.formatPlayerName(scorePlayerTeam, line.getPlayerName())); - scoreboardAsText.add(lineText.replace(line.getPlayerName(),"")); - } - return scoreboardAsText; - } - - private static List getTabList() { - ArrayList tabListAsString = new ArrayList<>(); - if (Minecraft.getMinecraft() == null || Minecraft.getMinecraft().getNetHandler() == null) { - return tabListAsString; - } - Collection playerInfoMap = Minecraft.getMinecraft().getNetHandler().getPlayerInfoMap(); - for (NetworkPlayerInfo playerInfo : playerInfoMap) { - String toDisplay; - if (playerInfo.getDisplayName() != null) { - toDisplay = playerInfo.getDisplayName().getFormattedText(); - } else { - toDisplay = ScorePlayerTeam.formatPlayerName(playerInfo.getPlayerTeam(), playerInfo.getGameProfile().getName()); - } - tabListAsString.add(EnumChatFormatting.getTextWithoutFormattingCodes(toDisplay)); - } - return tabListAsString; - } - private static void ProcessTabMenu(String line) { - if (Configuration.getInstance().collectLobbyChanges && line.contains("server:")) { - String server_ = line.split("server: ")[1]; - if (!server.equals(server_)) { - server = server_; - Command data = new Command<>(CommandType.updateServer, server); - CoflSky.Wrapper.SendMessage(data); - } - } else if (line.contains("area:")) { - String location_ = line.split("area: ")[1]; - if (!location.equals(location_)) { - location = location_; - Command data = new Command<>(CommandType.updateLocation, location); - CoflSky.Wrapper.SendMessage(data); - } - } - } - private static void checkIfInSkyblock(String s) { - if (s.contains("SKYBLOCK") && !isInSkyblock) { - if (config.autoStart){ - CoflSky.Wrapper.stop(); - CoflSky.Wrapper.startConnection(); - } - isInSkyblock = true; - } else if (!s.contains("SKYBLOCK") && isInSkyblock) { - if (config.autoStart){ - CoflSky.Wrapper.stop(); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("connection to ") - .appendSibling(new ChatComponentText("C").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_BLUE))) - .appendSibling(new ChatComponentText("oflnet").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GOLD))) - .appendSibling(new ChatComponentText(" has been stopped since you left skyblock.\n To reconnect enter ")) - .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) - .appendSibling(new ChatComponentText("/cofl start")) - .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) - .appendSibling(new ChatComponentText(" or click this message")) - .setChatStyle(new ChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/cofl start"))) - ); - } - isInSkyblock = false; - } - } - private static void ProcessScoreboard(String line){ - if (line.contains("purse") || line.contains("piggy")) { - int purse_ = 0; - try { - purse_ = Integer.parseInt(line.split(": ")[1].replace(",", "")); - } catch (NumberFormatException e) { - e.printStackTrace(); - } - if (purse != purse_) { - purse = purse_; - Command data = new Command<>(CommandType.updatePurse, purse); - CoflSky.Wrapper.SendMessage(data); - } - } else if (line.contains("bits")) { - int bits_ = 0; - try { - bits_ = Integer.parseInt(line.split(": ")[1].replace(",", "")); - } catch (NumberFormatException e) { - e.printStackTrace(); - } - if (bits != bits_) { - bits = bits_; - Command data = new Command<>(CommandType.updateBits, bits); - CoflSky.Wrapper.SendMessage(data); - } - } - } - -} diff --git a/src/main/java/de/torui/coflsky/EventRegistry.java b/src/main/java/de/torui/coflsky/EventRegistry.java deleted file mode 100644 index 9d82f14..0000000 --- a/src/main/java/de/torui/coflsky/EventRegistry.java +++ /dev/null @@ -1,217 +0,0 @@ -package de.torui.coflsky; - -import java.time.LocalDateTime; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.mojang.realmsclient.util.Pair; - -import de.torui.coflsky.FlipHandler.Flip; -import de.torui.coflsky.commands.Command; -import de.torui.coflsky.commands.CommandType; -import de.torui.coflsky.commands.JsonStringCommand; -import de.torui.coflsky.commands.models.AuctionData; -import de.torui.coflsky.configuration.Configuration; -import de.torui.coflsky.network.WSClient; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.inventory.GuiChest; -import net.minecraft.inventory.ContainerChest; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.client.event.ClientChatReceivedEvent; -import net.minecraftforge.client.event.GuiScreenEvent; -import net.minecraftforge.client.event.RenderGameOverlayEvent; -import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; -import net.minecraftforge.fml.common.eventhandler.EventPriority; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent; -import net.minecraftforge.fml.common.gameevent.InputEvent.MouseInputEvent; -import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.fml.common.gameevent.TickEvent; - -import static de.torui.coflsky.EventHandler.ScoreboardData; -import static de.torui.coflsky.EventHandler.TabMenuData; - -public class EventRegistry { - public static Pattern chatpattern = Pattern.compile("a^", Pattern.CASE_INSENSITIVE); - public final ExecutorService chatThreadPool = Executors.newFixedThreadPool(2); - public final ExecutorService tickThreadPool = Executors.newFixedThreadPool(2); - @SubscribeEvent - public void onDisconnectedFromServerEvent(ClientDisconnectionFromServerEvent event) { - if(CoflSky.Wrapper.isRunning) { - System.out.println("Disconnected from server"); - CoflSky.Wrapper.stop(); - System.out.println("CoflSky stopped"); - } - } - - public long LastClick = System.currentTimeMillis(); - - @SideOnly(Side.CLIENT) - @SubscribeEvent(priority = EventPriority.NORMAL, receiveCanceled = true) - public void onMouseEvent(MouseInputEvent event) { - onEvent(null); - } - - @SideOnly(Side.CLIENT) - @SubscribeEvent(priority = EventPriority.NORMAL, receiveCanceled = true) - public void onEvent(KeyInputEvent event) { - - if (CoflSky.keyBindings[0].isPressed()) { - if (WSCommandHandler.lastOnClickEvent != null) { - - String command = WSCommandHandler.lastOnClickEvent; - WSCommandHandler.lastOnClickEvent = null; - WSCommandHandler.HandleCommand( - new JsonStringCommand(CommandType.Execute, WSClient.gson.toJson(command)), - Minecraft.getMinecraft().thePlayer); - } - - } - if(CoflSky.keyBindings[1].isKeyDown()) { - if((System.currentTimeMillis() - LastClick) >= 400) { - - Flip f = WSCommandHandler.flipHandler.fds.GetHighestFlip(); - - if(f != null) { - WSCommandHandler.Execute("/viewauction " + f.id, null); - LastClick = System.currentTimeMillis(); - String command = WSClient.gson.toJson("/viewauction " + f.id); - WSCommandHandler.flipHandler.fds.InvalidateFlip(f); - - WSCommandHandler.Execute("/cofl track besthotkey " + f.id, Minecraft.getMinecraft().thePlayer); - CoflSky.Wrapper.SendMessage(new JsonStringCommand(CommandType.Clicked, command)); - } else { - WSCommandHandler.Execute("/cofl dialog nobestflip", Minecraft.getMinecraft().thePlayer); - } - - } - } - - } - - @SideOnly(Side.CLIENT) - //@SubscribeEvent - public void DrawOntoGUI(RenderGameOverlayEvent rgoe) { - - if (rgoe.type == ElementType.CROSSHAIRS) { - Minecraft mc = Minecraft.getMinecraft(); - mc.ingameGUI.drawString(Minecraft.getMinecraft().fontRendererObj, "Flips in Pipeline:" + WSCommandHandler.flipHandler.fds.CurrentFlips(), 0, 0, Integer.MAX_VALUE); - } - } - - public static String ExtractUuidFromInventory(IInventory inventory) { - - ItemStack stack = inventory.getStackInSlot(13); - if (stack != null) { - try { - String uuid = stack.serializeNBT().getCompoundTag("tag").getCompoundTag("ExtraAttributes") - .getString("uuid"); - if (uuid.length() == 0) { - throw new Exception(); - } - System.out.println("Item has the UUID: " + uuid); - return uuid; - } catch (Exception e) { - System.out.println("Clicked item " + stack.getDisplayName() + " has the following meta: " - + stack.serializeNBT().toString()); - } - } - return ""; - } - - public static ItemStack GOLD_NUGGET = new ItemStack( - Item.itemRegistry.getObject(new ResourceLocation("minecraft:gold_nugget"))); - - public static final Pair> EMPTY = Pair.of(null, Pair.of("",LocalDateTime.MIN)); - public static Pair> last = EMPTY; - - @SubscribeEvent - public void HandleChatEvent(ClientChatReceivedEvent sce) { - if(CoflSky.Wrapper.isRunning && Configuration.getInstance().collectChat) { - chatThreadPool.submit(() -> { - String msg = sce.message.getUnformattedText(); - Matcher matcher = chatpattern.matcher(msg); - boolean matchFound = matcher.find(); - if (matchFound) { - Command data = new Command<>(CommandType.chatBatch, new String[]{msg}); - CoflSky.Wrapper.SendMessage(data); - } - }); - } - - } - - public static long lastStartTime = Long.MIN_VALUE; - - public static long LastViewAuctionInvocation = Long.MIN_VALUE; - public static String LastViewAuctionUUID =null; - - @SideOnly(Side.CLIENT) - @SubscribeEvent - public void OnGuiClick(GuiScreenEvent.MouseInputEvent mie) { - if (!CoflSky.Wrapper.isRunning) return; - if (!(mie.gui instanceof GuiChest)) return; // verify that it's really a chest - if (!(((GuiChest) mie.gui).inventorySlots instanceof ContainerChest)) return; - ContainerChest chest = (ContainerChest) ((GuiChest) mie.gui).inventorySlots; - IInventory inv = chest.getLowerChestInventory(); - if (inv.hasCustomName()) { // verify that the chest actually has a custom name - String chestName = inv.getName(); - - if (chestName.equalsIgnoreCase("BIN Auction View") || chestName.equalsIgnoreCase("Ekwav")) { - - ItemStack heldItem = Minecraft.getMinecraft().thePlayer.inventory.getItemStack(); - - if (heldItem != null) { - System.out.println("Clicked on: " + heldItem.getItem().getRegistryName()); - - String itemUUID = ExtractUuidFromInventory(inv); - - if(System.currentTimeMillis() > lastStartTime) { - - if (heldItem.isItemEqual(GOLD_NUGGET)) { - AuctionData ad = new AuctionData(); - ad.setItemId(itemUUID); - - if((LastViewAuctionInvocation+60*1000) >= System.currentTimeMillis()) { - ad.setAuctionId(LastViewAuctionUUID); - } else { - ad.setAuctionId(""); - } - - Command data = new Command<>(CommandType.PurchaseStart, ad); - CoflSky.Wrapper.SendMessage(data); - System.out.println("PurchaseStart"); - last = Pair.of("You claimed ", Pair.of(itemUUID, LocalDateTime.now())); - lastStartTime = System.currentTimeMillis() + 200 /*ensure a small debounce*/; - } - } - } - } - } - } - - @SubscribeEvent - public void OnRenderTick(TickEvent.RenderTickEvent event) { - de.torui.coflsky.CountdownTimer.onRenderTick(event); - } - - int UpdateThisTick = 0; - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onTick(TickEvent.ClientTickEvent event) { - UpdateThisTick++; - if (UpdateThisTick >= 200) UpdateThisTick = 0; - if (UpdateThisTick == 0) { - tickThreadPool.submit(() -> { - ScoreboardData(); - TabMenuData(); - }); - } - } -} diff --git a/src/main/java/de/torui/coflsky/WSCommandHandler.java b/src/main/java/de/torui/coflsky/WSCommandHandler.java index 39c4495..ca583a2 100644 --- a/src/main/java/de/torui/coflsky/WSCommandHandler.java +++ b/src/main/java/de/torui/coflsky/WSCommandHandler.java @@ -10,7 +10,7 @@ import de.torui.coflsky.commands.models.FlipData; import de.torui.coflsky.commands.models.SoundData; import de.torui.coflsky.configuration.ConfigurationManager; import de.torui.coflsky.commands.models.TimerData; -import de.torui.coflsky.network.WSClient; +import de.torui.coflsky.handlers.EventRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.audio.SoundHandler; diff --git a/src/main/java/de/torui/coflsky/commands/CommandType.java b/src/main/java/de/torui/coflsky/commands/CommandType.java index 533af1e..7f196d4 100644 --- a/src/main/java/de/torui/coflsky/commands/CommandType.java +++ b/src/main/java/de/torui/coflsky/commands/CommandType.java @@ -51,6 +51,8 @@ public enum CommandType { updateLocation, @SerializedName("chatBatch") chatBatch, + @SerializedName("uploadTab") + uploadTab, ; public static Map data; static { diff --git a/src/main/java/de/torui/coflsky/configuration/Configuration.java b/src/main/java/de/torui/coflsky/configuration/Configuration.java index 1ef040f..58ca4fd 100644 --- a/src/main/java/de/torui/coflsky/configuration/Configuration.java +++ b/src/main/java/de/torui/coflsky/configuration/Configuration.java @@ -1,7 +1,7 @@ package de.torui.coflsky.configuration; import de.torui.coflsky.CoflSky; -import de.torui.coflsky.EventRegistry; +import de.torui.coflsky.handlers.EventRegistry; import java.util.regex.Pattern; @@ -21,6 +21,7 @@ public class Configuration { public static void setInstance(Configuration config) { instance = config; CoflSky.config.autoStart = instance.autoStart; + CoflSky.config.extendedtooltips = instance.extendDescriptions; EventRegistry.chatpattern = Pattern.compile(instance.chatRegex, Pattern.CASE_INSENSITIVE);; } @@ -36,7 +37,7 @@ public class Configuration { public boolean collectEntities; public boolean autoStart; @Description("Wherever or not to send item descriptions for extending to the server") - public boolean ExtendDescriptions; + public boolean extendDescriptions; @Description("Chat input starting with one of these prefixes is sent to the server") public String[] CommandPrefixes; diff --git a/src/main/java/de/torui/coflsky/configuration/LocalConfig.java b/src/main/java/de/torui/coflsky/configuration/LocalConfig.java index 28909c4..5c16fca 100644 --- a/src/main/java/de/torui/coflsky/configuration/LocalConfig.java +++ b/src/main/java/de/torui/coflsky/configuration/LocalConfig.java @@ -11,8 +11,10 @@ import java.nio.file.Paths; public class LocalConfig { public boolean autoStart; - public LocalConfig(boolean autoStart) { + public boolean extendedtooltips; + public LocalConfig(boolean autoStart,boolean extendedtooltips) { this.autoStart = autoStart; + this.extendedtooltips = extendedtooltips; } public static void saveConfig(File file, LocalConfig Config) { Gson gson = new Gson(); @@ -28,6 +30,6 @@ public class LocalConfig { } public static LocalConfig createDefaultConfig() { - return new LocalConfig(false); + return new LocalConfig(false,true); } } diff --git a/src/main/java/de/torui/coflsky/handlers/DescriptionHandler.java b/src/main/java/de/torui/coflsky/handlers/DescriptionHandler.java new file mode 100644 index 0000000..08eb819 --- /dev/null +++ b/src/main/java/de/torui/coflsky/handlers/DescriptionHandler.java @@ -0,0 +1,182 @@ +package de.torui.coflsky.handlers; + +import de.torui.coflsky.network.QueryServerCommands; +import de.torui.coflsky.network.WSClient; +import net.minecraft.client.gui.inventory.GuiChest; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.ContainerChest; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.client.event.GuiOpenEvent; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; + +public class DescriptionHandler { + + private static class InventoryWrapper { + public String chestName; + public String fullInventoryNbt; + } + private static class DescModification { + public String type; + public String value; + public int line; + } + + public static HashMap tooltipItemMap = new HashMap<>(); + public static HashMap tooltipItemUuidMap = new HashMap<>(); + public static HashMap tooltipItemIdMap = new HashMap<>(); + + public static final DescModification[] EMPTY_ARRAY = new DescModification[0]; + public static final NBTTagCompound EMPTY_COMPOUND = new NBTTagCompound(); + + public static String ExtractStackableIdFromItemStack(ItemStack stack) { + if (stack != null) { + try { + String uuid = stack.serializeNBT().getCompoundTag("tag").getCompoundTag("ExtraAttributes") + .getString("id") + ":" + stack.stackSize; + if (uuid.length() == 0) { + throw new Exception(); + } + return uuid; + } catch (Exception e) { + } + } + return ""; + } + public static String ExtractUuidFromItemStack(ItemStack stack) { + if (stack != null) { + try { + String uuid = stack.serializeNBT().getCompoundTag("tag").getCompoundTag("ExtraAttributes") + .getString("uuid"); + if (uuid.length() == 0) { + throw new Exception(); + } + return uuid; + } catch (Exception e) { + } + } + return ""; + } + private static DescModification[] getTooltipData(ItemStack itemStack) { + if (tooltipItemMap.containsKey(itemStack)) { + return tooltipItemMap.getOrDefault(itemStack, EMPTY_ARRAY); + } + if(!itemStack.isStackable()){ + String id = ExtractUuidFromItemStack(itemStack); + if (tooltipItemUuidMap.containsKey(id)) { + return tooltipItemUuidMap.getOrDefault(id, EMPTY_ARRAY); + } + } else { + String itemId = ExtractStackableIdFromItemStack(itemStack); + if(tooltipItemIdMap.containsKey(itemId)){ + return tooltipItemIdMap.getOrDefault(itemId, EMPTY_ARRAY); + } + } + + return EMPTY_ARRAY; + } + public static void getTooltipDataFromBackend(GuiOpenEvent event){ + + InventoryWrapper wrapper = new InventoryWrapper(); + + GuiContainer gc = (GuiContainer) event.gui; + + if (event.gui instanceof GuiChest) { + ContainerChest chest = (ContainerChest) ((GuiChest) event.gui).inventorySlots; + for(int i = 1; i < 10; i++) { + if(gc.inventorySlots.inventorySlots.get(gc.inventorySlots.inventorySlots.size()-37).getStack() != null) + break; + try { + // incremental backoff to wait for all inventory packages to arrive (each slot is sent individually) + Thread.sleep(20 * i); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + IInventory inv = chest.getLowerChestInventory(); + if (inv.hasCustomName()) { + String chestName = inv.getName(); + wrapper.chestName = chestName; + } + } + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList tl = new NBTTagList(); + + for (Slot obj : gc.inventorySlots.inventorySlots) { + ItemStack stack = obj.getStack(); + if (stack != null) { + tl.appendTag(stack.serializeNBT()); + } else { + tl.appendTag(EMPTY_COMPOUND); + } + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + compound.setTag("i", tl); + CompressedStreamTools.writeCompressed(compound, baos); + + wrapper.fullInventoryNbt = Base64.getEncoder().encodeToString(baos.toByteArray()); + + String data = WSClient.gson.toJson(wrapper); + String info = QueryServerCommands.PostRequest("https://sky.coflnet.com/api/mod/description/modifications", data); + + DescModification[][] arr = WSClient.gson.fromJson(info, DescModification[][].class); + int i = 0; + for (Slot obj : gc.inventorySlots.inventorySlots) { + ItemStack stack = obj.getStack(); + tooltipItemMap.put(stack, arr[i]); + String uuid = ExtractUuidFromItemStack(stack); + if(uuid.length()>0) tooltipItemUuidMap.put(uuid, arr[i]); + + String id = ExtractStackableIdFromItemStack(stack); + if(id.length()>0) tooltipItemIdMap.put(id, arr[i]); + i++; + } + + } catch (IOException e) { + e.printStackTrace(); + } + } + public static void setTooltips(ItemTooltipEvent event) { + DescModification[] data = getTooltipData(event.itemStack); + + if (data == null || data.length == 0) + return; + + for (DescModification datum : data) { + if (!(event.toolTip.size() >= datum.line)) return; + switch (datum.type) { + case "APPEND": + event.toolTip.add(datum.value); + break; + case "REPLACE": + event.toolTip.set(datum.line, datum.value); + break; + case "INSERT": + event.toolTip.add(datum.line, datum.value); + break; + case "DELETE": + event.toolTip.remove(datum.line); + break; + } + } + } + + public static void emptyTooltipData(){ + tooltipItemMap.clear(); + tooltipItemIdMap.clear(); + tooltipItemUuidMap.clear(); + } +} diff --git a/src/main/java/de/torui/coflsky/handlers/EventHandler.java b/src/main/java/de/torui/coflsky/handlers/EventHandler.java new file mode 100644 index 0000000..59db467 --- /dev/null +++ b/src/main/java/de/torui/coflsky/handlers/EventHandler.java @@ -0,0 +1,198 @@ +package de.torui.coflsky.handlers; + +import de.torui.coflsky.CoflSky; +import de.torui.coflsky.commands.Command; +import de.torui.coflsky.commands.CommandType; +import de.torui.coflsky.configuration.Configuration; +import net.minecraft.client.Minecraft; +import net.minecraft.client.network.NetworkPlayerInfo; +import net.minecraft.event.ClickEvent; +import net.minecraft.scoreboard.Score; +import net.minecraft.scoreboard.ScoreObjective; +import net.minecraft.scoreboard.ScorePlayerTeam; +import net.minecraft.scoreboard.Scoreboard; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ChatStyle; +import net.minecraft.util.EnumChatFormatting; +import java.util.*; + +import static de.torui.coflsky.CoflSky.config; +import static java.lang.Integer.parseInt; + +public class EventHandler { + + public static boolean isInSkyblock = false; + public static boolean isInTheCatacombs = false; + private static int purse = 0; + private static int bits = 0; + private static String location = ""; + private static String server = ""; + + public static void TabMenuData() { + if (isInSkyblock && CoflSky.Wrapper.isRunning && Configuration.getInstance().collectTab){ + List tabdata = getTabList(); + int size = tabdata.size() - 1; + for (int i = 0; i < tabdata.size(); i++) { + String line = tabdata.get(size - i).toLowerCase(); + ProcessTabMenu(line); + } + } + } + + public static void UploadTabData() { + if (!CoflSky.Wrapper.isRunning) + return; + Command> data = new Command<>(CommandType.uploadTab, getTabList()); + CoflSky.Wrapper.SendMessage(data); + } + + public static void ScoreboardData() { + String s; + try { + Scoreboard scoreboard = Minecraft.getMinecraft().theWorld.getScoreboard(); + ScoreObjective objective = scoreboard.getObjectiveInDisplaySlot(1); + s = EnumChatFormatting.getTextWithoutFormattingCodes(objective.getDisplayName()); + } catch (Exception e) { + s = ""; + } + checkIfInSkyblock(s); + if (isInSkyblock && CoflSky.Wrapper.isRunning) { + List scoreBoardLines = getScoreboard(); + int size = scoreBoardLines.size() - 1; + boolean hasFoundCatacombs = false; + for (int i = 0; i < scoreBoardLines.size(); i++) { + String line = EnumChatFormatting.getTextWithoutFormattingCodes(scoreBoardLines.get(size - i).toLowerCase()); + if (line.contains("the catacombs")) { + hasFoundCatacombs = true; + } + if (Configuration.getInstance().collectScoreboard) { + ProcessScoreboard(line); + } + + } + if (hasFoundCatacombs && !isInTheCatacombs) { + Command data = new Command<>(CommandType.set, "disableFlips true"); + CoflSky.Wrapper.SendMessage(data); + isInTheCatacombs = true; + } + if (isInTheCatacombs && !hasFoundCatacombs) { + Command data = new Command<>(CommandType.set, "disableFlips false"); + CoflSky.Wrapper.SendMessage(data); + isInTheCatacombs = false; + } + } + } + private static List getScoreboard() { + ArrayList scoreboardAsText = new ArrayList<>(); + if (Minecraft.getMinecraft() == null || Minecraft.getMinecraft().theWorld == null) { + return scoreboardAsText; + } + Scoreboard scoreboard = Minecraft.getMinecraft().theWorld.getScoreboard(); + ScoreObjective sideBarObjective = scoreboard.getObjectiveInDisplaySlot(1); + if (sideBarObjective == null) { + return scoreboardAsText; + } + String scoreboardTitle = sideBarObjective.getDisplayName(); + scoreboardTitle = EnumChatFormatting.getTextWithoutFormattingCodes(scoreboardTitle); + scoreboardAsText.add(scoreboardTitle); + Collection scoreboardLines = scoreboard.getSortedScores(sideBarObjective); + for (Score line : scoreboardLines) { + String playerName = line.getPlayerName(); + if (playerName == null || playerName.startsWith("#")) { + continue; + } + ScorePlayerTeam scorePlayerTeam = scoreboard.getPlayersTeam(playerName); + String lineText = EnumChatFormatting.getTextWithoutFormattingCodes( + ScorePlayerTeam.formatPlayerName(scorePlayerTeam, line.getPlayerName())); + scoreboardAsText.add(lineText.replace(line.getPlayerName(),"")); + } + return scoreboardAsText; + } + + private static List getTabList() { + ArrayList tabListAsString = new ArrayList<>(); + if (Minecraft.getMinecraft() == null || Minecraft.getMinecraft().getNetHandler() == null) { + return tabListAsString; + } + Collection playerInfoMap = Minecraft.getMinecraft().getNetHandler().getPlayerInfoMap(); + for (NetworkPlayerInfo playerInfo : playerInfoMap) { + String toDisplay; + if (playerInfo.getDisplayName() != null) { + toDisplay = playerInfo.getDisplayName().getFormattedText(); + } else { + toDisplay = ScorePlayerTeam.formatPlayerName(playerInfo.getPlayerTeam(), playerInfo.getGameProfile().getName()); + } + tabListAsString.add(EnumChatFormatting.getTextWithoutFormattingCodes(toDisplay)); + } + return tabListAsString; + } + private static void ProcessTabMenu(String line) { + if (Configuration.getInstance().collectLobbyChanges && line.contains("server:")) { + String server_ = line.split("server: ")[1]; + if (!server.equals(server_)) { + server = server_; + Command data = new Command<>(CommandType.updateServer, server); + CoflSky.Wrapper.SendMessage(data); + UploadTabData(); + } + } else if (line.contains("area:")) { + String location_ = line.split("area: ")[1]; + if (!location.equals(location_)) { + location = location_; + Command data = new Command<>(CommandType.updateLocation, location); + CoflSky.Wrapper.SendMessage(data); + } + } + } + private static void checkIfInSkyblock(String s) { + if (s.contains("SKYBLOCK") && !isInSkyblock) { + if (config.autoStart){ + CoflSky.Wrapper.stop(); + CoflSky.Wrapper.startConnection(); + } + isInSkyblock = true; + } else if (!s.contains("SKYBLOCK") && isInSkyblock) { + if (config.autoStart){ + CoflSky.Wrapper.stop(); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("connection to ") + .appendSibling(new ChatComponentText("C").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_BLUE))) + .appendSibling(new ChatComponentText("oflnet").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GOLD))) + .appendSibling(new ChatComponentText(" has been stopped since you left skyblock.\n To reconnect enter ")) + .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) + .appendSibling(new ChatComponentText("/cofl start")) + .appendSibling(new ChatComponentText("\"").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.AQUA))) + .appendSibling(new ChatComponentText(" or click this message")) + .setChatStyle(new ChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/cofl start"))) + ); + } + isInSkyblock = false; + } + } + private static void ProcessScoreboard(String line){ + if (line.contains("purse") || line.contains("piggy")) { + int purse_ = 0; + try { + purse_ = parseInt(line.split(" ")[1].replace(",", "")); + } catch (NumberFormatException e) { + e.printStackTrace(); + } + if (purse != purse_) { + purse = purse_; + Command data = new Command<>(CommandType.updatePurse, purse); + CoflSky.Wrapper.SendMessage(data); + } + } else if (line.contains("bits")) { + int bits_ = 0; + try { + bits_ = parseInt(line.split(" ")[1].replace(",", "")); + } catch (NumberFormatException e) { + e.printStackTrace(); + } + if (bits != bits_) { + bits = bits_; + Command data = new Command<>(CommandType.updateBits, bits); + CoflSky.Wrapper.SendMessage(data); + } + } + } +} diff --git a/src/main/java/de/torui/coflsky/handlers/EventRegistry.java b/src/main/java/de/torui/coflsky/handlers/EventRegistry.java new file mode 100644 index 0000000..d2b8113 --- /dev/null +++ b/src/main/java/de/torui/coflsky/handlers/EventRegistry.java @@ -0,0 +1,238 @@ +package de.torui.coflsky.handlers; + +import java.time.LocalDateTime; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.mojang.realmsclient.util.Pair; + +import de.torui.coflsky.CoflSky; +import de.torui.coflsky.FlipHandler.Flip; +import de.torui.coflsky.WSCommandHandler; +import de.torui.coflsky.commands.Command; +import de.torui.coflsky.commands.CommandType; +import de.torui.coflsky.commands.JsonStringCommand; +import de.torui.coflsky.commands.models.AuctionData; +import de.torui.coflsky.configuration.Configuration; +import de.torui.coflsky.network.WSClient; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.inventory.GuiChest; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.ContainerChest; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.client.event.GuiOpenEvent; +import net.minecraftforge.client.event.GuiScreenEvent; +import net.minecraftforge.client.event.RenderGameOverlayEvent; +import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; +import net.minecraftforge.fml.common.eventhandler.EventPriority; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent; +import net.minecraftforge.fml.common.gameevent.InputEvent.MouseInputEvent; +import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.fml.common.gameevent.TickEvent; + +import static de.torui.coflsky.CoflSky.config; +import static de.torui.coflsky.handlers.DescriptionHandler.*; +import static de.torui.coflsky.handlers.EventHandler.*; + +public class EventRegistry { + public static Pattern chatpattern = Pattern.compile("a^", Pattern.CASE_INSENSITIVE); + public final ExecutorService chatThreadPool = Executors.newFixedThreadPool(2); + public final ExecutorService tickThreadPool = Executors.newFixedThreadPool(2); + @SubscribeEvent + public void onDisconnectedFromServerEvent(ClientDisconnectionFromServerEvent event) { + if(CoflSky.Wrapper.isRunning) { + System.out.println("Disconnected from server"); + CoflSky.Wrapper.stop(); + System.out.println("CoflSky stopped"); + } + } + + public long LastClick = System.currentTimeMillis(); + + @SideOnly(Side.CLIENT) + @SubscribeEvent(priority = EventPriority.NORMAL, receiveCanceled = true) + public void onMouseEvent(MouseInputEvent event) { + onEvent(null); + } + + @SideOnly(Side.CLIENT) + @SubscribeEvent(priority = EventPriority.NORMAL, receiveCanceled = true) + public void onEvent(KeyInputEvent event) { + + if (CoflSky.keyBindings[0].isPressed()) { + if (WSCommandHandler.lastOnClickEvent != null) { + + String command = WSCommandHandler.lastOnClickEvent; + WSCommandHandler.lastOnClickEvent = null; + WSCommandHandler.HandleCommand( + new JsonStringCommand(CommandType.Execute, WSClient.gson.toJson(command)), + Minecraft.getMinecraft().thePlayer); + } + + } + if(CoflSky.keyBindings[1].isKeyDown()) { + if((System.currentTimeMillis() - LastClick) >= 400) { + + Flip f = WSCommandHandler.flipHandler.fds.GetHighestFlip(); + + if(f != null) { + WSCommandHandler.Execute("/viewauction " + f.id, null); + LastClick = System.currentTimeMillis(); + String command = WSClient.gson.toJson("/viewauction " + f.id); + WSCommandHandler.flipHandler.fds.InvalidateFlip(f); + + WSCommandHandler.Execute("/cofl track besthotkey " + f.id, Minecraft.getMinecraft().thePlayer); + CoflSky.Wrapper.SendMessage(new JsonStringCommand(CommandType.Clicked, command)); + } else { + WSCommandHandler.Execute("/cofl dialog nobestflip", Minecraft.getMinecraft().thePlayer); + } + + } + } + + } + + @SideOnly(Side.CLIENT) + //@SubscribeEvent + public void DrawOntoGUI(RenderGameOverlayEvent rgoe) { + + if (rgoe.type == ElementType.CROSSHAIRS) { + Minecraft mc = Minecraft.getMinecraft(); + mc.ingameGUI.drawString(Minecraft.getMinecraft().fontRendererObj, "Flips in Pipeline:" + WSCommandHandler.flipHandler.fds.CurrentFlips(), 0, 0, Integer.MAX_VALUE); + } + } + + public static String ExtractUuidFromInventory(IInventory inventory) { + + ItemStack stack = inventory.getStackInSlot(13); + if (stack != null) { + try { + String uuid = stack.serializeNBT().getCompoundTag("tag").getCompoundTag("ExtraAttributes") + .getString("uuid"); + if (uuid.length() == 0) { + throw new Exception(); + } + System.out.println("Item has the UUID: " + uuid); + return uuid; + } catch (Exception e) { + System.out.println("Clicked item " + stack.getDisplayName() + " has the following meta: " + + stack.serializeNBT()); + } + } + return ""; + } + + public static ItemStack GOLD_NUGGET = new ItemStack( + Item.itemRegistry.getObject(new ResourceLocation("minecraft:gold_nugget"))); + + public static final Pair> EMPTY = Pair.of(null, Pair.of("",LocalDateTime.MIN)); + public static Pair> last = EMPTY; + + @SubscribeEvent + public void HandleChatEvent(ClientChatReceivedEvent sce) { + if(CoflSky.Wrapper.isRunning && Configuration.getInstance().collectChat) { + chatThreadPool.submit(() -> { + String msg = sce.message.getUnformattedText(); + Matcher matcher = chatpattern.matcher(msg); + boolean matchFound = matcher.find(); + if (matchFound) { + Command data = new Command<>(CommandType.chatBatch, new String[]{msg}); + CoflSky.Wrapper.SendMessage(data); + } + }); + } + + } + + public static long lastStartTime = Long.MIN_VALUE; + + public static long LastViewAuctionInvocation = Long.MIN_VALUE; + public static String LastViewAuctionUUID =null; + + @SideOnly(Side.CLIENT) + @SubscribeEvent + public void OnGuiClick(GuiScreenEvent.MouseInputEvent mie) { + if (!CoflSky.Wrapper.isRunning) return; + if (!(mie.gui instanceof GuiChest)) return; // verify that it's really a chest + if (!(((GuiChest) mie.gui).inventorySlots instanceof ContainerChest)) return; + ContainerChest chest = (ContainerChest) ((GuiChest) mie.gui).inventorySlots; + IInventory inv = chest.getLowerChestInventory(); + if (inv.hasCustomName()) { // verify that the chest actually has a custom name + String chestName = inv.getName(); + + if (chestName.equalsIgnoreCase("BIN Auction View") || chestName.equalsIgnoreCase("Ekwav")) { + + ItemStack heldItem = Minecraft.getMinecraft().thePlayer.inventory.getItemStack(); + + if (heldItem != null) { + System.out.println("Clicked on: " + heldItem.getItem().getRegistryName()); + + String itemUUID = ExtractUuidFromInventory(inv); + + if(System.currentTimeMillis() > lastStartTime) { + + if (heldItem.isItemEqual(GOLD_NUGGET)) { + AuctionData ad = new AuctionData(); + ad.setItemId(itemUUID); + + if((LastViewAuctionInvocation+60*1000) >= System.currentTimeMillis()) { + ad.setAuctionId(LastViewAuctionUUID); + } else { + ad.setAuctionId(""); + } + + Command data = new Command<>(CommandType.PurchaseStart, ad); + CoflSky.Wrapper.SendMessage(data); + System.out.println("PurchaseStart"); + last = Pair.of("You claimed ", Pair.of(itemUUID, LocalDateTime.now())); + lastStartTime = System.currentTimeMillis() + 200 /*ensure a small debounce*/; + } + } + } + } + } + } + + @SubscribeEvent + public void OnRenderTick(TickEvent.RenderTickEvent event) { + de.torui.coflsky.CountdownTimer.onRenderTick(event); + } + + int UpdateThisTick = 0; + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onTick(TickEvent.ClientTickEvent event) { + UpdateThisTick++; + if (UpdateThisTick >= 200) UpdateThisTick = 0; + if (UpdateThisTick == 0) { + tickThreadPool.submit(() -> { + ScoreboardData(); + TabMenuData(); + }); + } + } + + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onGuiOpen(GuiOpenEvent event) { + if (!config.extendedtooltips) return; + emptyTooltipData(); + if (!(event.gui instanceof GuiContainer)) return; + new Thread(() -> { + getTooltipDataFromBackend(event); + }).start(); + } + @SubscribeEvent(priority = EventPriority.HIGHEST) + public void onItemTooltipEvent(ItemTooltipEvent event) { + if (!config.extendedtooltips) return; + setTooltips(event); + } +} diff --git a/src/main/java/de/torui/coflsky/network/QueryServerCommands.java b/src/main/java/de/torui/coflsky/network/QueryServerCommands.java index 0bf54a3..67f8f2a 100644 --- a/src/main/java/de/torui/coflsky/network/QueryServerCommands.java +++ b/src/main/java/de/torui/coflsky/network/QueryServerCommands.java @@ -1,9 +1,6 @@ package de.torui.coflsky.network; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; @@ -12,6 +9,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.torui.coflsky.CoflSky; +import de.torui.coflsky.minecraft_integration.CoflSessionManager; +import de.torui.coflsky.minecraft_integration.PlayerDataProvider; public class QueryServerCommands { @@ -37,7 +36,7 @@ public class QueryServerCommands { } - return "§4ERROR: Could not connect to command server!"; + return "§4ERROR: Could not connect to command server!"; } private static class CommandInfo { @@ -100,6 +99,46 @@ public class QueryServerCommands { e.printStackTrace(); } + return null; + } + public static String PostRequest(String uri, String data) { + try { + String username = PlayerDataProvider.getUsername(); + URL url = new URL(uri); + HttpURLConnection con; + con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + + con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("User-Agent", "CoflMod"); + con.setRequestProperty("conId", CoflSessionManager.GetCoflSession(username).SessionUUID); + con.setRequestProperty("uuid",username); + con.setDoInput(true); + con.setDoOutput(true); + // ... + + OutputStream os = con.getOutputStream(); + byte[] bytes = data.getBytes("UTF-8"); + os.write(bytes); + os.close(); + + InputStream in = new BufferedInputStream(con.getInputStream()); + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + for (int length; (length = in.read(buffer)) != -1; ) { + result.write(buffer, 0, length); + } + // StandardCharsets.UTF_8.name() > JDK 7 + String resString = result.toString("UTF-8"); + + System.out.println("Result= " + resString); + return resString; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; } } -- cgit