diff options
Diffstat (limited to 'src/main/java')
18 files changed, 2471 insertions, 789 deletions
diff --git a/src/main/java/de/torui/coflsky/CoflSky.java b/src/main/java/de/torui/coflsky/CoflSky.java index 7eba195..a1498ba 100644 --- a/src/main/java/de/torui/coflsky/CoflSky.java +++ b/src/main/java/de/torui/coflsky/CoflSky.java @@ -6,15 +6,16 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; - import com.google.gson.Gson; import de.torui.coflsky.configuration.LocalConfig; +import de.torui.coflsky.gui.GUIType; import de.torui.coflsky.handlers.EventRegistry; import de.torui.coflsky.listeners.ChatListener; import de.torui.coflsky.proxy.APIKeyManager; +import de.torui.coflsky.gui.tfm.ButtonRemapper; +import de.torui.coflsky.gui.tfm.ChatMessageSendHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import org.lwjgl.input.Keyboard; - import de.torui.coflsky.network.WSClientWrapper; import net.minecraft.client.settings.KeyBinding; import net.minecraftforge.client.ClientCommandHandler; @@ -26,11 +27,10 @@ import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.relauncher.Side; @Mod(modid = CoflSky.MODID, version = CoflSky.VERSION) -public class CoflSky -{ +public class CoflSky { public static final String MODID = "CoflSky"; - public static final String VERSION = "1.4.4-Alpha"; - + public static final String VERSION = "1.5.0-Alpha"; + public static WSClientWrapper Wrapper; public static KeyBinding[] keyBindings; @@ -38,14 +38,14 @@ public class CoflSky public static File configFile; private File coflDir; public static LocalConfig config; - - public static final String[] webSocketURIPrefix = new String [] { - "wss://sky.coflnet.com/modsocket", - "wss://sky-mod.coflnet.com/modsocket", - "ws://sky.coflnet.com/modsocket", - "ws://sky-mod.coflnet.com/modsocket", + + public static final String[] webSocketURIPrefix = new String[]{ + "wss://sky.coflnet.com/modsocket", + "wss://sky-mod.coflnet.com/modsocket", + "ws://sky.coflnet.com/modsocket", + "ws://sky-mod.coflnet.com/modsocket", }; - + public static String CommandUri = Config.BaseUrl + "/api/mod/commands"; private final static APIKeyManager apiKeyManager = new APIKeyManager(); @@ -66,12 +66,12 @@ public class CoflSky e.printStackTrace(); } if (config == null) { - config = LocalConfig.createDefaultConfig(); + config = LocalConfig.createDefaultConfig(); } try { this.apiKeyManager.loadIfExists(); - }catch (Exception exception){ + } catch (Exception exception) { exception.printStackTrace(); } @@ -82,44 +82,42 @@ public class CoflSky } @EventHandler - public void init(FMLInitializationEvent event) throws URISyntaxException - { - System.out.println(">>>Started"); - + public void init(FMLInitializationEvent event) { CoflSky.Wrapper = new WSClientWrapper(webSocketURIPrefix); - - keyBindings = new KeyBinding[] { - new KeyBinding("key.replay_last.onclick", Keyboard.KEY_NONE, "SkyCofl"), - new KeyBinding("key.start_highest_bid", Keyboard.KEY_NONE, "SkyCofl") + + keyBindings = new KeyBinding[]{ + new KeyBinding("key.replay_last.onclick", Keyboard.KEY_NONE, "SkyCofl"), + new KeyBinding("key.start_highest_bid", Keyboard.KEY_NONE, "SkyCofl") }; - - if(event.getSide() == Side.CLIENT) { - ClientCommandHandler.instance.registerCommand(new CoflSkyCommand()); - ClientCommandHandler.instance.registerCommand(new ColfCommand()); - ClientCommandHandler.instance.registerCommand(new FlipperChatCommand()); - - for (int i = 0; i < keyBindings.length; ++i) - { - ClientRegistry.registerKeyBinding(keyBindings[i]); - } - - - } + + if (event.getSide() == Side.CLIENT) { + ClientCommandHandler.instance.registerCommand(new CoflSkyCommand()); + ClientCommandHandler.instance.registerCommand(new ColfCommand()); + ClientCommandHandler.instance.registerCommand(new FlipperChatCommand()); + + for (int i = 0; i < keyBindings.length; ++i) { + ClientRegistry.registerKeyBinding(keyBindings[i]); + } + + + } Events = new EventRegistry(); MinecraftForge.EVENT_BUS.register(Events); - + if (config.purchaseOverlay == GUIType.TFM) { + MinecraftForge.EVENT_BUS.register(ButtonRemapper.getInstance()); + } + MinecraftForge.EVENT_BUS.register(new ChatMessageSendHandler()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { - config.saveConfig(configFile , config); + config.saveConfig(configFile, config); try { apiKeyManager.saveKey(); - }catch (Exception exception){ + } catch (Exception exception) { exception.printStackTrace(); } })); - } - + } - public static APIKeyManager getAPIKeyManager(){ + public static APIKeyManager getAPIKeyManager() { return apiKeyManager; } diff --git a/src/main/java/de/torui/coflsky/CoflSkyCommand.java b/src/main/java/de/torui/coflsky/CoflSkyCommand.java index de82f12..880127c 100644 --- a/src/main/java/de/torui/coflsky/CoflSkyCommand.java +++ b/src/main/java/de/torui/coflsky/CoflSkyCommand.java @@ -1,14 +1,16 @@ package de.torui.coflsky; import java.io.IOException; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; +import java.util.*; import de.torui.coflsky.commands.Command; import de.torui.coflsky.commands.CommandType; import de.torui.coflsky.commands.JsonStringCommand; import de.torui.coflsky.commands.RawCommand; +import de.torui.coflsky.commands.models.FlipData; +import de.torui.coflsky.gui.GUIType; +import de.torui.coflsky.gui.bingui.BinGuiManager; +import de.torui.coflsky.gui.tfm.ButtonRemapper; import de.torui.coflsky.minecraft_integration.CoflSessionManager; import de.torui.coflsky.minecraft_integration.CoflSessionManager.CoflSession; import de.torui.coflsky.network.QueryServerCommands; @@ -20,201 +22,245 @@ import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.event.ClickEvent; import net.minecraft.event.ClickEvent.Action; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import java.util.ArrayList; +import net.minecraftforge.common.MinecraftForge; public class CoflSkyCommand extends CommandBase { - - @Override - public int getRequiredPermissionLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getCommandName() { - return "cofl"; - } - @Override - public List getCommandAliases() - { - ArrayList<String> al = new ArrayList<String>(); - al.add("Cofl"); - al.add("coflnet"); - al.add("cl"); - return al; - } - - @Override - public String getCommandUsage(ICommandSender sender) { - return HelpText; - } - - public static final String HelpText = "Available local sub-commands:\n" - + "§bstart: §7starts a new connection\n" - + "§bstop: §7stops the connection\n" - + "§bconnect: §7Connects to a different server\n" - + "§breset: §7resets all local session information and stops the connection\n" - + "§bstatus: §7Emits status information\nServer-Only Commands:"; - @Override - public void processCommand(ICommandSender sender, String[] args) throws CommandException { - new Thread(()->{ - System.out.println(Arrays.toString(args)); - - if(args.length >= 1) { - switch(args[0]) { - case "start": - //todo: start - //possible workaround for https://github.com/Coflnet/SkyblockMod/issues/48 - CoflSky.Wrapper.stop(); - sender.addChatMessage(new ChatComponentText("starting connection...")); - CoflSky.Wrapper.startConnection(); - break; - case "stop": - CoflSky.Wrapper.stop(); - sender.addChatMessage(new ChatComponentText("you stopped the 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(".\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(Action.RUN_COMMAND, "/cofl start"))) - ); - break; - case "debug": - // WSCommandHandler.HandleCommand(new Command(CommandType.Execute, "/me hewwo"), sender.getCommandSenderEntity()); - // WSCommandHandler.HandleCommand(new Command(CommandType.WriteToChat, " {\"type\":\"writeToChat\",\"data\":\"{\\\"text\\\":\\\"\\\\nFLIP: º9Goblin Eg\r\n" - // + "g º87,000 -> 13,999 ºg[BUY]\\\",\\\"onClick\\\":\\\"/viewauction f7d7295ca72f43e9876bf6da7424000c\\\",\\\"hover\\\":\\\"\\\"}\"}"), sender.getCommandSenderEntity()); - //WSCommandHandler.HandleCommand(new Command(CommandType.PlaySound, "{\"name\":\"random.orb\",\"pitch\":0.5}"), sender.getCommandSenderEntity()); - break; - case "callback": - CallbackCommand(args); - break; - case "dev": - if(Config.BaseUrl.contains("localhost")) { - CoflSky.Wrapper.startConnection(); - Config.BaseUrl = "https://sky.coflnet.com"; - } else { - CoflSky.Wrapper.initializeNewSocket("ws://localhost:8009/modsocket"); - Config.BaseUrl = "http://localhost:5005"; - } - sender.addChatMessage(new ChatComponentText("toggled dev mode, now using " + Config.BaseUrl)); - break; - case "status": - sender.addChatMessage(new ChatComponentText(StatusMessage())); - break; - case "reset": - HandleReset(); - break; - case "connect": - - if(args.length == 2) { - String destination = args[1]; - - if(!destination.contains("://")) { - destination = new String(Base64.getDecoder().decode(destination)); - } - sender.addChatMessage(new ChatComponentText("Stopping connection!")); - CoflSky.Wrapper.stop(); - sender.addChatMessage(new ChatComponentText("Opening connection to " + destination)); - if(CoflSky.Wrapper.initializeNewSocket(destination)) { - sender.addChatMessage(new ChatComponentText("Success")); - } else { - sender.addChatMessage(new ChatComponentText("Could not open connection, please check the logs")); - } - } else { - sender.addChatMessage(new ChatComponentText("§cPleace specify a server to connect to")); - } - break; - default: - SendCommandToServer(args, sender); - return; - } - } - - else { - ListHelp(sender); - } - }).start(); - } - - private void HandleReset() { - CoflSky.Wrapper.SendMessage(new Command<String>(CommandType.Reset,"")); - CoflSky.Wrapper.stop(); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Stopping Connection to CoflNet")); - CoflSessionManager.DeleteAllCoflSessions(); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Deleting CoflNet sessions...")); - if(CoflSky.Wrapper.startConnection()) - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Started the Connection to CoflNet")); - } - - public String StatusMessage() { - - String vendor = System.getProperty("java.vm.vendor"); - String name = System.getProperty("java.vm.name"); - String version = System.getProperty("java.version"); - String detailedVersion = System.getProperty("java.vm.version"); - - String status = vendor + " " + name + " " + version + " " + detailedVersion + "|Connection = " + (CoflSky.Wrapper!=null?CoflSky.Wrapper.GetStatus():"UNINITIALIZED_WRAPPER"); - try { - status += " uri=" + CoflSky.Wrapper.socket.uri.toString(); - } catch(NullPointerException npe) {} - - - try { - CoflSession session = CoflSessionManager.GetCoflSession(PlayerDataProvider.getUsername()); - String sessionString = CoflSessionManager.gson.toJson(session); - status += " session=" + sessionString; - } catch (IOException e) { - } - - return status; - } - - public void SendCommandToServer(String[] args, ICommandSender sender) { - String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - - //JsonStringCommand sc = new JsonStringCommand(args[0], WSClient.gson.toJson(command)); - RawCommand rc = new RawCommand(args[0], WSClient.gson.toJson(command)); - if(CoflSky.Wrapper.isRunning) { - CoflSky.Wrapper.SendMessage(rc); - } else { - SendAfterStart(sender, rc); - } - } - - private static synchronized void SendAfterStart(ICommandSender sender, RawCommand rc) { - sender.addChatMessage(new ChatComponentText("CoflSky wasn't active.").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); - //CoflSky.Wrapper.stop(); - CoflSky.Wrapper.startConnection(); - CoflSky.Wrapper.SendMessage(rc); - } - - public void ListHelp(ICommandSender sender) { - sender.addChatMessage(new ChatComponentText(HelpText)); - sender.addChatMessage(new ChatComponentText(QueryServerCommands.QueryCommands())); - } - - public void CallbackCommand(String[] args) { - - String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); - System.out.println("CallbackData: " + command); - //new Thread(()->{ - System.out.println("Callback: " + command); - WSCommandHandler.HandleCommand(new JsonStringCommand(CommandType.Execute, WSClient.gson.toJson(command)), Minecraft.getMinecraft().thePlayer); - CoflSky.Wrapper.SendMessage(new JsonStringCommand(CommandType.Clicked, WSClient.gson.toJson(command))); - - System.out.println("Sent!"); - //}).start(); - - } + + @Override + public int getRequiredPermissionLevel() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getCommandName() { + return "cofl"; + } + + @Override + public List getCommandAliases() { + ArrayList<String> al = new ArrayList<String>(); + al.add("Cofl"); + al.add("coflnet"); + al.add("cl"); + return al; + } + + @Override + public String getCommandUsage(ICommandSender sender) { + return HelpText; + } + + public static final String HelpText = "Available local sub-commands:\n" + + "§bstart: §7starts a new connection\n" + + "§bstop: §7stops the connection\n" + + "§bconnect: §7Connects to a different server\n" + + "§breset: §7resets all local session information and stops the connection\n" + + "§bstatus: §7Emits status information\nServer-Only Commands:"; + + @Override + public void processCommand(ICommandSender sender, String[] args) throws CommandException { + new Thread(() -> { + System.out.println(Arrays.toString(args)); + + if (args.length >= 1) { + switch (args[0].toLowerCase()) { + case "start": + //todo: start + //possible workaround for https://github.com/Coflnet/SkyblockMod/issues/48 + CoflSky.Wrapper.stop(); + sender.addChatMessage(new ChatComponentText("starting connection...")); + CoflSky.Wrapper.startConnection(); + break; + case "stop": + CoflSky.Wrapper.stop(); + sender.addChatMessage(new ChatComponentText("you stopped the 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(".\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(Action.RUN_COMMAND, "/cofl start"))) + ); + break; + case "debug": + // WSCommandHandler.HandleCommand(new Command(CommandType.Execute, "/me hewwo"), sender.getCommandSenderEntity()); + // WSCommandHandler.HandleCommand(new Command(CommandType.WriteToChat, " {\"type\":\"writeToChat\",\"data\":\"{\\\"text\\\":\\\"\\\\nFLIP: º9Goblin Eg\r\n" + // + "g º87,000 -> 13,999 ºg[BUY]\\\",\\\"onClick\\\":\\\"/viewauction f7d7295ca72f43e9876bf6da7424000c\\\",\\\"hover\\\":\\\"\\\"}\"}"), sender.getCommandSenderEntity()); + //WSCommandHandler.HandleCommand(new Command(CommandType.PlaySound, "{\"name\":\"random.orb\",\"pitch\":0.5}"), sender.getCommandSenderEntity()); + break; + case "callback": + CallbackCommand(args); + break; + case "dev": + if (Config.BaseUrl.contains("localhost")) { + CoflSky.Wrapper.startConnection(); + Config.BaseUrl = "https://sky.coflnet.com"; + } else { + CoflSky.Wrapper.initializeNewSocket("ws://localhost:8009/modsocket"); + Config.BaseUrl = "http://localhost:5005"; + } + sender.addChatMessage(new ChatComponentText("toggled dev mode, now using " + Config.BaseUrl)); + break; + case "status": + sender.addChatMessage(new ChatComponentText(StatusMessage())); + break; + case "reset": + HandleReset(); + break; + case "connect": + if (args.length == 2) { + String destination = args[1]; + + if (!destination.contains("://")) { + destination = new String(Base64.getDecoder().decode(destination)); + } + sender.addChatMessage(new ChatComponentText("Stopping connection!")); + CoflSky.Wrapper.stop(); + sender.addChatMessage(new ChatComponentText("Opening connection to " + destination)); + if (CoflSky.Wrapper.initializeNewSocket(destination)) { + sender.addChatMessage(new ChatComponentText("Success")); + } else { + sender.addChatMessage(new ChatComponentText("Could not open connection, please check the logs")); + } + } else { + sender.addChatMessage(new ChatComponentText("§cPleace specify a server to connect to")); + } + break; + case "openauctiongui": + FlipData flip = WSCommandHandler.flipHandler.fds.getFlipById(args[1]); + boolean shouldInvalidate = args.length >= 3 && args[2].equals("true"); + + + // Is not a stored flip -> just open the auction + if (flip == null) { + WSCommandHandler.flipHandler.lastClickedFlipMessage = ""; + Minecraft.getMinecraft().thePlayer.sendChatMessage("/viewauction " + args[1]); + return; + } + + String oneLineMessage = String.join(" ", flip.getMessageAsString()).replaceAll("\n", "").split(",§7 sellers ah")[0]; + + if (shouldInvalidate) { + WSCommandHandler.flipHandler.fds.InvalidateFlip(flip); + } + + WSCommandHandler.flipHandler.lastClickedFlipMessage = oneLineMessage; + + BinGuiManager.openNewFlipGui(oneLineMessage, flip.Render); + + Minecraft.getMinecraft().thePlayer.sendChatMessage("/viewauction " + flip.Id); + break; + case "setgui": + if (args.length != 2) { + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Available GUIs:")); + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Cofl")); + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7TFM")); + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Off")); + return; + } + + if (args[1].equalsIgnoreCase("cofl")) { + CoflSky.config.purchaseOverlay = GUIType.COFL; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bPurchase Overlay §7to: §fCofl")); + MinecraftForge.EVENT_BUS.unregister(ButtonRemapper.getInstance()); + } + if (args[1].equalsIgnoreCase("tfm")) { + CoflSky.config.purchaseOverlay = GUIType.TFM; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bPurchase Overlay §7to: §fTFM")); + MinecraftForge.EVENT_BUS.register(ButtonRemapper.getInstance()); + } + if (args[1].equalsIgnoreCase("off") || args[1].equalsIgnoreCase("false")) { + CoflSky.config.purchaseOverlay = null; + sender.addChatMessage(new ChatComponentText("[§1C§6oflnet§f]§7: §7Set §bPurchase Overlay §7to: §fOff")); + MinecraftForge.EVENT_BUS.unregister(ButtonRemapper.getInstance()); + } + break; + default: + SendCommandToServer(args, sender); + } + } else { + ListHelp(sender); + } + }).start(); + } + + private void HandleReset() { + CoflSky.Wrapper.SendMessage(new Command<String>(CommandType.Reset, "")); + CoflSky.Wrapper.stop(); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Stopping Connection to CoflNet")); + CoflSessionManager.DeleteAllCoflSessions(); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Deleting CoflNet sessions...")); + if (CoflSky.Wrapper.startConnection()) + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Started the Connection to CoflNet")); + } + + public String StatusMessage() { + + String vendor = System.getProperty("java.vm.vendor"); + String name = System.getProperty("java.vm.name"); + String version = System.getProperty("java.version"); + String detailedVersion = System.getProperty("java.vm.version"); + + String status = vendor + " " + name + " " + version + " " + detailedVersion + "|Connection = " + (CoflSky.Wrapper != null ? CoflSky.Wrapper.GetStatus() : "UNINITIALIZED_WRAPPER"); + try { + status += " uri=" + CoflSky.Wrapper.socket.uri.toString(); + } catch (NullPointerException npe) { + } + + + try { + CoflSession session = CoflSessionManager.GetCoflSession(PlayerDataProvider.getUsername()); + String sessionString = CoflSessionManager.gson.toJson(session); + status += " session=" + sessionString; + } catch (IOException e) { + } + + return status; + } + + public void SendCommandToServer(String[] args, ICommandSender sender) { + String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); + + //JsonStringCommand sc = new JsonStringCommand(args[0], WSClient.gson.toJson(command)); + RawCommand rc = new RawCommand(args[0], WSClient.gson.toJson(command)); + if (CoflSky.Wrapper.isRunning) { + CoflSky.Wrapper.SendMessage(rc); + } else { + SendAfterStart(sender, rc); + } + } + + private static synchronized void SendAfterStart(ICommandSender sender, RawCommand rc) { + sender.addChatMessage(new ChatComponentText("CoflSky wasn't active.").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); + //CoflSky.Wrapper.stop(); + CoflSky.Wrapper.startConnection(); + CoflSky.Wrapper.SendMessage(rc); + } + + public void ListHelp(ICommandSender sender) { + sender.addChatMessage(new ChatComponentText(HelpText)); + sender.addChatMessage(new ChatComponentText(QueryServerCommands.QueryCommands())); + } + + public void CallbackCommand(String[] args) { + + String command = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); + System.out.println("CallbackData: " + command); + //new Thread(()->{ + System.out.println("Callback: " + command); + WSCommandHandler.HandleCommand(new JsonStringCommand(CommandType.Execute, WSClient.gson.toJson(command)), Minecraft.getMinecraft().thePlayer); + CoflSky.Wrapper.SendMessage(new JsonStringCommand(CommandType.Clicked, WSClient.gson.toJson(command))); + + System.out.println("Sent!"); + //}).start(); + + } } diff --git a/src/main/java/de/torui/coflsky/FlipHandler.java b/src/main/java/de/torui/coflsky/FlipHandler.java index 0c89f21..d3b683e 100644 --- a/src/main/java/de/torui/coflsky/FlipHandler.java +++ b/src/main/java/de/torui/coflsky/FlipHandler.java @@ -1,122 +1,127 @@ package de.torui.coflsky; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; +import de.torui.coflsky.commands.models.FlipData; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class FlipHandler { - public static class Flip { - public String id; - public int worth; - - public Flip(String id, int worth) { - super(); - this.id = id; - this.worth = worth; - } - - public Flip() { - - } - - } - - public static class FlipDataStructure { - - private Map<Long, Flip> Flips = new ConcurrentHashMap <>(); - private Map<Flip, Long> ReverseMap = new ConcurrentHashMap <>(); - - private Flip HighestFlip = null; - - private Timer t = new Timer(); - private TimerTask CurrentTask = null; - - public synchronized void RunHouseKeeping() { - synchronized (Flips) { - - Long RemoveAllPrior = System.currentTimeMillis() - (Config.KeepFlipsForSeconds*1000); - Flips.keySet().stream().filter(l -> l <= RemoveAllPrior).forEach(l -> RemoveLong(l)); - if (!Flips.isEmpty()) { - HighestFlip = Flips.values().stream().max((f1, f2) -> f1.worth - f2.worth).orElse(null); - } else { - HighestFlip = null; - } - } - - if (CurrentTask != null) { - CurrentTask.cancel(); - CurrentTask = null; - t.purge(); - } - if (!Flips.isEmpty()) { - CurrentTask = new TimerTask() { - @Override - public void run() { - RunHouseKeeping(); - } - }; - t.schedule(CurrentTask, Config.KeepFlipsForSeconds * 1000 + /* small arbitrary delay */150); - } - } - - public synchronized void Insert(Flip flip) { - Long l = System.currentTimeMillis(); - - synchronized(Flips) { - Flips.put(l, flip); - ReverseMap.put(flip, l); - } - - RunHouseKeeping(); - } - - private void RemoveLong(Long l) { - if (l == null) - return; - synchronized(Flips) { - Flip f = Flips.get(l); - if (f != null) { - ReverseMap.remove(f); - Flips.remove(l); - } - } - } - - private void RemoveFlip(Flip f) { - if (f == null) - return; - - synchronized(Flips) { - Long l = ReverseMap.get(f); - if (l != null) { - Flips.remove(l); - ReverseMap.remove(f); - } - } - } - - public Flip GetHighestFlip() { - return HighestFlip; - } - - public void InvalidateFlip(Flip flip) { - RemoveFlip(flip); - RunHouseKeeping(); - } - - public int CurrentFlips() { - return Flips.size(); - } - - } - - public FlipDataStructure fds; - - public FlipHandler() { - fds = new FlipDataStructure(); - } + + public static class FlipDataStructure { + + private Map<Long, FlipData> Flips = new ConcurrentHashMap<>(); + private Map<FlipData, Long> ReverseMap = new ConcurrentHashMap<>(); + + private FlipData HighestFlip = null; + private FlipData LastFlip = null; + + private Timer t = new Timer(); + private TimerTask CurrentTask = null; + + public synchronized void RunHouseKeeping() { + synchronized (Flips) { + + Long RemoveAllPrior = System.currentTimeMillis() - (Config.KeepFlipsForSeconds * 1000); + Flips.keySet().stream().filter(l -> l <= RemoveAllPrior).forEach(l -> RemoveLong(l)); + if (!Flips.isEmpty()) { + HighestFlip = Flips.values().stream().max((f1, f2) -> f1.Worth - f2.Worth).orElse(null); + } else { + HighestFlip = null; + } + } + + if (CurrentTask != null) { + CurrentTask.cancel(); + CurrentTask = null; + t.purge(); + } + if (!Flips.isEmpty()) { + CurrentTask = new TimerTask() { + @Override + public void run() { + RunHouseKeeping(); + } + }; + t.schedule(CurrentTask, Config.KeepFlipsForSeconds * 1000 + /* small arbitrary delay */150); + } + } + + public synchronized void Insert(FlipData flip) { + Long l = System.currentTimeMillis(); + LastFlip = flip; + + synchronized (Flips) { + Flips.put(l, flip); + ReverseMap.put(flip, l); + } + + RunHouseKeeping(); + } + + private void RemoveLong(Long l) { + if (l == null) + return; + synchronized (Flips) { + FlipData f = Flips.get(l); + if (f != null) { + ReverseMap.remove(f); + Flips.remove(l); + } + } + } + + private void RemoveFlip(FlipData f) { + if (f == null) + return; + + synchronized (Flips) { + Long l = ReverseMap.get(f); + if (l != null) { + Flips.remove(l); + ReverseMap.remove(f); + } + } + } + + public FlipData GetHighestFlip() { + return HighestFlip; + } + + public FlipData GetLastFlip() { + if (LastFlip == null) { + return null; + } + Long l = ReverseMap.get(LastFlip); + if (l == null) { + LastFlip = null; + } + return LastFlip; + } + + public FlipData getFlipById(String id) { + FlipData[] flips = Flips.values().stream().filter(flipData -> flipData.Id.equals(id)).toArray(FlipData[]::new); + Flips.forEach((key, value) -> System.out.println(value.Id)); + if (flips.length == 0) { + return null; + } + return flips[0]; + } + + public void InvalidateFlip(F |
