diff options
Diffstat (limited to 'src/main/java/de/hype/bbsentials')
37 files changed, 1582 insertions, 329 deletions
diff --git a/src/main/java/de/hype/bbsentials/chat/Chat.java b/src/main/java/de/hype/bbsentials/chat/Chat.java index 7a9c53a..00380ff 100644 --- a/src/main/java/de/hype/bbsentials/chat/Chat.java +++ b/src/main/java/de/hype/bbsentials/chat/Chat.java @@ -7,6 +7,7 @@ import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.text.Text; import net.minecraft.util.Formatting; + import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; @@ -57,13 +58,11 @@ public class Chat { if (java.lang.reflect.Modifier.isTransient(field.getModifiers())) { continue; } - String variableName = field.getName(); String variablePackageName = clazz.getPackage().getName(); String variableClassName = clazz.getSimpleName(); - String variableInfo = variableName; - variableInfoList.add(variableInfo); + variableInfoList.add(variableName); } return variableInfoList.toArray(new String[variableInfoList.size()]); @@ -167,7 +166,7 @@ public class Chat { //Handle in client public Text handleInClient(Text messageOriginal) { - String message = extractPlainText(messageOriginal.toString()).trim(); + String message = messageOriginal.getString().trim(); if (getConfig().messageFromAlreadyReported(message) && getPlayerNameFromMessage(message) != " " && getPlayerNameFromMessage(message) != "") { System.out.println("Message: " + message); sendPrivateMessageToSelf(Formatting.RED + "B: " + message); @@ -243,35 +242,6 @@ public class Chat { } } - } //Everything containing party is processed differently (split so fewer checks) - else if (message.contains("unlocked Wither Essence") && message.startsWith(getConfig().getUsername())) { - if (BBsentials.getConfig().isLeader()) { - repartyActive = true; - sendCommand("/pl"); - } - else { - System.out.println("No Reparty because not leader"); - } - if (getConfig().isLeaveDungeonAutomatically()) { - config.sender.addSendTask("/warp dhub", 3); - } - } - else if (message.contains("unlocked Crimson Essence") && message.startsWith(getConfig().getUsername())) { - if (BBsentials.getConfig().isLeader()) { - repartyActive = true; - sendCommand("/pl"); - } - else { - System.out.println("No Reparty because not leader"); - } - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - if (getConfig().isLeaveKuudraAutomatically()) { - sendCommand("/warp kuudra"); - } } else if (message.contains("bb:test")) { sendPrivateMessageToSelf(test()); @@ -321,19 +291,7 @@ public class Chat { } } } - else if (message.equals("You laid an Egg!")) { - Thread eggThread = new Thread(() -> { - try { - Thread.sleep(21000); // Wait for 21 seconds (in milliseconds) - sendPrivateMessageToSelf("Chicken Head is ready"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); - - eggThread.start(); - } - else if (message.contains("[OPEN MENU]") || message.contains("YES")) { + else if (message.contains("[OPEN MENU]") || message.contains("[YES]")) { setChatPromtId(messageOriginal.toString()); } @@ -535,7 +493,11 @@ public class Chat { new Thread(new Runnable() { @Override public void run() { - BBsentials.getConfig().setLastChatPromptAnswer("/cb " + finalLastPrompt1); + String promptCommand = "/cb " + finalLastPrompt1; + BBsentials.getConfig().setLastChatPromptAnswer(promptCommand); + if (config.isDevModeEnabled()) { + Chat.sendPrivateMessageToSelf("set the last prompt action too + \""+promptCommand+"\""); + } try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { @@ -552,13 +514,17 @@ public class Chat { new Thread(new Runnable() { @Override public void run() { - BBsentials.getConfig().setLastChatPromptAnswer("/chatprompt " + finalLastPrompt + " YES"); + String promptCommand = "/chatprompt " + finalLastPrompt + " YES"; + getConfig().setLastChatPromptAnswer(promptCommand); + if (config.isDevModeEnabled()) { + Chat.sendPrivateMessageToSelf("set the last prompt action too + \""+promptCommand+"\""); + } try { Thread.sleep(10 * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } - BBsentials.getConfig().setLastChatPromptAnswer(null); + getConfig().setLastChatPromptAnswer(null); return; } }).start(); @@ -575,4 +541,4 @@ public class Chat { Text output = Text.Serializer.fromJson(text); return output; } -}
\ No newline at end of file +} diff --git a/src/main/java/de/hype/bbsentials/client/BBsentials.java b/src/main/java/de/hype/bbsentials/client/BBsentials.java index 66807a0..2317a18 100644 --- a/src/main/java/de/hype/bbsentials/client/BBsentials.java +++ b/src/main/java/de/hype/bbsentials/client/BBsentials.java @@ -21,6 +21,9 @@ import org.lwjgl.glfw.GLFW; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import static de.hype.bbsentials.chat.Chat.*; @@ -29,7 +32,7 @@ public class BBsentials implements ClientModInitializer { public static Config config; public static BBsentialConnection bbserver; public static CommandsOLD coms; - + public static ScheduledExecutorService executionService = Executors.newScheduledThreadPool(1000); /** * Runs the mod initializer on the client environment. */ @@ -122,7 +125,7 @@ public class BBsentials implements ClientModInitializer { String variableName = StringArgumentType.getString(context, "variableName"); String variableValue = StringArgumentType.getString(context, "variableValue"); try { - if (!variableName.contains("dev")||config.bbsentialsRoles.contains("dev")){ + if (!variableName.toLowerCase().contains("dev")||config.hasBBRoles("dev")){ setVariableValue(getConfig(), variableName, variableValue);} getConfig().save(); } catch (ClassNotFoundException | NoSuchFieldException | @@ -166,6 +169,7 @@ public class BBsentials implements ClientModInitializer { }))) ); }); //bbi} + executionService.scheduleAtFixedRate(new DebugThread(),0,20, TimeUnit.SECONDS); } public static void refreshCommands() { diff --git a/src/main/java/de/hype/bbsentials/client/Commands/CommandsOLD.java b/src/main/java/de/hype/bbsentials/client/Commands/CommandsOLD.java index 10b3037..e1f3141 100644 --- a/src/main/java/de/hype/bbsentials/client/Commands/CommandsOLD.java +++ b/src/main/java/de/hype/bbsentials/client/Commands/CommandsOLD.java @@ -1,29 +1,41 @@ package de.hype.bbsentials.client.Commands; +import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; +import de.hype.bbsentials.chat.Chat; import de.hype.bbsentials.client.BBsentials; -import de.hype.bbsentials.communication.BBsentialConnection; +import de.hype.bbsentials.constants.enviromentShared.ChChestItems; +import de.hype.bbsentials.constants.enviromentShared.Islands; +import de.hype.bbsentials.constants.enviromentShared.MiningEvents; +import de.hype.bbsentials.packets.AbstractPacket; +import de.hype.bbsentials.packets.packets.*; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; +import net.fabricmc.fabric.api.event.Event; import net.minecraft.command.CommandSource; +import java.util.ArrayList; +import java.util.List; + import static de.hype.bbsentials.client.BBsentials.*; public class CommandsOLD { public CommandsOLD() { - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("warp").then(ClientCommandManager.argument("destination", StringArgumentType.string()).suggests((context, builder) -> { - // Provide tab-completion options for menu subfolder - return CommandSource.suggestMatching(new String[]{"desert", "hub", "dhub", "nether", "isle", "wizard", "portal", "mines", "forge", "ch", "crystals", "nucleus", "end", "drag", "void", "castle", "howl", "park", "jungle", "nest", "arachne", "spider", "deep", "barn", "home", "kuurda", "wasteland", "dragontail", "scarleton", "smold", "garden", "da", "crypt", "museum", "trapper", "dungeon_hub"}, builder); - }).executes((context) -> { - // Handle "variableName" and "variableValue" logic here - String destination = StringArgumentType.getString(context, "destination"); - getConfig().sender.addSendTask("/warp " + destination, 0); - return 1; - }))); - }); //warp test - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + Event<ClientCommandRegistrationCallback> event = ClientCommandRegistrationCallback.EVENT; +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("warp").then(ClientCommandManager.argument("destination", StringArgumentType.string()).suggests((context, builder) -> { +// // Provide tab-completion options for menu subfolder +// return CommandSource.suggestMatching(new String[]{"desert", "hub", "dhub", "nether", "isle", "wizard", "portal", "mines", "forge", "ch", "crystals", "nucleus", "end", "drag", "void", "castle", "howl", "park", "jungle", "nest", "arachne", "spider", "deep", "barn", "home", "kuurda", "wasteland", "dragontail", "scarleton", "smold", "garden", "da", "crypt", "museum", "trapper", "dungeon_hub"}, builder); +// }).executes((context) -> { +// // Handle "variableName" and "variableValue" logic here +// String destination = StringArgumentType.getString(context, "destination"); +// getConfig().sender.addSendTask("/warp " + destination, 0); +// return 1; +// }))); +// }); //warp test + event.register((dispatcher, registryAccess) -> { dispatcher.register(ClientCommandManager.literal("creport") .then(ClientCommandManager.argument("Player_Name", StringArgumentType.string()) .executes((context) -> { @@ -33,145 +45,128 @@ public class CommandsOLD { return 1; }))); });//creport helper → no double report during same launch - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("hp").then(ClientCommandManager.literal("accept").then(ClientCommandManager.argument("player", StringArgumentType.string()).executes((context) -> { - String player = StringArgumentType.getString(context, "player"); - getConfig().sender.addImmediateSendTask("/party accept " + player); - return 1; - }))).then(ClientCommandManager.literal("chat").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party chat"); - return 1; - })).then(ClientCommandManager.literal("demote").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { - // Provide tab-completion options for menu subfolder - return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); - }).executes((context) -> { - String player = StringArgumentType.getString(context, "player"); - getConfig().sender.addImmediateSendTask("/party demote " + player); - return 1; - }))).then(ClientCommandManager.literal("disband").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party disband"); - return 1; - })).then(ClientCommandManager.literal("kick").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { - // Provide tab-completion options for menu subfolder - return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); - }).executes((context) -> { - String player = StringArgumentType.getString(context, "player"); - getConfig().sender.addImmediateSendTask("/party kick " + player); - return 1; - }))).then(ClientCommandManager.literal("kickoffline").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party kickoffline"); - return 1; - })).then(ClientCommandManager.literal("leave").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party leave"); - return 1; - })).then(ClientCommandManager.literal("list").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party list"); - return 1; - })).then(ClientCommandManager.literal("mute").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party mute"); - return 1; - })).then(ClientCommandManager.literal("poll").then(ClientCommandManager.argument("question/answer/answer/answer", StringArgumentType.greedyString()).executes((context) -> { - String questionAndAnswers = StringArgumentType.getString(context, "question answer answer (answer)"); - getConfig().sender.addImmediateSendTask("/party poll " + questionAndAnswers); - return 1; - }))).then(ClientCommandManager.literal("private").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party private"); - return 1; - })).then(ClientCommandManager.literal("promote").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { - // Provide tab-completion options for menu subfolder - return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); - }).executes((context) -> { - String player = StringArgumentType.getString(context, "player"); - getConfig().sender.addImmediateSendTask("/party promote " + player); - return 1; - }))).then(ClientCommandManager.literal("setting").then(ClientCommandManager.literal("allinvite")).executes((context) -> { - String setting = StringArgumentType.getString(context, "setting"); - getConfig().sender.addImmediateSendTask("/party setting " + setting); - return 1; - }) - - ).then(ClientCommandManager.literal("transfer").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { - // Provide tab-completion options for menu subfolder - return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); - }).executes((context) -> { - String player = StringArgumentType.getString(context, "player"); - getConfig().sender.addImmediateSendTask("/party transfer " + player); - return 1; - }))).then(ClientCommandManager.literal("warp").executes((context) -> { - getConfig().sender.addImmediateSendTask("/party warp"); - return 1; - })).executes(context -> { - getConfig().sender.addImmediateSendTask("/p"); - return 1; - })); - }); //party test - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("goblinraid") - .executes((context) -> { - bbserver.sendMessage("?dwevent goblinraid"); - return 1; - }) - ); +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("hp").then(ClientCommandManager.literal("accept").then(ClientCommandManager.argument("player", StringArgumentType.string()).executes((context) -> { +// String player = StringArgumentType.getString(context, "player"); +// getConfig().sender.addImmediateSendTask("/party accept " + player); +// return 1; +// }))).then(ClientCommandManager.literal("chat").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party chat"); +// return 1; +// })).then(ClientCommandManager.literal("demote").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { +// // Provide tab-completion options for menu subfolder +// return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); +// }).executes((context) -> { +// String player = StringArgumentType.getString(context, "player"); +// getConfig().sender.addImmediateSendTask("/party demote " + player); +// return 1; +// }))).then(ClientCommandManager.literal("disband").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party disband"); +// return 1; +// })).then(ClientCommandManager.literal("kick").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { +// // Provide tab-completion options for menu subfolder +// return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); +// }).executes((context) -> { +// String player = StringArgumentType.getString(context, "player"); +// getConfig().sender.addImmediateSendTask("/party kick " + player); +// return 1; +// }))).then(ClientCommandManager.literal("kickoffline").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party kickoffline"); +// return 1; +// })).then(ClientCommandManager.literal("leave").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party leave"); +// return 1; +// })).then(ClientCommandManager.literal("list").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party list"); +// return 1; +// })).then(ClientCommandManager.literal("mute").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party mute"); +// return 1; +// })).then(ClientCommandManager.literal("poll").then(ClientCommandManager.argument("question/answer/answer/answer", StringArgumentType.greedyString()).executes((context) -> { +// String questionAndAnswers = StringArgumentType.getString(context, "question answer answer (answer)"); +// getConfig().sender.addImmediateSendTask("/party poll " + questionAndAnswers); +// return 1; +// }))).then(ClientCommandManager.literal("private").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party private"); +// return 1; +// })).then(ClientCommandManager.literal("promote").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { +// // Provide tab-completion options for menu subfolder +// return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); +// }).executes((context) -> { +// String player = StringArgumentType.getString(context, "player"); +// getConfig().sender.addImmediateSendTask("/party promote " + player); +// return 1; +// }))).then(ClientCommandManager.literal("setting").then(ClientCommandManager.literal("allinvite")).executes((context) -> { +// String setting = StringArgumentType.getString(context, "setting"); +// getConfig().sender.addImmediateSendTask("/party setting " + setting); +// return 1; +// }) +// +// ).then(ClientCommandManager.literal("transfer").then(ClientCommandManager.argument("player", StringArgumentType.string()).suggests((context, builder) -> { +// // Provide tab-completion options for menu subfolder +// return CommandSource.suggestMatching(getConfig().getPlayersInParty(), builder); +// }).executes((context) -> { +// String player = StringArgumentType.getString(context, "player"); +// getConfig().sender.addImmediateSendTask("/party transfer " + player); +// return 1; +// }))).then(ClientCommandManager.literal("warp").executes((context) -> { +// getConfig().sender.addImmediateSendTask("/party warp"); +// return 1; +// })).executes(context -> { +// getConfig().sender.addImmediateSendTask("/p"); +// return 1; +// })); +// }); //party test + event.register((dispatcher, registryAccess) -> { + miningEvent(dispatcher, "goblinraid", MiningEvents.GOBLIN_RAID); });/*goblinraid*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("2xpowder") - .executes((context) -> { - bbserver.sendMessage("?dwevent 2xpowder"); - return 1; - }) - ); + event.register((dispatcher, registryAccess) -> { + miningEvent(dispatcher, "2xpowder", MiningEvents.DOUBLE_POWDER); });/*2xpowder*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("bettertogether") - .executes((context) -> { - bbserver.sendMessage("?dwevent bettertogether"); - return 1; - }) - ); + event.register((dispatcher, registryAccess) -> { + miningEvent(dispatcher, "bettertogether", MiningEvents.BETTER_TOGETHER); });/*b2g*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("raffle") - .executes((context) -> { - bbserver.sendMessage("?dwevent raffle"); - return 1; - }) - ); + event.register((dispatcher, registryAccess) -> { + miningEvent(dispatcher, "raffle", MiningEvents.RAFFLE); });/*raffle*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("gonewiththewind") - .executes((context) -> { - bbserver.sendMessage("?dwevent gonewiththewind"); - return 1; - }) - ); + event.register((dispatcher, registryAccess) -> { + miningEvent(dispatcher, "gonewiththewind", MiningEvents.GONE_WITH_THE_WIND); + });/*gonewiththewind*/ + event.register((dispatcher, registryAccess) -> { + miningEvent(dispatcher, "mithrilgourmand", MiningEvents.MITHRIL_GOURMAND); });/*gonewiththewind*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + event.register((dispatcher, registryAccess) -> { dispatcher.register(ClientCommandManager.literal("chchest") .then(ClientCommandManager.argument("Item", StringArgumentType.string()) .suggests((context, builder) -> { - return CommandSource.suggestMatching(new String[]{"PrehistoricEgg", "Pickonimbus2000", "ElectronTransmitter", "FTX3070", "RobotronReflector", "ControlSwitch", "SyntheticHeart", "SuperliteMotor", "BlueGoblinEgg", "YellowGoblinEgg", "FlawlessAmberGemstone", "FlawlessJadeGemstone", "FlawlessSapphireGemstone", "FlawlessRubyGemstone", "FlawlessAmethystGemstone", "JungleHeart", "FlawlessTopazGemstone", "FlawlessJasperGemstone"}, builder); + String[] items = new String[]{"PrehistoricEgg", "Pickonimbus2000", "ElectronTransmitter", "FTX3070", "RobotronReflector", "ControlSwitch", "SyntheticHeart", "SuperliteMotor", "BlueGoblinEgg", "YellowGoblinEgg", "FlawlessAmberGemstone", "FlawlessJadeGemstone", "FlawlessSapphireGemstone", "FlawlessRubyGemstone", "FlawlessAmethystGemstone", "JungleHeart", "FlawlessTopazGemstone", "FlawlessJasperGemstone"}; + String input = builder.getRemaining().toLowerCase(); + int lastSemicolonIndex = input.lastIndexOf(";"); + List<String> suggestions = new ArrayList<>(); + if (lastSemicolonIndex >= 0) { + String inputBeforeSemicolon = input.substring(0, lastSemicolonIndex + 1); // Include the semicolon + + for (String item : items) { + suggestions.add(inputBeforeSemicolon + item); + } + } + return CommandSource.suggestMatching(suggestions, builder); }) .then(ClientCommandManager.argument("X", IntegerArgumentType.integer()) .then(ClientCommandManager.argument("Y", IntegerArgumentType.integer()) .then(ClientCommandManager.argument("Z", IntegerArgumentType.integer()) - .then(ClientCommandManager.argument("ContactWay", StringArgumentType.greedyString()) + .then(ClientCommandManager.argument("ContactWay", StringArgumentType.string()) .suggests(((context, builder) -> { return CommandSource.suggestMatching(new String[]{"/msg " + getConfig().getUsername() + " bb:party me", "/p join " + config.getUsername()}, builder); })) .executes((context) -> { - String destination = StringArgumentType.getString(context, "Item"); + String item = StringArgumentType.getString(context, "Item"); int x = IntegerArgumentType.getInteger(context, "X"); int y = IntegerArgumentType.getInteger(context, "Y"); int z = IntegerArgumentType.getInteger(context, "Z"); String contactWay = StringArgumentType.getString(context, "ContactWay"); - String combinedString = "?chchest " + destination + " " + x + " " + y + " " + z + " " + contactWay; - bbserver.sendMessage(combinedString); + bbserver.sendPacket(new ChChestPackage("", ChChestItems.getItem(item.split(";")), x + "" + y + "" + z, contactWay, "")); return 1; } ) @@ -182,7 +177,7 @@ public class CommandsOLD { ) ); }); /*chchest*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("bbserver") .then(ClientCommandManager.argument("Message", StringArgumentType.greedyString()) @@ -190,7 +185,8 @@ public class CommandsOLD { String message = StringArgumentType.getString(context, "Message"); if (message.equals("bb:reconnect")) { BBsentials.connectToBBserver(); - } else { + } + else { BBsentials.bbserver.sendMessage(message); } return 1; @@ -198,33 +194,33 @@ public class CommandsOLD { ) ); });/*BBserver*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("bc") .then(ClientCommandManager.argument("Message to Bingo Chat", StringArgumentType.greedyString()) .executes((context) -> { String message = StringArgumentType.getString(context, "Message to Bingo Chat"); - sendCommand("?bingochat " + message); + sendPacket(new BingoChatMessagePacket("", "", message, 0)); return 1; }) ) ); });/*BincoChatShort*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("bingochat") .then(ClientCommandManager.argument("Message to Bingo Chat", StringArgumentType.greedyString()) .executes((context) -> { String message = StringArgumentType.getString(context, "Message to Bingo Chat"); - sendCommand("?bingochat " + message); + sendPacket(new BingoChatMessagePacket("", "", message, 0)); return 1; }) ) ); });/*BingoChatLong*/ if (getConfig().bbsentialsRoles != null) { - if (getConfig().bbsentialsRoles.contains("mod")) { - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + if (getConfig().hasBBRoles("mod")) { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("bannounce") .then(ClientCommandManager.argument("message", StringArgumentType.greedyString()) @@ -236,7 +232,7 @@ public class CommandsOLD { ) ); });/*bAnnounce*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("bmute") .then(ClientCommandManager.argument("message", StringArgumentType.greedyString()) @@ -248,7 +244,7 @@ public class CommandsOLD { ) ); });/*bmute*/ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("bban") .then(ClientCommandManager.argument("message", StringArgumentType.greedyString()) @@ -261,47 +257,84 @@ public class CommandsOLD { ); });/*bmute*/ } - if (getConfig().bbsentialsRoles.contains("splasher")) { - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { + if (getConfig().hasBBRoles("splasher")) { + event.register((dispatcher, registryAccess) -> { dispatcher.register( ClientCommandManager.literal("splashAnnounce") .then(ClientCommandManager.argument("Hub", IntegerArgumentType.integer(1, 28)) .then(ClientCommandManager.argument("location", StringArgumentType.string()) .suggests((context, builder) -> { - return CommandSource.suggestMatching(new String[]{"kat","bea","guild-house"}, builder); + return CommandSource.suggestMatching(new String[]{"kat", "bea", "guild-house"}, builder); }) - .then(ClientCommandManager.argument("extramessage", StringArgumentType.greedyString()) + .then(ClientCommandManager.argument("lasswaste", StringArgumentType.string()) + .suggests((context, builder) -> { + return CommandSource.suggestMatching(new String[]{"true", "false"}, builder); + }) + .then(ClientCommandManager.argument("extramessage", StringArgumentType.greedyString()) + .executes((context) -> { + int hub = IntegerArgumentType.getInteger(context, "Hub"); + String extramessage = StringArgumentType.getString(context, "extramessage"); + String location = StringArgumentType.getString(context, "location"); + boolean lessWaste = Boolean.parseBoolean(StringArgumentType.getString(context, "lasswaste")); + sendPacket(new SplashNotifyPacket(hub, config.getUsername(), location, Islands.HUB, extramessage, lessWaste)); + return 1; + }) + ) .executes((context) -> { - int hub_Number = IntegerArgumentType.getInteger(context, "Hub"); - String extramessage = StringArgumentType.getString(context, "extramessage"); - String location = StringArgumentType.getString(context, "location"); - sendCommand("?splash " + hub_Number + " " + location+" "+extramessage); + int hub = IntegerArgumentType.getInteger(context, "Hub"); + String location = "bea"; + boolean lessWaste = Boolean.parseBoolean(StringArgumentType.getString(context, "lasswaste")); + sendPacket(new SplashNotifyPacket(hub, config.getUsername(), location, Islands.HUB, "", lessWaste)); return 1; }) - ) - .executes((context) -> { - int hub_Number = IntegerArgumentType.getInteger(context, "Hub"); - String message = ""; - String location = "bea"; - sendCommand("?splash " + hub_Number + " "+location+" " + message); - return 1; - }) - ) + )) .executes((context) -> { - int hub_Number = IntegerArgumentType.getInteger(context, "Hub"); - String message = ""; + int hub = IntegerArgumentType.getInteger(context, "Hub"); String location = StringArgumentType.getString(context, "location"); - sendCommand("?splash " + hub_Number + " "+location+" " + message); + sendPacket(new SplashNotifyPacket(hub, config.getUsername(), location, Islands.HUB, "", true)); return 1; }) + ) ); });/*SplashAnnounce*/ - } else { + } + else { } } } - public void sendCommand(String message){ + + private static void simpleCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, String commandName, String[] parameters) { + dispatcher.register( + ClientCommandManager.literal(commandName) + .executes((context) -> { + BBsentials.bbserver.sendPacket(new InternalCommandPacket(commandName, parameters)); + return 1; + }) + ); + } + + private static void miningEvent(CommandDispatcher<FabricClientCommandSource> dispatcher, String commandName, MiningEvents event) { + dispatcher.register( + ClientCommandManager.literal(commandName) + .executes((context) -> { + try { + BBsentials.bbserver.sendPacket(new MiningEventPacket(event,//TODO get the island + config.getUsername(), Islands.HUB)); + } catch (Exception e) { + Chat.sendPrivateMessageToSelf("§c" + e.getMessage()); + } + return 1; + }) + ); + } + + + public void sendCommand(String message) { BBsentials.bbserver.sendCommand(message); } + + public <E extends AbstractPacket> void sendPacket(E packet) { + BBsentials.bbserver.sendPacket(packet); + } }
\ No newline at end of file diff --git a/src/main/java/de/hype/bbsentials/client/Config.java b/src/main/java/de/hype/bbsentials/client/Config.java index 35ba61f..131b067 100644 --- a/src/main/java/de/hype/bbsentials/client/Config.java +++ b/src/main/java/de/hype/bbsentials/client/Config.java @@ -15,6 +15,7 @@ import java.util.ArrayList; public class Config implements Serializable { // Helper class for sending chat messages + public int version = 1; public transient final Sender sender = new Sender(); public transient boolean highlightitem = false; @@ -28,13 +29,14 @@ public class Config implements Serializable { private transient boolean isLeader; private transient String alreadyReported = ""; private String bbServerURL = "static.204.177.34.188.clients.your-server.de"; - public String bbsentialsRoles = ""; + public String[] bbsentialsRoles = {""}; public static ArrayList<String> partyMembers = new ArrayList<>(); // Set via load / default private String bbsentialsCommandPrefix = "."; private String apiKey = ""; private boolean leaveDungeonAutomatically; + public boolean showBingoChat = true; private boolean allowBBinviteMe = true; private boolean leaveKuudraAutomatically; private boolean devMode = false; @@ -42,6 +44,8 @@ public class Config implements Serializable { private boolean acceptReparty; private String nickname; private String getNotifForParty; + private final int apiVersion = 1; + public transient ToDisplayConfig toDisplayConfig = ToDisplayConfig.loadFromFile(); // Set default attribute values private void setDefaults() { @@ -146,16 +150,22 @@ public class Config implements Serializable { } catch (IOException e) { e.printStackTrace(); settings = new Config(); // Use default values if loading fails + settings.save(); + }catch (IllegalStateException e){ + System.out.println("Error loading config. Resetting it."); + settings = new Config(); + settings.save(); } } else { settings = new Config(); // Use default values if the file doesn't exist settings.username = MinecraftClient.getInstance().player.getName().getString(); } - if (!settings.bbsentialsRoles.contains("dev")) { + if (!settings.hasBBRoles("dev")) { settings.detailedDevMode = false; settings.devMode = false; } + settings.save(); return settings; } @@ -244,7 +254,7 @@ public class Config implements Serializable { return isBefore || isInRange; } - public boolean overrideBingoTime() { + public boolean overrideBingoTime() { return overrideBingoTime; } @@ -263,4 +273,21 @@ public class Config implements Serializable { public void setLastChatPromptAnswer(String lastChatPromptAnswer) { this.lastChatPromptAnswer = lastChatPromptAnswer; } + + public int getVersion() { + return version; + } + + public boolean hasBBRoles(String roleName) { + for (String role : bbsentialsRoles) { + if (role.equalsIgnoreCase(roleName)) { + return true; + } + } + return false; + } + + public int getApiVersion() { + return apiVersion; + } } diff --git a/src/main/java/de/hype/bbsentials/client/CustomGson.java b/src/main/java/de/hype/bbsentials/client/CustomGson.java new file mode 100644 index 0000000..e9a41da --- /dev/null +++ b/src/main/java/de/hype/bbsentials/client/CustomGson.java @@ -0,0 +1,28 @@ +package de.hype.bbsentials.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class CustomGson { + public static Gson create() { + return new GsonBuilder() +// .registerTypeHierarchyAdapter(BBDisplayNameProvider.class, new BBDisplayNameProviderSerializer()) + .create(); + + } + +// private static class BBDisplayNameProviderSerializer implements JsonSerializer<BBDisplayNameProvider>, JsonDeserializer<BBDisplayNameProvider> { +// @Override +// public JsonElement serialize(BBDisplayNameProvider src, Type typeOfSrc, JsonSerializationContext context) { +// return new JsonPrimitive(src.serialize()); // Serialize using the provided method +// } +// +// @Override +// public BBDisplayNameProvider deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { +// String serializedValue = json.getAsString(); +// +// // Deserialize using the provided method (you need to implement this) +// return BBDisplayNameProvider.deserialize(serializedValue); +// } +// } +} diff --git a/src/main/java/de/hype/bbsentials/client/DebugThread.java b/src/main/java/de/hype/bbsentials/client/DebugThread.java new file mode 100644 index 0000000..b10cad4 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/client/DebugThread.java @@ -0,0 +1,13 @@ +package de.hype.bbsentials.client; + +public class DebugThread implements Runnable { + @Override + public void run() { + loop(); + //place a breakpoint for only this thread here. + } + + public void loop() { + + } +} diff --git a/src/main/java/de/hype/bbsentials/client/ToDisplayConfig.java b/src/main/java/de/hype/bbsentials/client/ToDisplayConfig.java new file mode 100644 index 0000000..2c513d0 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/client/ToDisplayConfig.java @@ -0,0 +1,97 @@ +package de.hype.bbsentials.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import net.fabricmc.loader.api.FabricLoader; + +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.reflect.Field; + +public class ToDisplayConfig { + private boolean disableAll = true; + private boolean prehistoricEgg = true; + private boolean pickonimbus2000 = true; + private boolean controlSwitch = true; + private boolean electronTransmitter = true; + private boolean ftx3070 = true; + private boolean robotronReflector = true; + private boolean superliteMotor = true; + private boolean syntheticHeart = true; + private boolean flawlessGemstone = true; + private boolean allRoboPartCustomChChestItem = true; + private boolean allChChestItem = true; + private boolean dwBetterTogether = true; + private boolean dwDoublePowder = true; + private boolean dwGoneWithTheWind = true; + private boolean dwGoblinRaid = true; + private boolean dwMithrilGourmand = true; + private boolean dwRaffle = true; + private boolean dwEvents = true; + private boolean chBetterTogether = true; + private boolean chDoublePowder = true; + private boolean chGoneWithTheWind = true; + private boolean chEvents = true; + private boolean allBetterTogether = true; + private boolean allDoublePowder = true; + private boolean allGoneWithTheWind = true; + private boolean allEvents = true; + + // Serialize the object to JSON and save to file + public void saveToFile() { + File configFile = new File(FabricLoader.getInstance().getConfigDirectory(), "BBsentials_display_Config.json"); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + try (FileWriter writer = new FileWriter(configFile)) { + gson.toJson(this, writer); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // Deserialize the object from JSON file + public static ToDisplayConfig loadFromFile() { + File configFile = new File(FabricLoader.getInstance().getConfigDirectory(), "BBsentials_display_Config.json"); + Gson gson = new Gson(); + + try (FileReader reader = new FileReader(configFile)) { + return gson.fromJson(reader, ToDisplayConfig.class); + } catch (IOException e) { + e.printStackTrace(); + } + + // If file doesn't exist or there's an error, return a new instance + return new ToDisplayConfig(); + } + + public void setValueAndSave(String propertyName, Object newValue) { + String lowerCasePropertyName = propertyName.toLowerCase(); + + try { + Field field = getClass().getDeclaredField(lowerCasePropertyName); + field.setAccessible(true); + + field.set(this, newValue); + saveToFile(); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + + // Method to get a value based on property name + public boolean getValue(String propertyName) { + if (disableAll) return false; + String lowerCasePropertyName = propertyName.toLowerCase(); + try { + Field field = getClass().getDeclaredField(lowerCasePropertyName); + field.setAccessible(true); + return field.getBoolean(this); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/src/main/java/de/hype/bbsentials/communication/BBsentialConnection.java b/src/main/java/de/hype/bbsentials/communication/BBsentialConnection.java index 2c6c7d2..ddf8749 100644 --- a/src/main/java/de/hype/bbsentials/communication/BBsentialConnection.java +++ b/src/main/java/de/hype/bbsentials/communication/BBsentialConnection.java @@ -2,11 +2,21 @@ package de.hype.bbsentials.communication; import de.hype.bbsentials.chat.Chat; import de.hype.bbsentials.client.BBsentials; +import de.hype.bbsentials.constants.enviromentShared.AuthenticationConstants; +import de.hype.bbsentials.constants.enviromentShared.ChChestItem; +import de.hype.bbsentials.constants.enviromentShared.Islands; +import de.hype.bbsentials.packets.AbstractPacket; +import de.hype.bbsentials.packets.PacketManager; +import de.hype.bbsentials.packets.PacketUtils; +import de.hype.bbsentials.packets.packets.*; import net.minecraft.client.MinecraftClient; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; -import javax.net.ssl.*; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; import java.io.*; import java.net.Socket; import java.net.SocketException; @@ -17,9 +27,8 @@ import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class BBsentialConnection { @@ -28,8 +37,54 @@ public class BBsentialConnection { private PrintWriter writer; private LinkedBlockingQueue<String> messageQueue; private MessageReceivedCallback messageReceivedCallback; - private ScheduledExecutorService executorService; private String itemName = "Hub #0"; + private PacketManager packetManager; + + public BBsentialConnection() { + packetManager = new PacketManager(this); + } + + public void onBingoChatMessagePacket(BingoChatMessagePacket packet) { + if (BBsentials.config.showBingoChat) { + Chat.sendPrivateMessageToSelf("[" + packet.prefix + "] " + packet.username + ": " + packet.message); + } + } + + public void onChChestPackage(ChChestPackage packet) { + if (isCommandSafe(packet.bbcommand)) { + String tellrawText = ("{\"text\":\"BB: @username found @item in a chest at (@coords). Click here to get a party invite @extramessage\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"@inviteCommand\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"On clicking you will get invited to a party. Command executed: @inviteCommand\"]}}"); + tellrawText = tellrawText.replace("@username", packet.announcerUsername).replace("@item", Arrays.stream(packet.items).map(ChChestItem::getDisplayName).toList().toString()).replace("@coords", packet.locationCoords).replace("@inviteCommand", packet.bbcommand); + if (!(packet.extraMessage == null || packet.extraMessage.isEmpty())) { + tellrawText = tellrawText.replace("@extramessage", " : " + packet.extraMessage); + } + Chat.sendPrivateMessageToSelfText(Chat.createClientSideTellraw(tellrawText)); + } + else { + Chat.sendPrivateMessageToSelf("§cFiltered out a suspicious packet! Please send a screenshot of this message with ping Hype_the_Time (hackthetime) in Bingo Apothecary, BB, SBZ, offical Hypixel,..."); + Chat.sendPrivateMessageToSelf(PacketUtils.parsePacketToJson(packet)); + } + } + + public void onMiningEventPacket(MiningEventPacket packet) { + if (BBsentials.config.toDisplayConfig.getValue("disableAll")) { + //its will returns false cause disabled is checked already before. + Chat.sendPrivateMessageToSelf(packet.username + "There is a " + packet.event.getDisplayName() + "in the " + packet.island.getDisplayName() + " now/soon."); + } + } + + public void onWelcomePacket(WelcomeClientPacket packet) { + if (packet.success) { + BBsentials.config.bbsentialsRoles = packet.roles; + Chat.sendPrivateMessageToSelf("Login Success"); + if (!packet.motd.isEmpty()) { + Chat.sendPrivateMessageToSelf(packet.motd); + } + } + else { + Chat.sendPrivateMessageToSelf("Login Failed"); + } + + } public interface MessageReceivedCallback { void onMessageReceived(String message); @@ -77,30 +132,28 @@ public class BBsentialConnection { PublicKey serverPublicKey = serverCertificate.getPublicKey(); // Create a TrustManager that trusts only the server's public key - TrustManager[] trustManagers = new TrustManager[]{ - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return null; // We don't need to check the client's certificates - } + TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; // We don't need to check the client's certificates + } - public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { - // Do nothing, client certificate validation not required - } + public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { + // Do nothing, client certificate validation not required + } - public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { - // Check if the server certificate matches the expected one - if (certs.length == 1) { - PublicKey publicKey = certs[0].getPublicKey(); - if (!publicKey.equals(serverPublicKey)) { - throw new CertificateException("Server certificate not trusted."); - } - } - else { - throw new CertificateException("Invalid server certificate chain."); - } + public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { + // Check if the server certificate matches the expected one + if (certs.length == 1) { + PublicKey publicKey = certs[0].getPublicKey(); + if (!publicKey.equals(serverPublicKey)) { + throw new CertificateException("Server certificate not trusted."); } } - }; + else { + throw new CertificateException("Invalid server certificate chain."); + } + } + }}; // Create an SSL context with the custom TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); @@ -108,7 +161,7 @@ public class BBsentialConnection { // Create an SSL socket factory SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - socket = (SSLSocket) sslSocketFactory.createSocket(serverIP, serverPort); + socket = sslSocketFactory.createSocket(serverIP, serverPort); socket.setKeepAlive(true); // Enable Keep-Alive @@ -116,8 +169,6 @@ public class BBsentialConnection { writer = new PrintWriter(socket.getOutputStream(), true); messageQueue = new LinkedBlockingQueue<>(); - executorService = new ScheduledThreadPoolExecutor(2); // Adjust the pool size as needed - // Start message receiver thread Thread messageReceiverThread = new Thread(() -> { try { @@ -142,7 +193,7 @@ public class BBsentialConnection { } }); messageReceiverThread.start(); - + messageReceiverThread.setName("bb receiver thread"); // Start message sender thread Thread messageSenderThread = new Thread(() -> { try { @@ -155,12 +206,11 @@ public class BBsentialConnection { } }); messageSenderThread.start(); + messageSenderThread.setName("bb sender thread"); - } catch (IOException | NoSuchAlgorithmException | - KeyManagementException e) { + } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); - } catch ( - CertificateException e) { + } catch (CertificateException e) { throw new RuntimeException(e); } @@ -200,96 +250,96 @@ public class BBsentialConnection { //The following onMessageReceived may or may not be modified // or taken out of order in private/ non official versions of the mod! public void onMessageReceived(String message) { - if (message.startsWith("H-")) { - if (message.equals("H-BB-Login: ")) { - Chat.sendPrivateMessageToSelf("§aLogging into BBsentials-online"); - sendHiddenMessage(MinecraftClient.getInstance().player.getUuid().toString().replace("-", "")); - writer.println(BBsentials.getConfig().getApiKey()); - sendHiddenMessage("?getperms"); - } - else if (message.contains("H-potdurations?")) { - sendHiddenMessage("?potduration " + getPotTime()); - } - else if (message.startsWith("H-splash")) { - String[] arguments = message.split(" ", 7); - int min = (1 * 60 * 60) - Integer.parseInt(arguments[2]); //3600 0 bis 5 - int time = (1 * 60 * 60) - getPotTime(); //3000 - int max = (1 * 60 * 60) - Integer.parseInt(arguments[3]); //3300 - if ((time <= min) && (time >= max)) { - if (arguments.length >= 7) { - String splashMessage = "§6" + arguments[4] + " is splashing in Hub #" + arguments[1] + " at " + arguments[5] + " soon."; - splashMessage = splashMessage + " : " + arguments[6]; - Chat.sendPrivateMessageToSelf(splashMessage); - splashHighlightItem("Hub #" + arguments[1], 30000); + if (!PacketUtils.handleIfPacket(this, message)) { + if (message.startsWith("H-")) { + if (message.equals("H-BB-Login: ")) { + Chat.sendPrivateMessageToSelf("§aLogging into BBsentials-online"); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); } + sendPacket(new RequestConnectPacket(MinecraftClient.getInstance().player.getUuid().toString().replace("-", ""), BBsentials.getConfig().getApiKey(), BBsentials.getConfig().getApiVersion(), AuthenticationConstants.DATABASE)); } - } - else if (message.startsWith("H-roles")) { - BBsentials.getConfig().bbsentialsRoles = message.replace("H-Roles ", ""); - BBsentials.refreshCommands(); - } - else if (message.startsWith("H-chchest")) { - String[] arguments = message.replace("H-chchest", "").trim().split(" ", 6); // Split with limit of 5 - String username = arguments[0]; - String item = arguments[1]; - int x = Integer.parseInt(arguments[2]); - int y = Integer.parseInt(arguments[3]); - int z = Integer.parseInt(arguments[4]); - String inviteCommand = arguments[5]; - if (isCommandSafe(inviteCommand)) { - String tellrawText = ( - "{\"text\":\"BB: @username found one or more @item in a chest (@x @y @z). Click here to join\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"@inviteCommand\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"On clicking you will get invited to a party. Command executed: @inviteCommand\"]}}" - ); - tellrawText = tellrawText.replace("@username", username).replace("@item", item).replace("@x", x + "").replace("@y", y + "").replace("@z", z + "").replace("@inviteCommand", inviteCommand); - Chat.sendPrivateMessageToSelfText(Chat.createClientSideTellraw(tellrawText)); + else if (message.contains("H-potdurations?")) { + sendHiddenMessage("?potduration " + getPotTime()); } - } - else if (message.startsWith("H-event")) { - String[] arguments = message.replace("H-event", "").trim().split(" "); - Chat.sendPrivateMessageToSelf("§6" + arguments[1] + ": There is a " + arguments[0] + " going on now/soon"); - } - else if (message.startsWith("H-reconnect")) { - Chat.sendPrivateMessageToSelf("§4BBserver-online is going to restart soon. You will be automatically reconnected.\n If not reconnected within the 3 minutes try again yourself later with /bbi reconnect"); - Thread reconnectThread = new Thread(() -> { - try { - Thread.sleep((long) ((30 * 1000) + (Math.random() * 30 * 1000))); - } catch (InterruptedException e) { - e.printStackTrace(); +// else if (message.startsWith("H-reconnect")) { +// Chat.sendPrivateMessageToSelf("§4BBserver-online is going to restart soon. You will be automatically reconnected.\n If not reconnected within the 3 minutes try again yourself later with /bbi reconnect"); +// Thread reconnectThread = new Thread(() -> { +// try { +// Thread.sleep((long) ((30 * 1000) + (Math.random() * 30 * 1000))); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// BBsentials.connectToBBserver(); +// if (!socket.isConnected()) { +// try { +// Thread.sleep((long) ((30 * 1000) + (Math.random() * 30 * 1000))); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// BBsentials.connectToBBserver(); +// } +// }); +// reconnectThread.start(); +// } + else if (message.startsWith("H-hype")) { + String[] arguments = message.replace("H-hype", "").trim().split(" "); + if (arguments[0].equals("crash")) { + throw new RuntimeException(arguments[1]); } - BBsentials.connectToBBserver(); - if (!socket.isConnected()) { - try { - Thread.sleep((long) ((30 * 1000) + (Math.random() * 30 * 1000))); - } catch (InterruptedException e) { - e.printStackTrace(); - } - BBsentials.connectToBBserver(); + else if (arguments[0].equals("hub")) { + BBsentials.config.sender.addHiddenSendTask("/hub", 1); } - }); - reconnectThread.start(); - } - else if (message.startsWith("H-hype")) { - String[] arguments = message.replace("H-hype", "").trim().split(" "); - if (arguments[0].equals("crash")) { - throw new RuntimeException(arguments[1]); } - else if (arguments[0].equals("hub")) { - BBsentials.config.sender.addHiddenSendTask("/hub", 1); + if (BBsentials.getConfig().isDetailedDevModeEnabled()) { + Chat.sendPrivateMessageToSelf("BBDev-r: " + message); } } - if (BBsentials.getConfig().isDetailedDevModeEnabled()) { - Chat.sendPrivateMessageToSelf("BBDev-r: " + message); + else { + Chat.sendPrivateMessageToSelf("§aBB: " + message); } } + } + + public void onBroadcastMessage(BroadcastMessagePacket packet) { + String message = packet.message; + } + + public void onSplashNotify(SplashNotifyPacket packet) { + int waitTime; + if (packet.lessWaste) { + waitTime = (getPotTime() * 1000) / 80; + } + else { + waitTime = 0; + } + String where; + if (packet.hubType.equals(Islands.DUNGEON_HUB)) { + where = "§5DUNGEON HUB§6"; + } else { - Chat.sendPrivateMessageToSelf("§aBB: " + message); + where = "Hub"; } + BBsentials.executionService.schedule(() -> { + splashHighlightItem("HUB #" + packet.hub, 20); + String timeLoss = ""; + if (packet.lessWaste) { + timeLoss = "§c(" + waitTime + ")"; + } + Chat.sendPrivateMessageToSelf("§6" + packet.splasherUsername + " is Splashing in " + where + " #" + packet.hub + " at " + packet.location + ":" + packet.extraMessage + " | " + timeLoss); + }, waitTime, TimeUnit.MILLISECONDS); + } + + public void dummy(Object o) { + //this does absoloutely nothing } public void splashHighlightItem(String itemName, long displayTimeInMilliseconds) { this.itemName = itemName; BBsentials.config.highlightitem = true; - executorService.schedule(() -> { + BBsentials.executionService.schedule(() -> { BBsentials.config.highlightitem = false; try { socket.setSoTimeout(0); @@ -319,15 +369,16 @@ public class BBsentialConnection { } //TODO search - public static boolean isCommandSafe(String command){ - if (command.startsWith("/p ") || command.startsWith("/party ") || command.startsWith("/boop ") || command.startsWith("/msg ")||command.startsWith("/hub ")) { + public static boolean isCommandSafe(String command) { + if (command.startsWith("/p ") || command.startsWith("/party ") || command.startsWith("/boop ") || command.startsWith("/msg ") || command.startsWith("/hub ")) { return true; - }else { + } + else { BBsentials.bbserver.sendCommand("?emergency server-hacked? chchest command " + command); - String emergencyMessage = "We detected that there was a command used which is not configured to be safe! "+command+" please check if its safe. IMMEDIATELY report this to the Admins and Developer Hype_the_Time (@hackthetime). If it is not safe immediately remove BBsentials!!!!!!!! "; + String emergencyMessage = "We detected that there was a command used which is not configured to be safe! " + command + " please check if its safe. IMMEDIATELY report this to the Admins and Developer Hype_the_Time (@hackthetime). If it is not safe immediately remove BBsentials!!!!!!!! "; System.out.println(emergencyMessage); - Chat.sendPrivateMessageToSelf("§4"+emergencyMessage+"\n\n"); - Chat.sendPrivateMessageToSelf("§4"+emergencyMessage+"\n\n"); + Chat.sendPrivateMessageToSelf("§4" + emergencyMessage + "\n\n"); + Chat.sendPrivateMessageToSelf("§4" + emergencyMessage + "\n\n"); /*try { Thread.sleep(5000); } catch (InterruptedException e) { @@ -337,4 +388,14 @@ public class BBsentialConnection { } return false; } + + public <E extends AbstractPacket> void sendPacket(E packet) { + String packetName = packet.getClass().getSimpleName(); + if (packet.getClass().equals(RequestConnectPacket.class)) { + sendMessage(packetName + "." + PacketUtils.parsePacketToJson(packet)); + } + else { + sendHiddenMessage(packetName + "." + PacketUtils.parsePacketToJson(packet)); + } + } } diff --git a/src/main/java/de/hype/bbsentials/constants/BBDisplayNameProvider.java b/src/main/java/de/hype/bbsentials/constants/BBDisplayNameProvider.java new file mode 100644 index 0000000..308e705 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/BBDisplayNameProvider.java @@ -0,0 +1,23 @@ +package de.hype.bbsentials.constants; + +public interface BBDisplayNameProvider { + String getDisplayName(); + + default String serialize() { + return name() + ":" + getDisplayName(); + } + + default String name() { + return ((Enum<?>) this).name(); + } + +// public static BBDisplayNameProvider deserialize(String serializedValue) { +// String[] parts = serializedValue.split(":"); +// if (parts.length != 2) { +// throw new IllegalArgumentException("Invalid serialized value format"); +// } +// String enumName = parts[0]; +// String displayName = parts[1]; +// return ; +// } +} diff --git a/src/main/java/de/hype/bbsentials/constants/BBDisplayNameProviderWithCustom.java b/src/main/java/de/hype/bbsentials/constants/BBDisplayNameProviderWithCustom.java new file mode 100644 index 0000000..4088443 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/BBDisplayNameProviderWithCustom.java @@ -0,0 +1,6 @@ +package de.hype.bbsentials.constants; + +public interface BBDisplayNameProviderWithCustom<T extends Enum<T>> extends BBDisplayNameProvider { + T setDisplayName(String displayname); + +} diff --git a/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableChChestPingRole.java b/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableChChestPingRole.java new file mode 100644 index 0000000..35d7470 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableChChestPingRole.java @@ -0,0 +1,11 @@ +package de.hype.bbsentials.constants.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface BBSelectableChChestPingRole { +} diff --git a/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableMiningEventPingRole.java b/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableMiningEventPingRole.java new file mode 100644 index 0000000..8e2e503 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableMiningEventPingRole.java @@ -0,0 +1,11 @@ +package de.hype.bbsentials.constants.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface BBSelectableMiningEventPingRole { +} diff --git a/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableRole.java b/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableRole.java new file mode 100644 index 0000000..8597cbc --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/annotations/BBSelectableRole.java @@ -0,0 +1,12 @@ +package de.hype.bbsentials.constants.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface BBSelectableRole { + +} diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/AuthenticationConstants.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/AuthenticationConstants.java new file mode 100644 index 0000000..878f303 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/AuthenticationConstants.java @@ -0,0 +1,7 @@ +package de.hype.bbsentials.constants.enviromentShared; + +public class AuthenticationConstants { + //Authentication Types + public static final String MOJANG = "MOJANG"; + public static final String DATABASE = "DATABASE"; +} diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/ChChestItem.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/ChChestItem.java new file mode 100644 index 0000000..3e6a346 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/ChChestItem.java @@ -0,0 +1,46 @@ +package de.hype.bbsentials.constants.enviromentShared; + +public class ChChestItem { + private String displayName; + private boolean custom; + + public ChChestItem(String displayName) { + this.displayName = displayName; + this.custom = false; + } + + public ChChestItem(String displayName, boolean custom) { + this.displayName = displayName; + this.custom = custom; + } + + public String getDisplayName() { + return displayName; + } + + public ChChestItem setDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + public boolean isCustom() { + return custom; + } + + @Override + public String toString() { + return displayName; + } + + public boolean isGemstone() { + return displayName.startsWith("Flawless") && displayName.endsWith("Gemstone"); + } + + public boolean isRoboPart() { + String[] roboParts = {"Control Switch", "Electron Transmitter", "FTX 3070", "Robotron Reflector", "Superlite Motor", "Synthetic Heart"}; + for (String roboPart : roboParts) { + if (displayName.equals(roboPart)) return true; + } + return false; + } +}
\ No newline at end of file diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/ChChestItems.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/ChChestItems.java new file mode 100644 index 0000000..a416f6e --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/ChChestItems.java @@ -0,0 +1,87 @@ +package de.hype.bbsentials.constants.enviromentShared; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class ChChestItems { + private static final List<ChChestItem> items = new ArrayList<>(); + + public static final ChChestItem PrehistoricEgg = new ChChestItem("Prehistoric Egg"); + public static final ChChestItem Pickonimbus2000 = new ChChestItem("Pickonimbus 2000"); + public static final ChChestItem ControlSwitch = new ChChestItem("Control Switch"); + public static final ChChestItem ElectronTransmitter = new ChChestItem("Electron Transmitter"); + public static final ChChestItem FTX3070 = new ChChestItem("FTX 3070"); + public static final ChChestItem RobotronReflector = new ChChestItem("Robotron Reflector"); + public static final ChChestItem SuperliteMotor = new ChChestItem("Superlite Motor"); + public static final ChChestItem SyntheticHeart = new ChChestItem("Synthetic Heart"); + public static final ChChestItem FlawlessGemstone = new ChChestItem("Flawless Gemstone"); + public static final ChChestItem JungleHeart = new ChChestItem("Jungle Heart"); + + // Automatically populate predefined items using reflection + static { + Field[] fields = ChChestItems.class.getDeclaredFields(); + for (Field field : fields) { + if (field.getType().equals(ChChestItem.class) && isPublicStaticFinal(field)) { + try { + items.add((ChChestItem) field.get(null)); + } catch (IllegalAccessException e) { + // Handle exception + } + } + } + } + + public static ChChestItem getItem(String displayName) { + ChChestItem existingItem = getPredefinedItem(displayName); + + if (existingItem != null) { + return existingItem; + } + + ChChestItem customItem = new ChChestItem(displayName, true); + return customItem; + } + + private static ChChestItem getPredefinedItem(String displayName) { + for (ChChestItem item : items) { + if (item.getDisplayName().equals(displayName)) { + return item; + } + } + return null; + } + + public static ChChestItem[] getItem(String[] displayNames) { + ChChestItem[] result = new ChChestItem[displayNames.length]; + for (int i = 0; i < displayNames.length; i++) { + result[i] = getItem(displayNames[i]); + } + return result; + } + + // Utility method to check if a field is public, static, and final + private static boolean isPublicStaticFinal(Field field) { + return java.lang.reflect.Modifier.isPublic(field.getModifiers()) && + java.lang.reflect.Modifier.isStatic(field.getModifiers()) && + java.lang.reflect.Modifier.isFinal(field.getModifiers()); + } + + public static ChChestItem createCustomItem(String displayName) { + ChChestItem customItem = new ChChestItem(displayName, true); + items.add(customItem); + return customItem; + } + + public static List<ChChestItem> getAllItems() { + return items; + } + + public static List<String> getAllItemNames() { + return items.stream() + .map(ChChestItem::getDisplayName) + .collect(Collectors.toList()); + //very fancy way to convert a list to a list of values from the previous list + } +}
\ No newline at end of file diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/EnumUtils.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/EnumUtils.java new file mode 100644 index 0000000..8407774 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/EnumUtils.java @@ -0,0 +1,209 @@ +package de.hype.bbsentials.constants.enviromentShared; + + +import de.hype.bbsentials.constants.BBDisplayNameProvider; +import de.hype.bbsentials.constants.BBDisplayNameProviderWithCustom; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class EnumUtils { + public static List<String> getAllDisplayNames(Class<? extends BBDisplayNameProvider> enumClass) { + List<String> displayNames = new ArrayList<>(); + + for (BBDisplayNameProvider item : enumClass.getEnumConstants()) { + displayNames.add(item.getDisplayName()); + } + + return displayNames; + } + + public static <T extends Enum<T> & BBDisplayNameProvider> List<T> getEnumsAsList(Class<T> enumClass) { + List<T> enumList = new ArrayList<>(); + + for (T item : enumClass.getEnumConstants()) { + enumList.add(item); + } + + return enumList; + } + + public static List<String> getDisplayNames(Collection<? extends BBDisplayNameProvider> itemList) { + List<String> displayNames = new ArrayList<>(); + for (BBDisplayNameProvider item : itemList) { + displayNames.add(item.getDisplayName()); + } + return displayNames; + } + + public static <T extends BBDisplayNameProvider> List<T> getEnumsAsList(List<T> itemList) { + List<T> enumList = new ArrayList<>(itemList); + return enumList; + } + + public static List<String> getAllEnumNames(Class<? extends Enum<?>> enumClass) { + List<String> enumNames = new ArrayList<>(); + Enum<?>[] enumConstants = enumClass.getEnumConstants(); + + for (Enum<?> enumConstant : enumConstants) { + enumNames.add(enumConstant.name()); + } + + return enumNames; + } + +// public interface BBDisplayNameProvider { +// String getDisplayName(); +// default public String serialize() { +// return name() + ":" + displayName; +// } +// +// default public ChChestItems deserialize(String serializedValue) { +// String[] parts = serializedValue.split(":"); +// if (parts.length != 2) { +// throw new IllegalArgumentException("Invalid serialized value format"); +// } +// String enumName = parts[0]; +// String displayName = parts[1]; +// +// return ChChestItems.valueOf(enumName).setDisplayName(displayName); +// } +// } + + + + // Methods for BBDisplayNameProviderWithCustom + + public static <T extends Enum<T> & BBDisplayNameProviderWithCustom> T getEnumByNameWithCustom(Class<T> enumClass, String enumName) { + boolean found = false; + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.name().equals(enumName)) { + return (enumValue); + } + } + return createCustomEnum(enumClass, enumName); + } + + public static <T extends Enum<T> & BBDisplayNameProviderWithCustom> T getEnumByValueWithCustom(Class<T> enumClass, String value) { + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.getDisplayName().equals(value)) { + return enumValue; + } + } + return (createCustomEnum(enumClass, value)); + + } + + public static <T extends Enum<T> & BBDisplayNameProviderWithCustom> T[] getEnumsByNameWithCustom(Class<T> enumClass, String[] names) { + List<T> matchingEnums = new ArrayList<>(); + + for (String name : names) { + boolean found = false; + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.name().equals(name)) { + matchingEnums.add(enumValue); + found = true; + break; + } + } + if (!found) { + matchingEnums.add(createCustomEnum(enumClass, name)); + } + } + + return matchingEnums.toArray((T[]) java.lang.reflect.Array.newInstance(enumClass, 0)); + } + + public static <T extends Enum<T> & BBDisplayNameProviderWithCustom> T[] getEnumsByValueWithCustom(Class<T> enumClass, String[] values) { + List<T> matchingEnums = new ArrayList<>(); + + for (String value : values) { + boolean found = false; + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.toString().equals(value)) { + matchingEnums.add(enumValue); + found = true; + break; + } + } + if (!found) { + matchingEnums.add(createCustomEnum(enumClass, value)); + } + } + + return matchingEnums.toArray((T[]) java.lang.reflect.Array.newInstance(enumClass, 0)); + } + + // Methods for BBDisplayNameProvider + + public static <T extends Enum<T> & BBDisplayNameProvider> T getEnumByName(Class<T> enumClass, String enumName) { + try { + return Enum.valueOf(enumClass, enumName); + } catch (IllegalArgumentException e) { + return null; // Enum value not found + } + } + + public static <T extends Enum<T> & BBDisplayNameProvider> T getEnumByValue(Class<T> enumClass, String value) { + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.getDisplayName().equals(value)) { + return enumValue; + } + } + return null; + } + + public static <T extends Enum<T> & BBDisplayNameProvider> T[] getEnumsByName(Class<T> enumClass, String[] names) { + List<T> matchingEnums = new ArrayList<>(); + + for (String name : names) { + boolean found = false; + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.name().equals(name)) { + matchingEnums.add(enumValue); + found = true; + break; + } + } + } + + return matchingEnums.toArray((T[]) java.lang.reflect.Array.newInstance(enumClass, 0)); + } + + public static <T extends Enum<T> & BBDisplayNameProvider> T[] getEnumsByValue(Class<T> enumClass, String[] values) { + List<T> matchingEnums = new ArrayList<>(); + + for (String value : values) { + boolean found = false; + for (T enumValue : enumClass.getEnumConstants()) { + if (enumValue.getDisplayName().equals(value)) { + matchingEnums.add(enumValue); + found = true; + break; + } + } + } + + return matchingEnums.toArray((T[]) java.lang.reflect.Array.newInstance(enumClass, 0)); + } + + private static <T extends Enum<T> & BBDisplayNameProviderWithCustom> T createCustomEnum(Class<T> enumClass, String value) { + T customEnum = null; + try { + customEnum = Enum.valueOf(enumClass, "Custom"); + } catch (Exception ignored) { + try { + customEnum = Enum.valueOf(enumClass, "CUSTOM"); + } catch (Exception ignored2) { + } + } + if (customEnum == null) { + } + customEnum.setDisplayName(value); + return customEnum; + + } +} + + diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/InternalReasonConstants.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/InternalReasonConstants.java new file mode 100644 index 0000000..79bf13a --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/InternalReasonConstants.java @@ -0,0 +1,14 @@ +package de.hype.bbsentials.constants.enviromentShared; + +public enum InternalReasonConstants { + INVALID_PARAMETER, + MISSING_PARAMETER, + INSUFFICIENT_PRIVILEGES, + MUTED, + BANNED, + API_UNSUPPORTED, + INVALID_LOGIN, + KICKED, + ANOTHER_LOGIN, + SERVER_RESTART +} diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/Islands.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/Islands.java new file mode 100644 index 0000000..f03c8ae --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/Islands.java @@ -0,0 +1,39 @@ +package de.hype.bbsentials.constants.enviromentShared; + +import de.hype.bbsentials.constants.BBDisplayNameProvider; + +public enum Islands implements BBDisplayNameProvider { + CRYSTAL_HOLLOWS("crystal_hollows", "Crystal Hollows"), + CRIMSON_ISLE("crimson_isle", "Crimson Isle"), + DEEP_CAVERNS("mining_2", "Deep Caverns"), + DUNGEON("dungeon", "Dungeon"), + DUNGEON_HUB("dungeon_hub", "Dungeon Hub"), + DWARVEN_MINES("mining_3", "Dwarven Mines"), + GOLD_MINE("mining_1", "Gold Mine"), + HUB("hub", "Hub"), + KUUDRA("kuudra", "Kuudra"), + PRIVATE_ISLAND("dynamic", "Private Islands"), + SPIDERS_DEN("combat_1", "Spider's Den"), + THE_END("combat_3", "The End"), + THE_FARMING_ISLANDS("farming_1", "The Farming Islands"), + THE_RIFT("rift", "The Rift"); + + + private final String internalName; + private final String displayName; + + Islands(String internalName, String displayName) { + this.internalName = internalName; + this.displayName = displayName; + } + + public String getInternalName() { + return internalName; + } + + public String getDisplayName() { + return displayName; + } + + +} diff --git a/src/main/java/de/hype/bbsentials/constants/enviromentShared/MiningEvents.java b/src/main/java/de/hype/bbsentials/constants/enviromentShared/MiningEvents.java new file mode 100644 index 0000000..1dc72d1 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/constants/enviromentShared/MiningEvents.java @@ -0,0 +1,40 @@ +package de.hype.bbsentials.constants.enviromentShared; + + +import de.hype.bbsentials.constants.BBDisplayNameProvider; + +// Mining Events +public enum MiningEvents implements BBDisplayNameProvider { + BETTER_TOGETHER("Better Together"), + DOUBLE_POWDER("Double Powder"), + GONE_WITH_THE_WIND("Gone with the Wind"), + GOBLIN_RAID("Goblin Raid"), + MITHRIL_GOURMAND("Mithril Gourmand"), + RAFFLE("Raffle"); + + private final String displayName; + + MiningEvents(String displayName) { + this.displayName = displayName; + } + + @Override + public String getDisplayName() { + return displayName; + } + + //Some Events cant happen in Crystal Holows + public boolean isDWEventOnly() { + if (this.equals(MiningEvents.MITHRIL_GOURMAND) || this.equals(MiningEvents.RAFFLE) || this.equals(MiningEvents.GOBLIN_RAID)) { + return true; + } + return false; + } + + public static boolean isDWEventOnly(String event) { + if (event.equals(MiningEvents.MITHRIL_GOURMAND.getDisplayName()) || event.equals(MiningEvents.RAFFLE.getDisplayName()) || event.equals(MiningEvents.GOBLIN_RAID.getDisplayName())) { + return true; + } + return false; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/AbstractPacket.java b/src/main/java/de/hype/bbsentials/packets/AbstractPacket.java new file mode 100644 index 0000000..116c9b2 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/AbstractPacket.java @@ -0,0 +1,67 @@ +package de.hype.bbsentials.packets; + +import de.hype.bbsentials.chat.Chat; +import de.hype.bbsentials.client.BBsentials; +import de.hype.bbsentials.client.Config; +import de.hype.bbsentials.communication.BBsentialConnection; +import de.hype.bbsentials.packets.packets.InvalidCommandFeedbackPacket; + +import java.lang.reflect.Field; + +public class AbstractPacket { + public final int apiVersionMin; + public final int apiVersionMax; + + protected AbstractPacket(int apiVersionMin, int apiVersionMax) { + this.apiVersionMax = apiVersionMax; + this.apiVersionMin = apiVersionMin; + + } + + public boolean isValid(BBsentialConnection connection, String[] allowedNullFields) { + if (isApiSupported(BBsentials.config)) { + Chat.sendPrivateMessageToSelf("You are using an outdated version of the mod"); + } + return true; + } + + public boolean isApiSupported(Config config) { + //int version = Core.getConfig().getVersion(); + int version = config.getApiVersion(); + if (version >= apiVersionMin && version <= apiVersionMax) { + return true; + } + return false; + } + + public String hasNullFields(String[] allowedNullFields) { + Field[] fields = this.getClass().getDeclaredFields(); + if (!this.getClass().getSimpleName().equals(InvalidCommandFeedbackPacket.class.getSimpleName())) { + for (Field field : fields) { + field.setAccessible(true); + try { + if (field.get(this) == null) { + if (allowedNullFields == null) return field.getName(); + if (isAllowedNull(allowedNullFields, field.getName())) { + return field.getName(); + } + } + } catch (IllegalAccessException e) { + // Handle the exception if needed + e.printStackTrace(); + } + } + } + return null; + + } + + public boolean isAllowedNull(String[] allowedFields, String fieldName) { + for (String allowedField : allowedFields) { + if (allowedField.equals(fieldName)) { + return true; + } + } + return false; + } +}
\ No newline at end of file diff --git a/src/main/java/de/hype/bbsentials/packets/EnviromentPacketConfig.java b/src/main/java/de/hype/bbsentials/packets/EnviromentPacketConfig.java new file mode 100644 index 0000000..da05704 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/EnviromentPacketConfig.java @@ -0,0 +1,7 @@ +package de.hype.bbsentials.packets; + +public class EnviromentPacketConfig { + public static final String enviroment = "Client"; + public static final String notEnviroment = "Server"; + public static final int apiVersion = 1; +} diff --git a/src/main/java/de/hype/bbsentials/packets/Packet.java b/src/main/java/de/hype/bbsentials/packets/Packet.java new file mode 100644 index 0000000..6a4ecbf --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/Packet.java @@ -0,0 +1,26 @@ +package de.hype.bbsentials.packets; + +import java.util.function.Consumer; + +public class Packet<T extends AbstractPacket> { + + private final Class<T> clazz; + private final Consumer<T> consumer; + + public Packet(Class<T> clazz, Consumer<T> consumer) { + this.clazz = clazz; + this.consumer = consumer; + } + + public String getName() { + return clazz.getSimpleName(); + } + + public Class<T> getClazz() { + return clazz; + } + + public Consumer<T> getConsumer() { + return consumer; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/PacketManager.java b/src/main/java/de/hype/bbsentials/packets/PacketManager.java new file mode 100644 index 0000000..a6d94d4 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/PacketManager.java @@ -0,0 +1,48 @@ +package de.hype.bbsentials.packets; + +import de.hype.bbsentials.communication.BBsentialConnection; +import de.hype.bbsentials.packets.packets.*; + +import java.util.ArrayList; +import java.util.List; + +public class PacketManager { + private static List<Packet<? extends AbstractPacket>> packets = new ArrayList<>(); + + public List<Packet<? extends AbstractPacket>> getPackets() { + return packets; + } + + // Define a map to store packet classes and their associated actions + BBsentialConnection connection; + + // Method to initialize packet actions + public PacketManager(BBsentialConnection connection) { + this.connection = connection; + initializePacketActions(connection); + } + + public static void initializePacketActions(BBsentialConnection connection) { + packets.add(new Packet<>(SplashNotifyPacket.class, connection::onSplashNotify)); + packets.add(new Packet<>(BingoChatMessagePacket.class, connection::onBingoChatMessagePacket)); + packets.add(new Packet<>(ChChestPackage.class, connection::onChChestPackage)); +// packets.add(new Packet<>(DisconnectPacket.class, connection::dummy)); +// packets.add(new Packet<>(InternalCommandPacket.class, connection::dummy)); + packets.add(new Packet<>(MiningEventPacket.class, connection::onMiningEventPacket)); +// packets.add(new Packet<>(RequestConnectPacket.class, connection::dummy)); + packets.add(new Packet<>(WelcomeClientPacket.class, connection::onWelcomePacket)); + } + + // Method to handle a received packet + + + // method to get a list of all packets + public static List<Class<? extends AbstractPacket>> getAllPacketClasses() { + initializePacketActions(null); + List<Class<? extends AbstractPacket>> allPackets = new ArrayList<>(); + for (int i = 0; i < allPackets.size(); i++) { + allPackets.add(packets.get(i).getClazz()); + } + return allPackets; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/PacketUtils.java b/src/main/java/de/hype/bbsentials/packets/PacketUtils.java new file mode 100644 index 0000000..2c6d8a5 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/PacketUtils.java @@ -0,0 +1,122 @@ +package de.hype.bbsentials.packets; + +import com.google.gson.Gson; +import de.hype.bbsentials.client.CustomGson; +import de.hype.bbsentials.communication.BBsentialConnection; + +import java.util.function.Consumer; + + +public class PacketUtils { + public static final Gson gson = CustomGson.create(); + + public static String parsePacketToJson(AbstractPacket packet) { + return gson.toJson(packet); + } + + public static <T extends AbstractPacket> void tryToProcessPacket(Packet<T> packet, String rawJson) { + Class<T> clazz = packet.getClazz(); + Consumer<T> consumer = packet.getConsumer(); + T abstractPacket = gson.fromJson(rawJson, clazz); + consumer.accept(abstractPacket); + } + + private static void showError(Throwable t, String errorMessage) { + System.out.println(errorMessage + " because of: " + t.getClass().getSimpleName() + ": " + t.getMessage()); + new Error(errorMessage, t).printStackTrace(); + } + + public static class APIException extends Error { + + public APIException(String errorMessage, Throwable t) { + super(errorMessage, t); + } + + public APIException(String errorMessage) { + super(errorMessage); + } + } + + public static <T extends AbstractPacket> T getAsPacket(String message, Class<T> clazz) { + if (!message.contains(".")) return null; + String packetName = message.split("\\.")[0]; + String rawJson = message.substring(packetName.length() + 1); + if (!packetName.equals(clazz.getSimpleName())) { + try { + T parsedPacket = gson.fromJson(rawJson, clazz); + return parsedPacket; + } catch (Throwable t) { + showError(t, "Could not process packet '" + packetName + "' from " + EnviromentPacketConfig.notEnviroment); + } + } + String errorMessage = "Could not process packet '" + packetName + "' from " + EnviromentPacketConfig.notEnviroment; + + showError(new APIException("Found unknown packet: " + packetName + "'"), errorMessage); + return null; + } + +// public static <T extends AbstractPacket> T getAsPacket(String message) { +// if (!message.contains(".")) return null; +// String packetName = message.split("\\.")[0]; +// String rawJson = message.substring(packetName.length() + 1); +// +// for (Class<? extends AbstractPacket> clazz : PacketManager.getAllPacketClasses()) { +// if (packetName.equals(clazz.getSimpleName())) { +// try { +// if (clazz.isAssignableFrom(clazz)) { +// //TODO the problem +// T parsedPacket = (T) gson.fromJson(rawJson, clazz); +// return parsedPacket; +// } +// else { +// return null; +// } +// } catch (Throwable t) { +// showError(t, "Could not process packet '" + packetName + "' from " + EnviromentPacketConfig.notEnviroment); +// } +// } +// } +// return null; +// } + + public static boolean isPacket(String message, Class<? extends AbstractPacket> clazz) { + if (!message.contains(".")) return false; + String packetName = message.split("\\.")[0]; + if (packetName.equals(clazz.getSimpleName())) { + return true; + } + return false; + } + + public static boolean isPacket(String message) { + if (!message.contains(".")) return false; + String packetName = message.split("\\.")[0]; + for (Class<? extends AbstractPacket> packetClass : PacketManager.getAllPacketClasses()) { + if (!packetName.equals(packetClass.getSimpleName())) { + return true; + } + } + return false; + } + + public static <T extends AbstractPacket> boolean handleIfPacket(BBsentialConnection connection, String message) { + //Return = is Packet + if (!message.contains(".")) return false; + String packetName = message.split("\\.")[0]; + String rawJson = message.substring(packetName.length() + 1); + PacketManager manager = new PacketManager(connection); + for (Packet<? extends AbstractPacket> packet : manager.getPackets()) { + if (!packetName.equals(packet.getClazz().getSimpleName())) continue; + try { + tryToProcessPacket(packet, rawJson); + return true; + } catch (Throwable t) { + showError(t, "Could not process packet '" + packetName + "' from " + EnviromentPacketConfig.notEnviroment); + } + } + String errorMessage = "Could not process packet '" + packetName + "' from " + EnviromentPacketConfig.notEnviroment; + + showError(new APIException("Found unknown packet: " + packetName + "'"), errorMessage); + return false; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/BingoChatMessagePacket.java b/src/main/java/de/hype/bbsentials/packets/packets/BingoChatMessagePacket.java new file mode 100644 index 0000000..56a7152 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/BingoChatMessagePacket.java @@ -0,0 +1,26 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class BingoChatMessagePacket extends AbstractPacket { + + public BingoChatMessagePacket(String prefix, String username, String message, int bingo_cards) { + super(1, 1); //Min and Max supported Version + this.message = message; + this.username = username; + this.prefix = prefix; + this.bingo_cards = bingo_cards; + } + + public final String message; + public final String username; + public final String prefix; + public final int bingo_cards; + + public boolean baseCheck() { + boolean cancelPacket = false; + + return !cancelPacket; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/BroadcastMessagePacket.java b/src/main/java/de/hype/bbsentials/packets/packets/BroadcastMessagePacket.java new file mode 100644 index 0000000..2e507c7 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/BroadcastMessagePacket.java @@ -0,0 +1,17 @@ +package de.hype.bbsentials.packets.packets; + +import de.hype.bbsentials.packets.AbstractPacket; + +public class BroadcastMessagePacket extends AbstractPacket { + + public final String message; + public final String username; + public final String prefix; + + public BroadcastMessagePacket(String prefix, String username, String message) { + super(1, 1); //Min and Max supported Version + this.message = message; + this.username = username; + this.prefix = prefix; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/ChChestPackage.java b/src/main/java/de/hype/bbsentials/packets/packets/ChChestPackage.java new file mode 100644 index 0000000..e2252e8 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/ChChestPackage.java @@ -0,0 +1,24 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.constants.enviromentShared.ChChestItem; +import de.hype.bbsentials.packets.AbstractPacket; + +public class ChChestPackage extends AbstractPacket { + + public ChChestPackage(String announcerUsername, ChChestItem[] items, String locationCoords, String bbcommand, String extraMessage) { + super(1, 1); //Min and Max supported Version + this.announcerUsername = announcerUsername; + this.locationCoords = locationCoords; + this.bbcommand = bbcommand; + this.extraMessage = extraMessage; + this.items = items; + } + + public final String announcerUsername; + public final String locationCoords; + public final String bbcommand; + public final String extraMessage; + public final ChChestItem[] items; + +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/DisconnectPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/DisconnectPacket.java new file mode 100644 index 0000000..4a37693 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/DisconnectPacket.java @@ -0,0 +1,20 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class DisconnectPacket extends AbstractPacket { + + public DisconnectPacket(String internalReason, int[] waitBeforeReconnect, String displayReason, String displayMessage) { + super(1, 1); //Min and Max supportet Version + this.internalReason = internalReason; + this.waitBeforeReconnect = waitBeforeReconnect; + this.displayReason = displayReason; + this.displayMessage = displayMessage; + } + public final String internalReason; + public final int[] waitBeforeReconnect; + public final String displayReason; + public final String displayMessage; + +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/DisplayMessagePacket.java b/src/main/java/de/hype/bbsentials/packets/packets/DisplayMessagePacket.java new file mode 100644 index 0000000..da99a99 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/DisplayMessagePacket.java @@ -0,0 +1,14 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class DisplayMessagePacket extends AbstractPacket { + + public final String message; + + public DisplayMessagePacket(String message) { + super(1, 1); //Min and Max supported Version + this.message = message; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/DisplayTellrawMessagePacket.java b/src/main/java/de/hype/bbsentials/packets/packets/DisplayTellrawMessagePacket.java new file mode 100644 index 0000000..9329878 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/DisplayTellrawMessagePacket.java @@ -0,0 +1,13 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class DisplayTellrawMessagePacket extends AbstractPacket { + public final String rawJson; + + public DisplayTellrawMessagePacket(String rawJson) { + super(1, 1); //Min and Max supported Version + this.rawJson = rawJson; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/InternalCommandPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/InternalCommandPacket.java new file mode 100644 index 0000000..cf8c8f7 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/InternalCommandPacket.java @@ -0,0 +1,18 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +//Only used for small things which don't really need an own Packet. +public class InternalCommandPacket extends AbstractPacket { + + public InternalCommandPacket(String command, String[] parameters) { + super(1, 1); //Min and Max supported Version + this.command = command; + this.parameters = parameters; + } + + public final String command; + public final String[] parameters; + +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/InvalidCommandFeedbackPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/InvalidCommandFeedbackPacket.java new file mode 100644 index 0000000..b57be4a --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/InvalidCommandFeedbackPacket.java @@ -0,0 +1,25 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class InvalidCommandFeedbackPacket extends AbstractPacket { + + public InvalidCommandFeedbackPacket(String internalReason, String command, String displayMessage, String argument, String permissionNeeded, String[] userPermissions) { + super(1, 1); //Min and Max supportet Version + this.internalReason = internalReason; + this.argument = argument; + this.permissionNeeded = permissionNeeded; + this.userPermissions = userPermissions; + this.command = command; + this.displayMessage = displayMessage; + } + + public final String internalReason; + public final String argument; + public final String permissionNeeded; + public final String[] userPermissions; + public final String command; + public final String displayMessage; + +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/MiningEventPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/MiningEventPacket.java new file mode 100644 index 0000000..5dd383f --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/MiningEventPacket.java @@ -0,0 +1,26 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.constants.enviromentShared.Islands; +import de.hype.bbsentials.constants.enviromentShared.MiningEvents; +import de.hype.bbsentials.packets.AbstractPacket; + +public class MiningEventPacket extends AbstractPacket { + + + public final MiningEvents event; + public final String username; + public final Islands island; + + public MiningEventPacket(MiningEvents event, String username, Islands island) throws Exception { + super(1, 1); //Min and Max supported Version + this.event = event; + this.username = username; + if (island.equals(Islands.CRYSTAL_HOLLOWS)) { + if (event.equals(MiningEvents.MITHRIL_GOURMAND) || event.equals(MiningEvents.RAFFLE) || event.equals(MiningEvents.GOBLIN_RAID)) { + throw new Exception("The specified event can not happen on this Server"); + } + } + this.island = island; + } +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/RequestConnectPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/RequestConnectPacket.java new file mode 100644 index 0000000..62bac83 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/RequestConnectPacket.java @@ -0,0 +1,21 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class RequestConnectPacket extends AbstractPacket { + + + public RequestConnectPacket(String mcuuid, String key, int clientApiVersion, String authType ) { + super(1, 1); //Min and Max supported Version + this.mcuuid = mcuuid; + this.key = key; + this.authType = authType; + this.clientApiVersion = clientApiVersion; + } + + public final String mcuuid; + public final String key; + public final String authType; + public final int clientApiVersion; +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/SplashNotifyPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/SplashNotifyPacket.java new file mode 100644 index 0000000..bfdc275 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/SplashNotifyPacket.java @@ -0,0 +1,26 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.constants.enviromentShared.Islands; +import de.hype.bbsentials.packets.AbstractPacket; + +public class SplashNotifyPacket extends AbstractPacket { + + + public SplashNotifyPacket(int hub, String splasherUsername, String location, Islands hubType, String extraMessage, boolean lessWaste) { + super(1, 1); //Min and Max supported Version + this.hub = hub; + this.lessWaste = lessWaste; + this.splasherUsername = splasherUsername; + this.location = location; + this.hubType = hubType; + this.extraMessage = extraMessage; + } + + public final int hub; + public final boolean lessWaste; + public final String splasherUsername; + public final String location; + public final Islands hubType; + public final String extraMessage; +} diff --git a/src/main/java/de/hype/bbsentials/packets/packets/WelcomeClientPacket.java b/src/main/java/de/hype/bbsentials/packets/packets/WelcomeClientPacket.java new file mode 100644 index 0000000..4b2f7c3 --- /dev/null +++ b/src/main/java/de/hype/bbsentials/packets/packets/WelcomeClientPacket.java @@ -0,0 +1,19 @@ +package de.hype.bbsentials.packets.packets; + + +import de.hype.bbsentials.packets.AbstractPacket; + +public class WelcomeClientPacket extends AbstractPacket { + + public WelcomeClientPacket(String[] roles, String motd, boolean success) { + super(1, 1); //Min and Max supportet Version + this.roles = roles; + this.motd = motd; + this.success = success; + } + + public final String[] roles; + public final String motd; + public final boolean success; + +}
\ No newline at end of file |