diff options
author | HacktheTime <l4bg0jb7@duck.com> | 2023-10-14 12:10:15 +0200 |
---|---|---|
committer | HacktheTime <l4bg0jb7@duck.com> | 2023-10-14 12:10:15 +0200 |
commit | 77fb80356b42260a95610aa5971d2b03d8d30e1d (patch) | |
tree | 6d9892029e1f682e357811e61f3632ade2615aec /forge/src/main/java/de/hype | |
parent | 764cd84919c5b30a6bb0e6ec2e32feba07633ebf (diff) | |
download | BBsentials-77fb80356b42260a95610aa5971d2b03d8d30e1d.tar.gz BBsentials-77fb80356b42260a95610aa5971d2b03d8d30e1d.tar.bz2 BBsentials-77fb80356b42260a95610aa5971d2b03d8d30e1d.zip |
more changes
Diffstat (limited to 'forge/src/main/java/de/hype')
28 files changed, 309 insertions, 1648 deletions
diff --git a/forge/src/main/java/de/hype/bbsentials/forge/BBUtils.java b/forge/src/main/java/de/hype/bbsentials/forge/BBUtils.java index a6b2a3e..3acf95e 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/BBUtils.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/BBUtils.java @@ -2,34 +2,33 @@ package de.hype.bbsentials.forge; import com.google.common.collect.Lists; import de.hype.bbsentials.common.constants.enviromentShared.Islands; -import de.hype.bbsentials.forge.chat.Chat; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.network.PlayerListEntry; -import java.util.Iterator; import java.util.List; public class BBUtils implements de.hype.bbsentials.common.mclibraries.BBUtils { public Islands getCurrentIsland() { - try { - String string = MinecraftClient.getInstance().player.networkHandler.getPlayerListEntry("!C-b").getDisplayName().getString(); - if (!string.startsWith("Area: ")) { - Chat.sendPrivateMessageToSelfError("Could not get Area data. Are you in Skyblock?"); - } - else { - return Islands.getByDisplayName(string.replace("Area: ", "").trim()); - } - } catch (Exception e) { - } - return null; +// try { +// String string = MinecraftClient.getInstance().player.networkHandler.getPlayerListEntry("!C-b").getDisplayName().getString(); +// if (!string.startsWith("Area: ")) { +// Chat.sendPrivateMessageToSelfError("Could not get Area data. Are you in Skyblock?"); +// } +// else { +// return Islands.getByDisplayName(string.replace("Area: ", "").trim()); +// } +// } catch (Exception e) { +// } +// return null; + return Islands.PRIVATE_ISLAND; } public int getPlayerCount() { - return Integer.parseInt(MinecraftClient.getInstance().player.networkHandler.getPlayerListEntry("!B-a").getDisplayName().getString().trim().replaceAll("[^0-9]", "")); +// return Integer.parseInt(MinecraftClient.getInstance().player.networkHandler.getPlayerListEntry("!B-a").getDisplayName().getString().trim().replaceAll("[^0-9]", "")); + return 0; } public String getServer() { - return MinecraftClient.getInstance().player.networkHandler.getPlayerListEntry("!C-c").getDisplayName().getString().replace("Server:", "").trim(); +// return MinecraftClient.getInstance().player.networkHandler.getPlayerListEntry("!C-c").getDisplayName().getString().replace("Server:", "").trim(); + return "mini0b"; } public boolean isOnMegaServer() { @@ -53,14 +52,14 @@ public class BBUtils implements de.hype.bbsentials.common.mclibraries.BBUtils { public List<String> getPlayers() { List<String> list = Lists.newArrayList(); - Iterator var2 = MinecraftClient.getInstance().getNetworkHandler().getPlayerList().iterator(); - while (var2.hasNext()) { - PlayerListEntry playerListEntry = (PlayerListEntry) var2.next(); - String playerName = playerListEntry.getProfile().getName(); - if (!playerName.startsWith("!")) { - list.add(playerName); - } - } +// Iterator var2 = MinecraftClient.getInstance().getNetworkHandler().getPlayerList().iterator(); +// while (var2.hasNext()) { +// PlayerListEntry playerListEntry = (PlayerListEntry) var2.next(); +// String playerName = playerListEntry.getProfile().getName(); +// if (!playerName.startsWith("!")) { +// list.add(playerName); +// } +// } return list; } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/Command2xPowder.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/Command2xPowder.java index 8044991..0914bad 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/Command2xPowder.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/Command2xPowder.java @@ -1,9 +1,9 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import static de.hype.bbsentials.forge.client.BBsentials.bbserver; +import static de.hype.bbsentials.common.client.BBsentials.connection; public class Command2xPowder extends CommandBase { @@ -20,7 +20,7 @@ public class Command2xPowder extends CommandBase { @Override public void processCommand(ICommandSender sender, String[] args) { - bbserver.sendMessage("?dwevent 2xpowder"); + connection.sendMessage("?dwevent 2xpowder"); } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBAnnounce.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBAnnounce.java index 3d2afb7..032c599 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBAnnounce.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBAnnounce.java @@ -1,6 +1,6 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBBServer.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBBServer.java index 7c94a27..6150b6e 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBBServer.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBBServer.java @@ -1,5 +1,6 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; +import de.hype.bbsentials.common.client.BBsentials; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; @@ -29,7 +30,7 @@ public class CommandBBServer extends CommandBase { BBsentials.connectToBBserver(); } else { - BBsentials.bbserver.sendMessage(message); + BBsentials.connection.sendMessage(message); } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBBan.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBBan.java index 15d99b7..09efc8b 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBBan.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBBan.java @@ -1,6 +1,7 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; + +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBC.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBC.java index 0b46507..08f9bee 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBC.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBC.java @@ -1,6 +1,7 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; + +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBMute.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBMute.java index 3fd6390..0dab562 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBMute.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBMute.java @@ -1,6 +1,7 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; + +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBetterTogether.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBetterTogether.java index 78f20f8..fb3d647 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBetterTogether.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBetterTogether.java @@ -1,9 +1,9 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import static de.hype.bbsentials.forge.client.BBsentials.bbserver; +import static de.hype.bbsentials.common.client.BBsentials.connection; public class CommandBetterTogether extends CommandBase { @@ -20,7 +20,7 @@ public class CommandBetterTogether extends CommandBase { @Override public void processCommand(ICommandSender sender, String[] args) { - bbserver.sendMessage("?dwevent bettertogether"); + connection.sendMessage("?dwevent bettertogether"); } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBingoChat.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBingoChat.java index 655cfdb..6967259 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandBingoChat.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandBingoChat.java @@ -1,6 +1,7 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; + +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandChChest.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandChChest.java index daaa1f3..3914d03 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandChChest.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandChChest.java @@ -1,12 +1,12 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; -import static de.hype.bbsentials.forge.client.BBsentials.bbserver; +import static de.hype.bbsentials.common.client.BBsentials.connection; public class CommandChChest extends CommandBase { @@ -36,9 +36,9 @@ public class CommandChChest extends CommandBase { String contactWay = args[4]; String combinedString = "?chchest " + item + " " + x + " " + y + " " + z + " " + contactWay; - bbserver.sendMessage(combinedString); + connection.sendMessage(combinedString); } catch (Exception e) { - Chat.sendPrivateMessageToSelf("§cYour coords were invalid."); + Chat.sendPrivateMessageToSelfError("Your coords were invalid."); } } @Override diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandGoblinRaid.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandGoblinRaid.java index bb7d276..2b0ec28 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandGoblinRaid.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandGoblinRaid.java @@ -1,9 +1,9 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import static de.hype.bbsentials.forge.client.BBsentials.bbserver; +import static de.hype.bbsentials.common.client.BBsentials.connection; public class CommandGoblinRaid extends CommandBase { @@ -20,7 +20,7 @@ public class CommandGoblinRaid extends CommandBase { @Override public void processCommand(ICommandSender sender, String[] args) { - bbserver.sendMessage("?dwevent goblinraid"); + connection.sendMessage("?dwevent goblinraid"); } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandGoneWithTheWind.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandGoneWithTheWind.java index 602e422..c079ed1 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandGoneWithTheWind.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandGoneWithTheWind.java @@ -1,9 +1,9 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import static de.hype.bbsentials.forge.client.BBsentials.bbserver; +import static de.hype.bbsentials.common.client.BBsentials.connection; public class CommandGoneWithTheWind extends CommandBase { @@ -20,7 +20,7 @@ public class CommandGoneWithTheWind extends CommandBase { @Override public void processCommand(ICommandSender sender, String[] args) { - bbserver.sendMessage("?dwevent gonewiththewind"); + connection.sendMessage("?dwevent gonewiththewind"); } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandRaffle.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandRaffle.java index 235c538..4e17c42 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandRaffle.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandRaffle.java @@ -1,9 +1,9 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; -import static de.hype.bbsentials.forge.client.BBsentials.bbserver; +import static de.hype.bbsentials.common.client.BBsentials.connection; public class CommandRaffle extends CommandBase { @@ -20,7 +20,7 @@ public class CommandRaffle extends CommandBase { @Override public void processCommand(ICommandSender sender, String[] args) { - bbserver.sendMessage("?dwevent raffle"); + connection.sendMessage("?dwevent raffle"); } @Override public boolean canCommandSenderUseCommand(ICommandSender sender) { diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandSplashAnnounce.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandSplashAnnounce.java index 041d0fc..52e4167 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandSplashAnnounce.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandSplashAnnounce.java @@ -1,6 +1,6 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; -import de.hype.bbsentials.forge.chat.Chat; +import de.hype.bbsentials.common.chat.Chat; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.NumberInvalidException; @@ -28,7 +28,7 @@ public class CommandSplashAnnounce extends CommandBase { try { hub_Number = parseInt(args[0], 1, 28); } catch (NumberInvalidException e) { - Chat.sendPrivateMessageToSelf("§cInvalid hub number"); + Chat.sendPrivateMessageToSelfError("§cInvalid hub number"); } String location = args[1]; String message = ""; diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandsOLD.java b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandsOLD.java index d42970f..349013d 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Commands/CommandsOLD.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/CommandImplementations/CommandsOLD.java @@ -1,8 +1,9 @@ -package de.hype.bbsentials.forge.client.Commands; +package de.hype.bbsentials.forge.CommandImplementations; +import de.hype.bbsentials.common.client.BBsentials; import net.minecraftforge.client.ClientCommandHandler; -import static de.hype.bbsentials.forge.client.BBsentials.getConfig; +import static de.hype.bbsentials.common.client.BBsentials.getConfig; public class CommandsOLD { @@ -17,12 +18,12 @@ public class CommandsOLD { ClientCommandHandler.instance.registerCommand(new CommandBC()); ClientCommandHandler.instance.registerCommand(new CommandBingoChat()); if (getConfig().bbsentialsRoles != null) { - if (getConfig().bbsentialsRoles.contains("mod")) { + if (getConfig().hasBBRoles("mod")) { ClientCommandHandler.instance.registerCommand(new CommandBAnnounce()); ClientCommandHandler.instance.registerCommand(new CommandBMute()); ClientCommandHandler.instance.registerCommand(new CommandBBan()); } - if (getConfig().bbsentialsRoles.contains("splasher")) { + if (getConfig().hasBBRoles("splasher")) { ClientCommandHandler.instance.registerCommand(new CommandSplashAnnounce()); } else { @@ -31,7 +32,7 @@ public class CommandsOLD { } public void sendCommand(String message) { - BBsentials.bbserver.sendCommand(message); + BBsentials.connection.sendCommand(message); } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/Commands.java b/forge/src/main/java/de/hype/bbsentials/forge/Commands.java index a5af004..cf6083b 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/Commands.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/Commands.java @@ -1,312 +1,189 @@ package de.hype.bbsentials.forge; -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.arguments.IntegerArgumentType; -import com.mojang.brigadier.arguments.StringArgumentType; import de.hype.bbsentials.common.client.BBsentials; -import de.hype.bbsentials.common.constants.enviromentShared.ChChestItems; -import de.hype.bbsentials.common.constants.enviromentShared.MiningEvents; import de.hype.bbsentials.common.mclibraries.EnvironmentCore; import de.hype.bbsentials.common.mclibraries.MCCommand; import de.hype.bbsentials.common.packets.AbstractPacket; -import de.hype.bbsentials.forge.chat.Chat; -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 java.util.Objects; +import de.hype.bbsentials.common.packets.packets.SplashNotifyPacket; +import de.hype.bbsentials.forge.client.CommandBBI; +import net.minecraftforge.client.ClientCommandHandler; public class Commands implements MCCommand { - Event<ClientCommandRegistrationCallback> event = ClientCommandRegistrationCallback.EVENT; - public void registerMain(){ - event.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("creport") - .then(ClientCommandManager.argument("Player_Name", StringArgumentType.string()) - .executes((context) -> { - String playerName = StringArgumentType.getString(context, "Player_Name"); - BBsentials.getConfig().sender.addSendTask("/creport " + playerName, 0); - BBsentials.getConfig().addReported(playerName); - return 1; - }))); - });//creport helper → no double report during same launch - event.register((dispatcher, registryAccess) -> { - miningEvent(dispatcher, "goblinraid", MiningEvents.GOBLIN_RAID); - });/*goblinraid*/ - event.register((dispatcher, registryAccess) -> { - miningEvent(dispatcher, "2xpowder", MiningEvents.DOUBLE_POWDER); - });/*2xpowder*/ - event.register((dispatcher, registryAccess) -> { - miningEvent(dispatcher, "bettertogether", MiningEvents.BETTER_TOGETHER); - });/*b2g*/ - event.register((dispatcher, registryAccess) -> { - miningEvent(dispatcher, "raffle", MiningEvents.RAFFLE); - });/*raffle*/ - event.register((dispatcher, registryAccess) -> { - miningEvent(dispatcher, "gonewiththewind", MiningEvents.GONE_WITH_THE_WIND); - });/*gonewiththewind*/ - event.register((dispatcher, registryAccess) -> { - miningEvent(dispatcher, "mithrilgourmand", MiningEvents.MITHRIL_GOURMAND); - });/*gonewiththewind*/ - event.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("chchest") - .then(ClientCommandManager.argument("Item", StringArgumentType.string()) - .suggests((context, 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.string()) - .suggests(((context, builder) -> { - return CommandSource.suggestMatching(new String[]{"\"/msg " + BBsentials.getConfig().getUsername() + " bb:party me\"", "\"/p join " + BBsentials.config.getUsername() + "\""}, builder); - })) - .executes((context) -> { - 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"); - - sendPacket(new ChChestPacket("", ChChestItems.getItem(item.split(";")), x + " " + y + " " + z, contactWay, "")); - return 1; - } - ) - ) - ) - ) - ) - ) - ); - });/*chchest*/ - 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"); - sendPacket(new BingoChatMessagePacket("", "", message, 0)); - return 1; - }) - ) - ); - });/*BincoChatShort*/ - 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"); - sendPacket(new BingoChatMessagePacket("", "", message, 0)); - return 1; - }) - ) - ); - });/*BingoChatLong*/ + public static <T extends AbstractPacket> void sendPacket(T packet) { + BBsentials.connection.sendPacket(packet); } - public void registerRoleRequired(boolean hasDev, boolean hasAdmin, boolean hasMod, boolean hasSplasher, boolean hasBeta, boolean hasMiningEvents, boolean hasChChest) { - if (hasMod) { - event.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("bannounce") - .then(ClientCommandManager.argument("message", StringArgumentType.greedyString()) - .executes((context) -> { - String message = StringArgumentType.getString(context, "message"); - sendPacket(new BroadcastMessagePacket("","",message)); - return 1; - }) - ) - ); - });/*bAnnounce*/ - event.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("bmute") - .then(ClientCommandManager.argument("userId/mcusername", StringArgumentType.string()) - .then(ClientCommandManager.argument("[Duration(d/h/m/s) | 0 forever]", StringArgumentType.string()) - .then(ClientCommandManager.argument("reason", StringArgumentType.greedyString()) - .executes((context) -> { - String identification = StringArgumentType.getString(context, "userId/mcusername"); - String duration = StringArgumentType.getString(context, "[Duration(d/h/m/s) | 0 forever]"); - String reason = StringArgumentType.getString(context, "reason"); - int userId = -1; - String mcusername = ""; - if (identification.replaceAll("[\\d]", "").trim().isEmpty()) { - userId = Integer.parseInt(identification); - } - else { - mcusername = identification; - } - sendPacket(new PunishUserPacket(PunishUserPacket.PUNISHMENT_TYPE_MUTE, userId, mcusername, duration, reason)); - return 1; - }) - ) - ) - ) - ); - });/*bmute*/ - event.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("bban") - .then(ClientCommandManager.argument("userId/mcusername", StringArgumentType.string()) - .then(ClientCommandManager.argument("[Duration(d/h/m/s) | 0 forever]", StringArgumentType.string()) - .then(ClientCommandManager.argument("reason", StringArgumentType.greedyString()) - .executes((context) -> { - String identification = StringArgumentType.getString(context, "userId/mcusername"); - String duration = StringArgumentType.getString(context, "[Duration(d/h/m/s) | 0 forever]"); - String reason = StringArgumentType.getString(context, "reason"); - int userId = -1; - String mcusername = ""; - if (identification.replaceAll("[\\d]", "").trim().isEmpty()) { - userId = Integer.parseInt(identification); - } - else { - mcusername = identification; - } - sendPacket(new PunishUserPacket(PunishUserPacket.PUNISHMENT_TYPE_BAN, userId, mcusername, duration, reason)); - return 1; - }) - ) - ) - ) - ); - });/*ban*/ - event.register((dispatcher, registryAccess) -> { - dispatcher.register(ClientCommandManager.literal("bgetinfo") - .then(ClientCommandManager.argument("userId/mcusername", StringArgumentType.string()) - .executes((context) -> { - String identification = StringArgumentType.getString(context, "userId/mcusername"); - sendPacket(new InternalCommandPacket(InternalCommandPacket.GET_USER_INFO, new String[]{identification})); - return 1; - }) - ) - ); - });/*getInfo*/ - } - if (hasSplasher) { - 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); - }) - .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")); - splashAnnounce(hub, location, extramessage, lessWaste); - return 1; - }) - ) - .executes((context) -> { - int hub = IntegerArgumentType.getInteger(context, "Hub"); - String location = StringArgumentType.getString(context, "location"); - boolean lessWaste = Boolean.parseBoolean(StringArgumentType.getString(context, "lasswaste")); - splashAnnounce(hub, location, "", lessWaste); - return 1; - }) - )) - .executes((context) -> { - int hub = IntegerArgumentType.getInteger(context, "Hub"); - String location = "bea"; - splashAnnounce(hub, location, "", true); - return 1; - }) - - ) - ); - });/*SplashAnnounce*/ - event.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("requestpottimes") - .executes((context) -> { - sendPacket(new InternalCommandPacket(InternalCommandPacket.REQUEST_POT_DURATION, new String[0])); - return 1; - }) - ); - });/*requestpottimes*/ - } - if (hasAdmin) { - event.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("bshutdown") - .then(ClientCommandManager.argument("Reason", StringArgumentType.greedyString()) - .suggests((context, builder) -> { - return CommandSource.suggestMatching(new String[]{"Emergency Shutdown", "System Shutdown", "Other"}, builder); - }) - .executes((context) -> { - String reason = StringArgumentType.getString(context, "Reason"); - sendPacket(new InternalCommandPacket(InternalCommandPacket.SHUTDOWN_SERVER, new String[]{reason})); - return 1; - }) - ) - ); - });/*BBShutdown*/ - event.register((dispatcher, registryAccess) -> { - dispatcher.register( - ClientCommandManager.literal("bsetmotd") - .then(ClientCommandManager.argument("Message", StringArgumentType.greedyString()) - .suggests((context, builder) -> { - return CommandSource.suggestMatching(new String[]{""}, builder); - }) - .executes((context) -> { - String message = StringArgumentType.getString(context, "Message").trim(); - sendPacket(new InternalCommandPacket(InternalCommandPacket.SET_MOTD, new String[]{message})); - return 1; - }) - ) - ); - });/*BBServerMotd*/ - } + public void registerMain() { + ClientCommandHandler.instance.registerCommand(new CommandBBI()); +// event.register((dispatcher, registryAccess) -> { +// miningEvent(dispatcher, "goblinraid", MiningEvents.GOBLIN_RAID); +// });/*goblinraid*/ +// event.register((dispatcher, registryAccess) -> { +// miningEvent(dispatcher, "2xpowder", MiningEvents.DOUBLE_POWDER); +// });/*2xpowder*/ +// event.register((dispatcher, registryAccess) -> { +// miningEvent(dispatcher, "bettertogether", MiningEvents.BETTER_TOGETHER); +// });/*b2g*/ +// event.register((dispatcher, registryAccess) -> { +// miningEvent(dispatcher, "raffle", MiningEvents.RAFFLE); +// });/*raffle*/ +// event.register((dispatcher, registryAccess) -> { +// miningEvent(dispatcher, "gonewiththewind", MiningEvents.GONE_WITH_THE_WIND); +// });/*gonewiththewind*/ +// event.register((dispatcher, registryAccess) -> { +// miningEvent(dispatcher, "mithrilgourmand", MiningEvents.MITHRIL_GOURMAND); +// });/*gonewiththewind*/ +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("chchest").then(ClientCommandManager.argument("Item", StringArgumentType.string()).suggests((context, 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.string()).suggests(((context, builder) -> { +// return CommandSource.suggestMatching(new String[]{"\"/msg " + BBsentials.getConfig().getUsername() + " bb:party me\"", "\"/p join " + BBsentials.config.getUsername() + "\""}, builder); +// })).executes((context) -> { +// 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"); +// +// sendPacket(new ChChestPacket("", ChChestItems.getItem(item.split(";")), x + " " + y + " " + z, contactWay, "")); +// return 1; +// }))))))); +// });/*chchest*/ +// 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"); +// sendPacket(new BingoChatMessagePacket("", "", message, 0)); +// return 1; +// }))); +// });/*BincoChatShort*/ +// 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"); +// sendPacket(new BingoChatMessagePacket("", "", message, 0)); +// return 1; +// }))); +// });/*BingoChatLong*/ } - private static void simpleCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, String commandName, String[] parameters) { - dispatcher.register( - ClientCommandManager.literal(commandName) - .executes((context) -> { - sendPacket(new InternalCommandPacket(commandName, parameters)); - return 1; - }) - ); + public void registerRoleRequired(boolean hasDev, boolean hasAdmin, boolean hasMod, boolean hasSplasher, boolean hasBeta, boolean hasMiningEvents, boolean hasChChest) { +// if (hasMod) { +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("bannounce").then(ClientCommandManager.argument("message", StringArgumentType.greedyString()).executes((context) -> { +// String message = StringArgumentType.getString(context, "message"); +// sendPacket(new BroadcastMessagePacket("", "", message)); +// return 1; +// }))); +// });/*bAnnounce*/ +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("bmute").then(ClientCommandManager.argument("userId/mcusername", StringArgumentType.string()).then(ClientCommandManager.argument("[Duration(d/h/m/s) | 0 forever]", StringArgumentType.string()).then(ClientCommandManager.argument("reason", StringArgumentType.greedyString()).executes((context) -> { +// String identification = StringArgumentType.getString(context, "userId/mcusername"); +// String duration = StringArgumentType.getString(context, "[Duration(d/h/m/s) | 0 forever]"); +// String reason = StringArgumentType.getString(context, "reason"); +// int userId = -1; +// String mcusername = ""; +// if (identification.replaceAll("[\\d]", "").trim().isEmpty()) { +// userId = Integer.parseInt(identification); +// } +// else { +// mcusername = identification; +// } +// sendPacket(new PunishUserPacket(PunishUserPacket.PUNISHMENT_TYPE_MUTE, userId, mcusername, duration, reason)); +// return 1; +// }))))); +// });/*bmute*/ +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("bban").then(ClientCommandManager.argument("userId/mcusername", StringArgumentType.string()).then(ClientCommandManager.argument("[Duration(d/h/m/s) | 0 forever]", StringArgumentType.string()).then(ClientCommandManager.argument("reason", StringArgumentType.greedyString()).executes((context) -> { +// String identification = StringArgumentType.getString(context, "userId/mcusername"); +// String duration = StringArgumentType.getString(context, "[Duration(d/h/m/s) | 0 forever]"); +// String reason = StringArgumentType.getString(context, "reason"); +// int userId = -1; +// String mcusername = ""; +// if (identification.replaceAll("[\\d]", "").trim().isEmpty()) { +// userId = Integer.parseInt(identification); +// } +// else { +// mcusername = identification; +// } +// sendPacket(new PunishUserPacket(PunishUserPacket.PUNISHMENT_TYPE_BAN, userId, mcusername, duration, reason)); +// return 1; +// }))))); +// });/*ban*/ +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("bgetinfo").then(ClientCommandManager.argument("userId/mcusername", StringArgumentType.string()).executes((context) -> { +// String identification = StringArgumentType.getString(context, "userId/mcusername"); +// sendPacket(new InternalCommandPacket(InternalCommandPacket.GET_USER_INFO, new String[]{identification})); +// return 1; +// }))); +// });/*getInfo*/ +// } +// if (hasSplasher) { +// 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); +// }).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")); +// splashAnnounce(hub, location, extramessage, lessWaste); +// return 1; +// })).executes((context) -> { +// int hub = IntegerArgumentType.getInteger(context, "Hub"); +// String location = StringArgumentType.getString(context, "location"); +// boolean lessWaste = Boolean.parseBoolean(StringArgumentType.getString(context, "lasswaste")); +// splashAnnounce(hub, location, "", lessWaste); +// return 1; +// }))).executes((context) -> { +// int hub = IntegerArgumentType.getInteger(context, "Hub"); +// String location = "bea"; +// splashAnnounce(hub, location, "", true); +// return 1; +// }) +// +// )); +// });/*SplashAnnounce*/ +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("requestpottimes").executes((context) -> { +// sendPacket(new InternalCommandPacket(InternalCommandPacket.REQUEST_POT_DURATION, new String[0])); +// return 1; +// })); +// });/*requestpottimes*/ +// } +// if (hasAdmin) { +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("bshutdown").then(ClientCommandManager.argument("Reason", StringArgumentType.greedyString()).suggests((context, builder) -> { +// return CommandSource.suggestMatching(new String[]{"Emergency Shutdown", "System Shutdown", "Other"}, builder); +// }).executes((context) -> { +// String reason = StringArgumentType.getString(context, "Reason"); +// sendPacket(new InternalCommandPacket(InternalCommandPacket.SHUTDOWN_SERVER, new String[]{reason})); +// return 1; +// }))); +// });/*BBShutdown*/ +// event.register((dispatcher, registryAccess) -> { +// dispatcher.register(ClientCommandManager.literal("bsetmotd").then(ClientCommandManager.argument("Message", StringArgumentType.greedyString()).suggests((context, builder) -> { +// return CommandSource.suggestMatching(new String[]{""}, builder); +// }).executes((context) -> { +// String message = StringArgumentType.getString(context, "Message").trim(); +// sendPacket(new InternalCommandPacket(InternalCommandPacket.SET_MOTD, new String[]{message})); +// return 1; +// }))); +// });/*BBServerMotd*/ +// } } - private static void miningEvent(CommandDispatcher<FabricClientCommandSource> dispatcher, String commandName, MiningEvents event) { - dispatcher.register( - ClientCommandManager.literal(commandName) - .executes((context) -> { - try { - sendPacket(new MiningEventPacket(event, - BBsentials.config.getUsername(), Objects.requireNonNull(EnvironmentCore.utils.getCurrentIsland()))); - } catch (Exception e) { - Chat.sendPrivateMessageToSelfError(e.getMessage()); - } - return 1; - }) - ); - } - public static <T extends AbstractPacket> void sendPacket(T packet){ - BBsentials.connection.sendPacket(packet); - } public void splashAnnounce(int hubNumber, String locationInHub, String extramessage, boolean lessWaste) { sendPacket(new SplashNotifyPacket(0, hubNumber, BBsentials.config.getUsername(), locationInHub, EnvironmentCore.utils.getCurrentIsland(), extramessage, lessWaste)); } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/DebugThread.java b/forge/src/main/java/de/hype/bbsentials/forge/DebugThread.java index 23f4db8..6fb61fb 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/DebugThread.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/DebugThread.java @@ -1,5 +1,6 @@ package de.hype.bbsentials.forge; +import java.util.Collections; import java.util.List; public class DebugThread implements de.hype.bbsentials.common.client.DebugThread { @@ -10,6 +11,6 @@ public class DebugThread implements de.hype.bbsentials.common.client.DebugThread @Override public List<String> test() { - return List.of(""); + return Collections.singletonList(""); } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/ExampleMod.java b/forge/src/main/java/de/hype/bbsentials/forge/ExampleMod.java index 4043ba1..d181296 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/ExampleMod.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/ExampleMod.java @@ -1,8 +1,7 @@ package de.hype.bbsentials.forge; import de.hype.bbsentials.common.client.BBsentials; -import de.hype.bbsentials.forge.client.CommandBBI; -import net.minecraftforge.client.ClientCommandHandler; +import de.hype.bbsentials.common.mclibraries.EnvironmentCore; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.Mod; @@ -15,21 +14,13 @@ public class ExampleMod { @Mod.EventHandler public void init(FMLInitializationEvent event) { + EnvironmentCore core = new EnvironmentCore(new BBUtils(), new ForgeChat(), new MCUtils(), new Commands(), new Options(), new DebugThread()); MinecraftForge.EVENT_BUS.register(this); } - public void clientSetup() { - if (!alreadyInialised) { - ClientCommandHandler.instance.registerCommand(new CommandBBI()); - alreadyInialised = true; - sentials.init(); - } - } - @SubscribeEvent public void onEntityJoinWorld(EntityJoinWorldEvent event) { - EnvironmentCore core = new EnvironmentCore(new BBUtils(), new FabricChat(), new MCUtils(), new Commands(), new Options(), new DebugThread()); - BBsentials.(); + BBsentials.onServerSwap(); } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/FabricChat.java b/forge/src/main/java/de/hype/bbsentials/forge/FabricChat.java deleted file mode 100644 index f25f4ad..0000000 --- a/forge/src/main/java/de/hype/bbsentials/forge/FabricChat.java +++ /dev/null @@ -1,37 +0,0 @@ -package de.hype.bbsentials.forge; - -import de.hype.bbsentials.common.chat.Message; -import de.hype.bbsentials.common.mclibraries.MCChat; -import de.hype.bbsentials.forge.chat.Chat; -import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; -import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents; -import net.minecraft.client.MinecraftClient; -import net.minecraft.text.Text; - -public class FabricChat implements MCChat { - public FabricChat() { - init(); - } - public Chat chat = new Chat(); - public void init() { - // Register a callback for a custom message type - ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, receptionTimestamp) -> { - chat.onEvent(new Message(Text.Serializer.toJson(message),message.getString())); - }); - ClientReceiveMessageEvents.MODIFY_GAME.register((message, overlay) -> (Text.Serializer.fromJson(chat.onEvent(new Message(Text.Serializer.toJson(message),message.getString())).getJson()))); - ClientSendMessageEvents.CHAT.register(message -> { - if (message.startsWith("/")) { - System.out.println("Sent command: " + message); - } - }); - } - public void sendClientSideMessage(Message message) { - MinecraftClient client = MinecraftClient.getInstance(); - if (client.player != null) { - client.player.sendMessage(Text.Serializer.fromJson(message.getJson())); - } - } - public void sendChatMessage(String message) { - MinecraftClient.getInstance().getNetworkHandler().sendChatMessage(message); - } -} diff --git a/forge/src/main/java/de/hype/bbsentials/forge/ForgeChat.java b/forge/src/main/java/de/hype/bbsentials/forge/ForgeChat.java new file mode 100644 index 0000000..d36106f --- /dev/null +++ b/forge/src/main/java/de/hype/bbsentials/forge/ForgeChat.java @@ -0,0 +1,39 @@ +package de.hype.bbsentials.forge; + +import de.hype.bbsentials.common.chat.Chat; +import de.hype.bbsentials.common.chat.Message; +import de.hype.bbsentials.common.mclibraries.MCChat; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.util.IChatComponent; +import net.minecraftforge.client.event.ClientChatReceivedEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + +public class ForgeChat implements MCChat { + public ForgeChat() { + init(); + } + public Chat chat = new Chat(); + public void init() { + MinecraftForge.EVENT_BUS.register(this); + } + + @SubscribeEvent + public void onClientChatReceived(ClientChatReceivedEvent event) { + Message newMessage = chat.onEvent(new Message(IChatComponent.Serializer.componentToJson(event.message),event.message.getUnformattedText())); + if (!newMessage.equals(event.message)){ + event.setCanceled(true); + Chat.sendPrivateMessageToSelfText(newMessage); + } + } + public void sendClientSideMessage(Message message) { + EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; + if (player != null) { + player.addChatMessage(IChatComponent.Serializer.jsonToComponent(message.getJson())); + } + } + public void sendChatMessage(String message) { + Minecraft.getMinecraft().thePlayer.sendChatMessage(message); + } +} diff --git a/forge/src/main/java/de/hype/bbsentials/forge/MCUtils.java b/forge/src/main/java/de/hype/bbsentials/forge/MCUtils.java index 0a0800b..a9334d5 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/MCUtils.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/MCUtils.java @@ -1,40 +1,39 @@ package de.hype.bbsentials.forge; -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.sound.PositionedSoundInstance; -import net.minecraft.entity.effect.StatusEffectInstance; -import net.minecraft.entity.effect.StatusEffects; -import net.minecraft.sound.SoundEvent; -import net.minecraft.util.Identifier; +import net.minecraft.client.Minecraft; +import net.minecraft.client.audio.PositionedSoundRecord; +import net.minecraft.potion.Potion; +import net.minecraft.potion.PotionEffect; +import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.Display; import java.io.File; public class MCUtils implements de.hype.bbsentials.common.mclibraries.MCUtils { public boolean isWindowFocused() { - return MinecraftClient.getInstance().isWindowFocused(); + return Display.isActive(); } public File getConfigPath() { - return FabricLoader.getInstance().getConfigDir().toFile(); + return new File(Minecraft.getMinecraft().mcDataDir, "config"); } public String getUsername() { - return MinecraftClient.getInstance().player.getName().getString(); + return Minecraft.getMinecraft().thePlayer.getName(); } public String getMCUUID() { - return MinecraftClient.getInstance().player.getUuid().toString(); + return Minecraft.getMinecraft().thePlayer.getUniqueID().toString(); } public void playsound(String eventName) { - MinecraftClient.getInstance().getSoundManager().play(PositionedSoundInstance - .master(SoundEvent.of(new Identifier(eventName)), 1.0F, 1.0F)); + Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation(eventName), 1.0F, 1.0F, 0.0F)); } + public int getPotTime() { int remainingDuration = 0; - StatusEffectInstance potTimeRequest = MinecraftClient.getInstance().player.getStatusEffect(StatusEffects.STRENGTH); + PotionEffect potTimeRequest = Minecraft.getMinecraft().thePlayer.getActivePotionEffect(Potion.damageBoost); if (potTimeRequest != null) { if (potTimeRequest.getAmplifier() >= 7) { remainingDuration = (int) (potTimeRequest.getDuration() / 20.0); diff --git a/forge/src/main/java/de/hype/bbsentials/forge/Options.java b/forge/src/main/java/de/hype/bbsentials/forge/Options.java index bdf0861..047718b 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/Options.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/Options.java @@ -1,14 +1,13 @@ package de.hype.bbsentials.forge; -import de.hype.bbsentials.common.api.ISimpleOption; -import net.minecraft.client.MinecraftClient; +import net.minecraft.client.Minecraft; public class Options implements de.hype.bbsentials.common.mclibraries.Options { public void setFov(int value) { - ((ISimpleOption) (Object) MinecraftClient.getInstance().options.getFov()).set(value); + Minecraft.getMinecraft().gameSettings.fovSetting=value; } public void setGamma(double value) { - ((ISimpleOption) (Object) MinecraftClient.getInstance().options.getGamma()).set(value); + Minecraft.getMinecraft().gameSettings.gammaSetting= (float) value; } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/Temphook.java b/forge/src/main/java/de/hype/bbsentials/forge/Temphook.java index 8441624..05c4cef 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/Temphook.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/Temphook.java @@ -1,5 +1,6 @@ package de.hype.bbsentials.forge; +import de.hype.bbsentials.common.client.BBsentials; import net.minecraft.client.gui.FontRenderer; import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -8,7 +9,7 @@ public class Temphook { public static void renderItemOverlayPost(FontRenderer fr, ItemStack stack, int xPosition, int yPosition, String text, CallbackInfo ci) { if (BBsentials.config.highlightitem) { if (stack != null) { - if (stack.getDisplayName().contains(BBsentials.bbserver.getItemName())) { + if (stack.getDisplayName().contains(BBsentials.connection.getItemName())) { stack.setStackDisplayName("§6(Bingo Splash) " + stack.getDisplayName()); } } diff --git a/forge/src/main/java/de/hype/bbsentials/forge/chat/Chat.java b/forge/src/main/java/de/hype/bbsentials/forge/chat/Chat.java deleted file mode 100644 index 6b12ba1..0000000 --- a/forge/src/main/java/de/hype/bbsentials/forge/chat/Chat.java +++ /dev/null @@ -1,579 +0,0 @@ -package de.hype.bbsentials.forge.chat; - -import de.hype.bbsentials.forge.client.Config; -import net.minecraft.client.Minecraft; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import net.minecraftforge.client.event.ClientChatReceivedEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import org.lwjgl.opengl.Display; - -import javax.sound.sampled.AudioInputStream; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.Clip; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.time.Instant; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static de.hype.bbsentials.forge.client.BBsentials.config; -import static de.hype.bbsentials.forge.client.BBsentials.getConfig; - -public class Chat { - public Chat() { - init(); - } - - public static String[] getVariableInfo(String packageName, String className) { - List<String> variableInfoList = new ArrayList<>(); - - // Combine the class name with the package name - String fullClassName = packageName + "." + className; - - // Load the class - Class<?> clazz = null; - try { - clazz = Class.forName(fullClassName); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - - // Extract fields of the class - Field[] fields = clazz.getDeclaredFields(); - - // Collect information for each field - for (Field field : fields) { - // Exclude transient fields - if (Modifier.isTransient(field.getModifiers())) { - continue; - } - - String variableName = field.getName(); - String variablePackageName = clazz.getPackage().getName(); - String variableClassName = clazz.getSimpleName(); - - String variableInfo = variableName; - variableInfoList.add(variableInfo); - } - - return variableInfoList.toArray(new String[variableInfoList.size()]); - } - - public static void setVariableValue(Object obj, String variableName, String value) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { - if (value == null) { - // Handle null value case - sendPrivateMessageToSelf(EnumChatFormatting.RED + "Invalid value: null"); - return; - } - - Class<?> objClass = obj.getClass(); - Field field = objClass.getDeclaredField(variableName); - field.setAccessible(true); - - // Get the type of the field - Class<?> fieldType = field.getType(); - - // Convert the value to the appropriate type - Object convertedValue = parseValue(value, fieldType); - - if (Modifier.isStatic(field.getModifiers())) { - // If the field is static - field.set(null, convertedValue); - } - else { - field.set(obj, convertedValue); - } - - // Check and output the value of the variable - sendPrivateMessageToSelf(EnumChatFormatting.GREEN + "The variable " + field.getName() + " is now: " + field.get(obj)); - } - - private static Object parseValue(String value, Class<?> targetType) { - if (targetType == int.class || targetType == Integer.class) { - return Integer.parseInt(value); - } - else if (targetType == double.class || targetType == Double.class) { - return Double.parseDouble(value); - } - else if (targetType == float.class || targetType == Float.class) { - return Float.parseFloat(value); - } - else if (targetType == long.class || targetType == Long.class) { - return Long.parseLong(value); - } - else if (targetType == boolean.class || targetType == Boolean.class) { - return Boolean.parseBoolean(value); - } - else { - // For other types, return the original string value - return value; - } - } - - public static void getVariableValue(Object object, String variableName) throws NoSuchFieldException, IllegalAccessException { - Class<?> objClass = object.getClass(); - Field field = objClass.getDeclaredField(variableName); - field.setAccessible(true); - sendPrivateMessageToSelf(EnumChatFormatting.GREEN + "The variable " + field.getName() + " is: " + field.get(object)); - } - - private void init() { - MinecraftForge.EVENT_BUS.register(this); - } - - @SubscribeEvent - public void onClientChatReceived(ClientChatReceivedEvent event) { - IChatComponent newMessage = onEvent(event.message); - if (!newMessage.equals(event.message)){ - event.setCanceled(true); - Chat.sendPrivateMessageToSelfText(newMessage); - } - } - - private net.minecraft.util.IChatComponent onEvent(net.minecraft.util.IChatComponent message) { - Callable<net.minecraft.util.IChatComponent> callable = () -> { - if (!isSpam(message.toString())) { - if (getConfig().isDetailedDevModeEnabled()) { - System.out.println("got a message: " + net.minecraft.util.IChatComponent.Serializer.componentToJson(message)); - } - return handleInClient(message); - } - return message; // Return the original message if it is spam - }; - - FutureTask<net.minecraft.util.IChatComponent> future = new FutureTask<>(callable); - Thread thread = new Thread(future); - thread.start(); - - try { - return future.get(); // Retrieve the result from the background thread - } catch (InterruptedException | ExecutionException e) { - // Handle exceptions, if needed - e.printStackTrace(); - } - - return message; // Return the original message if an exception occurred - } - - //Handle in client - public net.minecraft.util.IChatComponent handleInClient(net.minecraft.util.IChatComponent messageOriginal) { - String message = extractPlainText(messageOriginal.toString()).trim(); - if (getConfig().messageFromAlreadyReported(message) && getPlayerNameFromMessage(message) != " " && getPlayerNameFromMessage(message) != "") { - System.out.println("Message: " + message); - sendPrivateMessageToSelf(EnumChatFormatting.RED + "B: " + message); - return null; - } - if (getConfig().isDevModeEnabled()) { - System.out.println("Got message to analyse internally: " + message); - } - //party accepter - if (message != null) { - if (message.contains("party")) { - if (message.contains("disbanded the party")) { - lastPartyDisbandedMessage = message; - partyDisbandedMap.put(getPlayerNameFromMessage(message), Instant.now()); - if (getConfig().isDevModeEnabled()) { - sendPrivateMessageToSelf("Watching next 20 Sec for invite: " + getPlayerNameFromMessage(message)); - } - } - else if (message.contains("invited you to join their party")) { - if (lastPartyDisbandedMessage != null && partyDisbandedMap != null) { - Instant lastDisbandedInstant = partyDisbandedMap.get(getPlayerNameFromMessage(lastPartyDisbandedMessage)); - if (lastDisbandedInstant != null && lastDisbandedInstant.isAfter(Instant.now().minusSeconds(20)) && (getPlayerNameFromMessage(message).equals(getPlayerNameFromMessage(lastPartyDisbandedMessage)))) { - sendCommand("/p accept " + getPlayerNameFromMessage(lastPartyDisbandedMessage)); - } - } - if (!Display.isActive()) { - sendNotification("BBsentials Party Notifier", "You got invited too a party by: " + getPlayerNameFromMessage(message)); - } - - } - else if (message.equals("Party > " + BBsentials.getConfig().getUsername() + ": rp")) { - sendCommand("/pl"); - repartyActive = true; - } - else if (message.startsWith("Party Members (")) { - Config.partyMembers = new ArrayList<String>(); - } - else if (message.startsWith("Party Moderators:") && repartyActive) { - message = message.replace("Party Moderators:", "").replace(" ●", "").replaceAll("\\s*\\[[^\\]]+\\]", "").trim(); - if (message.contains(",")) { - for (int i = 0; i < message.split(",").length; i++) { - Config.partyMembers.add(message.split(",")[i - 1]); - } - } - else { - Config.partyMembers.add(message); - } - } - else if (message.startsWith("Party Members:")) { - message = message.replace("Party Members:", "").replace(" ●", "").replaceAll("\\s*\\[[^\\]]+\\]", "").trim(); - if (message.contains(",")) { - for (int i = 0; i < message.split(",").length; i++) { - System.out.println("Added to plist: " + (message.split(",")[i - 1])); - Config.partyMembers.add(message.split(",")[i - 1]); - } - } - else { - Config.partyMembers.add(message); - } - if (repartyActive) { - repartyActive = false; - sendCommand("/p disband"); - for (int i = 0; i < Integer.max(4, getConfig().getPlayersInParty().length); i++) { - if (i < getConfig().getPlayersInParty().length) { - sendCommand("/p invite " + getConfig().getPlayersInParty()[i]); - } - } - } - } - else if (message.endsWith("bb:party me") && message.startsWith("From ")) { - if (BBsentials.getConfig().allowBBinviteMe()) { - sendCommand("/p " + getPlayerNameFromMessage(message.replace("From ", ""))); - } - } - - } //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()); - } - else if ((message.endsWith("is visiting Your Garden !") || message.endsWith("is visiting Your Island !")) && !Display.isActive()) { - sendNotification("BBsentials Visit-Watcher", message); - } - else if (message.equals("Please type /report confirm to log your report for staff review.")) { - sendCommand("/report confirm"); - } - else if (message.contains(":") && !Display.isActive()) { - if (message.startsWith("Party >")) { - String partyMessage = message.replaceFirst("Party >", "").trim(); - messageOriginal = replaceAllForText(messageOriginal, "\"action\":\"run_command\",\"value\":\"/viewprofile", "\"action\":\"run_command\",\"value\":\"/hci menu pcm " + partyMessage); - if (partyMessage.split(":", 2)[1].toLowerCase().contains(getConfig().getUsername().toLowerCase()) || (partyMessage.toLowerCase().contains(getConfig().getNickname().toLowerCase() + " ") && getConfig().getNotifForParty().toLowerCase().equals("nick")) || getConfig().getNotifForParty().toLowerCase().equals("all")) { - sendNotification("BBsentials Party Chat Notification", partyMessage); - } - } - else if (message.startsWith("From ")) { - String sender = getPlayerNameFromMessage(message.replaceFirst("From", "").trim()); - String content = message.split(":", 2)[1]; - sendNotification("BBsentials Message Notifier", sender + " sent you the following message: " + content); - } - else if (message.toLowerCase().contains("party")) { - if ((message.contains("Party Leader:") && !message.contains(getConfig().getUsername())) || message.equals("You are not currently in a party.") || (message.contains("warped the party into a Skyblock Dungeon") && !message.startsWith(getConfig().getUsername()) || (!message.startsWith("The party was transferred to " + getConfig().getUsername()) && message.startsWith("The party was transferred to"))) || message.equals(getConfig().getUsername() + " is now a Party Moderator") || (message.equals("The party was disbanded because all invites expired and the party was empty.")) || (message.contains("You have joined ") && message.contains("'s party!")) || (message.contains("Party Leader, ") && message.contains(" , summoned you to their server.")) || (message.contains("warped to your dungeon"))) { - BBsentials.getConfig().setIsLeader(false); - if (getConfig().isDetailedDevModeEnabled()) { - sendPrivateMessageToSelf("Leader: " + getConfig().isLeader()); - } - } - if ((message.equals("Party Leader: " + getConfig().getUsername() + " ●")) || (message.contains(getConfig().getUsername() + " warped the party to a SkyBlock dungeon!")) || message.startsWith("The party was transferred to " + getConfig().getUsername()) || message.equals("Raul_J has promoted " + getConfig().getUsername() + " to Party Leader") || (message.contains("warped to your dungeon"))) { - BBsentials.getConfig().setIsLeader(true); - if (getConfig().isDetailedDevModeEnabled()) { - sendPrivateMessageToSelf("Leader: " + getConfig().isLeader()); - } - } - else if (repartyActive && !BBsentials.getConfig().isLeader()) { - repartyActive = false; - sendPrivateMessageToSelf("Resetted Reparty is Active since you are not leader "); - } - } - else { - String[] temp = message.split(":", 2); - String content = temp[temp.length - 1]; - if (temp.length == 2 && (content.toLowerCase().contains(getConfig().getUsername().toLowerCase()) || content.toLowerCase().contains(config.getNickname().toLowerCase() + " "))) { - sendNotification("BBsentials Notifier", "You got mentioned in chat! " + content); - } - } - } - 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")) { - setChatPromtId(messageOriginal.toString()); - } - - } - return messageOriginal; - } - - //{"strikethrough":false,"extra":[{"strikethrough":false,"clickEvent":{"action":"run_command","value":"/viewprofile 4fa1228c-8dd6-47c4-8fe3-b04b580311b8"},"hoverEvent":{"action":"show_text","contents":{"strikethrough":false,"text":"§eClick here to view §bHype_the_Time§e's profile"}},"text":"§9Party §8> §b[MVP§2+§b] Hype_the_Time§f: "},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"text":"h:test"}],"text":""}// {"strikethrough":false,"extra":[{"strikethrough":false,"clickEvent":{"action":"run_command","value":"/viewprofile f772b2c7-bd2a-46e1-b1a2-41fa561157d6"},"hoverEvent":{"action":"show_text","contents":{"strikethrough":false,"text":"§eClick here to view §bShourtu§e's profile"}},"text":"§9Party §8> §b[MVP§c+§b] Shourtu§f: "},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"text":"Hype_the_Time TEST"}],"text":""} - //{"strikethrough":false,"extra":[{"strikethrough":false,"clickEvent":{"action":"run_command","value":"/viewprofile 4fa1228c-8dd6-47c4-8fe3-b04b580311b8"},"hoverEvent":{"action":"show_text","contents":{"strikethrough":false,"text":"§eClick here to view §bHype_the_Time§e's profile"}},"text":"§9Party §8> §b[MVP§2+§b] Hype_the_Time§f: "},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"text":"h:test"}],"text":""} - private final Map<String, Instant> partyDisbandedMap = new HashMap<>(); - private String lastPartyDisbandedMessage = null; - - public static String getPlayerNameFromMessage(String message) { - message = message.replaceAll("\\[.*?\\]", "").trim(); - message = message.replaceAll("-----------------------------------------------------", "").replaceAll(":", ""); - String[] temp = message.split(" "); - String playerName = ""; - - for (int i = 0; i < temp.length; i++) { - if (!temp[i].equals(" ") && !temp[i].equals("")) { - playerName = temp[i]; - break; // Stop looping after finding the first non-empty value - } - } - - // Remove the rank from the player name, if it exists - Pattern rankPattern = Pattern.compile("\\s*\\[[^\\]]+\\]"); - playerName = rankPattern.matcher(playerName).replaceAll(" "); - - return playerName; - } - - public String extractPlainText(String input) { - String returns = ""; - String[] literals = input.split("literal\\{"); - if (!input.startsWith("literal")) { - literals[0] = ""; - } - for (int i = 0; i < literals.length; i++) { - if (dontExclude(literals, i) && !literals[i].equals("")) { - String literal = literals[i].split("}")[0]; - - if (!literal.isEmpty()) { - returns = returns + literal; - } - } - } - // Remove § formatting - returns = returns.replaceAll("§.", ""); - // Remove brackets that contain only uppercase letters or pluses - returns = returns.replaceAll("\\[[A-Z+]+\\]", ""); - returns = returns.replaceAll("\\[[0-9]+\\]", ""); - returns = returns.trim(); - returns = returns.replaceAll("\\s+", " "); - - return returns; - } - - private boolean dontExclude(String[] s, int i) { - if ((i - 1) < 0) { - return true; - } - else { - if (s[i - 1].endsWith("value='")) { - return false; - } - else { - return true; - } - } - } - - public boolean isSpam(String message) { - if (message.contains("Mana")) return true; - if (message.contains("Achievement Points")) return true; - return false; - } - - private boolean repartyActive = false; - - public String test() { - //put test code here - sendNotification("test", "This is an example which was run of the h:test test"); - return new String(); - } - - private static String removeMultipleSpaces(String input) { - return input.replaceAll("\\s+", " "); - } - - public static void sendPrivateMessageToSelf(String message) { - if (Minecraft.getMinecraft().thePlayer != null) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + message)); - } - } - - public static void sendPrivateMessageToSelfText(net.minecraft.util.IChatComponent message) { - if (Minecraft.getMinecraft().thePlayer != null) { - Minecraft.getMinecraft().thePlayer.addChatMessage(message); - } - } - - public static void sendCommand(String s) { - getConfig().sender.addSendTask(s); - } - - public void sendNotification(String title, String text) { - Thread soundThread = new Thread(() -> { - try { - InputStream inputStream = getClass().getResourceAsStream("/sounds/mixkit-sci-fi-confirmation-914.wav"); - AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputStream); - Clip clip = AudioSystem.getClip(); - clip.open(audioInputStream); - clip.start(); - Thread.sleep(clip.getMicrosecondLength() / 1000); - clip.close(); - audioInputStream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - - soundThread.start(); - - List<String> argsList = new ArrayList<>(); - argsList.add("--title"); - argsList.add(title); - argsList.add("--passivepopup"); - argsList.add(text); - argsList.add("5"); - - try { - ProcessBuilder processBuilder = new ProcessBuilder(); - processBuilder.command("kdialog"); - processBuilder.command().addAll(argsList); - - Process process = processBuilder.start(); - process.waitFor(); - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } - - public static net.minecraft.util.IChatComponent createClientSideTellraw(String tellrawInput) { - net.minecraft.util.IChatComponent formattedMessage = null; - try { - formattedMessage = net.minecraft.util.IChatComponent.Serializer.jsonToComponent(tellrawInput); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Invalid Json: \n" + tellrawInput); - } - return formattedMessage; - } - - public static void followMenu(String menu, String message) { - // Check the "menu" argument and execute the appropriate logic - String command; - String username = getPlayerNameFromMessage(message); - if (message.contains(":")) { - message = message.split(":", 2)[1].trim(); - if (menu.equalsIgnoreCase("pcm")) { - command = "[\"\",{\"text\":\"@@username\",\"color\":\"gray\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/pc @username\"}},{\"text\":\" [Copy_Message]\",\"color\":\"blue\",\"clickEvent\":{\"action\":\"copy_to_clipboard\",\"value\":\"Copy-Text-Message\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Copy the message the Player send without their name into the clipboard.\"]}},{\"text\":\" [Kick_Player]\",\"color\":\"dark_red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p kick @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Kick the player from the party\"]}},{\"text\":\" [Promote_Player]\",\"color\":\"dark_green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p promote @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Promote the player\"]}},{\"text\":\" [Demote_Player]\",\"color\":\"red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p demote @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Demote the player\"]}},{\"text\":\" [Transfer_to_Player]\",\"color\":\"gold\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p transfer @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Transfer the Party to the player\"]}},{\"text\":\" [Mute/Unmute_Party]\",\"color\":\"dark_aqua\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p mute @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Mutes the ENTIRE party but party moderators or Hypixel Staff can still type.\"]}}]"; - //{"jformat":8,"jobject":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"gray","insertion":"","click_event_type":"suggest_command","click_event_value":"/pc @username","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"@username"},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"blue","insertion":"","click_event_type":"copy_to_clipboard","click_event_value":"Copy-Text-Message","hover_event_type":"show_text","hover_event_value":"","hover_event_object":{},"hover_event_children":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"none","insertion":"","click_event_type":"none","click_event_value":"","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"Copy the message the Player send without their name into the clipboard."}],"text":" [Copy_Message]"},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"dark_red","insertion":"","click_event_type":"run_command","click_event_value":"/p kick @username","hover_event_type":"show_text","hover_event_value":"","hover_event_object":{},"hover_event_children":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"none","insertion":"","click_event_type":"none","click_event_value":"","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"Kick the player from the party"}],"text":" [Kick_Player]"},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"dark_green","insertion":"","click_event_type":"run_command","click_event_value":"/p promote @username","hover_event_type":"show_text","hover_event_value":"","hover_event_object":{},"hover_event_children":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"none","insertion":"","click_event_type":"none","click_event_value":"","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"Promote the player"}],"text":" [Promote_Player]"},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"red","insertion":"","click_event_type":"run_command","click_event_value":"/p demote @username","hover_event_type":"show_text","hover_event_value":"","hover_event_object":{},"hover_event_children":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"none","insertion":"","click_event_type":"none","click_event_value":"","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"Demote the player"}],"text":" [Demote_Player]"},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"gold","insertion":"","click_event_type":"run_command","click_event_value":"/p transfer @username","hover_event_type":"show_text","hover_event_value":"","hover_event_object":{},"hover_event_children":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"none","insertion":"","click_event_type":"none","click_event_value":"","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"Transfer the Party to the player"}],"text":" [Transfer_to_Player]"},{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"dark_aqua","insertion":"","click_event_type":"run_command","click_event_value":"/p mute @username","hover_event_type":"show_text","hover_event_value":"","hover_event_object":{},"hover_event_children":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"font":null,"color":"none","insertion":"","click_event_type":"none","click_event_value":"","hover_event_type":"none","hover_event_value":"","hover_event_object":{},"hover_event_children":[],"text":"Mutes the ENTIRE party but party moderators or Hypixel Staff can still type."}],"text":" [Mute/Unmute_Party]"}],"command":"%s","jtemplate":"tellraw"} - } - else if (menu.equalsIgnoreCase("sbacm")) { - command = "[\"\",\"\\n\",{\"text\":\"@@username\",\"color\":\"gray\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"@username\"}},{\"text\":\" [Party_Player]\",\"color\":\"gold\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p invite @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Invite the player to the party\"]}},{\"text\":\" [Ignore_Player]\",\"color\":\"yellow\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/ignore add @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Add the player to your ignore list.\"]}},{\"text\":\" [Chat_Report_Player]\",\"color\":\"dark_red\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/creport @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Chat report the user with /creport.\"]}},{\"text\":\" [Visit_Player]\",\"color\":\"dark_green\",\"insertion\":\" \",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/visit @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[]}},{\"text\":\" [/Invite_Player]\",\"color\":\"green\",\"insertion\":\" \",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/invite @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"/invite the player to visit your Island / Garden.\"]}},{\"text\":\" [Copy_Message] \",\"color\":\"blue\",\"clickEvent\":{\"action\":\"copy_to_clipboard\",\"value\":\"Copy-Text-Message\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Copy the message the user send without their prefixes nor their username\"]}},{\"text\":\" [Copy_Username]\",\"color\":\"dark_aqua\",\"insertion\":\" \",\"clickEvent\":{\"action\":\"copy_to_clipboard\",\"value\":\"@username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Copy the players username into the clipboard.\"]}},{\"text\":\" [/msg_Chat_Player]\",\"color\":\"light_purple\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/msg @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"/msg the Player. the chat will be set to message them. This means you do not need to type /msg upfront. To return to normal do /chat a\"]}},{\"text\":\" [Sky_shiiyu_player]\",\"color\":\"aqua\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://sky.shiiyu.moe/stats/@username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Opens the players Skyblock Profile in Sky Crypt (sky.shiiyu.moe)\"]}},\"\\n\"]"; - } - else if (menu.equalsIgnoreCase("acm")) { - command = "[\"\",\"\\n\",{\"text\":\"@@username\",\"color\":\"gray\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"@username\"}},{\"text\":\" [Party_Player]\",\"color\":\"gold\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/p invite @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Invite the player to the party\"]}},{\"text\":\" [Ignore_Player]\",\"color\":\"yellow\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/ignore add @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Add the player to your ignore list.\"]}},{\"text\":\" [Chat_Report_Player]\",\"color\":\"dark_red\",\"clickEvent\":{\"action\":\"suggest_command\",\"value\":\"/creport @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Chat report the user with /creport.\"]}},{\"text\":\" [Copy_Message] \",\"color\":\"blue\",\"clickEvent\":{\"action\":\"copy_to_clipboard\",\"value\":\"Copy-Text-Message\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Copy the message the user send without their prefixes nor their username\"]}},{\"text\":\" [Copy_Username]\",\"color\":\"dark_aqua\",\"insertion\":\" \",\"clickEvent\":{\"action\":\"copy_to_clipboard\",\"value\":\"@username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"Copy the players username into the clipboard.\"]}},{\"text\":\" [/msg_Chat_Player]\",\"color\":\"light_purple\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/msg @username\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":[\"/msg the Player. the chat will be set to message them. This means you do not need to type /msg upfront. To return to normal do /chat a\"]}}"; - } - else { - // Handle unrecognized menu argument - sendPrivateMessageToSelf(EnumChatFormatting.RED + "Unrecognized menu argument! Do not use this command unless you know exactly what you are doing aka only use it as a developer!"); - return; - } - command = command.replaceAll("@username", username); - command = command.replaceAll("Copy-Text-Message", message); - sendPrivateMessageToSelfText(createClientSideTellraw(command)); - } - else { - sendPrivateMessageToSelf("Invalid message!: " + message); - } - } - - public static void setChatPromtId(String logMessage) { - String cbUUIDPattern = "/cb ([a-fA-F0-9-]+)"; - Pattern cbPattern = Pattern.compile(cbUUIDPattern); - Matcher cbMatcher = cbPattern.matcher(logMessage); - - String yesClickAction = "/chatprompt ([a-fA-F0-9-]+) YES"; - Pattern yesPattern = Pattern.compile(yesClickAction); - Matcher yesMatcher = yesPattern.matcher(logMessage); - String lastPrompt = null; - if (cbMatcher.find()) { - lastPrompt = cbMatcher.group(1); - String finalLastPrompt1 = lastPrompt; - new Thread(new Runnable() { - @Override - public void run() { - BBsentials.getConfig().setLastChatPromptAnswer("/cb " + finalLastPrompt1); - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - BBsentials.getConfig().setLastChatPromptAnswer(null); - return; - } - }).start(); - } - if (yesMatcher.find()) { - lastPrompt = yesMatcher.group(1); - String finalLastPrompt = lastPrompt; - new Thread(new Runnable() { - @Override - public void run() { - BBsentials.getConfig().setLastChatPromptAnswer("/chatprompt " + finalLastPrompt + " YES"); - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - BBsentials.getConfig().setLastChatPromptAnswer(null); - return; - } - }).start(); - - } - } - - public static net.minecraft.util.IChatComponent replaceAllForText(net.minecraft.util.IChatComponent input, String replace, String replaceWith) { - String text = net.minecraft.util.IChatComponent.Serializer.componentToJson(input); - if (text.contains(replace)) { - text = text.replaceAll("\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}", ""); - } - text = text.replace(replace, replaceWith); - net.minecraft.util.IChatComponent output = net.minecraft.util.IChatComponent.Serializer.jsonToComponent(text); - return output; - } -}
\ No newline at end of file diff --git a/forge/src/main/java/de/hype/bbsentials/forge/chat/Sender.java b/forge/src/main/java/de/hype/bbsentials/forge/chat/Sender.java deleted file mode 100644 index 15cd3d7..0000000 --- a/forge/src/main/java/de/hype/bbsentials/forge/chat/Sender.java +++ /dev/null @@ -1,100 +0,0 @@ -package de.hype.bbsentials.forge.chat; - -import com.mojang.realmsclient.gui.ChatFormatting; -import net.minecraft.client.Minecraft; - -import java.util.ArrayList; -import java.util.List; - -public class Sender { - private final List<String> sendQueue; - private final List<Double> sendQueueTiming; - private final List<Boolean> hidden; - - public Sender() { - this.sendQueue = new ArrayList<>(); - this.sendQueueTiming = new ArrayList<>(); - this.hidden = new ArrayList<>(); - startSendingThread(); - } - - public void addSendTask(String task, double timing) { - synchronized (sendQueue) { - Chat.sendPrivateMessageToSelf(ChatFormatting.GREEN + "Scheduled send-task (as " + sendQueueTiming.size() + " in line): " + task + " | Delay: " + timing); - sendQueueTiming.add(timing); - sendQueue.add(task); - hidden.add(false); - sendQueue.notify(); // Notify the waiting thread that a new String has been added - } - } - - public void addHiddenSendTask(String task, double timing) { - synchronized (sendQueue) { - sendQueueTiming.add(timing); - sendQueue.add(task); - hidden.add(true); - sendQueue.notify(); // Notify the waiting thread that a new String has been added - } - } - - public void addImmediateSendTask(String task) { - synchronized (sendQueue) { - sendQueueTiming.add(0, 0.0); - sendQueue.add(0, task); - hidden.add(false); - sendQueue.notify(); // Notify the waiting thread that a new String has been added - } - } - - public void addSendTask(String task) { - addSendTask(task, 1); - } - - public void startSendingThread() { - Thread sendingThread = new Thread(new SendingRunnable()); - sendingThread.start(); - } - - private class SendingRunnable implements Runnable { - @Override - public void run() { - while (true) { - String task = getNextTask(); - if (task != null) { - send(task, sendQueueTiming.remove(0), hidden.remove(0)); - } - else { - synchronized (sendQueue) { - try { - sendQueue.wait(); // Wait for new Send - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - } - } - } - - private String getNextTask() { - synchronized (sendQueue) { - if (!sendQueue.isEmpty()) { - return sendQueue.remove(0); - } - return null; - } - } - - private void send(String toSend, double timing, boolean hidden) { - try { - Thread.sleep((long) (timing * 1000)); // Simulate the send operation - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - Minecraft.getMinecraft().thePlayer.sendChatMessage(toSend); - if (!hidden) { - Chat.sendPrivateMessageToSelf("Sent Command to Server: " + toSend); - } - - } - } -}
\ No newline at end of file diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/CommandBBI.java b/forge/src/main/java/de/hype/bbsentials/forge/client/CommandBBI.java index 352a7b6..208caa3 100644 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/CommandBBI.java +++ b/forge/src/main/java/de/hype/bbsentials/forge/client/CommandBBI.java @@ -1,13 +1,16 @@ package de.hype.bbsentials.forge.client; +import de.hype.bbsentials.common.client.BBsentials; +import de.hype.bbsentials.common.client.Config; import net.minecraft.client.Minecraft; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; -import static de.hype.bbsentials.forge.client.BBsentials.connectToBBserver; -import static de.hype.bbsentials.forge.client.BBsentials.getConfig; +import static de.hype.bbsentials.common.client.BBsentials.connectToBBserver; +import static de.hype.bbsentials.common.client.BBsentials.getConfig; + public class CommandBBI extends CommandBase { diff --git a/forge/src/main/java/de/hype/bbsentials/forge/client/Config.java b/forge/src/main/java/de/hype/bbsentials/forge/client/Config.java deleted file mode 100644 index f4fff7e..0000000 --- a/forge/src/main/java/de/hype/bbsentials/forge/client/Config.java +++ /dev/null @@ -1,198 +0,0 @@ -//Keep in mind that a lot of the stuff in here may never be used and is here because its copied from the 1.20 version which is the main part of the code. - -package de.hype.bbsentials.forge.client; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import de.hype.bbsentials.forge.chat.Chat; -import de.hype.bbsentials.forge.chat.Sender; -import net.minecraft.client.Minecraft; - -import java.io.*; -import java.time.LocalDate; -import java.util.ArrayList; - -public class Config implements Serializable { - // Helper class for sending chat messages - public transient final Sender sender = new Sender(); - - public transient boolean highlightitem = false; - public transient String lastChatPromptAnswer = null; - - // Automatically set, no need for config - private transient String username; - private boolean overrideBingoTime = false; - - // Set in-game - private transient boolean isLeader; - private transient String alreadyReported = ""; - private String bbServerURL = "static.204.177.34.188.clients.your-server.de"; - public String bbsentialsRoles = ""; - public static ArrayList<String> partyMembers = new ArrayList<>(); - - // Set via load / default - private String bbsentialsCommandPrefix = "."; - private String apiKey = ""; - private boolean leaveDungeonAutomatically; - private boolean allowBBinviteMe = true; - private boolean leaveKuudraAutomatically; - private boolean devMode = false; - private boolean detailedDevMode = false; - private boolean acceptReparty; - private String nickname; - private String getNotifForParty; - - // Set default attribute values - private void setDefaults() { - username = Minecraft.getMinecraft().thePlayer.getName(); - leaveKuudraAutomatically = true; - leaveDungeonAutomatically = true; - acceptReparty = true; - if (username.equals("Hype_the_Time")) { - nickname = "hype"; - getNotifForParty = "nick"; - } - else { - nickname = ""; - getNotifForParty = "none"; - } - } - // Gson object for serialization - private final transient Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - // File object for storing the config - private final transient File CONFIG_FILE = new File("./config/BBsential_settings.json"); - - // Constructor - public Config() { - setDefaults(); - } - - // Load the config from file - public static Config load() { - Config settings; - File CONFIG_FILE = new File("./config/BBsential_settings.json"); - Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - if (CONFIG_FILE.exists()) { - try (FileReader reader = new FileReader(CONFIG_FILE)) { - settings = GSON.fromJson(reader, Config.class); - } catch (IOException e) { - e.printStackTrace(); - settings = new Config(); // Use default values if loading fails - } - } - else { - settings = new Config(); // Use default values if the file doesn't exist - } - if (!settings.bbsentialsRoles.contains("dev")) { - settings.detailedDevMode = false; - settings.devMode = false; - } - settings.save(); - return settings; - } - - // Save the config to file - public void save() { - try (FileWriter writer = new FileWriter(CONFIG_FILE)) { - GSON.toJson(this, writer); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // Getter methods for various config attributes - public String getUsername() { - return username; - } - - public boolean isLeader() { - return isLeader; - } - - public void setIsLeader(boolean value) { - isLeader = value; - } - - public String getNickname() { - return nickname; - } - - public String getNotifForParty() { - return getNotifForParty; - } - - public boolean isLeaveDungeonAutomatically() { - return leaveDungeonAutomatically; - } - - public boolean isLeaveKuudraAutomatically() { - return leaveKuudraAutomatically; - } - - public boolean isDevModeEnabled() { - return devMode; - } - - public boolean isDetailedDevModeEnabled() { - return detailedDevMode; - } - - public String[] getPlayersInParty() { - return partyMembers.toArray(new String[0]); - } - - public boolean messageFromAlreadyReported(String message) { - return alreadyReported.contains(Chat.getPlayerNameFromMessage(message)); - } - - public void addReported(String playerName) { - alreadyReported = alreadyReported + " , " + playerName; - } - - public String getApiKey() { - return apiKey; - } - - public String getBBServerURL() { - return bbServerURL; - } - - public String getCommandPrefix(String type) { - if (type.equals("BBsentials")) { - System.out.println("Registered command with: " + bbsentialsCommandPrefix); - return bbsentialsCommandPrefix; - } - else { - return "/"; - } - } - - public static boolean isBingoTime() { - LocalDate currentDate = LocalDate.now(); - LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth()); - LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1); - Boolean isBefore = currentDate.isAfter(lastDayOfMonth.minusDays(4)); - Boolean isInRange = currentDate.isBefore(firstDayOfMonth.plusDays(15)); - return isBefore || isInRange; - } - - public boolean overrideBingoTime() { - return overrideBingoTime; - } - - public boolean isHighlightitem() { - return highlightitem; - } - - public String getLastChatPromptAnswer() { - return lastChatPromptAnswer; - } - - public boolean allowBBinviteMe() { - return allowBBinviteMe; - } - - public void setLastChatPromptAnswer(String lastChatPromptAnswer) { - this.lastChatPromptAnswer = lastChatPromptAnswer; - } -} diff --git a/forge/src/main/java/de/hype/bbsentials/forge/communication/BBsentialConnection.java b/forge/src/main/java/de/hype/bbsentials/forge/communication/BBsentialConnection.java deleted file mode 100644 index 3d8106b..0000000 --- a/forge/src/main/java/de/hype/bbsentials/forge/communication/BBsentialConnection.java +++ /dev/null @@ -1,340 +0,0 @@ -package de.hype.bbsentials.forge.communication; - -import de.hype.bbsentials.forge.chat.Chat; -import net.minecraft.client.Minecraft; -import net.minecraft.potion.Potion; -import net.minecraft.potion.PotionEffect; - -import javax.net.ssl.*; -import java.io.*; -import java.net.Socket; -import java.net.SocketException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -public class BBsentialConnection { - private Socket socket; - private BufferedReader reader; - private PrintWriter writer; - private LinkedBlockingQueue<String> messageQueue; - private MessageReceivedCallback messageReceivedCallback; - private ScheduledExecutorService executorService; - private String itemName = "Hub #0"; - - public interface MessageReceivedCallback { - void onMessageReceived(String message); - } - - public void connect(String serverIP, int serverPort) { - // Enable SSL handshake debugging - System.setProperty("javax.net.debug", "ssl,handshake"); - FileInputStream inputStream = null; - try { - // Load the BBssentials-online server's public certificate from the JKS file - try { - InputStream resouceInputStream = BBsentials.class.getResourceAsStream("/assets/public_bbsentials_cert.crt"); - - // Check if the resource exists - if (resouceInputStream == null) { - System.out.println("The resource '/assets/public_bbsentials_cert.crt' was not found."); - return; - } - - File tempFile = File.createTempFile("public_bbsentials_cert", ".crt"); - tempFile.deleteOnExit(); - - FileOutputStream outputStream = new FileOutputStream(tempFile); - - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = resouceInputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - - outputStream.close(); - resouceInputStream.close(); - - // Now you have the .crt file as a FileInputStream in the tempFile - inputStream = new FileInputStream(tempFile); - - // Use the fileInputStream as needed - - } catch (IOException e) { - e.printStackTrace(); - } - CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); - X509Certificate serverCertificate = (X509Certificate) certFactory.generateCertificate(inputStream); - 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 - } - - 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."); - } - } - } - }; - - // Create an SSL context with the custom TrustManager - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, trustManagers, new SecureRandom()); - - // Create an SSL socket factory - SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - socket = (SSLSocket) sslSocketFactory.createSocket(serverIP, serverPort); - - socket.setKeepAlive(true); // Enable Keep-Alive - - reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); - 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 { - while (true) { - String message = reader.readLine(); - if (message != null) { - if (messageReceivedCallback != null) { - messageReceivedCallback.onMessageReceived(message); - } - else { - Chat.sendPrivateMessageToSelf("BB: It seemed like you disconnected. Reconnecting..."); - BBsentials.connectToBBserver(); - try { - Thread.sleep(1000 * 10); - } catch (Exception ignored) { - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } - }); - messageReceiverThread.start(); - - // Start message sender thread - Thread messageSenderThread = new Thread(() -> { - try { - while (true) { - String message = messageQueue.take(); - writer.println(message); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - }); - messageSenderThread.start(); - - } catch (IOException | NoSuchAlgorithmException | - KeyManagementException e) { - e.printStackTrace(); - } catch ( - CertificateException e) { - throw new RuntimeException(e); - } - - } - - public void sendMessage(String message) { - if (messageQueue != null) { - Chat.sendPrivateMessageToSelf("§aBBs: " + message); - messageQueue.offer(message); - } - else { - Chat.sendPrivateMessageToSelf("§4BB: It seems like the connection was lost. Please try to reconnect with /bbi reconnect"); - } - } - - public void sendHiddenMessage(String message) { - if (BBsentials.getConfig().isDetailedDevModeEnabled()) { - Chat.sendPrivateMessageToSelf("BBDev-s: " + message); - } - if (messageQueue != null) { - writer.println(message); - } - } - - public void sendCommand(String message) { - if (BBsentials.getConfig().isDetailedDevModeEnabled()) { - Chat.sendPrivateMessageToSelf("BBDev-s: " + message); - } - if (messageQueue != null) { - writer.println(message); - } - else { - Chat.sendPrivateMessageToSelf("§4BB: It seems like the connection was lost. Please try to reconnect with /bbi reconnect"); - } - } - - //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(Minecraft.getMinecraft().thePlayer.getUniqueID().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); - } - } - } - 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.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(); - } - 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]); - } - else if (arguments[0].equals("hub")) { - BBsentials.config.sender.addHiddenSendTask("/hub", 1); - } - } - if (BBsentials.getConfig().isDetailedDevModeEnabled()) { - Chat.sendPrivateMessageToSelf("BBDev-r: " + message); - } - } - else { - Chat.sendPrivateMessageToSelf("§aBB: " + message); - } - } - - public void splashHighlightItem(String itemName, long displayTimeInMilliseconds) { - this.itemName = itemName; - BBsentials.config.highlightitem = true; - executorService.schedule(() -> { - BBsentials.config.highlightitem = false; - try { - socket.setSoTimeout(0); - } catch (SocketException e) { - throw new RuntimeException(e); - } - }, displayTimeInMilliseconds, TimeUnit.MILLISECONDS); - } - - public String getItemName() { - return itemName; - } - - public static int getPotTime() { - int remainingTimeInMinutes = 0; - PotionEffect potTimeRequest = Minecraft.getMinecraft().thePlayer.getActivePotionEffect(Potion.damageBoost); - if (potTimeRequest != null) { - if (potTimeRequest.getAmplifier() >= 7) { - remainingTimeInMinutes = (int) (potTimeRequest.getDuration() / 20.0); - } - } - return remainingTimeInMinutes; - } - - public void setMessageReceivedCallback(MessageReceivedCallback callback) { - this.messageReceivedCallback = callback; - } - //TODO search - - 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 { - 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!!!!!!!! "; - System.out.println(emergencyMessage); - Chat.sendPrivateMessageToSelf("§4" + emergencyMessage + "\n\n"); - Chat.sendPrivateMessageToSelf("§4" + emergencyMessage + "\n\n"); - /*try { - Thread.sleep(5000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - throw new RuntimeException(emergencyMessage);*/ - } - return false; - } -} |